Files
lucisv/crates/vlog_parser/src/token.rs
T
lucioandClaude Fable 5 29096cbbac Vendor and formal collateral: specify, UDPs, checkers, configs, interface classes, alias, union tagged - proven output-neutral
TODO section 23, coverage_gaps M1-M3 with the evidence corrected: every
construct here has zero declarations in the corpus and in opentitan (the
analysis's '13 checker files' were UVM protocol-checker filenames), so
this is a completeness round for vendored cell/IO/memory models and
formal collateral, and the formatted output of all 860 corpus and all
3975 opentitan files is byte-identical to v0.29.0.

Five keywords reserved on a measured zero-collision census (checker,
endchecker, config, endconfig, library); five deliberately not - expect
has 41 real task-call sites, so the statement form is recognised only
when its parentheses hold a sequence operator. One parse_opaque_block
(counts its own opener, keeps the label, leaves a trailing ';' as the
null item empty-item sees) serves specify, primitive with table,
checker and config; library lines parse; specparam is a real
declaration with a rewind for PATHPULSE$; alias a = b = c binds every
term; union tagged formats; interface class routes through the class
prefix with no new kind and no FACTS bump - deliberately, so it cannot
collide with the parallel lane's bump - and implements now contributes
type-hierarchy supertypes. pairs.rs pairs table, checker and config.

docs/features/vendor-formal-grammar/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-09-02 08:33:30 -07:00

362 lines
9.6 KiB
Rust

//! Token definitions for the Verilog/SystemVerilog lexer.
use crate::span::TextRange;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TokenKind {
/// Identifier, including escaped identifiers (`\foo`).
Ident,
/// System identifier such as `$display`.
SystemIdent,
/// Reserved keyword (the text field holds which one).
Keyword,
/// Any numeric literal, including sized/based literals (`8'hFF`) and time
/// literals (`10ns`). The text is normalized to contain no whitespace.
Number,
/// String literal, including the surrounding quotes.
String,
/// Compiler directive: from a backtick to the end of the (possibly
/// continued) line, e.g. `` `timescale 1ns / 1ps `` or `` `ifdef FOO ``.
Directive,
/// Attribute instance `(* ... *)`, stored verbatim.
Attribute,
/// Operator or punctuation.
Symbol,
/// End of file.
Eof,
}
/// A comment that has been detached from the token stream.
#[derive(Debug, Clone)]
pub struct Comment {
/// Full text including the `//` or `/* */` markers. Never contains a
/// trailing newline.
pub text: String,
/// True if at least one blank line separated this comment from whatever
/// preceded it.
pub blank_before: bool,
/// 1-based source line of the opening `//` or `/*`.
pub line: u32,
/// 1-based source column of the opening `//` or `/*`. The formatter
/// dedents the continuation lines of a multi-line comment by this much
/// before re-indenting them, which is what keeps re-formatting a fixed
/// point.
pub col: u32,
/// Byte extent in the source text, markers included. Trivia spans live
/// here rather than on AST nodes: a node's span is its code extent, and
/// the comments attached to it are outside that.
pub span: TextRange,
}
#[derive(Debug, Clone)]
pub struct Token {
pub kind: TokenKind,
pub text: String,
/// 1-based source line of the first character.
pub line: u32,
/// 1-based source column of the first character.
pub col: u32,
/// Byte extent in the source text. `source[span] == text` for every kind
/// except [`TokenKind::Number`], whose text drops the whitespace a sized
/// literal may write around its tick (`8 'hFF` → `8'hFF`).
pub span: TextRange,
/// Comments that appeared before this token (on their own lines, or on
/// earlier lines).
pub leading: Vec<Comment>,
/// A comment that appeared after this token on the same source line.
/// Several such comments are merged into one, joined by a space.
pub trailing: Option<Comment>,
/// True if at least one blank line separated this token from the previous
/// token or comment.
pub blank_before: bool,
}
impl Token {
pub fn is_kw(&self, kw: &str) -> bool {
self.kind == TokenKind::Keyword && self.text == kw
}
pub fn is_sym(&self, sym: &str) -> bool {
self.kind == TokenKind::Symbol && self.text == sym
}
/// True for a macro usage token: a backtick name that is not one of the
/// line-oriented compiler directives (those lex as [`TokenKind::Directive`]).
/// The text is the whole invocation, argument list included.
pub fn is_macro(&self) -> bool {
self.kind == TokenKind::Ident && self.text.starts_with('`')
}
/// True if this macro usage carries an argument list: `` `NAME(...) ``.
pub fn has_macro_args(&self) -> bool {
self.is_macro() && self.text.contains('(')
}
/// True for a based number whose digits are missing because a macro
/// supplies them: the `32'h` of `` 32'h`DM_ADDR ``. The lexer emits one
/// only when the very next source character is the backtick, so the
/// macro token always follows immediately.
pub fn is_base_only_number(&self) -> bool {
if self.kind != TokenKind::Number {
return false;
}
let Some((_, tail)) = self.text.rsplit_once('\'') else {
return false;
};
// The optional sign marker (`32'sh`) sits between the tick and base.
let base = tail.strip_prefix(['s', 'S']).unwrap_or(tail);
base.len() == 1
&& matches!(base.as_bytes()[0], b'd' | b'D' | b'b' | b'B' | b'o' | b'O' | b'h' | b'H')
}
}
/// Every reserved word the lexer knows, in the order they are written
/// below. Verilog-2001 plus the SystemVerilog subset the parser understands;
/// words not listed here lex as plain identifiers.
///
/// [`is_keyword`] and this slice are generated from the same list, so a word
/// can never be one without being the other — which is what lets a completion
/// list offer exactly what the lexer reserves.
macro_rules! keywords {
($($word:literal),* $(,)?) => {
pub const KEYWORDS: &[&str] = &[$($word),*];
/// Whether `s` is one of [`KEYWORDS`].
pub fn is_keyword(s: &str) -> bool {
matches!(s, $($word)|*)
}
};
}
keywords![
"module",
"macromodule",
"endmodule",
"interface",
"endinterface",
"package",
"endpackage",
"program",
"endprogram",
"modport",
"clocking",
"endclocking",
"input",
"output",
"inout",
"ref",
"wire",
"tri",
"tri0",
"tri1",
"wand",
"wor",
"trireg",
"supply0",
"supply1",
"uwire",
"reg",
"logic",
"bit",
"byte",
"shortint",
"int",
"longint",
"integer",
"time",
"realtime",
"real",
"shortreal",
"string",
"chandle",
"event",
"var",
"void",
"signed",
"unsigned",
"packed",
"parameter",
"localparam",
"defparam",
"specparam",
"type",
"typedef",
"enum",
"struct",
"union",
"assign",
"alias",
"always",
"always_comb",
"always_ff",
"always_latch",
"initial",
"final",
"begin",
"end",
"if",
"else",
"case",
"casex",
"casez",
// `randcase` is reserved (IEEE 1800 Table B.1) and opens a
// statement of its own; `let` is reserved too and opens an item.
// Both are here rather than matched by text so a declaration can
// never accidentally be named after one.
"randcase",
"let",
"endcase",
"default",
"unique",
"unique0",
"priority",
"for",
"while",
"repeat",
"forever",
"do",
"foreach",
"break",
"continue",
"return",
"fork",
"join",
"join_any",
"join_none",
"disable",
"wait",
"posedge",
"negedge",
"edge",
"or",
"and",
"nand",
"nor",
"xor",
"xnor",
"not",
"buf",
"bufif0",
"bufif1",
"notif0",
"notif1",
"pullup",
"pulldown",
"generate",
"endgenerate",
"genvar",
// Class-related reserved words. `new`, `this`, `super` and `null`
// are deliberately *not* here: they stand in expression position
// and already parse as ordinary names, so promoting them to
// keywords would break `x = new(...)` and `super.f()` for nothing.
"class",
"endclass",
"extends",
"implements",
"virtual",
"pure",
"extern",
"rand",
"randc",
"local",
"protected",
"constraint",
"covergroup",
"endgroup",
"function",
"endfunction",
"task",
"endtask",
"automatic",
"static",
"const",
"import",
"export",
"timeunit",
"timeprecision",
"assert",
"assume",
"cover",
"property",
"endproperty",
"sequence",
"endsequence",
"inside",
"with",
"iff",
"release",
"force",
"deassign",
"primitive",
"endprimitive",
"specify",
"endspecify",
"table",
"endtable",
// Vendor and formal collateral (`vendor-formal-grammar`, 2026-09-02).
// All five are reserved words in IEEE 1800 Table B.1, so a file that
// spells one as an identifier is already illegal SystemVerilog — and a
// census of 4 839 corpus + opentitan files found **zero** code-shaped
// uses of any of them. The rest of the vendor/config vocabulary
// (`expect`, `tagged`, `design`, `instance`, `cell`, `liblist`, `use`,
// `showcancelled`, `ifnone`) is deliberately *not* here: real code does
// spell those as identifiers — `expect(word1[7:0]);` is a task call in 41
// corpus sites — so they are matched by text where they are needed at
// all. See `docs/features/vendor-formal-grammar/README.md`.
"checker",
"endchecker",
"config",
"endconfig",
"library",
"small",
"medium",
"large",
"scalared",
"vectored",
"highz0",
"highz1",
"strong0",
"strong1",
"pull0",
"pull1",
"weak0",
"weak1",
"cmos",
"rcmos",
"nmos",
"pmos",
"rnmos",
"rpmos",
"tran",
"rtran",
"tranif0",
"tranif1",
"rtranif0",
"rtranif1",
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_slice_and_the_predicate_are_the_same_list() {
// They are generated from one `keywords!` invocation, so this can only
// fail if the macro is edited into disagreeing with itself — which is
// exactly the drift the macro exists to prevent.
assert!(KEYWORDS.iter().all(|word| is_keyword(word)));
assert!(!is_keyword("clk"), "an ordinary name is not reserved");
assert!(!is_keyword("new"), "deliberately not a keyword, see the list");
assert!(!KEYWORDS.contains(&"clk"));
}
#[test]
fn no_keyword_is_listed_twice() {
let mut sorted = KEYWORDS.to_vec();
sorted.sort_unstable();
let mut unique = sorted.clone();
unique.dedup();
assert_eq!(sorted, unique, "a duplicate entry would double a completion list");
}
}