//! The module, interface and program header, and the body constructs that //! belong only to them: parameter ports, ports (ANSI and non-ANSI), //! modports and clocking blocks. use super::split::UnitHead; use super::*; /// The three pieces a `#( parameter ... )` port list yields, so module and /// class headers can share one parse. #[derive(Default)] pub(super) struct ParamPortList { /// `None` when no `#( ... )` was written at all. pub(super) ports: Option>>, pub(super) directives: Vec, pub(super) dangling: Vec, /// Comments written between the `#` and the `(`. pub(super) after_hash: Vec, } impl<'a> Parser<'a> { /// A `module` / `macromodule` / `interface` declaration. The three share /// one header grammar (IEEE 1800 §23.2.1, §25.3) and one body item list — /// only the closing keyword differs, so `end_kw` is the whole difference. pub(super) fn parse_module(&mut self, end_kw: &str) -> PResult { let conds = self.open_conds; let kw = self.bump().text; let before_name = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; let mut imports = Vec::new(); while self.cur().is_kw("import") { let mut meta = self.take_meta(); let paths = self.parse_import_list()?; meta.trailing = self.take_trailing(); imports.push(HeaderImport { meta, paths }); } let param_comments = self.take_before_open("#"); let mark = self.diags_mark(); let ParamPortList { ports: param_ports, directives: param_directives, dangling: param_dangling, after_hash: param_after_hash, } = self.parse_param_port_list()?; let port_comments = self.take_before_open("("); let (ports, port_dangling, port_directives) = self.parse_port_list()?; let before_semi = self.gap_before(";"); // A header that already reported something keeps its `;` optional: the // missing one is part of the typo already reported, and the body // behind it is what the module is for. self.expect_after_recovery(";", self.recovered_since(mark))?; let mut items = Vec::new(); let mut head = UnitHead { kw: &kw, name: &name, conds, floor: conds }; while !self.at_body_end(end_kw) { // Two rival headers written across the arms of one `ifdef region // are bracket-balanced, so nothing else in the grammar objects // until this unit runs out of file looking for its `end` keyword. // Failing here instead routes the whole unit into the split // recovery; see `docs/features/parser-skips/README.md`. if self.at_rival_header(&head) { return self.error(format!("rival header for `{name}` in a conditional region")); } items.push(self.item_or_recover()?); head.floor = head.floor.min(self.open_conds); } let dangling = self.take_dangling(); self.expect_closer(end_kw)?; let (end_label_comments, end_name) = self.parse_label_with()?; let (end_label, end_label_span) = split_label(end_name); Ok(Module { kw, before_name, name, param_after_hash, name_span, imports, param_comments, param_ports, param_directives, param_dangling, port_comments, ports, port_directives, port_dangling, before_semi, items, dangling, end_label_comments, end_label, end_label_span, }) } /// `modport a (input x, output y), b (...);` (IEEE 1800 §25.5). pub(super) fn parse_modport(&mut self) -> PResult> { self.expect_kw("modport")?; let mut out = Vec::new(); loop { let start = self.here(); let mut meta = self.take_meta(); let Name { text: name, span: name_span } = self.expect_name()?; self.expect_sym("(")?; let mut ports = Vec::new(); while !self.cur().is_sym(")") && !self.at_eof() { ports.push(self.parse_modport_port()?); if !ports.last().is_some_and(|p: &ModportPort| p.comma) { break; } } let dangling = self.take_dangling(); self.expect_sym(")")?; let span = self.span_from(start); if let Some(last) = ports.last_mut() { if last.meta.trailing.is_none() { last.meta.trailing = self.take_trailing(); } } self.take_before_sep(&mut meta, ","); let comma = self.eat_sym(","); meta.trailing = self.take_trailing(); out.push(ModportDecl { meta, name, name_span, ports, dangling, comma, span }); if !comma { break; } } self.expect_sym(";")?; Ok(out) } /// One direction group of a modport's port list. `input a, b, output c` is /// two groups: the comma keeps the group open only while a plain name /// follows it — a direction keyword starts the next group. /// /// An `import` or `export` may write a method prototype instead of a name /// (IEEE 1800 §25.5.4); that is a group of its own. fn parse_modport_port(&mut self) -> PResult { const MODPORT_KEYWORDS: &[&str] = &["input", "output", "inout", "ref", "import", "export", "clocking"]; let start = self.here(); let mut meta = self.take_meta(); let t = self.cur(); if t.kind != TokenKind::Keyword || !MODPORT_KEYWORDS.contains(&t.text.as_str()) { return self.error("expected a modport port direction"); } let kw = self.bump().text; let after_kw = self.take_gap(); if let Some(kind) = self.at_modport_prototype(&kw) { return self.parse_modport_prototype(meta, kw, after_kw, kind, start); } let mut names = vec![self.expect_name()?]; let mut span = self.span_from(start); let mut comma = false; loop { self.take_before_sep(&mut meta, ","); if !self.eat_sym(",") { break; } if self.cur().kind != TokenKind::Ident { // The comma separates this group from the next one. comma = true; break; } names.push(self.expect_name()?); span = self.span_from(start); } if meta.trailing.is_none() { meta.trailing = self.take_trailing(); } Ok(ModportPort { meta, kw, after_kw, names, prototype: None, comma, span }) } /// Which method prototype an `import`/`export` group is about to write, if /// it is writing one at all (IEEE 1800 §25.5.4). fn at_modport_prototype(&self, kw: &str) -> Option { if kw != "import" && kw != "export" { return None; } if self.cur().is_kw("task") { Some(TfKind::Task) } else if self.cur().is_kw("function") { Some(TfKind::Function) } else { None } } /// `import task drive(int x)` — one modport list element holding a whole /// subroutine header and nothing else. It ends where the modport list /// says: at the `,` that starts the next group or the `)` that closes the /// list, never at a `;`, because a prototype here has no body to open. fn parse_modport_prototype( &mut self, mut meta: Meta, kw: String, after_kw: Vec, kind: TfKind, start: u32, ) -> PResult { let prototype = self.parse_tf_header(kind, false)?; let span = self.span_from(start); self.take_before_sep(&mut meta, ","); let comma = self.eat_sym(","); if meta.trailing.is_none() { meta.trailing = self.take_trailing(); } Ok(ModportPort { meta, kw, after_kw, names: Vec::new(), prototype: Some(Box::new(prototype)), comma, span, }) } /// `clocking cb @(posedge clk); ... endclocking` (IEEE 1800 §14.3). The /// `default` keyword, when written, has already been consumed. pub(super) fn parse_clocking(&mut self, is_default: bool) -> PResult { self.expect_kw("clocking")?; let after_kw = self.take_gap(); let name = if self.cur().kind == TokenKind::Ident { Some(self.expect_name()?) } else { None }; let before_event = if self.cur().is_sym("@") { self.take_gap() } else { Vec::new() }; // `default clocking cb;` selects an existing block and has no body. let event = if self.eat_sym("@") { Some(self.parse_sens_list()?) } else { None }; let before_semi = self.gap_before(";"); self.expect_sym(";")?; if event.is_none() { return Ok(ClockingDecl { is_default, after_kw, name, before_event, before_semi, event, items: Vec::new(), dangling: Vec::new(), has_end: false, end_label_comments: Box::default(), end_label: None, end_label_span: None, }); } let mut items = Vec::new(); while !self.at_body_end("endclocking") { items.push(self.parse_clocking_item()?); } let dangling = self.take_dangling(); self.expect_closer("endclocking")?; let (end_label_comments, end_name) = self.parse_label_with()?; let (end_label, end_label_span) = split_label(end_name); Ok(ClockingDecl { is_default, after_kw, name, before_event, before_semi, event, items, dangling, end_label_comments, has_end: true, end_label, end_label_span, }) } /// One item of a clocking block's body: `default input #1step output #0;` /// or a direction group (`input #2 a, b;`). fn parse_clocking_item(&mut self) -> PResult { let start = self.here(); let mut meta = self.take_meta(); let kind = if self.eat_kw("default") { let input = self.parse_clocking_default("input")?; let output = self.parse_clocking_default("output")?; if input.is_none() && output.is_none() { return self.error("expected `input` or `output` after `default`"); } ClockingItemKind::Default { input, output } } else { let t = self.cur(); if !(t.is_kw("input") || t.is_kw("output") || t.is_kw("inout")) { return self.error("expected a clocking item"); } let dir = self.bump().text; let after_dir = self.take_gap(); let mut after_skew = Vec::new(); let skew = if self.at_clocking_skew() { let skew = self.parse_clocking_skew()?; after_skew = self.take_gap(); Some(skew) } else { None }; let mut signals = vec![self.parse_clocking_signal()?]; while self.eat_sym(",") { signals.push(self.parse_clocking_signal()?); } ClockingItemKind::Signals { dir, after_dir, skew, after_skew, signals } }; let span = self.span_from(start); let before_semi = self.gap_before(";"); self.expect_sym(";")?; if meta.trailing.is_none() { meta.trailing = self.take_trailing(); } Ok(ClockingItem { meta, kind, before_semi, span }) } /// One `signal [= expression]` of a clocking direction group — IEEE 1800 /// §14.4's `clocking_decl_assign`. The expression names what the clocking /// signal is really bound to (`output tms = _tms_internal;`), and it is an /// ordinary expression rather than a second grammar. fn parse_clocking_signal(&mut self) -> PResult { let name = self.expect_name()?; let value = if self.eat_sym("=") { Some(self.parse_expr()?) } else { None }; Ok(ClockingSignal { name, value }) } /// One half of a `default input #1step output #0;` item: the direction /// keyword `dir` and its skew, or `None` when this half was not written. /// /// The gap in front of the keyword is the half's own, so the two halves /// keep their own sides of the word that separates them. fn parse_clocking_default(&mut self, dir: &str) -> PResult> { if !self.cur().is_kw(dir) { return Ok(None); } let before_dir = self.take_gap(); self.bump(); let after_dir = self.take_gap(); Ok(Some(ClockingDefault { before_dir, after_dir, skew: self.parse_clocking_skew()? })) } /// True when the cursor is on a clocking skew rather than on the first /// signal name: `#2`, `#1step`, `posedge`, `negedge`, `edge`. fn at_clocking_skew(&self) -> bool { let t = self.cur(); t.is_sym("#") || t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") } /// A clocking skew, as written: `#2`, `#1step`, the parenthesized /// `#(1:2:3)`, an edge identifier, or — IEEE 1800 §14.3's first /// alternative — an edge identifier with a delay behind it /// (`negedge #(1:2:3)`). fn parse_clocking_skew(&mut self) -> PResult { if self.cur().is_sym("#") { return Ok(ClockingSkew::Delay(self.parse_clocking_delay()?)); } let t = self.cur(); if t.is_kw("posedge") || t.is_kw("negedge") || t.is_kw("edge") { let word = self.bump().text; // Only a gap that really is in front of a `#` is the edge's own; // otherwise it belongs to the caller's slot before the name. let after_edge = self.gap_before("#"); let delay = if self.cur().is_sym("#") { Some(self.parse_clocking_delay()?) } else { None }; return Ok(ClockingSkew::Edge { word, after_edge, delay }); } self.error("expected a clocking skew") } /// The `# …` half of a clocking skew. /// /// The one-token spellings are kept as text — a delay is never something /// lucisv re-lays out — so the printer writes back exactly what the source /// said. The parenthesized one goes through the delay-value grammar every /// other `#( … )` uses, which is what gives its `:` and its parens their /// comment slots. fn parse_clocking_delay(&mut self) -> PResult { self.expect_sym("#")?; let after_hash = self.take_gap(); if self.cur().is_sym("(") { return Ok(ClockingDelay::Paren { after_hash, expr: self.parse_delay_value()? }); } let t = self.cur(); if !matches!(t.kind, TokenKind::Number | TokenKind::Ident) { return self.error("expected a clocking skew delay"); } Ok(ClockingDelay::Word { after_hash, word: self.bump().text }) } /// A `#( parameter ... )` port list, shared by module and class headers. /// `ports` is `None` when no `#(` was written at the cursor at all. pub(super) fn parse_param_port_list(&mut self) -> PResult { let mut out = ParamPortList::default(); if !self.cur().is_sym("#") { return Ok(out); } self.bump(); out.after_hash = self.take_gap(); self.expect_sym("(")?; let mark = self.diags_mark(); let mut list = Vec::new(); self.take_list_directives(&mut out.directives, 0); if !self.cur().is_sym(")") { loop { let at = self.pos; list.push(self.element_or_recover(|p| p.parse_param_port())?); let recovered = list.last().is_some_and(ListElem::is_error); if let Some(ListElem::Ok(last)) = list.last_mut() { self.take_before_sep(&mut last.meta, ","); } let comma = self.eat_sym(","); if let Some(ListElem::Ok(last)) = list.last_mut() { last.comma = comma; if comma && last.meta.trailing.is_none() { last.meta.trailing = self.take_trailing(); } } let dirs = self.take_list_directives(&mut out.directives, list.len()); // Without a comma and without a directive the list is over. // With one, only the closing bracket says so: an `` `ifdef`` // arm may end without a comma and another arm may still follow // (`` `else``), or the arm may have been the tail of the list. // In tolerant mode the closing bracket decides on its own; see // [`Parser::list_ends`]. if self.list_ends(at, comma, dirs.any, recovered) { break; } } } out.dangling = self.take_dangling(); self.close_list(mark)?; out.ports = Some(list); Ok(out) } /// An optional `= value`, with the comments written on either side of the /// `=` (`W /*a*/ = /*b*/ 8`). The value is read by `parse`, since a /// `type` parameter's default is a type and everything else's is an /// expression. pub(super) fn parse_eq_default( &mut self, parse: fn(&mut Self) -> PResult, ) -> PResult<(Box, Option)> { if !self.cur().is_sym("=") { return Ok((Box::default(), None)); } let before = self.take_gap(); self.bump(); let after = self.take_gap(); let value = parse(self)?; Ok((Box::new(BinaryComments { before, after }), Some(value))) } fn parse_param_port(&mut self) -> PResult { let start = self.here(); let mut meta = self.take_meta(); let mut after_kw = Vec::new(); let kw = if self.cur().is_kw("parameter") || self.cur().is_kw("localparam") { let word = self.bump().text; after_kw = self.take_gap(); Some(word) } else { None }; if self.eat_kw("type") { let before_name = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; let (eq_comments, default) = self.parse_eq_default(|p| p.parse_type_expr())?; let span = self.span_from(start); meta.trailing = self.take_trailing(); return Ok(ParamPort { meta, kw, after_kw, ty: self.implicit_type(), is_type: true, before_name, name, name_span, unpacked: Vec::new(), eq_comments, default, comma: false, span, }); } let ty = self.parse_opt_data_type()?; let before_name = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; let unpacked = self.parse_dims()?; let (eq_comments, default) = self.parse_eq_default(|p| p.parse_expr())?; let span = self.span_from(start); meta.trailing = self.take_trailing(); Ok(ParamPort { meta, kw, after_kw, ty, is_type: false, before_name, name, name_span, unpacked, eq_comments, default, comma: false, span, }) } /// The header port list, the comments written before its closing `)`, and /// the directives written between its ports. fn parse_port_list(&mut self) -> PResult<(PortList, Vec, Vec)> { if !self.cur().is_sym("(") { return Ok((PortList::None, Vec::new(), Vec::new())); } self.bump(); let mark = self.diags_mark(); // Directives before the first port. Harvested here rather than in the // loop below because both the ANSI/non-ANSI decision and the // written-but-empty check read the token after them. let mut directives = Vec::new(); self.take_list_directives(&mut directives, 0); if self.cur().is_sym(")") { // `module m (/* c */);` — the comments stay between the parens. let dangling = self.take_dangling(); self.bump(); return Ok((PortList::Empty, dangling, directives)); } let ansi = { let t = self.cur(); t.is_kw("input") || t.is_kw("output") || t.is_kw("inout") || 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(); loop { let at = self.pos; ports.push(self.element_or_recover(|p| p.parse_ansi_port())?); let recovered = ports.last().is_some_and(ListElem::is_error); if let Some(ListElem::Ok(last)) = ports.last_mut() { self.take_before_sep(&mut last.meta, ","); } let comma = self.eat_sym(","); if let Some(ListElem::Ok(last)) = ports.last_mut() { last.comma = comma; if comma && last.meta.trailing.is_none() { last.meta.trailing = self.take_trailing(); } } let dirs = self.take_list_directives(&mut directives, ports.len()); if self.list_ends(at, comma, dirs.any, recovered) { break; } } // Comments on their own lines before the `)` belong inside it. let dangling = self.take_dangling(); self.close_list(mark)?; // A trailing comment on the closing line belongs to the last // port — but only when the header did not write a `;` right // after the `)`. `module m (input a) /*c*/ ;` writes its comment // in the *header's* gap, and printing it back inside the parens // moves it across the `)`. if !self.cur().is_sym(";") { if let Some(ListElem::Ok(last)) = ports.last_mut() { if last.meta.trailing.is_none() { last.meta.trailing = self.take_trailing(); } } } Ok((PortList::Ansi(ports), dangling, directives)) } else { let mut ports = Vec::new(); loop { let at = self.pos; ports.push(self.element_or_recover(|p| p.parse_non_ansi_port())?); let recovered = ports.last().is_some_and(ListElem::is_error); let comma = match ports.last() { Some(ListElem::Ok(last)) => last.comma, // A non-ANSI port reads its own separator, so an error // element — which never got that far — leaves the `,` for // the list to take. Leaving it under the cursor was the // 2026-09-03 runaway: see the work log. _ => self.eat_sym(","), }; let dirs = self.take_list_directives(&mut directives, ports.len()); if self.list_ends(at, comma, dirs.any, recovered) { break; } } let dangling = self.take_dangling(); self.close_list(mark)?; Ok((PortList::NonAnsi(ports), dangling, directives)) } } /// One name of a non-ANSI header's port list (`module m (a, b);`), /// its separator included: the port *is* its name, so there is nothing /// else to read and the `,` is what says whether another follows. fn parse_non_ansi_port(&mut self) -> PResult { let start = self.here(); let mut meta = self.take_meta(); let name = self.expect_ident()?; let span = self.span_from(start); self.take_before_sep(&mut meta, ","); let comma = self.eat_sym(","); meta.trailing = self.take_trailing(); Ok(NonAnsiPort { meta, name, comma, span }) } fn parse_ansi_port(&mut self) -> PResult { let start = self.here(); let mut meta = self.take_meta(); let dir = { let t = self.cur(); if t.is_kw("input") || t.is_kw("output") || t.is_kw("inout") || t.is_kw("ref") { Some(self.bump().text) } else { None } }; let after_dir = if dir.is_some() { self.take_gap() } else { Vec::new() }; let net = { let t = self.cur(); let is_net = t.kind == TokenKind::Keyword && NET_KEYWORDS.contains(&t.text.as_str()); if is_net || t.is_kw("var") { Some(self.bump().text) } else { None } }; let ty = if self.at_modport_port() { self.parse_modport_port_type()? } else { self.parse_opt_data_type()? }; let before_name = self.take_gap(); let Name { text: name, span: name_span } = self.expect_name()?; let unpacked = self.parse_dims()?; let (eq_comments, default) = self.parse_eq_default(|p| p.parse_expr())?; let span = self.span_from(start); meta.trailing = self.take_trailing(); Ok(AnsiPort { meta, dir, after_dir, net, ty, before_name, name, name_span, unpacked, eq_comments, 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`. pub(super) 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 a type name still sees one string; /// [`DataType::segments`] splits it back into its two halves and their /// ranges. pub(super) fn parse_modport_port_type(&mut self) -> PResult { let name_start = self.here(); let mut name = self.expect_ident()?; self.expect_sym(".")?; name.push('.'); name.push_str(&self.expect_ident()?); Ok(DataType { name, name_start, ..DataType::default() }) } }