Files
lucisv/crates/lucisv_server/src/expand.rs
T
Guoliang ChenandClaude Mythos 5.2 71d13b5fbe
ci / checks (push) Successful in 1m0s
ci / corpus (push) Successful in 18s
ci / linux (push) Successful in 6m4s
release / build-and-publish (push) Successful in 5m31s
Release 0.66.2: every source file names its author
Every tracked file that can carry a comment (880 of them) now opens with
"Author: Guoliang Chen, a Senior Digital Design Engineer" and closes with
"Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love,
luciochen.com", in the file's own comment syntax. No behaviour change: the
diff outside the version bump and changelogs is comment lines only.

- tools/stamp_author.py: writes the lines; idempotent, `--check` lists
  what is missing. Headers go under a shebang and under Markdown front
  matter.
- Left alone: test fixtures, cases and snapshots (byte-exact inputs), JSON
  and JSONL, logs, images, lockfiles, docs/site/dist (regenerated) and the
  LICENSE files (already carry the copyright line).
- tools/linux_check.sh: --help reads its header from line 3, now that the
  author line sits under the shebang.
- tools/gates.sh green on this tree: 5 545 tests, corpus 814/6 as before.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
2026-11-24 12:11:09 -08:00

437 lines
16 KiB
Rust

// Author: Guoliang Chen, a Senior Digital Design Engineer
//! Single-step macro expansion, for hover **display** only.
//!
//! One step means one thing: the definition's body with the call site's
//! arguments substituted for the parameters. A nested `` `INNER`` inside the
//! body stays exactly as written — expanding it too would be preprocessing,
//! and TODO.md §7 says lucisv does not preprocess. So this module is the same
//! kind of bookkeeping `vlog_parser::defines` is: it never touches the
//! formatter, never rewrites the buffer, and its only consumer is the hover
//! card. See `docs/features/macro-expansion/README.md` for the full rule
//! table and the non-goals.
use vlog_parser::defines::Define;
/// How many characters of expansion a hover card shows before it stops.
pub const CAP: usize = 2000;
/// A macro use expanded one step.
pub struct Expansion {
/// The expansion text: at most [`CAP`] characters, plus an ellipsis when
/// it was cut.
pub text: String,
/// Whether the body was longer than [`CAP`] and had to be cut.
pub truncated: bool,
}
/// Expand one macro use against the definition a hover card is already
/// showing, or `None` when there is nothing worth showing.
///
/// `call` is the whole macro-use token — `` `NAME`` or `` `NAME(a, b)`` — as
/// the lexer kept it. `None` covers every case where an expansion would be a
/// guess or a duplicate: an argument count that does not match the parameter
/// list, a function-like macro used without one, a parameter that is not an
/// identifier, and an object-like macro whose body holds no further macro use
/// (its expansion *is* the body the card already prints).
pub fn single_step(call: &str, define: &Define) -> Option<Expansion> {
let text = match &define.params {
None => object_like(&define.body)?,
Some(params) => substituted(&define.body, params, &split_arguments(call)?)?,
};
Some(capped(text))
}
/// Whether `text` still contains a macro use — a `` ` `` starting a name, and
/// not the second backtick of a ```` `` ```` paste.
///
/// The hover card asks so it can say that one step stopped there.
pub fn has_macro_use(text: &str) -> bool {
let b = text.as_bytes();
(0..b.len()).any(|i| {
b[i] == b'`'
&& (i == 0 || b[i - 1] != b'`')
&& b.get(i + 1).is_some_and(|c| is_name_byte(*c))
})
}
/// An object-like macro expands to its body, which is worth a section of its
/// own only when the body holds another macro use — otherwise it is the text
/// the card already shows one paragraph higher.
fn object_like(body: &str) -> Option<String> {
if has_macro_use(body) {
Some(body.to_string())
} else {
None
}
}
/// The body with each parameter replaced by the argument written at the call
/// site, or `None` when the two lists do not line up.
fn substituted(body: &str, params: &[String], args: &[String]) -> Option<String> {
if params.len() != args.len() {
return None;
}
let mut values: Vec<(&str, &str)> = Vec::with_capacity(params.len());
for (param, arg) in params.iter().zip(args) {
let (name, default) = split_parameter(param)?;
// An argument written empty asks for the default the parameter
// declares (LRM 22.5.1); with no default it really is empty text.
values.push((name, if arg.is_empty() { default } else { arg }));
}
Some(replace_names(body, &values))
}
/// A parameter as the define table stores it (`"a"`, `"b = 8"`) split into its
/// name and its default. `None` when the name is not a plain identifier, which
/// is the one shape substitution could not do anything sensible with.
fn split_parameter(param: &str) -> Option<(&str, &str)> {
let (name, default) = match param.split_once('=') {
Some((name, default)) => (name.trim(), default.trim()),
None => (param.trim(), ""),
};
if name.is_empty() || !name.bytes().all(is_name_byte) {
return None;
}
Some((name, default))
}
/// Walk the body once, replacing whole names that are parameters.
///
/// Four things are copied through untouched rather than looked inside, and
/// each is a deliberate rule (see the feature README): a string literal, a
/// nested macro use `` `INNER`` (one step leaves the name as written), the
/// `` `"`` and ```` `` ```` escapes, and an escaped identifier `\name`. After
/// a ```` `` ```` paste the text is ordinary again, so `` a``b`` substitutes
/// both halves.
fn replace_names(body: &str, values: &[(&str, &str)]) -> String {
let b = body.as_bytes();
let mut out = String::with_capacity(body.len());
let mut copied = 0;
let mut i = 0;
while i < b.len() {
match b[i] {
b'"' => i = end_of_string(b, i),
b'`' => i = end_of_backtick_escape(b, i),
b'\\' => i = end_of_escaped_identifier(b, i),
c if is_name_byte(c) => {
let end = end_of_name(b, i);
if let Some((_, value)) =
values.iter().find(|(name, _)| body.get(i..end) == Some(name))
{
out.push_str(body.get(copied..i).unwrap_or(""));
out.push_str(value);
copied = end;
}
i = end;
}
_ => i += 1,
}
}
out.push_str(body.get(copied..).unwrap_or(""));
out
}
/// Split a macro call's `(...)` on its top-level commas, or `None` when the
/// call carries no argument list at all.
///
/// The conventions are `vlog_parser::defines::read_params`' own, so a
/// parameter list and an argument list are counted the same way: nesting is
/// tracked through `()`, `[]` and `{}`, a string is opaque, and `` `NAME()``
/// is zero arguments rather than one empty one. Comments are skipped so a
/// comma or a bracket inside one cannot split an argument.
fn split_arguments(call: &str) -> Option<Vec<String>> {
let open = call.find('(')?;
let b = call.as_bytes();
let mut depth = 0usize;
let mut piece_start = open + 1;
let mut args: Vec<String> = Vec::new();
let mut i = open;
while i < b.len() {
match b[i] {
b'"' => {
i = end_of_string(b, i);
continue;
}
b'/' if b.get(i + 1) == Some(&b'/') => {
i = end_of_line_comment(b, i);
continue;
}
b'/' if b.get(i + 1) == Some(&b'*') => {
i = end_of_block_comment(b, i);
continue;
}
b'(' | b'[' | b'{' => depth += 1,
b')' | b']' | b'}' => {
depth = depth.saturating_sub(1);
if depth == 0 {
let piece = call.get(piece_start..i)?.trim();
if !(args.is_empty() && piece.is_empty()) {
args.push(piece.to_string());
}
return Some(args);
}
}
b',' if depth == 1 => {
args.push(call.get(piece_start..i)?.trim().to_string());
piece_start = i + 1;
}
_ => {}
}
i += 1;
}
None
}
/// Cut an expansion down to [`CAP`] characters. A hover card that fills the
/// screen is worse than one that says it stopped.
fn capped(text: String) -> Expansion {
match text.char_indices().nth(CAP) {
None => Expansion { text, truncated: false },
Some((cut, _)) => {
let mut text = text.get(..cut).unwrap_or_default().to_string();
text.push_str(" …");
Expansion { text, truncated: true }
}
}
}
/// Just past the string literal starting at `start`, or the end of the text.
fn end_of_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()
}
/// Just past a `` ` ``-introduced run that substitution must not look inside:
/// a nested macro name, or the `` `"``/```` `` ```` escapes (whose *following*
/// text is ordinary again, so only the escape itself is skipped).
fn end_of_backtick_escape(b: &[u8], start: usize) -> usize {
let mut i = start + 1;
if matches!(b.get(i), Some(b'`' | b'"' | b'\\')) {
return i + 1;
}
while matches!(b.get(i), Some(&c) if is_name_byte(c)) {
i += 1;
}
i
}
/// Just past an escaped identifier `\name`, which ends at whitespace
/// (LRM 5.6.1). Its letters are not a name substitution may touch.
fn end_of_escaped_identifier(b: &[u8], start: usize) -> usize {
let mut i = start + 1;
while matches!(b.get(i), Some(&c) if !c.is_ascii_whitespace()) {
i += 1;
}
i
}
fn end_of_line_comment(b: &[u8], start: usize) -> usize {
let mut i = start + 2;
while i < b.len() && b[i] != b'\n' {
i += 1;
}
i
}
fn end_of_block_comment(b: &[u8], start: usize) -> usize {
let mut i = start + 2;
while i < b.len() {
if b[i] == b'*' && b.get(i + 1) == Some(&b'/') {
return i + 2;
}
i += 1;
}
b.len()
}
fn end_of_name(b: &[u8], start: usize) -> usize {
let mut i = start;
while matches!(b.get(i), Some(&c) if is_name_byte(c)) {
i += 1;
}
i
}
fn is_name_byte(c: u8) -> bool {
c == b'_' || c == b'$' || c.is_ascii_alphanumeric()
}
#[cfg(test)]
mod tests {
use super::*;
use vlog_parser::defines::collect_defines;
use vlog_parser::tokenize;
/// The single definition `text` writes, read the way the server reads it.
fn define(text: &str) -> Define {
let tokens = tokenize(text).expect("lexes");
let table = collect_defines(&tokens);
table.entries().first().expect("one define").clone()
}
fn expand(text: &str, call: &str) -> Option<String> {
single_step(call, &define(text)).map(|e| e.text)
}
#[test]
fn a_parameter_is_replaced_by_the_argument_at_the_call_site() {
assert_eq!(
expand("`define MAX(a, b) ((a) > (b) ? (a) : (b))\n", "`MAX(x, y+1)"),
Some("((x) > (y+1) ? (x) : (y+1))".to_string())
);
}
#[test]
fn a_parameter_that_the_body_never_uses_is_simply_dropped() {
assert_eq!(expand("`define FIRST(a, b) a\n", "`FIRST(1, 2)"), Some("1".to_string()));
}
#[test]
fn a_name_that_only_contains_a_parameter_is_not_a_parameter() {
// `ab` and `a_b` both hold an `a`; only the whole name substitutes.
assert_eq!(
expand("`define M(a) ab + a_b + a\n", "`M(z)"),
Some("ab + a_b + z".to_string())
);
}
#[test]
fn an_argument_may_hold_commas_inside_nested_brackets_and_strings() {
assert_eq!(
expand("`define SHOW(a, b) $display(a, b)\n", "`SHOW(\"x, y\", f(1, {2, 3}))"),
Some("$display(\"x, y\", f(1, {2, 3}))".to_string())
);
}
#[test]
fn too_few_or_too_many_arguments_expand_to_nothing() {
assert_eq!(expand("`define M(a, b) a + b\n", "`M(1)"), None);
assert_eq!(expand("`define M(a, b) a + b\n", "`M(1, 2, 3)"), None);
}
#[test]
fn a_function_like_macro_used_without_an_argument_list_expands_to_nothing() {
assert_eq!(expand("`define M(a) a\n", "`M"), None);
}
#[test]
fn a_nested_macro_name_is_left_as_written() {
// The one rule that makes this "single step": `INNER is not expanded,
// and its name is not mistaken for a parameter either.
assert_eq!(
expand("`define OUTER(x) `INNER(x) + x\n", "`OUTER(7)"),
Some("`INNER(7) + 7".to_string())
);
assert_eq!(expand("`define OUTER(x) `x\n", "`OUTER(7)"), Some("`x".to_string()));
}
#[test]
fn the_backtick_quote_escape_passes_through_and_still_substitutes() {
assert_eq!(
expand("`define STR(x) `\"x`\"\n", "`STR(hello)"),
Some("`\"hello`\"".to_string())
);
}
#[test]
fn a_token_paste_pastes_both_halves() {
assert_eq!(expand("`define CAT(a, b) a``b\n", "`CAT(u, v)"), Some("u``v".to_string()));
}
#[test]
fn a_plain_string_in_the_body_is_not_substituted_into() {
assert_eq!(
expand("`define M(x) $display(\"x is %d\", x)\n", "`M(7)"),
Some("$display(\"x is %d\", 7)".to_string())
);
}
#[test]
fn an_escaped_identifier_in_the_body_is_not_substituted_into() {
assert_eq!(expand("`define M(x) \\x + x\n", "`M(7)"), Some("\\x + 7".to_string()));
}
#[test]
fn an_empty_argument_takes_the_parameters_default() {
assert_eq!(expand("`define M(a = 8) a\n", "`M()"), None, "zero arguments, one parameter");
assert_eq!(expand("`define M(a, b = 8) a + b\n", "`M(1, )"), Some("1 + 8".to_string()));
assert_eq!(expand("`define M(a, b) a + b\n", "`M(1, )"), Some("1 + ".to_string()));
}
#[test]
fn an_object_like_macro_expands_only_when_its_body_holds_a_macro_use() {
assert_eq!(expand("`define W 8\n", "`W"), None);
assert_eq!(expand("`define W `BASE + 1\n", "`W"), Some("`BASE + 1".to_string()));
}
#[test]
fn a_long_expansion_is_cut_at_the_cap() {
let body = "z".repeat(CAP + 50);
let expansion =
single_step("`M(1)", &define(&format!("`define M(a) {body}\n"))).expect("expansion");
assert!(expansion.truncated);
assert_eq!(expansion.text.chars().count(), CAP + 2, "the cap plus ` …`");
assert!(expansion.text.ends_with(" …"));
}
#[test]
fn an_expansion_at_the_cap_is_not_cut() {
let body = "z".repeat(CAP);
let expansion =
single_step("`M(1)", &define(&format!("`define M(a) {body}\n"))).expect("expansion");
assert!(!expansion.truncated);
assert_eq!(expansion.text, body);
}
#[test]
fn a_multi_byte_body_survives_substitution_and_truncation() {
assert_eq!(
expand("`define M(x) \"λ\" + x\n", "`M(1)"),
Some("\"λ\" + 1".to_string()),
"no byte slicing through a multi-byte character"
);
let body = "λ".repeat(CAP + 10);
let expansion =
single_step("`M(1)", &define(&format!("`define M(a) {body}\n"))).expect("expansion");
assert!(expansion.truncated && expansion.text.chars().count() == CAP + 2);
}
#[test]
fn a_real_corpus_macro_expands_the_way_the_rules_say() {
// `prim_assert.sv`'s `ASSERT_ERROR`, trimmed to two of its continued
// lines: an `` `ifdef`` inside the body (body text, per the LRM),
// three nested macro uses, and the parameter used twice.
let source = "\
`define ASSERT_ERROR(__name) \\
`ifdef UVM \\
uvm_pkg::uvm_report_error(\"FAILED\", `PRIM_STRINGIFY(__name), \\
`__FILE__, __name); \\
`endif
";
let expansion = expand(source, "`ASSERT_ERROR(MyCheck)").expect("expansion");
assert!(expansion.contains("`PRIM_STRINGIFY(MyCheck)"), "got {expansion}");
assert!(expansion.contains("`__FILE__, MyCheck);"), "used twice: got {expansion}");
assert!(expansion.starts_with("`ifdef UVM"), "the `ifdef is body text: got {expansion}");
assert!(!expansion.contains("__name"), "every occurrence replaced: got {expansion}");
assert!(has_macro_use(&expansion), "three names survive one step");
}
#[test]
fn has_macro_use_ignores_a_token_paste_and_a_backtick_quote() {
assert!(!has_macro_use("a``b"));
assert!(!has_macro_use("`\"x`\""));
assert!(has_macro_use("`INNER"));
assert!(!has_macro_use("plain text"));
}
}
// Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com