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");
|
||||
}
|
||||
Reference in new issue
Block a user