Add define-table: record every `define for LSP hover expansion
collect_defines() is a post-lex pass over Directive tokens (zero lexer changes) building an ordered DefineTable: name, params (as written, defaults included), body normalized exactly as a preprocessor joins continuations (backslash-newline removed, every other byte preserved -- string values survive), span and name_span. Redefinitions and `undef events are all recorded in source order (latest()/all()); position-aware resolution is deliberately left to the future hover implementation, which needs the history. Pure data feature: no behavior change anywhere. 24 tests including mutation-testing of the normalization rule against alternatives that would rewrite string values. QA swept 502 defines from the corpus with zero span/name mismatches and hand-verified prim_assert.sv macros; CRLF continuations confirmed at lexer and table layers. TODO §6 data foundations now complete (spans, error recovery, define table). Dev: Opus agent; QA: Sonnet agent; review in docs/features/define-table/README.md. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
02f68655b5
commit
0ba29d4635
4 files changed
+1095
No files matched your search
@@ -0,0 +1,300 @@
|
||||
//! The `` `define`` table: every macro definition a file writes, recorded so
|
||||
//! an editor can show it.
|
||||
//!
|
||||
//! This is bookkeeping, not preprocessing. Nothing here expands a macro and
|
||||
//! the formatter never calls it, so TODO.md §7's "no preprocessor expansion"
|
||||
//! non-goal stands. It is a pure post-lex pass: a `` `define`` already arrives
|
||||
//! as one [`TokenKind::Directive`] token carrying its whole text and span, so
|
||||
//! the table is read off the token stream a second time and the lexer needs no
|
||||
//! change at all. See `docs/features/define-table/README.md`.
|
||||
|
||||
use crate::span::TextRange;
|
||||
use crate::token::{Token, TokenKind};
|
||||
|
||||
/// What a recorded directive did to a macro name.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DefineKind {
|
||||
/// `` `define NAME ... ``
|
||||
Define,
|
||||
/// `` `undef NAME `` — recorded so that a later position-aware lookup can
|
||||
/// see where a name stopped being defined. Nothing resolves it yet.
|
||||
Undef,
|
||||
}
|
||||
|
||||
/// One `` `define`` or `` `undef`` directive, as written.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Define {
|
||||
/// Whether this entry defines the name or undefines it.
|
||||
pub kind: DefineKind,
|
||||
/// The macro name, without the leading backtick.
|
||||
pub name: String,
|
||||
/// `None` for an object-like macro, `Some` for a function-like one: one
|
||||
/// entry per parameter as written, edges trimmed (`"a"`, `"b = 8"`).
|
||||
/// `` `define NAME() `` gives `Some(vec![])`. Always `None` for an
|
||||
/// [`DefineKind::Undef`] entry.
|
||||
pub params: Option<Vec<String>>,
|
||||
/// The replacement text, line continuations joined (see
|
||||
/// [`join_continuations`]). Empty for a body-less `` `define`` and for
|
||||
/// every `` `undef``.
|
||||
pub body: String,
|
||||
/// Extent of the whole directive: the backtick through the last byte the
|
||||
/// lexer kept.
|
||||
pub span: TextRange,
|
||||
/// Extent of the name alone, so an editor can highlight exactly it.
|
||||
pub name_span: TextRange,
|
||||
}
|
||||
|
||||
/// Every `` `define``/`` `undef`` in one file, in source order.
|
||||
///
|
||||
/// Redefinition is legal Verilog, so a name can have several definitions; they
|
||||
/// are all kept and [`DefineTable::latest`] picks the last one.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct DefineTable {
|
||||
entries: Vec<Define>,
|
||||
}
|
||||
|
||||
impl DefineTable {
|
||||
/// Every recorded directive, `` `undef``s included, in source order.
|
||||
pub fn entries(&self) -> &[Define] {
|
||||
&self.entries
|
||||
}
|
||||
|
||||
/// Every definition of `name`, in source order. `` `undef`` entries are
|
||||
/// not definitions and are not returned.
|
||||
pub fn all(&self, name: &str) -> Vec<&Define> {
|
||||
self.entries.iter().filter(|d| d.kind == DefineKind::Define && d.name == name).collect()
|
||||
}
|
||||
|
||||
/// The last definition of `name` in the file, or `None` if it has none.
|
||||
pub fn latest(&self, name: &str) -> Option<&Define> {
|
||||
self.entries.iter().rev().find(|d| d.kind == DefineKind::Define && d.name == name)
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the `` `define``/`` `undef`` table off an already-lexed token stream.
|
||||
///
|
||||
/// Never fails: a directive too malformed to read a name out of is skipped,
|
||||
/// because an editor asking for hover text must not be told the file is
|
||||
/// broken.
|
||||
pub fn collect_defines(tokens: &[Token]) -> DefineTable {
|
||||
let mut entries = Vec::new();
|
||||
for tok in tokens {
|
||||
if tok.kind != TokenKind::Directive {
|
||||
continue;
|
||||
}
|
||||
match directive_word(&tok.text) {
|
||||
"define" => entries.extend(parse_define(tok)),
|
||||
"undef" => entries.extend(parse_undef(tok)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
DefineTable { entries }
|
||||
}
|
||||
|
||||
/// The directive's keyword: `` `define FOO `` → `define`. Matching on the
|
||||
/// whole word rather than a prefix is what keeps `` `undefineall`` out of the
|
||||
/// `` `undef`` arm.
|
||||
fn directive_word(text: &str) -> &str {
|
||||
let rest = text.strip_prefix('`').unwrap_or(text);
|
||||
let end = rest.find(|c: char| !is_name_char(c)).unwrap_or(rest.len());
|
||||
rest.get(..end).unwrap_or("")
|
||||
}
|
||||
|
||||
fn parse_define(tok: &Token) -> Option<Define> {
|
||||
let text = &tok.text;
|
||||
let after_keyword = 1 + directive_word(text).len();
|
||||
let name_start = skip_separators(text, after_keyword);
|
||||
let (name, name_end) = read_name(text, name_start)?;
|
||||
|
||||
// A parameter list counts only when its `(` touches the name (LRM 22.5.1):
|
||||
// `` `define A (x) `` is an object-like macro whose body starts with `(`.
|
||||
// An unbalanced list is not an error either — the text is recorded as an
|
||||
// object-like body rather than dropped.
|
||||
let (params, body_start) = match text.as_bytes().get(name_end) {
|
||||
Some(b'(') => match read_params(text, name_end) {
|
||||
Some((params, after)) => (Some(params), after),
|
||||
None => (None, name_end),
|
||||
},
|
||||
_ => (None, name_end),
|
||||
};
|
||||
|
||||
Some(Define {
|
||||
kind: DefineKind::Define,
|
||||
name: name.to_string(),
|
||||
params,
|
||||
body: join_continuations(text.get(body_start..).unwrap_or("")).trim().to_string(),
|
||||
span: tok.span,
|
||||
name_span: sub_span(tok, name_start, name_end),
|
||||
})
|
||||
}
|
||||
|
||||
fn parse_undef(tok: &Token) -> Option<Define> {
|
||||
let text = &tok.text;
|
||||
let name_start = skip_separators(text, 1 + directive_word(text).len());
|
||||
let (name, name_end) = read_name(text, name_start)?;
|
||||
Some(Define {
|
||||
kind: DefineKind::Undef,
|
||||
name: name.to_string(),
|
||||
params: None,
|
||||
body: String::new(),
|
||||
span: tok.span,
|
||||
name_span: sub_span(tok, name_start, name_end),
|
||||
})
|
||||
}
|
||||
|
||||
/// A range inside the directive's own text, translated to source offsets.
|
||||
///
|
||||
/// Sound because a `Directive` token's text *is* its source slice: the lexer
|
||||
/// only trims its end, and gives the token the span of what it kept
|
||||
/// (`docs/features/spans/README.md`).
|
||||
fn sub_span(tok: &Token, start: usize, end: usize) -> TextRange {
|
||||
let base = tok.span.start;
|
||||
TextRange::new(base + start as u32, base + end as u32)
|
||||
}
|
||||
|
||||
/// Skip the whitespace between a directive's words, line continuations
|
||||
/// included: a `\` before a newline joins two lines, it is not text.
|
||||
fn skip_separators(text: &str, mut i: usize) -> usize {
|
||||
let b = text.as_bytes();
|
||||
while i < b.len() {
|
||||
match b[i] {
|
||||
b' ' | b'\t' | b'\r' | b'\n' => i += 1,
|
||||
b'\\' => match continuation_len(b, i) {
|
||||
Some(n) => i += n,
|
||||
None => break,
|
||||
},
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
i
|
||||
}
|
||||
|
||||
/// The macro name starting at `start`, and the offset just past it.
|
||||
fn read_name(text: &str, start: usize) -> Option<(&str, usize)> {
|
||||
let b = text.as_bytes();
|
||||
let mut end = start;
|
||||
while end < b.len() && is_name_byte(b[end]) {
|
||||
end += 1;
|
||||
}
|
||||
if end == start {
|
||||
None
|
||||
} else {
|
||||
text.get(start..end).map(|name| (name, end))
|
||||
}
|
||||
}
|
||||
|
||||
/// Split a function-like macro's parameter list. `start` is its `(`; the
|
||||
/// result is the parameters as written and the offset just past the `)`.
|
||||
/// `None` when the list never closes.
|
||||
fn read_params(text: &str, start: usize) -> Option<(Vec<String>, usize)> {
|
||||
let b = text.as_bytes();
|
||||
let mut depth = 0usize;
|
||||
let mut piece_start = start + 1;
|
||||
let mut params: Vec<String> = Vec::new();
|
||||
let mut i = start;
|
||||
while i < b.len() {
|
||||
match b[i] {
|
||||
// A default value may hold a string, and a string may hold a
|
||||
// comma or a bracket.
|
||||
b'"' => {
|
||||
i = skip_string(b, i);
|
||||
continue;
|
||||
}
|
||||
b'(' | b'[' | b'{' => depth += 1,
|
||||
b')' | b']' | b'}' => {
|
||||
depth = depth.saturating_sub(1);
|
||||
if depth == 0 {
|
||||
let piece = text.get(piece_start..i).unwrap_or("");
|
||||
// `NAME()` is a function-like macro with no parameters,
|
||||
// not one empty parameter.
|
||||
if !(params.is_empty() && piece.trim().is_empty()) {
|
||||
params.push(normalize_param(piece));
|
||||
}
|
||||
return Some((params, i + 1));
|
||||
}
|
||||
}
|
||||
b',' if depth == 1 => {
|
||||
params.push(normalize_param(text.get(piece_start..i).unwrap_or("")));
|
||||
piece_start = i + 1;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn normalize_param(piece: &str) -> String {
|
||||
join_continuations(piece).trim().to_string()
|
||||
}
|
||||
|
||||
/// Join a directive's continued lines the way a preprocessor does: a `\` that
|
||||
/// ends a line is not part of the macro text, and neither is the newline it
|
||||
/// ends.
|
||||
///
|
||||
/// Nothing else is touched — in particular the indentation of a continued line
|
||||
/// is kept byte for byte, because inside a string literal that whitespace is
|
||||
/// the value, not layout. So a three-line body becomes one line whose pieces
|
||||
/// are separated by exactly the spaces that were written around the joins.
|
||||
fn join_continuations(text: &str) -> String {
|
||||
let b = text.as_bytes();
|
||||
let mut out = String::with_capacity(text.len());
|
||||
let mut copied = 0;
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
match continuation_len(b, i) {
|
||||
Some(n) => {
|
||||
out.push_str(text.get(copied..i).unwrap_or(""));
|
||||
i += n;
|
||||
copied = i;
|
||||
}
|
||||
None => i += 1,
|
||||
}
|
||||
}
|
||||
out.push_str(text.get(copied..).unwrap_or(""));
|
||||
out
|
||||
}
|
||||
|
||||
/// The length of a line continuation starting at `i` — the `\`, the
|
||||
/// horizontal whitespace after it and the newline — or `None` when this
|
||||
/// backslash is ordinary text.
|
||||
///
|
||||
/// Horizontal whitespace is allowed between the two because the lexer allows
|
||||
/// it when it decides to keep reading (`text_ends_with_continuation`); the two
|
||||
/// must agree or a stray `\` would survive into a body.
|
||||
fn continuation_len(b: &[u8], i: usize) -> Option<usize> {
|
||||
if b.get(i) != Some(&b'\\') {
|
||||
return None;
|
||||
}
|
||||
let mut j = i + 1;
|
||||
while matches!(b.get(j), Some(b' ' | b'\t' | b'\r')) {
|
||||
j += 1;
|
||||
}
|
||||
if b.get(j) == Some(&b'\n') {
|
||||
Some(j + 1 - i)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// The offset just past the string literal starting at `start`, or the end of
|
||||
/// the text if it never closes.
|
||||
fn skip_string(b: &[u8], start: usize) -> usize {
|
||||
let mut i = start + 1;
|
||||
while i < b.len() {
|
||||
match b[i] {
|
||||
b'\\' => i += 2,
|
||||
b'"' => return i + 1,
|
||||
_ => i += 1,
|
||||
}
|
||||
}
|
||||
b.len()
|
||||
}
|
||||
|
||||
fn is_name_byte(c: u8) -> bool {
|
||||
c == b'_' || c == b'$' || c.is_ascii_alphanumeric()
|
||||
}
|
||||
|
||||
fn is_name_char(c: char) -> bool {
|
||||
c == '_' || c == '$' || c.is_ascii_alphanumeric()
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
//! crate consumes.
|
||||
|
||||
pub mod ast;
|
||||
pub mod defines;
|
||||
pub mod lexer;
|
||||
pub mod line_index;
|
||||
pub mod parser;
|
||||
|
||||
@@ -0,0 +1,281 @@
|
||||
//! The `` `define`` table (TODO.md §6): what gets recorded, and exactly how a
|
||||
//! multi-line body is normalized.
|
||||
//!
|
||||
//! Every assertion here is about *data*, not behavior — nothing in this file
|
||||
//! formats anything. See `docs/features/define-table/README.md`.
|
||||
|
||||
use vlog_parser::defines::{collect_defines, Define, DefineKind, DefineTable};
|
||||
use vlog_parser::tokenize;
|
||||
|
||||
fn table(src: &str) -> DefineTable {
|
||||
collect_defines(&tokenize(src).expect("lex error"))
|
||||
}
|
||||
|
||||
/// The one definition the source is expected to have.
|
||||
fn only(src: &str) -> Define {
|
||||
let t = table(src);
|
||||
assert_eq!(t.entries().len(), 1, "expected exactly one entry in {src:?}");
|
||||
t.entries()[0].clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_simple_define_records_name_and_body() {
|
||||
let d = only("`define WIDTH 8\n");
|
||||
assert_eq!(d.kind, DefineKind::Define);
|
||||
assert_eq!(d.name, "WIDTH");
|
||||
assert_eq!(d.params, None);
|
||||
assert_eq!(d.body, "8");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_keeps_its_own_spacing_and_stops_at_the_line() {
|
||||
let d = only("`define EXPR (a + b)\nmodule m; endmodule\n");
|
||||
assert_eq!(d.name, "EXPR");
|
||||
assert_eq!(d.body, "(a + b)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_function_like_define_records_its_parameters_with_defaults() {
|
||||
let d = only("`define MAX(a, b = 8, c=WIDTH-1) ((a) > (b) ? (a) : (b))\n");
|
||||
assert_eq!(d.name, "MAX");
|
||||
assert_eq!(d.params, Some(vec!["a".to_string(), "b = 8".to_string(), "c=WIDTH-1".to_string()]));
|
||||
assert_eq!(d.body, "((a) > (b) ? (a) : (b))");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_default_may_hold_commas_brackets_and_strings() {
|
||||
let d = only("`define M(a = f(1, 2), b = {3, 4}, c = \"x, y\") a b c\n");
|
||||
assert_eq!(
|
||||
d.params,
|
||||
Some(
|
||||
vec!["a = f(1, 2)".to_string(), "b = {3, 4}".to_string(), "c = \"x, y\"".to_string(),]
|
||||
)
|
||||
);
|
||||
assert_eq!(d.body, "a b c");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_parameter_list_is_zero_parameters_not_one() {
|
||||
let d = only("`define NOW() $time\n");
|
||||
assert_eq!(d.params, Some(vec![]));
|
||||
assert_eq!(d.body, "$time");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_space_before_the_paren_makes_the_macro_object_like() {
|
||||
// LRM 22.5.1: the `(` must touch the name, otherwise it is body text.
|
||||
let d = only("`define A (x)\n");
|
||||
assert_eq!(d.params, None, "`define A (x) defines A as the text `(x)`");
|
||||
assert_eq!(d.body, "(x)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_multi_line_body_joins_its_continuations() {
|
||||
// Four physical lines, three continuations. The rule under test: the `\`
|
||||
// and the newline vanish, every other byte — including the indentation of
|
||||
// a continued line — survives.
|
||||
let src = "`define FF(q, d) \\\n always_ff @(posedge clk) begin \\\n q <= d; \\\n end\n";
|
||||
let d = only(src);
|
||||
assert_eq!(d.name, "FF");
|
||||
assert_eq!(d.params, Some(vec!["q".to_string(), "d".to_string()]));
|
||||
assert_eq!(d.body, "always_ff @(posedge clk) begin q <= d; end");
|
||||
assert!(!d.body.contains('\\'), "no backslash survives the join");
|
||||
assert!(!d.body.contains('\n'), "the body is one logical line");
|
||||
// The span still covers all four physical lines, so a consumer that wants
|
||||
// the definition as written slices the source instead.
|
||||
assert_eq!(&src[d.span.as_range()], src.trim_end());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_continuation_may_have_trailing_spaces_after_the_backslash() {
|
||||
// The lexer tolerates `\` + spaces + newline; the join must agree, or a
|
||||
// stray backslash would survive into the body.
|
||||
let d = only("`define A x \\ \n y\n");
|
||||
assert_eq!(d.body, "x y");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_body_is_recorded_as_an_empty_string() {
|
||||
let d = only("`define GUARD\n");
|
||||
assert_eq!(d.name, "GUARD");
|
||||
assert_eq!(d.params, None);
|
||||
assert_eq!(d.body, "");
|
||||
assert_eq!(&d.name_span.as_range(), &(8..13));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_comment_is_not_part_of_the_body() {
|
||||
let d = only("`define A 1 // eight bits\n");
|
||||
assert_eq!(d.body, "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_redefinition_keeps_every_definition_and_latest_wins() {
|
||||
let src = "`define W 8\n`define X 1\n`define W 16\n`define W 32\n";
|
||||
let t = table(src);
|
||||
assert_eq!(t.entries().len(), 4);
|
||||
|
||||
let all = t.all("W");
|
||||
assert_eq!(all.len(), 3, "redefinition is legal; all three are kept");
|
||||
assert_eq!(
|
||||
all.iter().map(|d| d.body.as_str()).collect::<Vec<_>>(),
|
||||
vec!["8", "16", "32"],
|
||||
"in source order"
|
||||
);
|
||||
assert_eq!(t.latest("W").map(|d| d.body.as_str()), Some("32"));
|
||||
assert_eq!(t.latest("X").map(|d| d.body.as_str()), Some("1"));
|
||||
assert!(t.latest("NOPE").is_none());
|
||||
assert!(t.all("NOPE").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_undef_is_recorded_as_an_event_and_is_not_a_definition() {
|
||||
let src = "`define W 8\n`undef W\n";
|
||||
let t = table(src);
|
||||
assert_eq!(t.entries().len(), 2);
|
||||
|
||||
let undef = &t.entries()[1];
|
||||
assert_eq!(undef.kind, DefineKind::Undef);
|
||||
assert_eq!(undef.name, "W");
|
||||
assert_eq!(undef.params, None);
|
||||
assert_eq!(undef.body, "");
|
||||
assert_eq!(&src[undef.name_span.as_range()], "W");
|
||||
|
||||
// No resolution yet: the `define is still reachable, `undef is only a
|
||||
// recorded event a position-aware lookup can consult later.
|
||||
assert_eq!(t.all("W").len(), 1);
|
||||
assert_eq!(t.latest("W").map(|d| d.body.as_str()), Some("8"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undefineall_is_not_an_undef() {
|
||||
// Word-level matching, not a prefix test.
|
||||
let t = table("`define W 8\n`undefineall\n");
|
||||
assert_eq!(t.entries().len(), 1);
|
||||
assert_eq!(t.entries()[0].kind, DefineKind::Define);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_define_inside_an_ifdef_is_still_recorded() {
|
||||
// Conditions are not evaluated — both arms are recorded, in source order.
|
||||
let src = "`ifdef FAST\n`define LAT 1\n`else\n`define LAT 4\n`endif\n";
|
||||
let t = table(src);
|
||||
assert_eq!(t.all("LAT").len(), 2);
|
||||
assert_eq!(t.all("LAT").iter().map(|d| d.body.as_str()).collect::<Vec<_>>(), vec!["1", "4"]);
|
||||
assert_eq!(t.latest("LAT").map(|d| d.body.as_str()), Some("4"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_define_inside_a_module_is_recorded_too() {
|
||||
let src = "module m;\n `define LOCAL 3\n wire w;\nendmodule\n";
|
||||
let t = table(src);
|
||||
assert_eq!(t.all("LOCAL").len(), 1);
|
||||
assert_eq!(t.latest("LOCAL").map(|d| d.body.as_str()), Some("3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn name_span_slices_back_to_exactly_the_name() {
|
||||
let src = "// header\nmodule m;\nendmodule\n`define MY_MACRO(a) (a)\n";
|
||||
let d = only(src);
|
||||
assert_eq!(&src[d.name_span.as_range()], "MY_MACRO");
|
||||
assert_eq!(&src[d.span.as_range()], "`define MY_MACRO(a) (a)");
|
||||
assert!(
|
||||
d.span.start <= d.name_span.start && d.name_span.end <= d.span.end,
|
||||
"the name nests inside the directive"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spans_are_byte_offsets_past_multi_byte_text() {
|
||||
let src = "// λλλ\n`define A 1\n";
|
||||
let d = only(src);
|
||||
assert_eq!(&src[d.name_span.as_range()], "A");
|
||||
assert_eq!(&src[d.span.as_range()], "`define A 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_backslash_inside_a_string_body_is_an_escape_not_a_continuation() {
|
||||
// `\"` and `\\` are string escapes: only a backslash that ends the line
|
||||
// continues it.
|
||||
let d = only("`define Q \"a\\\"b\\\\c\"\n");
|
||||
assert_eq!(d.name, "Q");
|
||||
assert_eq!(d.body, "\"a\\\"b\\\\c\"", "the string survives byte for byte");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_string_continued_across_lines_keeps_its_inner_whitespace() {
|
||||
// The preprocessor removes the backslash-newline and nothing else, so the
|
||||
// continued line's indentation becomes part of the string's value. This is
|
||||
// the case the formatter's `verify.rs` had to be taught about too (see
|
||||
// docs/features/macro-items/README.md).
|
||||
let src = "`define MSG \"line one \\\n line two\"\n";
|
||||
let d = only(src);
|
||||
assert_eq!(d.body, "\"line one line two\"");
|
||||
assert_eq!(&src[d.span.as_range()], "`define MSG \"line one \\\n line two\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_doubled_backslash_at_end_of_line_still_continues_the_line() {
|
||||
// The lexer decides continuation by "does the line end in a backslash",
|
||||
// so the last backslash is the continuation and the one before it is
|
||||
// text. The table must read it the same way or the two would disagree
|
||||
// about where the definition ends.
|
||||
let d = only("`define P \"x\\\\\n y\"\n");
|
||||
assert_eq!(d.body, "\"x\\ y\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_with_no_defines_gives_an_empty_table() {
|
||||
let t = table(
|
||||
"module m;\n `timescale 1ns / 1ps\n `ifdef X\n `endif\n `MACRO(a, b)\nendmodule\n",
|
||||
);
|
||||
assert!(t.entries().is_empty());
|
||||
assert!(t.latest("MACRO").is_none());
|
||||
assert!(t.all("X").is_empty());
|
||||
assert!(table("").entries().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_define_with_no_name_is_skipped_rather_than_recorded() {
|
||||
// Malformed input must not produce a nameless entry, and must not fail:
|
||||
// an editor asks for hover text on buffers that are mid-edit.
|
||||
assert!(table("`define\n").entries().is_empty());
|
||||
assert!(table("`undef\n").entries().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unclosed_parameter_list_is_recorded_as_an_object_like_body() {
|
||||
let d = only("`define A(x, y\n");
|
||||
assert_eq!(d.name, "A");
|
||||
assert_eq!(d.params, None);
|
||||
assert_eq!(d.body, "(x, y");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_table_reads_the_formatter_fixtures_without_panicking() {
|
||||
// The repo's real Verilog lives next door; this is the closest thing to a
|
||||
// corpus this crate has. If the fixtures ever move, this test says so
|
||||
// rather than quietly passing on nothing.
|
||||
let dir =
|
||||
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../vlog_formatter/tests/fixtures");
|
||||
let entries = std::fs::read_dir(&dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
|
||||
let mut seen = 0;
|
||||
let mut defines = 0;
|
||||
for entry in entries {
|
||||
let path = entry.expect("dir entry").path();
|
||||
if !matches!(path.extension().and_then(|e| e.to_str()), Some("sv") | Some("v")) {
|
||||
continue;
|
||||
}
|
||||
let src = std::fs::read_to_string(&path).expect("read fixture");
|
||||
for d in table(&src).entries() {
|
||||
// Whatever was recorded must slice back to the source it came
|
||||
// from, in every file, not just the hand-written ones above.
|
||||
assert_eq!(&src[d.name_span.as_range()], d.name, "in {}", path.display());
|
||||
assert!(src[d.span.as_range()].starts_with('`'), "in {}", path.display());
|
||||
defines += 1;
|
||||
}
|
||||
seen += 1;
|
||||
}
|
||||
assert!(seen > 0, "no fixtures found in {}", dir.display());
|
||||
assert!(defines > 0, "fixtures have `defines; the check would be vacuous otherwise");
|
||||
}
|
||||
@@ -0,0 +1,513 @@
|
||||
# define-table
|
||||
|
||||
## Goal
|
||||
|
||||
Record every `` `define`` a file writes — name, parameter list, replacement
|
||||
text, and byte spans — so the LSP can answer "hover a macro usage, see its
|
||||
value" (TODO.md §6). This is a pure *data* feature: `collect_defines` reads an
|
||||
already-lexed token stream and returns a `DefineTable`. Nothing expands a
|
||||
macro, nothing formats differently, and the formatter never calls it — TODO.md
|
||||
§7's "no preprocessor expansion in the formatter" non-goal is untouched, which
|
||||
that section already anticipated ("recording definitions for hover display is
|
||||
bookkeeping, not expansion"). The table is also the substrate for the later
|
||||
single-step expansion display and for `` `WIDTH`` → "defined as 8 in
|
||||
defs.svh:12".
|
||||
|
||||
## Zero lexer changes, and why that worked
|
||||
|
||||
The task allowed touching `lexer.rs` if directive granularity made a post-lex
|
||||
pass impossible. It did not: the lexer already delivers a whole `` `define``,
|
||||
continuation lines included, as **one** `TokenKind::Directive` token
|
||||
(`lexer.rs`, the `` ` `` arm — it reads to end of line and keeps going while
|
||||
the line ends in `\`), and `docs/features/spans/README.md` already gives that
|
||||
token a `span` for which `source[span] == text` holds exactly. So everything
|
||||
this feature needs — the full directive text and the offset it starts at — is
|
||||
already on the token. `defines.rs` is a second read of the token vector and
|
||||
touches nothing else.
|
||||
|
||||
The one consequence worth naming: because the *lexer* decides where a
|
||||
directive ends, this module must agree with the lexer's rules rather than with
|
||||
the LRM's where they differ. Both places that matter are called out below
|
||||
(horizontal whitespace after a continuation backslash; `\\` at end of line).
|
||||
|
||||
## The body normalization rule (exact)
|
||||
|
||||
A `` `define``'s `body` is the directive text from the first byte after the
|
||||
name — or after the `)` closing a parameter list — to the end of the token,
|
||||
with this transformation and no other:
|
||||
|
||||
> **Every `\` that ends a line is deleted together with the horizontal
|
||||
> whitespace after it and the newline it ends. Every other byte survives
|
||||
> unchanged.** The result is then trimmed at both ends.
|
||||
|
||||
That is the LRM 22.5.1 reading ("the backslash-newline is not part of the
|
||||
macro text") applied literally. Consequences, all pinned by tests:
|
||||
|
||||
- **The body is one logical line.** It never contains a `\n`, and it never
|
||||
contains a continuation `\`.
|
||||
- **Indentation of a continued line survives into the body**, so a three-line
|
||||
body reads as `begin q <= d; end` — the joined-up pieces keep exactly
|
||||
the spaces that were written around the joins. This looks lossy for display,
|
||||
but it is the only choice that is *correct*: inside a string literal that
|
||||
whitespace is the value, not layout. `` `define MSG "line one \`` +
|
||||
` line two"` must normalize to `"line one line two"`, which is what a
|
||||
preprocessor produces, and what a hover must show. Collapsing the join to a
|
||||
single space would silently rewrite the string. (This is the same trap the
|
||||
formatter fell into once — see `docs/features/macro-items/README.md`, the
|
||||
masked-corruption round.)
|
||||
- **A consumer that wants the definition *as written* slices `span`.** The
|
||||
span still covers every physical line of the directive, so hover can show
|
||||
either the joined body or the original multi-line text. Because the joined
|
||||
form loses line structure, keeping the span the raw extent is what makes the
|
||||
choice the caller's.
|
||||
- **Horizontal whitespace between the `\` and the newline is part of the
|
||||
continuation.** The lexer tolerates `` `define A x \·· `` + newline
|
||||
(`text_ends_with_continuation` trims ` `/`\t`/`\r` before checking), so this
|
||||
module must too. If it did not, a stray backslash would survive into the
|
||||
body of a directive the lexer had already joined. Mutation-tested: removing
|
||||
the tolerance fails a test.
|
||||
- **`\\` at end of line continues the line, it is not an escaped backslash.**
|
||||
The lexer's rule is "does the trimmed line end in a backslash", and the join
|
||||
scans left to right, so the *second* backslash is consumed as the
|
||||
continuation and the first survives as text. The two agree by construction.
|
||||
A preprocessor runs before string lexing, so this is also the defensible
|
||||
reading.
|
||||
|
||||
Parameters get the same join, then a trim, and are stored **as written**:
|
||||
`` `define MAX(a, b = 8) `` gives `Some(["a", "b = 8"])`. Keeping the default
|
||||
in the string is what lets hover render the signature; a caller that wants
|
||||
only the name splits at the first `=`.
|
||||
|
||||
## API
|
||||
|
||||
```rust
|
||||
vlog_parser::defines::collect_defines(tokens: &[Token]) -> DefineTable
|
||||
|
||||
struct Define {
|
||||
kind: DefineKind, // Define | Undef
|
||||
name: String, // no backtick
|
||||
params: Option<Vec<String>>, // None = object-like; Some([]) = `NAME()`
|
||||
body: String, // joined, trimmed; empty for Undef
|
||||
span: TextRange, // the whole directive, all physical lines
|
||||
name_span: TextRange, // exactly the name
|
||||
}
|
||||
|
||||
impl DefineTable {
|
||||
fn entries(&self) -> &[Define]; // source order, `undef`s included
|
||||
fn all(&self, name: &str) -> Vec<&Define>; // every definition, in order
|
||||
fn latest(&self, name: &str) -> Option<&Define>;
|
||||
}
|
||||
```
|
||||
|
||||
Design notes:
|
||||
|
||||
- **Every definition is kept, not just the last.** Redefinition is legal and
|
||||
the corpus does it (`` `ifdef``-guarded pairs); a position-aware
|
||||
"which definition is in force at offset N" needs them all, and that is what
|
||||
hover will eventually want. `latest` is today's answer and is the last
|
||||
`Define` in the file, ignoring `` `undef``.
|
||||
- **`` `undef`` is an event in the same ordered list**, not a deletion. A
|
||||
future position-aware lookup walks `entries()` up to the cursor and honors
|
||||
the `` `undef``; nothing resolves it now, deliberately — `all`/`latest`
|
||||
report definitions and say nothing about whether one is still in force.
|
||||
- **`` `undefineall`` is not an `` `undef``.** The keyword is matched as a
|
||||
whole word, not a prefix.
|
||||
- **Lookup is a linear scan, not an index.** A file has a handful of defines
|
||||
and hover does one lookup per keystroke; a `HashMap` here would be a second
|
||||
copy of the same facts to keep in sync, for no measurable gain.
|
||||
- **`collect_defines` cannot fail.** A directive it cannot read a name out of
|
||||
is skipped. An editor asks for hover text on buffers that are mid-edit, so a
|
||||
`Result` here would only push the same "ignore it" decision onto the caller.
|
||||
- **Malformed input is recorded, not rejected.** An unclosed parameter list
|
||||
(`` `define A(x, y ``) is recorded as an object-like macro whose body is
|
||||
`(x, y`. That keeps the shape "what the source says", which is what an
|
||||
editor should show.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Conditional compilation is not evaluated.** A `` `define`` inside an
|
||||
`` `ifdef``/`` `else`` is recorded exactly like any other, so both arms of a
|
||||
conditional pair appear in the table. Evaluating conditions needs a
|
||||
preprocessor and a set of active defines, which vfmt deliberately does not
|
||||
have; the ordered list plus the `` `undef`` events is the raw material a
|
||||
future position-aware resolver would need.
|
||||
- **One file.** No `` `include`` following, no cross-file merge. That is the
|
||||
workspace index's job (TODO.md §6), and a `TextRange` has no file identity —
|
||||
the same assumption `docs/features/spans/README.md` records.
|
||||
- **A `` `define`` is what the lexer says it is.** Anything not lexed as a
|
||||
`TokenKind::Directive` is invisible here — which is exactly right for a
|
||||
`` `define`` written inside a comment or a string, and is why the table
|
||||
cannot be fooled by them.
|
||||
- **Macro names are plain identifiers.** A name is a run of
|
||||
`[A-Za-z0-9_$]`. An escaped identifier name (`` `define \odd$name 1 ``) is
|
||||
not recorded — the leading `\` is unreadable here without re-deciding what
|
||||
the lexer already decided about continuations, and no corpus file writes
|
||||
one. Skipping is safe (the entry is absent, never wrong).
|
||||
- **Known gap: a `//` comment on a *continuation* line rides along in the
|
||||
body.** The lexer stops a directive before a comment on its *first* line
|
||||
(so `` `define A 1 // c `` has body `1`), but the continuation loop does
|
||||
not, so `` `define A x \`` + ` y // note` has body `x y // note`. Per
|
||||
the LRM the comment is not macro text. Stripping it needs a string-aware
|
||||
scan (a `//` inside a string is not a comment) — the formatter has one, in
|
||||
`verify.rs`, but it is `pub(crate)` in the *other* crate. Deferred until a
|
||||
hover implementation shows it matters; it is a display wart, not a
|
||||
correctness risk, and nothing consumes the table yet.
|
||||
- **Known gap, pre-existing: a block comment truncates a directive.**
|
||||
`` `define A 1 /* c */ more `` lexes as a directive ending at `1`, with
|
||||
` more` continuing as ordinary tokens. That is the lexer's behavior since
|
||||
before this feature; the table reports what the token holds.
|
||||
- **Digit-leading names are not rejected** (QA find): `` `define 123abc x ``
|
||||
records name `123abc`. Nothing validates names as identifiers here — the
|
||||
table reports what was written; a future lint rule is the right place to
|
||||
complain. Documented so nobody mistakes acceptance for endorsement.
|
||||
- **Known gap (QA find): a continuation backslash before a *blank final
|
||||
line* leaves a literal `\` in the body.** The lexer's `trim_end()` on the
|
||||
token text strips the newline that closed the continuation, re-exposing
|
||||
the backslash before this module sees it. `source[span] == text` still
|
||||
holds; nothing expands macros, so it's a display wart of the same family
|
||||
as the continuation-line comment above.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser::lexer` / `token`:** nothing new.
|
||||
`TokenKind::Directive` tokens with their `text` and `span`, exactly as they
|
||||
are. Two lexer behaviors are relied on and would break this module if they
|
||||
changed, so they are stated here rather than left implicit:
|
||||
|
||||
1. **`source[tok.span] == tok.text` for a `Directive`.** This is what makes
|
||||
`name_span` derivable by offset arithmetic inside the text rather than by
|
||||
re-scanning the source. Guaranteed by `span_of_trimmed` and asserted by
|
||||
`crates/vlog_parser/tests/spans.rs`.
|
||||
2. **A continued `` `define`` is one token**, and the continuation rule is
|
||||
"the trimmed line ends in `\`". `defines.rs::continuation_len` mirrors it,
|
||||
trailing-whitespace tolerance included.
|
||||
|
||||
**Promised to future consumers (`vfmt_server`, `vlog_semantic`):** the API
|
||||
above. Nothing depends on it yet, so it is free to change; the two things
|
||||
worth not changing casually are the body normalization rule (a hover string is
|
||||
user-visible) and "all definitions are kept".
|
||||
|
||||
**Requested of nobody.** No other module needs a change. In particular
|
||||
`parser.rs`, `format.rs` and `verify.rs` are untouched — CLAUDE.md hard
|
||||
invariant #4 does not apply to this round, because the safety net's
|
||||
forgiveness was neither widened nor narrowed. `ItemKind::Directive` still
|
||||
carries the same `RawText` it did, and the formatter still passes
|
||||
`` `define`` through verbatim.
|
||||
|
||||
**Recursion/chain budgets (`docs/features/recursion-limit/README.md`):**
|
||||
nothing is charged and nothing is needed. Every scan in this module is a flat
|
||||
`while` over bytes with an explicit index; there is no recursion, no `Box`,
|
||||
and no AST node. The parameter-list scan tracks nesting with one `usize` that
|
||||
`saturating_sub`s, so unbalanced brackets terminate rather than underflow.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `src/defines.rs`: `collect_defines`, `Define`, `DefineKind`,
|
||||
`DefineTable` (`entries`/`all`/`latest`). ~250 lines, no dependencies.
|
||||
- [x] One-line wiring in `lib.rs` (`pub mod defines;`). No re-export, so the
|
||||
crate's public surface grows by one module and nothing else.
|
||||
- [x] Body normalization: backslash-newline (plus horizontal whitespace
|
||||
between them) deleted, everything else byte-for-byte.
|
||||
- [x] Function-like macros: `(` must touch the name; defaults, nested
|
||||
parens/brackets/braces and strings in a default handled; `NAME()` is
|
||||
zero parameters.
|
||||
- [x] `` `undef`` recorded as an ordered event; `` `undefineall`` excluded.
|
||||
- [x] Spans: `span` = the whole directive, `name_span` = exactly the name,
|
||||
both slicing back to the source (tested, multi-byte included).
|
||||
- [x] `tests/defines.rs`: 24 tests — the eleven the task listed plus
|
||||
commas/brackets/strings in a default, `NAME()`, space-before-paren,
|
||||
CRLF-safe multi-byte spans, trailing comment, `` `undefineall``,
|
||||
no-name, unclosed parameter list, `` `define`` inside a module.
|
||||
- [x] Two mutation tests run against the normalization rule (below).
|
||||
- [x] TODO.md §6 checkbox.
|
||||
- [ ] **Not done, deliberately:** position-aware `in_force_at(offset, name)`
|
||||
resolving `` `undef``s and `` `ifdef``s. The data is all recorded; the
|
||||
resolution rule is a hover-design question (does hover show the
|
||||
definition in force at the cursor, or all of them?) and building it now
|
||||
would be building for a consumer that does not exist.
|
||||
- [ ] **Not done:** stripping a `//` comment from a continuation line (see
|
||||
Assumptions), and cross-file `` `include`` following (workspace index).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-19 — dev agent
|
||||
|
||||
- Read `CLAUDE.md`, `README.md`, TODO.md §6/§7, and the Handshakes of
|
||||
`spans` and `macro-items` before writing anything. Baseline for the two
|
||||
files I own: `cargo test -p vlog_parser` **80 passed** (49 unit + 19 spans +
|
||||
12 error_recovery), clippy silent, fmt clean.
|
||||
- **Confirmed the post-lex pass was possible before designing around it.**
|
||||
Read the `` ` `` arm of `lexer.rs` first: a `` `define`` with three
|
||||
continuation lines is one `Directive` token whose text is the whole thing,
|
||||
and `spans` already guarantees `source[span] == text` for it. So the
|
||||
"document why you had to touch the lexer" branch never opened — the lexer is
|
||||
byte-identical, and this feature is a second read of the token vector.
|
||||
- **The body normalization was the only real decision.** Three candidates:
|
||||
(a) delete the backslash-newline and nothing else, (b) replace each join
|
||||
with a single space, (c) keep the line structure (join → `\n`) for prettier
|
||||
hover. Went with (a), which is the LRM's own wording, because it is the only
|
||||
one that is *correct for strings*: a body may carry a string across a line
|
||||
and the continued line's indentation is then part of the value. (b) and (c)
|
||||
both rewrite that value. The cost — a multi-line body displays as one long
|
||||
line — is paid back by `span`, which still covers the original text, so a
|
||||
hover that wants the pretty form slices the source. This is the same lesson
|
||||
`macro-items` learned the expensive way, applied up front.
|
||||
- **Made the module agree with the lexer, not with the LRM, in two places**,
|
||||
because disagreement is what produces garbage: horizontal whitespace between
|
||||
the `\` and the newline is part of the continuation (the lexer's
|
||||
`text_ends_with_continuation` trims before checking), and `\\` at end of
|
||||
line continues the line rather than being an escaped backslash. Both are
|
||||
written down under "The body normalization rule" and both have a test.
|
||||
- **Mutation-tested the rule rather than trusting a green first run**
|
||||
(all 24 tests passed on the first execution, which is a reason for
|
||||
suspicion, not comfort):
|
||||
1. Removed the horizontal-whitespace tolerance from `continuation_len` →
|
||||
`a_continuation_may_have_trailing_spaces_after_the_backslash` fails with
|
||||
the raw `x \\ \n y` leaking through. Detected.
|
||||
2. Changed the join to emit a single space and swallow the continued line's
|
||||
indent — i.e. shipped candidate (b) above → three tests fail, including
|
||||
`a_string_continued_across_lines_keeps_its_inner_whitespace`, which is
|
||||
exactly the corruption the rule exists to prevent. Detected.
|
||||
Both reverted; `defines.rs` is byte-identical to the pre-mutation file.
|
||||
- **Probed the shapes the tests do not assert**, to write the Assumptions
|
||||
section from observed behavior rather than from guessing: a `//` comment on
|
||||
a continuation line (rides along — recorded as a known gap), a block comment
|
||||
mid-directive (truncates the token — pre-existing, recorded), CRLF (works,
|
||||
spans correct), an escaped-identifier name (not recorded — recorded as an
|
||||
assumption), multi-byte UTF-8 in a body (spans stay byte-exact),
|
||||
`` `define A(a,b) `B(a) ## b `` (body kept verbatim, `##` untouched).
|
||||
- **Kept the lookup a linear scan.** An index was the obvious "real" answer
|
||||
and is the wrong one here: two representations of the same list, for a
|
||||
lookup that runs once per hover over a handful of entries.
|
||||
- Did not touch `parser.rs`, `lexer.rs`, `format.rs`, `verify.rs`, any
|
||||
existing test file, `tools/` or `corpus/` — the concurrent agent's files
|
||||
are untouched by this diff. Did not run `git commit`/`git push`.
|
||||
|
||||
**Results:** `cargo test -p vlog_parser` **104 passed, 0 failed** (49 unit +
|
||||
24 `tests/defines.rs` + 19 `tests/spans.rs` + 12 `tests/error_recovery.rs`) —
|
||||
up from 80, and no existing test changed. `cargo clippy -p vlog_parser
|
||||
--all-targets` reports **0 warnings in this feature's files**; the single
|
||||
warning the crate emits at the end of this round
|
||||
(`clippy::large_enum_variant` on `GenElse`, `ast.rs:434`) comes from the
|
||||
concurrent agent's in-flight `ast.rs`/`parser.rs` edits, not from here —
|
||||
`ast.rs` shows as modified in `git status` and this diff does not touch it.
|
||||
`cargo fmt --all --check` clean. Files
|
||||
touched: `crates/vlog_parser/src/defines.rs` (new),
|
||||
`crates/vlog_parser/src/lib.rs` (one line),
|
||||
`crates/vlog_parser/tests/defines.rs` (new), `TODO.md` (§6 checkbox), this
|
||||
README. The rest of the workspace was churning under a concurrent agent
|
||||
(`parser.rs`, token/lexer trivia, `vlog_formatter`) and was not run to a
|
||||
conclusion by me; nothing in this diff can affect it, since no existing file's
|
||||
behavior changed.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-19 — QA agent
|
||||
|
||||
**Scope note:** a concurrent dev agent was actively editing
|
||||
`crates/vlog_parser/src/{ast.rs,parser.rs}` and `vlog_formatter` throughout
|
||||
this pass. All gates below were scoped to the `defines` feature; a full
|
||||
`-p vlog_parser` run is reported where it succeeded, and one transient
|
||||
compile break in `tests/spans.rs` (type mismatch, `ast::Expr` vs.
|
||||
`ast::ExprItem`) hit mid-pass and is attributed to that concurrent edit, not
|
||||
to this feature — `crates/vlog_parser/src/defines.rs`,
|
||||
`crates/vlog_parser/tests/defines.rs`, and `lib.rs` were not touched.
|
||||
|
||||
**1. API/scope claim — PASS.** `git diff crates/vlog_parser/src/lib.rs` is
|
||||
exactly `+pub mod defines;` (+1 line, confirmed twice). `git status --short`
|
||||
shows this feature's only changes are `crates/vlog_parser/src/defines.rs`
|
||||
(new), `crates/vlog_parser/tests/defines.rs` (new),
|
||||
`docs/features/define-table/` (new) and the `TODO.md` §6 checkbox (10
|
||||
insertions, all one honest paragraph describing what was built — verified by
|
||||
reading the diff). `crates/vlog_parser/src/lexer.rs`,
|
||||
`crates/vlog_parser/src/token.rs`, `crates/vlog_formatter/src/verify.rs`,
|
||||
`crates/vlog_formatter/tests/verification.rs` are untouched by this diff
|
||||
(not even in `git status`) — CLAUDE.md invariant #4 does not apply, correctly,
|
||||
as the README says. `crates/vlog_parser/src/ast.rs`,
|
||||
`crates/vlog_parser/src/parser.rs`, `crates/vlog_formatter/src/format.rs` are
|
||||
modified but that's the *other* agent's in-flight work (confirmed by reading
|
||||
their diffs — no mention of `defines`). API shape (`Define`/`DefineKind`/
|
||||
`DefineTable`, `entries`/`all`/`latest`) matches the README exactly, read
|
||||
directly from `defines.rs`.
|
||||
|
||||
**2/3. Body normalization + span/lexer agreement — PASS.** Ran all 24
|
||||
`tests/defines.rs` tests: **24 passed, 0 failed.** Also ran
|
||||
`cargo test -p vlog_parser` in full before the workspace churn hit:
|
||||
**104 passed, 0 failed** (49 unit + 24 defines + 19 spans + 12
|
||||
error_recovery), matching the work log's own count exactly. Read
|
||||
`lexer.rs`'s directive arm (`` ` `` handling, lines ~178–229) and
|
||||
`text_ends_with_continuation` (line 475) directly: confirmed
|
||||
`` `\r` `` is trimmed as trailing horizontal whitespace before the
|
||||
continuation check on *both* sides (lexer and `defines.rs::continuation_len`
|
||||
independently implement the same trim set: space/tab/CR), so the two
|
||||
cannot disagree on CRLF — verified empirically too (below). `PRIM_STRINGIFY`
|
||||
+ `MSG "line one \...line two"` style cases match the LRM-literal join rule
|
||||
as documented.
|
||||
|
||||
**Attack probes** (temporary test file, deleted after the run — not left in
|
||||
the tree): every case below went through the *real* `tokenize()`, not
|
||||
hand-built tokens.
|
||||
|
||||
| input shape | result | verdict |
|
||||
|---|---|---|
|
||||
| `` `define`` no name, no newline | 0 entries | OK, no panic |
|
||||
| `` `define\n`` no name | 0 entries | OK |
|
||||
| `` `define 123abc x`` (digit-leading name) | recorded as name `"123abc"` | accepted — see finding QA-1 |
|
||||
| `` `define module 1`` (keyword as name) | recorded as name `"module"` | OK — Verilog preprocessor doesn't type-check names |
|
||||
| `` `define A(x,\n y) x+y`` (newline inside param list, no `\`) | directive ends at line 1 (`` `define A(x,``), body `"(x,"` | OK, matches lexer's real line-ending rule + documented unclosed-list fallback |
|
||||
| `` `define A(x = f(b,c)) x`` | `params = Some(["x = f(b,c)"])`, body `"x"` | OK, nested parens in default handled |
|
||||
| `` `define A \\\n\n`` (continuation into an *empty* final line) | body `"\\"` (one literal backslash survives) | **finding QA-2, see below** |
|
||||
| `` `define A x \`` at EOF, no trailing newline | body `"x \\"` | OK — nothing to continue into, backslash correctly kept literal |
|
||||
| `` `undef X garbage here`` | recorded, `name="X"`, trailing junk silently ignored (not part of `Undef`'s empty body) | OK |
|
||||
| `` `define A 1\n`define B 2\n`` | two entries, correct spans, no bleed | OK |
|
||||
| CRLF continuation (`` `define A x \\\r\n y\r\n``) | body `"x y"` | OK, matches LF case exactly |
|
||||
| tab between `\` and newline | body `"x y"` | OK |
|
||||
| `//` comment on the continuation's last line | body `"x y // trailing"` | OK, matches documented known gap |
|
||||
| body containing literal `` `undef`` text | one `Define` entry, body carries the literal text, no phantom second entry | OK |
|
||||
| re-indented multi-line define (`name_span` offset arithmetic) | `name_span` and `span` both slice back exactly | OK, offset arithmetic survives re-indentation |
|
||||
|
||||
No panics in any of the 15 probes.
|
||||
|
||||
**Finding QA-1 (informational, not blocking).** `defines.rs::read_name`
|
||||
accepts a digit-leading run as a macro name (`` `define 123abc x`` → name
|
||||
`"123abc"`). The README's Assumptions section says "a name is a run of
|
||||
`[A-Za-z0-9_$]`" but doesn't call out that it doesn't enforce
|
||||
identifier-start rules (no leading digit). Harmless in practice — no real
|
||||
Verilog writes this, `collect_defines` cannot fail either way, and a
|
||||
consumer can validate `name` itself if it cares — but the Assumptions
|
||||
section could say so explicitly for a future reader who wonders whether it
|
||||
was deliberate. Not fixed by QA (adding it to Assumptions is a wording
|
||||
call for the dev agent, not a code bug).
|
||||
|
||||
**Finding QA-2 (should-look-into, not blocking).** A `` `define`` whose
|
||||
continuation backslash is immediately followed by a *blank* final physical
|
||||
line (`` `define A \`` then an empty line) produces a token whose raw text,
|
||||
after the lexer's `.trim_end()`, ends in a bare literal `\` with no
|
||||
following newline — because `trim_end()` strips the `\n` that closed the
|
||||
real continuation, re-exposing the backslash underneath it.
|
||||
`defines.rs::continuation_len` then correctly (per its own contract: a `\`
|
||||
needs a *following* `\n` in the token text to count) treats that exposed
|
||||
backslash as ordinary text rather than a continuation, so it survives into
|
||||
`body` as a literal character. Traced to `lexer.rs` — `text_ends_with_continuation`
|
||||
trims trailing space/tab/CR only, not `\n`, so it correctly returns `false`
|
||||
once the token has absorbed the first continuation's `\n` and hit the
|
||||
second (empty) line's own `\n`; the token's raw text is
|
||||
`` "`define A \\\n" `` at that point, and `.trim_end()` afterward is what
|
||||
strips the `\n` back off, re-exposing the backslash. This is a lexer
|
||||
property, not something `defines.rs` introduces, and it's the same
|
||||
category as the two gaps already documented (comment-on-continuation-line,
|
||||
block-comment-truncates-directive) — `source[span] == text` still holds
|
||||
exactly (verified), nothing panics, and nothing consumes the table for
|
||||
expansion yet, so it isn't corruption. Recommend the dev agent add it as a
|
||||
third documented "known gap" under Assumptions; did not fix it myself since
|
||||
it's a genuine judgment call whether the right fix lives in the lexer's
|
||||
`trim_end` or in `defines.rs` reading the raw untrimmed span.
|
||||
|
||||
**4. Test count / mutation — PASS.** 24/24 green, no existing test file
|
||||
touched (confirmed via `git status` — `tests/defines.rs` is `??`, i.e. new,
|
||||
not modified). Work log's two mutation runs (removing the CR/tab
|
||||
tolerance; collapsing the join to a single space) are described with the
|
||||
specific tests that catch each — read and judged sound; did not
|
||||
re-execute the mutations myself since the work log already shows the
|
||||
before/after and the specific failing assertions match the normalization
|
||||
rule being tested (`a_continuation_may_have_trailing_spaces_after_the_backslash`,
|
||||
`a_string_continued_across_lines_keeps_its_inner_whitespace`).
|
||||
|
||||
**5. Redefinition/undef ordering — PASS.** `a_redefinition_keeps_every_definition_and_latest_wins`
|
||||
and `an_undef_is_recorded_as_an_event_and_is_not_a_definition` both green;
|
||||
independently re-verified with `` `define X` `/` `undef X` `/` `define X` ``
|
||||
via the corpus/attack harness: `entries().len() == 3`, `all("X").len() == 2`
|
||||
(the two `Define`s only), `latest("X")` returns the *last* `Define`'s body,
|
||||
ignoring the `` `undef`` in between — matches the README's stated design
|
||||
("`undef` is an event, not a deletion").
|
||||
|
||||
**Corpus sweep — PASS.** Built a temporary harness (deleted after the run)
|
||||
walking every `.sv`/`.v`/`.svh`/`.vh` file under `corpus/` through the real
|
||||
`tokenize()` → `collect_defines()`. Result: **860 files, 857 tokenized
|
||||
successfully, 502 `` `define``/`` `undef`` entries recorded, 0 panics, 0
|
||||
span/name_span mismatches** (every entry's `name_span` sliced back to
|
||||
exactly its `name`, every `span` sliced back to text starting with `` ` ``,
|
||||
across all 502). The 3 tokenize failures are pre-existing, unrelated lexer
|
||||
limitations (`riscv_core_setting.tpl.sv`, `core_ibex_tb_top.sv`,
|
||||
`core_ibex_base_test.sv` — all "expected digits after number base", a
|
||||
numeric-literal lexing gap, nothing to do with directives).
|
||||
|
||||
Hand-checked 8 real entries from `corpus/ibex/vendor/lowrisc_ip/ip/prim/rtl/prim_assert.sv`
|
||||
against the source directly:
|
||||
- `` `define ASSERT_DEFAULT_CLK clk_i`` → name `ASSERT_DEFAULT_CLK`, body
|
||||
`"clk_i"` — exact match.
|
||||
- `` `define ASSERT_DEFAULT_RST !rst_ni`` → body `"!rst_ni"` — exact match.
|
||||
- `` `define PRIM_STRINGIFY(__x) `"__x`"`` → params `["__x"]`, body
|
||||
`` "`\"__x`\"" `` — exact match, backtick-quote pairs preserved literally.
|
||||
- `` `define ASSERT_ERROR(__name)`` (5-line continuation, nested
|
||||
`` `ifdef UVM``/`` `else``/`` `endif`` inside the body) → params
|
||||
`["__name"]`, body opens with `` "`ifdef UVM ... uvm_pkg::uvm_report_error(...` `` —
|
||||
correct: an `` `ifdef`` *inside* a `` `define``'s continuation is body
|
||||
text, not a separate directive, per LRM 22.5.1, and the table treats it
|
||||
that way because the lexer already lexed the whole thing as one token.
|
||||
- `` `define ASSERT_STATIC_LINT_ERROR(__name, __prop)`` (4-line
|
||||
continuation) → body reads as the four lines joined with the exact
|
||||
interior whitespace from the source — exact match by eye.
|
||||
No wrong name or wrong body found in the spot check.
|
||||
|
||||
**6. CLAUDE.md compliance — PASS.** Every `pub` item in `defines.rs` (2
|
||||
enums/structs, 6 fields, 3 inherent methods, 1 free function) has a
|
||||
preceding doc comment — read the whole file, confirmed line by line.
|
||||
`grep -n "unwrap()\|expect(\|panic!" crates/vlog_parser/src/defines.rs` →
|
||||
no matches. `git diff crates/vlog_parser/Cargo.toml` → empty, no new
|
||||
dependency. `cargo fmt --all --check` clean for this feature's files.
|
||||
`cargo clippy -p vlog_parser --lib` → 1 warning total in the whole crate
|
||||
(`clippy::large_enum_variant` on `ast.rs:434`, `GenElse`) — attributed to
|
||||
the concurrent agent's in-flight `ast.rs` (confirmed: `ast.rs` shows
|
||||
modified in `git status`, `defines.rs` doesn't touch `ast.rs` or `GenElse`
|
||||
at all). README has all seven required sections (Goal, Assumptions,
|
||||
Handshakes, Status/TODO, Work log, QA log, Review) present and non-empty
|
||||
except Review (correctly reserved for the lead). TODO.md §6 checkbox is
|
||||
honest — read the diff, the added paragraph accurately describes what
|
||||
exists (`collect_defines`, the API shape, the normalization rule, the two
|
||||
documented gaps), makes no claim beyond what was built.
|
||||
|
||||
### Summary
|
||||
|
||||
No BLOCKING findings (no panic, no wrong name/body/span for a well-formed
|
||||
`` `define``, no corruption — this module doesn't touch formatter output at
|
||||
all). Two non-blocking findings, both informational/should-look-into:
|
||||
QA-1 (digit-leading names accepted, undocumented but harmless) and QA-2 (a
|
||||
continuation into a blank final line loses its backslash-erasure because of
|
||||
`lexer.rs`'s `.trim_end()`, undocumented third "known gap", not corruption
|
||||
since nothing expands macros yet). All 24 `defines.rs` tests green, 104/104
|
||||
crate-wide before the concurrent churn, 860-file/502-define corpus sweep
|
||||
clean, spot check of 5+ real macros correct by hand.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted and committed; no code changes
|
||||
needed, two QA findings recorded as Assumptions above.**
|
||||
|
||||
Exactly what a data-layer feature should look like: zero changes to any
|
||||
existing behavior (one `pub mod` line is the entire footprint outside
|
||||
the new files), the "documented impossibility" escape hatch never
|
||||
needed, and the hard design question — body normalization — answered by
|
||||
reading the LRM literally and *mutation-testing the rule* against the
|
||||
prettier alternatives that would have rewritten string values. The two
|
||||
places the module follows the lexer over the LRM (whitespace between
|
||||
`\` and newline; `\\` at line end) are the right call: a table that
|
||||
disagrees with the lexer that produced its input is worse than either
|
||||
convention alone.
|
||||
|
||||
Storing all definitions plus `` `undef`` events, rather than resolving
|
||||
to one winner, is the correct shape for the future position-aware
|
||||
hover (`latest-before-position` needs the history; collapsing it now
|
||||
would be premature resolution). QA's corpus sweep — 502 entries, five
|
||||
prim_assert.sv macros hand-checked, zero span mismatches, CRLF
|
||||
confirmed at both layers — is the acceptance evidence that matters.
|
||||
|
||||
Both QA findings (digit-leading names accepted; the blank-final-line
|
||||
backslash wart) are recorded as Assumptions rather than fixed: neither
|
||||
can corrupt anything (nothing expands macros), and both belong to
|
||||
their real owners — a future lint rule and the lexer's trim behavior
|
||||
respectively.
|
||||
|
||||
With this, TODO §6's data foundations are complete: spans,
|
||||
error-tolerant parsing, define table. Next: `vlog_semantic` + the
|
||||
workspace index, then `vfmt_server`.
|
||||
Reference in new issue
Block a user