vlog_parser: a direction-less first ANSI port parses

IEEE 1800 §23.2.2.2 allows an ANSI header's first port to carry no
direction — the normal spelling for interface ports — but
parse_port_list classified any leading identifier as a non-ANSI list
and errored on what followed. One clause fixes it: a leading Ident is
ANSI when the parser's existing type-then-name lookahead
(at_typed_declarator, which already walks pkg:: chains, #() overrides
and packed dims) or the new 4-token modport lookahead (ident.ident
ident) says so; the complement is exactly the old non-ANSI list, and
macro-led lists never enter the clause. bus_if.mp was a second,
independent gap (it parsed in no position before) and is glued into
DataType::name the way pkg::t already was. No AST change — the new
ports are AnsiPort { dir: None }, the shape later ports always had.
Two match-widenings ride along: bind_data_type and type_def's
type_span read the pre-dot half as the type, and the modport half is
bindable by nothing — pinned for rename by QA.

The safety case, established twice (dev, then QA independently via a
worktree build): corpus 813/820 both sides, TSVs byte-identical, and
all 820 formatted outputs SHA-256-identical across the change; zero
snapshot churn; verify.rs untouched. QA's boundary AST-diff harness
(~20 shapes at the classification edge) and a 50-file
direction-stripping fuzz sweep found no misfire. The
previously-blocked fixtures flipped to first-port order; instantiate
now plans interface-typed port lists instead of refusing. The two
remaining unsupported shapes (generic interface ports, virtual
modport declarations) are pinned by a lead-added test so a future
round changes them on purpose.

24 tests added (dev 21 + QA 2 + lead 1).

docs/features/ansi-first-port/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-08-26 20:49:16 -07:00
1 parent 662e323802
commit 839a28ec8d
10 files changed
+851 -31

No files matched your search

+199 -1
View File
@@ -2412,6 +2412,16 @@ impl<'a> Parser<'a> {
|| t.is_kw("ref")
|| TYPE_KEYWORDS.contains(&t.text.as_str())
|| NET_KEYWORDS.contains(&t.text.as_str())
// A direction is optional on the *first* ANSI port too (IEEE
// 1800 §23.2.2.2), and an interface port is normally written
// with none at all: `module m (bus_if bus, input logic clk);`.
// Such a port opens with a plain identifier, exactly as a
// non-ANSI name list does, so the two are told apart by what
// follows it — a second identifier (past any `pkg::` chain,
// `#( ... )` override or packed dimensions) means a type and a
// name, while the `,` or `)` of `module m (a, b);` does not.
|| (t.kind == TokenKind::Ident
&& (self.at_typed_declarator() || self.at_modport_port()))
};
if ansi {
let mut ports = Vec::new();
@@ -2484,7 +2494,11 @@ impl<'a> Parser<'a> {
None
}
};
let ty = self.parse_opt_data_type()?;
let ty = if self.at_modport_port() {
self.parse_modport_port_type()?
} else {
self.parse_opt_data_type()?
};
let Name { text: name, span: name_span } = self.expect_name()?;
let unpacked = self.parse_dims()?;
let default = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None };
@@ -2493,6 +2507,28 @@ impl<'a> Parser<'a> {
Ok(AnsiPort { meta, dir, net, ty, name, name_span, unpacked, default, comma: false, span })
}
/// Does the cursor sit on an interface port that names a modport,
/// `bus_if.mp bus` (IEEE 1800 §25.4)? Only a *port header* is spelled this
/// way — after an identifier anywhere else a `.` opens a member access —
/// so the shape is recognized here rather than in `parse_opt_data_type`.
fn at_modport_port(&self) -> bool {
self.cur().kind == TokenKind::Ident
&& self.nth(1).is_sym(".")
&& self.nth(2).kind == TokenKind::Ident
&& self.nth(3).kind == TokenKind::Ident
}
/// The `bus_if.mp` of an interface port, as its type. The modport is glued
/// onto the interface name exactly as a `pkg::` qualifier is, so every
/// consumer that prints or scans a type name still sees one string.
fn parse_modport_port_type(&mut self) -> PResult<DataType> {
let mut name = self.expect_ident()?;
self.expect_sym(".")?;
name.push('.');
name.push_str(&self.expect_ident()?);
Ok(DataType { name, ..DataType::default() })
}
/// Parse a possibly-implicit data type. Stops before the declarator name.
fn parse_opt_data_type(&mut self) -> PResult<DataType> {
let mut ty = DataType::default();
@@ -5738,6 +5774,168 @@ mod tests {
assert_eq!(ports.iter().map(|p| p.comma).collect::<Vec<_>>(), vec![true, false]);
}
// ------------------------------------------------------------------
// A direction-less first ANSI port (IEEE 1800 §23.2.2.2)
// `docs/features/ansi-first-port/README.md`
// ------------------------------------------------------------------
/// The `(dir, type, name)` of every port of an ANSI header.
fn ansi_ports(src: &str) -> Vec<(String, String, String)> {
let file = parse_ok(src);
let m = module_of(&file);
let PortList::Ansi(ports) = &m.ports else { panic!("expected ANSI ports in {src:?}") };
ports
.iter()
.map(|p| (p.dir.clone().unwrap_or_default(), p.ty.name.clone(), p.name.clone()))
.collect()
}
fn cell(dir: &str, ty: &str, name: &str) -> (String, String, String) {
(dir.to_string(), ty.to_string(), name.to_string())
}
#[test]
fn an_interface_typed_first_port_needs_no_direction() {
assert_eq!(
ansi_ports("module m (bus_if bus, input logic clk);\nendmodule\n"),
[cell("", "bus_if", "bus"), cell("input", "logic", "clk")]
);
assert_eq!(
ansi_ports("module m (bus_if bus);\nendmodule\n"),
[cell("", "bus_if", "bus")],
"alone in the list"
);
assert_eq!(
ansi_ports("interface i (bus_if bus);\nendinterface\n"),
[cell("", "bus_if", "bus")],
"an interface header is the same node and the same list"
);
}
#[test]
fn a_modport_qualified_port_keeps_the_modport_in_its_type() {
// IEEE 1800 §25.4. The modport is glued onto the interface name, the
// way a `pkg::` qualifier already is, so nothing downstream needs a
// second field to print or scan.
assert_eq!(
ansi_ports("module m (bus_if.mp bus);\nendmodule\n"),
[cell("", "bus_if.mp", "bus")]
);
assert_eq!(
ansi_ports("module m (input logic clk, bus_if.mp bus);\nendmodule\n"),
[cell("input", "logic", "clk"), cell("", "bus_if.mp", "bus")],
"later in the list too, which never parsed either"
);
}
#[test]
fn a_package_scoped_first_port_is_a_type_and_a_name() {
assert_eq!(
ansi_ports("module m (my_pkg::state_t s);\nendmodule\n"),
[cell("", "my_pkg::state_t", "s")]
);
assert_eq!(
ansi_ports("module m (my_pkg::state_t s, output logic q);\nendmodule\n"),
[cell("", "my_pkg::state_t", "s"), cell("output", "logic", "q")]
);
}
#[test]
fn a_direction_less_first_port_mixes_with_directed_ones_in_both_orders() {
assert_eq!(
ansi_ports("module m (state_t s, input a, output logic q);\nendmodule\n"),
[cell("", "state_t", "s"), cell("input", "", "a"), cell("output", "logic", "q")]
);
assert_eq!(
ansi_ports("module m (input a, state_t s);\nendmodule\n"),
[cell("input", "", "a"), cell("", "state_t", "s")],
"the ordering that always parsed is unchanged"
);
}
#[test]
fn a_typed_first_port_carries_its_dimensions_like_any_other() {
assert_eq!(
ansi_ports("module m (word_t [3:0] d, input a);\nendmodule\n"),
[cell("", "word_t", "d"), cell("input", "", "a")],
"packed dimensions sit between the type and the name"
);
assert_eq!(
ansi_ports("module m (item #(A, B) req);\nendmodule\n"),
[cell("", "item", "req")],
"a parameterized type, whose `#( ... )` is kept in the type"
);
}
#[test]
fn a_name_only_port_list_is_still_non_ansi() {
// The disambiguation must not eat the non-ANSI list: what follows the
// first identifier is a `,` or a `)`, not a second name.
let file = parse_ok("module m (a, b, c);\ninput a;\ninput b;\noutput c;\nendmodule\n");
let m = module_of(&file);
let PortList::NonAnsi(ports) = &m.ports else { panic!("expected a non-ANSI port list") };
assert_eq!(ports.iter().map(|p| p.name.as_str()).collect::<Vec<_>>(), vec!["a", "b", "c"]);
assert_eq!(ports.iter().map(|p| p.comma).collect::<Vec<_>>(), vec![true, true, false]);
let file = parse_ok("module m (a);\ninput a;\nendmodule\n");
let PortList::NonAnsi(ports) = &module_of(&file).ports else { panic!("non-ANSI") };
assert_eq!(ports.len(), 1, "a one-name list has no comma to look past either");
}
#[test]
fn the_other_port_list_spellings_are_untouched() {
let file = parse_ok("module m ();\nendmodule\n");
assert!(matches!(module_of(&file).ports, PortList::Empty), "empty parens");
let file = parse_ok("module m;\nendmodule\n");
assert!(matches!(module_of(&file).ports, PortList::None), "no list at all");
assert_eq!(
ansi_ports("module m (input a, b);\nendmodule\n"),
[cell("input", "", "a"), cell("", "", "b")],
"a continuation port still inherits its direction from the one before"
);
}
#[test]
fn what_is_not_a_bare_identifier_classifies_exactly_as_it_did() {
// The clause only fires on a `TokenKind::Ident`, so a macro-produced
// list (a `Directive` token) and an escaped name are read the way
// they always were, and a comment between the name and its comma is
// trivia that the lookahead never sees.
for src in [
"module m (`PORT_LIST);\nendmodule\n",
"module m (\\esc_name , b);\nendmodule\n",
"module m (a /* why */, b);\nendmodule\n",
] {
let file = parse_ok(src);
assert!(
matches!(module_of(&file).ports, PortList::NonAnsi(_)),
"still a non-ANSI list: {src:?}"
);
}
}
#[test]
fn a_broken_header_still_reports_its_own_token() {
// Recovery is unchanged: neither new shape swallows a genuinely
// broken list, and the diagnostic still names what blocked it.
assert!(parse_err("module m (bus_if bus;\nendmodule\n").contains("expected `)`"));
assert!(parse_err("module m (a[3], b);\nendmodule\n").contains("expected `)`"));
let (file, diags) = crate::parse_source_tolerant("module m (bus_if bus\nendmodule\n");
assert!(!diags.is_empty(), "a header that never closes is still an error");
assert!(!file.items.is_empty(), "and the file is still addressable");
}
#[test]
fn the_two_shapes_left_open_by_ansi_first_port_still_refuse() {
// Pinned so a future round that changes either does it on purpose
// (docs/features/ansi-first-port/README.md, Status): the generic
// `interface` port is a different production wanting a "any
// interface" DataType, and a modport-qualified *declaration* type
// would change how a `.` after an identifier reads everywhere.
assert!(parse_err("module m (interface bus);\nendmodule\n").contains("expected"));
assert!(parse_err("module m;\n virtual bus_if.mp v;\nendmodule\n").contains("expected"));
}
#[test]
fn both_arms_of_an_else_are_ordinary_elements_of_one_list() {
// lucisv does not evaluate the condition: an `ifdef/`else pair simply