// Author: Guoliang Chen, a Senior Digital Design Engineer //! 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_formal_list_split_over_lines_records_the_same_parameters_as_one_line() { // TODO.md §22: a `define whose *formal argument list* spans a line break // with no backslash. The table must not be able to tell the two spellings // apart — see `docs/features/fragment-mode/README.md`. let two = only("`define A(x,\n y = 3,\n z) body_here\n"); let one = only("`define A(x, y = 3, z) body_here\n"); assert_eq!(two.params, one.params); assert_eq!(two.params, Some(vec!["x".to_string(), "y = 3".to_string(), "z".to_string()])); assert_eq!(two.body, one.body); assert_eq!(two.body, "body_here"); } #[test] fn the_opentitan_tl_errors_macro_reads_exactly_as_written() { // The first 25 lines of opentitan's // `hw/dv/sv/cip_lib/seq_lib/cip_base_vseq__tl_errors.svh`, copied here so // the pin does not depend on a checkout: the formal list runs from line 8 // to line 10 with no backslash, and the body continues with them. let src = "`define create_tl_access_error_case(task_name_, with_c_,\n\ \x20 seq_t_ = tl_host_custom_seq #(cip_tl_seq_item),\n\ \x20 seqr_t) \\\n\ \x20 begin \\\n\ \x20 seq_t_ tl_seq; \\\n\ \x20 end\n"; let d = only(src); assert_eq!(d.name, "create_tl_access_error_case"); assert_eq!( d.params, Some(vec![ "task_name_".to_string(), "with_c_".to_string(), "seq_t_ = tl_host_custom_seq #(cip_tl_seq_item)".to_string(), "seqr_t".to_string(), ]) ); assert!(d.body.starts_with("begin"), "the body starts after the `)`: {:?}", d.body); assert!(!d.body.contains('\\'), "no backslash survives the join"); 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!["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!["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"); } // Author: Guoliang Chen. Lucisv is made by Guoliang Chen with love, luciochen.com