Files
lucisv/crates/vlog_parser/src/lexer.rs
T

1732 lines
68 KiB
Rust

//! Hand-written lexer for Verilog/SystemVerilog.
//!
//! The lexer runs in two phases, mirroring how ruff's parser handles trivia:
//! a raw phase that produces every token including comments, and an
//! attachment phase that folds comments into the neighboring "real" tokens as
//! leading/trailing trivia and records blank-line information. The parser and
//! formatter then never have to think about interleaved comment tokens.
use crate::span::TextRange;
use crate::token::{is_keyword, Comment, Token, TokenKind};
#[derive(Debug, Clone)]
pub struct LexError {
pub line: u32,
pub col: u32,
pub message: String,
}
impl std::fmt::Display for LexError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}: {}", self.line, self.col, self.message)
}
}
impl std::error::Error for LexError {}
/// Raw token produced by phase one. Comments are still ordinary tokens here.
struct RawTok {
kind: RawKind,
text: String,
line: u32,
col: u32,
/// Byte extent in the source text.
span: TextRange,
/// Number of newlines seen between the previous raw token and this one.
newlines_before: u32,
}
#[derive(PartialEq, Eq, Clone, Copy)]
enum RawKind {
Real(TokenKind),
LineComment,
BlockComment,
}
struct RawLexer<'a> {
src: &'a [u8],
pos: usize,
line: u32,
col: u32,
}
/// Multi-character operators, longest first so greedy matching works.
const OPERATORS: &[&str] = &[
"<<<=", ">>>=", "===", "!==", "==?", "!=?", "<<<", ">>>", "<<=", ">>=", "<->", "->>", "**",
"==", "!=", "<=", ">=", "&&", "||", "<<", ">>", "->", "=>", "::", "+:", "-:", "+=", "-=", "*=",
"/=", "%=", "&=", "|=", "^=", "++", "--", "~&", "~|", "~^", "^~", "##", "'{",
];
const SINGLE_OPS: &[u8] = b"+-*/%&|^~!<>=?:;,.#@()[]{}'$";
/// How deeply brackets may nest inside a macro invocation's argument list.
///
/// The scan is iterative, so this is not a stack bound — it is a guard that
/// turns pathologically unbalanced input into a lex error at the offending
/// position instead of a token that swallows the rest of the file.
const MAX_MACRO_ARG_NESTING: usize = 256;
/// The UTF-8 encoding of U+FEFF, the byte order mark editors on Windows
/// prepend to files. Accepted at the start of the source only, like leading
/// whitespace; anywhere else it is an error with a message that names it.
const BOM: &[u8] = b"\xEF\xBB\xBF";
impl<'a> RawLexer<'a> {
fn new(src: &'a [u8]) -> Self {
// Skip a leading BOM as if it were whitespace. Columns count bytes,
// so the first real character sits at column 4, which is where
// `LineIndex` (also byte-based) puts it too.
let pos = if src.starts_with(BOM) { BOM.len() } else { 0 };
RawLexer { src, pos, line: 1, col: pos as u32 + 1 }
}
fn peek(&self) -> u8 {
*self.src.get(self.pos).unwrap_or(&0)
}
fn peek_at(&self, offset: usize) -> u8 {
*self.src.get(self.pos + offset).unwrap_or(&0)
}
fn bump(&mut self) -> u8 {
let c = self.peek();
self.pos += 1;
if c == b'\n' {
self.line += 1;
self.col = 1;
} else {
self.col += 1;
}
c
}
fn starts_with(&self, s: &str) -> bool {
self.src[self.pos..].starts_with(s.as_bytes())
}
fn text_from(&self, start: usize) -> String {
String::from_utf8_lossy(&self.src[start..self.pos]).into_owned()
}
/// The byte extent from `start` to the cursor.
fn span_from(&self, start: usize) -> TextRange {
TextRange::new(start as u32, self.pos as u32)
}
/// The extent of a token whose text was trimmed at the end (a line
/// comment, a compiler directive): the trailing whitespace the trim
/// dropped is not part of the token, so the span stops where its text
/// does and `source[span] == text` still holds.
fn span_of_trimmed(&self, start: usize, text: &str) -> TextRange {
TextRange::new(start as u32, (start + text.len()) as u32)
}
/// Skip spaces/tabs/newlines, returning how many newlines were skipped.
fn skip_whitespace(&mut self) -> u32 {
let mut newlines = 0;
while matches!(self.peek(), b' ' | b'\t' | b'\r' | b'\n') {
if self.bump() == b'\n' {
newlines += 1;
}
}
newlines
}
fn error(&self, message: String) -> LexError {
LexError { line: self.line, col: self.col, message }
}
fn next_raw(&mut self) -> Result<RawTok, LexError> {
let newlines_before = self.skip_whitespace();
let (line, col) = (self.line, self.col);
let start = self.pos;
if self.pos >= self.src.len() {
return Ok(RawTok {
kind: RawKind::Real(TokenKind::Eof),
text: String::new(),
line,
col,
span: self.span_from(start),
newlines_before,
});
}
let c = self.peek();
// Comments.
if c == b'/' && self.peek_at(1) == b'/' {
while self.pos < self.src.len() && self.peek() != b'\n' {
self.bump();
}
let text = self.text_from(start).trim_end().to_string();
let span = self.span_of_trimmed(start, &text);
return Ok(RawTok {
kind: RawKind::LineComment,
text,
line,
col,
span,
newlines_before,
});
}
if c == b'/' && self.peek_at(1) == b'*' {
self.skip_block_comment()?;
let text = self.text_from(start);
let span = self.span_from(start);
return Ok(RawTok {
kind: RawKind::BlockComment,
text,
line,
col,
span,
newlines_before,
});
}
// Compiler directives: capture through end of line, honoring `\`
// continuations (used by `define).
if c == b'`' {
// One tracker per directive: it carries the formal list's paren
// depth across the lines below instead of re-deriving it, which is
// what keeps an *unclosed* list linear. See [`DefineParams`].
let mut params = DefineParams::new();
loop {
while self.pos < self.src.len() && self.peek() != b'\n' {
// Stop before a trailing comment on the same line — unless
// a formal-argument list is still open, in which case the
// comment is written *inside* the directive and rides
// along with it, exactly as one on a backslash-continued
// line does (`docs/features/define-table/README.md`).
if self.peek() == b'/'
&& (self.peek_at(1) == b'/' || self.peek_at(1) == b'*')
&& !params.open(self.src, start, self.pos)
{
break;
}
self.bump();
}
// A function-like `` `define`` whose formal-argument list is
// still open at end of line continues onto the next one with
// no backslash: every tool accepts it and real code writes it
// (`cip_base_vseq__tl_errors.svh:8`). The macro *body* is
// unaffected — it still needs the backslashes below.
if self.peek() != b'\n' || !params.open(self.src, start, self.pos) {
break;
}
self.bump();
}
// Line continuation: `define FOO \ <next line>
while self.text_ends_with_continuation(start) && self.peek() == b'\n' {
// A blank continuation line ends the directive and is *not*
// part of it: the token's text is trimmed back to the last
// `\` anyway, so consuming the newline here would hide a
// blank line from the attachment phase — and the formatter
// would then print whatever follows directly under a line
// ending in `\`, which re-lexes as part of the directive.
let mark = (self.pos, self.line, self.col);
self.bump();
let line_start = self.pos;
while self.pos < self.src.len() && self.peek() != b'\n' {
self.bump();
}
if self.src[line_start..self.pos].iter().all(u8::is_ascii_whitespace) {
let (pos, line, col) = mark;
self.pos = pos;
self.line = line;
self.col = col;
break;
}
}
let text = self.text_from(start).trim_end().to_string();
// Short directives like `WIDTH used inside expressions (macro
// usage) should not swallow the rest of the line. Only treat
// known line-oriented directives as raw lines.
let first_word: String = text
.trim_start_matches('`')
.chars()
.take_while(|ch| ch.is_ascii_alphanumeric() || *ch == '_')
.collect();
if is_line_directive(&first_word) {
let span = self.span_of_trimmed(start, &text);
return Ok(RawTok {
kind: RawKind::Real(TokenKind::Directive),
text,
line,
col,
span,
newlines_before,
});
}
// Macro usage: rewind and lex just `NAME as an identifier-like
// token so it can appear inside expressions.
self.pos = start;
self.line = line;
self.col = col;
self.bump(); // backtick
while is_ident_char(self.peek()) {
self.bump();
}
// Macro call with arguments: `NAME(...) — capture balanced text.
if self.peek() == b'(' {
self.scan_macro_args()?;
}
let text = self.text_from(start);
return Ok(RawTok {
kind: RawKind::Real(TokenKind::Ident),
text,
line,
col,
span: self.span_from(start),
newlines_before,
});
}
// Attribute instance `(* ... *)`.
if self.starts_attribute() {
self.bump();
self.bump();
loop {
if self.pos >= self.src.len() {
return Err(self.error("unterminated attribute (* ... *)".to_string()));
}
if self.peek() == b'*' && self.peek_at(1) == b')' {
self.bump();
self.bump();
break;
}
self.bump();
}
let text = self.text_from(start);
return Ok(RawTok {
kind: RawKind::Real(TokenKind::Attribute),
text,
line,
col,
span: self.span_from(start),
newlines_before,
});
}
// String literal.
if c == b'"' {
self.skip_string()?;
let text = self.text_from(start);
return Ok(RawTok {
kind: RawKind::Real(TokenKind::String),
text,
line,
col,
span: self.span_from(start),
newlines_before,
});
}
// Escaped identifier: backslash to next whitespace.
if c == b'\\' {
self.bump();
while self.pos < self.src.len() && !self.peek().is_ascii_whitespace() {
self.bump();
}
let text = self.text_from(start);
return Ok(RawTok {
kind: RawKind::Real(TokenKind::Ident),
text,
line,
col,
span: self.span_from(start),
newlines_before,
});
}
// System identifier.
if c == b'$' && is_ident_char(self.peek_at(1)) {
self.bump();
while is_ident_char(self.peek()) {
self.bump();
}
let text = self.text_from(start);
return Ok(RawTok {
kind: RawKind::Real(TokenKind::SystemIdent),
text,
line,
col,
span: self.span_from(start),
newlines_before,
});
}
// Number literals. The text is normalized (whitespace around the tick
// of `8 'hFF` is dropped), so this is the one token kind whose text
// can be shorter than `source[span]`; the span is the real extent.
if c.is_ascii_digit() {
let text = self.lex_number()?;
return Ok(RawTok {
kind: RawKind::Real(TokenKind::Number),
text,
line,
col,
span: self.span_from(start),
newlines_before,
});
}
// Based literal without a size (`'hFF`, `'0`, `'x`), but not the
// assignment-pattern opener `'{` or a cast tick `'(`.
if c == b'\'' && is_base_intro(self.peek_at(1)) {
let text = self.lex_based_part()?;
return Ok(RawTok {
kind: RawKind::Real(TokenKind::Number),
text,
line,
col,
span: self.span_from(start),
newlines_before,
});
}
// Identifier or keyword.
if c == b'_' || c.is_ascii_alphabetic() {
while is_ident_char(self.peek()) {
self.bump();
}
let text = self.text_from(start);
let kind = if is_keyword(&text) { TokenKind::Keyword } else { TokenKind::Ident };
let span = self.span_from(start);
return Ok(RawTok {
kind: RawKind::Real(kind),
text,
line,
col,
span,
newlines_before,
});
}
// Operators, longest match first. The first-byte test is not a second
// way of matching — `starts_with` still decides — it is what keeps a
// `;` from being compared against all 42 spellings: one byte compare
// rejects every operator that cannot start here (TODO §63.2).
for op in OPERATORS {
if op.as_bytes()[0] != c {
continue;
}
if self.starts_with(op) {
for _ in 0..op.len() {
self.bump();
}
return Ok(RawTok {
kind: RawKind::Real(TokenKind::Symbol),
text: (*op).to_string(),
line,
col,
span: self.span_from(start),
newlines_before,
});
}
}
if SINGLE_OPS.contains(&c) {
self.bump();
return Ok(RawTok {
kind: RawKind::Real(TokenKind::Symbol),
text: (c as char).to_string(),
line,
col,
span: self.span_from(start),
newlines_before,
});
}
if c.is_ascii() {
return Err(self.error(format!("unexpected character {:?}", c as char)));
}
// A non-ASCII byte: decode the whole character so the message shows
// it, not the mojibake of its first byte. The source arrived as a
// `&str`, so the bytes here are valid UTF-8; the lossy fallback only
// guards a cursor that somehow stopped mid-character.
let end = (self.pos + 4).min(self.src.len());
let tail = String::from_utf8_lossy(&self.src[self.pos..end]);
let ch = tail.chars().next().unwrap_or(c as char);
if ch == '\u{feff}' {
return Err(self.error(
"byte order mark (U+FEFF) is only allowed at the start of the file".into(),
));
}
Err(self.error(format!(
"character '{ch}' (U+{:04X}) is not valid in Verilog source",
ch as u32
)))
}
/// True when the cursor sits on the `(*` that opens an attribute
/// instance. `(*` followed — possibly after whitespace — by `)` is the
/// implicit sensitivity list `@(*)` spelled with spaces: an attribute
/// holds at least one attr_spec, which cannot begin with `)`, so those
/// characters lex as the plain symbols `(` `*` `)` instead.
fn starts_attribute(&self) -> bool {
if self.peek() != b'(' || self.peek_at(1) != b'*' {
return false;
}
let mut i = 2;
while matches!(self.peek_at(i), b' ' | b'\t' | b'\r' | b'\n') {
i += 1;
}
self.peek_at(i) != b')'
}
/// Scan a macro invocation's argument list, from the `(` the caller is
/// sitting on through its matching `)`.
///
/// Macro arguments are token soup, not an expression: they are handed to
/// the preprocessor, not to the grammar. So this only tracks bracket
/// nesting, and skips over strings and comments because either can hold
/// an unmatched bracket (`` `uvm_info("(", ...) ``). The scan is a flat
/// loop with an explicit counter — it never recurses, so the only reason
/// for [`MAX_MACRO_ARG_NESTING`] is to fail loudly on pathological input
/// instead of scanning to end of file.
fn scan_macro_args(&mut self) -> Result<(), LexError> {
let mut depth = 0usize;
loop {
if self.pos >= self.src.len() {
return Err(self.error("unterminated macro call".to_string()));
}
if self.peek() == b'"' {
self.skip_string()?;
continue;
}
if self.peek() == b'/' && self.peek_at(1) == b'/' {
while self.pos < self.src.len() && self.peek() != b'\n' {
self.bump();
}
continue;
}
if self.peek() == b'/' && self.peek_at(1) == b'*' {
self.skip_block_comment()?;
continue;
}
match self.bump() {
b'(' | b'[' | b'{' => {
depth += 1;
if depth > MAX_MACRO_ARG_NESTING {
return Err(self.error(format!(
"macro argument nesting too deep (limit {MAX_MACRO_ARG_NESTING})"
)));
}
}
b')' | b']' | b'}' => {
depth = depth.saturating_sub(1);
if depth == 0 {
return Ok(());
}
}
_ => {}
}
}
}
/// Consume a string literal starting at the opening quote.
fn skip_string(&mut self) -> Result<(), LexError> {
self.bump(); // opening quote
loop {
if self.pos >= self.src.len() {
return Err(self.error("unterminated string literal".to_string()));
}
match self.bump() {
b'\\' => {
self.bump();
}
b'"' => return Ok(()),
_ => {}
}
}
}
/// Consume a `/* ... */` comment starting at the opening `/`.
fn skip_block_comment(&mut self) -> Result<(), LexError> {
self.bump();
self.bump();
loop {
if self.pos >= self.src.len() {
return Err(self.error("unterminated block comment".to_string()));
}
if self.peek() == b'*' && self.peek_at(1) == b'/' {
self.bump();
self.bump();
return Ok(());
}
self.bump();
}
}
fn text_ends_with_continuation(&self, start: usize) -> bool {
let text = &self.src[start..self.pos];
let trimmed: &[u8] = {
let mut t = text;
while let Some((&last, rest)) = t.split_last() {
if last == b' ' || last == b'\t' || last == b'\r' {
t = rest;
} else {
break;
}
}
t
};
trimmed.last() == Some(&b'\\')
}
/// Lex a number starting at an ASCII digit. Handles plain decimal, real
/// numbers with exponents, sized based literals (`8'hFF`, `4'b10_10`,
/// with optional whitespace around the tick), and time-unit suffixes
/// (`10ns`). The returned text is normalized to contain no whitespace.
fn lex_number(&mut self) -> Result<String, LexError> {
let start = self.pos;
while self.peek().is_ascii_digit() || self.peek() == b'_' {
self.bump();
}
// Real number.
if self.peek() == b'.' && self.peek_at(1).is_ascii_digit() {
self.bump();
while self.peek().is_ascii_digit() || self.peek() == b'_' {
self.bump();
}
}
if matches!(self.peek(), b'e' | b'E')
&& (self.peek_at(1).is_ascii_digit()
|| (matches!(self.peek_at(1), b'+' | b'-') && self.peek_at(2).is_ascii_digit()))
{
self.bump();
if matches!(self.peek(), b'+' | b'-') {
self.bump();
}
while self.peek().is_ascii_digit() {
self.bump();
}
}
let mut text = self.text_from(start);
// Time unit suffix directly attached (1ns, 2.5us).
if self.peek().is_ascii_alphabetic() {
let unit_start = self.pos;
while self.peek().is_ascii_alphabetic() {
self.bump();
}
text.push_str(&self.text_from(unit_start));
return Ok(text);
}
// Sized based literal: whitespace is allowed around the tick
// (`8 'hFF`); normalize it away.
let save = (self.pos, self.line, self.col);
let mut probe = self.pos;
while matches!(self.src.get(probe), Some(b' ') | Some(b'\t')) {
probe += 1;
}
if self.src.get(probe) == Some(&b'\'')
&& probe + 1 < self.src.len()
&& is_base_intro(self.src[probe + 1])
&& self.src.get(probe + 1) != Some(&b'{')
{
while self.pos < probe {
self.bump();
}
match self.lex_based_part() {
Ok(based) => {
text.push_str(&based);
return Ok(text);
}
Err(_) => {
self.pos = save.0;
self.line = save.1;
self.col = save.2;
}
}
}
Ok(text)
}
/// Lex the `'h FF` / `'b1010` / `'0` part, starting at the tick.
fn lex_based_part(&mut self) -> Result<String, LexError> {
let start = self.pos;
self.bump(); // '
let c = self.peek();
if matches!(c, b'0' | b'1' | b'x' | b'X' | b'z' | b'Z') && !is_ident_char(self.peek_at(1)) {
// Unbased unsized literal: '0 '1 'x 'z
self.bump();
return Ok(self.text_from(start));
}
let mut text = String::from("'");
if matches!(self.peek(), b's' | b'S') {
text.push(self.bump() as char);
}
if !matches!(self.peek(), b'd' | b'D' | b'b' | b'B' | b'o' | b'O' | b'h' | b'H') {
return Err(self.error("expected number base after '".to_string()));
}
text.push(self.bump() as char);
// A based number whose digits come from a macro: `` 32'h`DM_ADDR ``
// (corpus `ibex/dv/uvm/core_ibex/tb/core_ibex_tb_top.sv:75`). The
// digits are preprocessor output lucisv does not expand, so the number
// token ends here, with no digits, and the invocation lexes as the
// macro token it is; the parser rejoins the pair into one primary
// expression and the formatter prints them adjacent, as written.
//
// The backtick must *touch* the base: `` 32'h `DM_ADDR `` keeps the
// "expected digits" error below, because a space there is far more
// likely a typo than this idiom, and accepting it would silently
// change what the source says.
if self.peek() == b'`' {
return Ok(text);
}
// Whitespace is allowed between base and value.
while matches!(self.peek(), b' ' | b'\t') {
self.bump();
}
let value_start = self.pos;
while self.peek().is_ascii_alphanumeric() || matches!(self.peek(), b'_' | b'?') {
self.bump();
}
if self.pos == value_start {
return Err(self.error("expected digits after number base".to_string()));
}
text.push_str(&self.text_from(value_start));
Ok(text)
}
}
/// Incremental tracker for a function-like `` `define``'s formal-argument
/// list: how deep its parens are, and whether it is still open.
///
/// One of these lives for the length of one directive, and
/// [`DefineParams::open`] walks **only the bytes added since the last call**.
/// That is the whole point of the type: the question is asked once per line
/// the list stays open on, so re-deriving the depth from the directive's first
/// byte every time would be quadratic in the number of lines — and an
/// unclosed list never stops asking, so a vendor file with one dropped `)`
/// would stall the lexer for minutes (QA, 2026-09-02: 20 000 unclosed lines
/// took 2.5 s that way, and it grew with the square).
struct DefineParams {
/// Absolute byte offset in the source that the scan has consumed.
scanned: usize,
/// Open parens at `scanned`, counting the `(` that opens the list.
depth: u32,
/// What the scan is in the middle of, carried across lines: a default
/// value may hold a paren inside a string or a comment.
mode: ScanMode,
/// `None` until the header has been read. `Some(false)` is **terminal** —
/// either this is not a function-like `` `define``, or its list has
/// closed — and no byte is ever looked at again.
open: Option<bool>,
/// Bytes [`DefineParams::advance`] has actually looked at. Counted only in
/// test builds, where it is the structural pin that this scan is one pass
/// and not a rescan — the property a wall-clock bound can only imply.
#[cfg(test)]
walked: usize,
}
/// What [`DefineParams::advance`] is in the middle of.
#[derive(Clone, Copy, PartialEq)]
enum ScanMode {
Code,
String,
LineComment,
BlockComment,
}
impl DefineParams {
fn new() -> DefineParams {
DefineParams {
scanned: 0,
depth: 0,
mode: ScanMode::Code,
open: None,
#[cfg(test)]
walked: 0,
}
}
/// True when the directive running from `start` to `end` is a
/// function-like `` `define`` whose formal-argument list is still open.
///
/// `end` must never move backwards between calls, which is what makes the
/// whole scan one pass over the directive.
fn open(&mut self, src: &[u8], start: usize, end: usize) -> bool {
if self.open.is_none() {
// The header is decided once. It is a prefix of the directive, so
// the answer cannot change later: the only case where the text so
// far is too short to see a `(` is one where the directive ends
// right there anyway (a `\n` or a comment straight after the name).
self.open = Some(match define_params_start(&src[start..end]) {
Some(at) => {
self.scanned = start + at;
true
}
None => false,
});
}
if self.open != Some(true) {
return false;
}
self.advance(src, end);
self.open == Some(true)
}
/// Walk the bytes added since the last call, and nothing else.
fn advance(&mut self, src: &[u8], end: usize) {
#[cfg(test)]
let from = self.scanned;
let mut i = self.scanned;
while i < end {
match self.mode {
ScanMode::String => match src[i] {
b'\\' => i += 1,
b'"' => self.mode = ScanMode::Code,
_ => {}
},
ScanMode::LineComment => {
if src[i] == b'\n' {
self.mode = ScanMode::Code;
}
}
ScanMode::BlockComment => {
if src[i] == b'*' && src.get(i + 1) == Some(&b'/') {
self.mode = ScanMode::Code;
i += 1;
}
}
ScanMode::Code => match src[i] {
b'"' => self.mode = ScanMode::String,
b'/' if src.get(i + 1) == Some(&b'/') => {
self.mode = ScanMode::LineComment;
i += 1;
}
b'/' if src.get(i + 1) == Some(&b'*') => {
self.mode = ScanMode::BlockComment;
i += 1;
}
b'(' => self.depth += 1,
b')' => {
self.depth = self.depth.saturating_sub(1);
if self.depth == 0 {
// The list closed: the parens of the macro *body*
// can never reopen it, so this is the last byte
// this tracker ever looks at.
self.open = Some(false);
self.scanned = i + 1;
#[cfg(test)]
{
self.walked += self.scanned - from;
}
return;
}
}
_ => {}
},
}
i += 1;
}
// `i`, not `end`: a two-byte step (`\` in a string, `//`, `*/`) may
// have carried the scan one past `end`, and that byte is consumed.
self.scanned = i;
#[cfg(test)]
{
self.walked += self.scanned - from;
}
}
}
/// The offset of the `(` that opens a function-like `` `define``'s formal
/// argument list, or `None` when `text` does not start one.
///
/// Only a `(` that *touches* the macro name opens a list (IEEE 1800 §22.5.1,
/// the same rule `defines.rs` reads the parameters by): `` `define A (x) `` is
/// object-like and its body merely starts with a paren. Everything else that
/// begins with a backtick — a macro invocation above all — answers `None` and
/// keeps the one-line capture it always had.
fn define_params_start(text: &[u8]) -> Option<usize> {
const KEYWORD: &[u8] = b"`define";
let rest = text.strip_prefix(KEYWORD)?;
if !matches!(rest.first(), Some(b' ' | b'\t')) {
return None;
}
let mut i = 0;
while matches!(rest.get(i), Some(b' ' | b'\t')) {
i += 1;
}
let name_start = i;
while rest.get(i).is_some_and(|&c| is_ident_char(c)) {
i += 1;
}
if i == name_start || rest.get(i) != Some(&b'(') {
return None;
}
Some(KEYWORD.len() + i)
}
fn is_ident_char(c: u8) -> bool {
c == b'_' || c == b'$' || c.is_ascii_alphanumeric()
}
fn is_base_intro(c: u8) -> bool {
matches!(
c,
b's' | b'S'
| b'd'
| b'D'
| b'b'
| b'B'
| b'o'
| b'O'
| b'h'
| b'H'
| b'0'
| b'1'
| b'x'
| b'X'
| b'z'
| b'Z'
)
}
/// Directives that consume the rest of the source line. Anything else that
/// starts with a backtick is treated as a macro usage token.
///
/// The list is closed on purpose: every backtick name *not* named here is a
/// macro invocation, so adding a name here takes it away from the macro
/// population for good. `` `error`` / `` `warning`` are in because IEEE 1800
/// §22.8 spells them as directives whose operand is a bare string on the rest
/// of the line (`` `error "must be read first!" ``, corpus
/// `picorv32/picosoc/icebreaker.v:21`), which nothing else in the grammar can
/// parse.
fn is_line_directive(word: &str) -> bool {
matches!(
word,
"define"
| "error"
| "warning"
| "undef"
| "undefineall"
| "ifdef"
| "ifndef"
| "elsif"
| "else"
| "endif"
| "include"
| "timescale"
| "default_nettype"
| "resetall"
| "celldefine"
| "endcelldefine"
| "line"
| "pragma"
| "unconnected_drive"
| "nounconnected_drive"
| "begin_keywords"
| "end_keywords"
)
}
/// What the attachment phase carries from one raw token to the next.
#[derive(Default)]
struct Attaching {
/// Comments waiting for the real token they lead.
pending: Vec<Comment>,
/// Whether a blank line was seen since the last pending comment.
pending_blank: bool,
}
/// Tokenize source text, attaching comments and blank-line info to tokens.
///
/// The two phases are **fused**: each raw token is attached as it is lexed,
/// rather than collected into a `Vec<RawTok>` the attachment loop then walks.
/// Attachment only ever reads the raw token in hand and the token last pushed,
/// so the fusion is a pure reordering — it drops a second whole-file vector
/// (a 40 267-line file's worth of it is ~22 MB of allocation, growth copying
/// and teardown), which is why the first request after an edit pays less for
/// the same tokens (TODO §63.2).
pub fn tokenize(source: &str) -> Result<Vec<Token>, LexError> {
let mut raw_lexer = RawLexer::new(source.as_bytes());
let mut tokens: Vec<Token> = Vec::with_capacity(estimated_tokens(source.len()));
let mut state = Attaching::default();
loop {
let raw = raw_lexer.next_raw()?;
let is_eof = raw.kind == RawKind::Real(TokenKind::Eof);
attach(raw, &mut tokens, &mut state);
if is_eof {
break;
}
}
Ok(tokens)
}
/// How many tokens a source of `bytes` bytes is guessed to hold.
///
/// Only to spare the growing vector its early doublings; a wrong guess costs
/// nothing but the growth it would have paid anyway. Six bytes a token is the
/// measured average over the corpus and over opentitan's generated register
/// files alike, and the guess is capped so a pathological file (one enormous
/// string literal) cannot reserve more than it could ever need.
fn estimated_tokens(bytes: usize) -> usize {
(bytes / 6).min(1 << 20)
}
/// Fold one raw token into the token stream: a comment onto its neighbour,
/// a real token onto the end with whatever comments were waiting for it.
fn attach(raw: RawTok, tokens: &mut Vec<Token>, state: &mut Attaching) {
match raw.kind {
RawKind::LineComment | RawKind::BlockComment => {
let same_line_as_prev =
raw.newlines_before == 0 && !tokens.is_empty() && state.pending.is_empty();
let comment = Comment {
text: raw.text,
blank_before: raw.newlines_before > 1 || state.pending_blank,
line: raw.line,
col: raw.col,
span: raw.span,
};
// A comment that finds no token to trail — unreachable while
// `same_line_as_prev` requires one, kept as a rule rather than a
// hope — leads the next token instead of vanishing (invariant 3).
let orphan =
if same_line_as_prev { attach_trailing(tokens, comment) } else { Some(comment) };
if let Some(comment) = orphan {
state.pending.push(comment);
state.pending_blank = false;
}
}
RawKind::Real(kind) => {
// Comments already carry their own blank flags; the token is
// blank-separated only if there was a blank line between the last
// comment and the token itself — which is the same test either
// way, so `pending` does not enter into it.
let blank_before = raw.newlines_before > 1;
tokens.push(Token {
kind,
text: raw.text,
line: raw.line,
col: raw.col,
span: raw.span,
leading: std::mem::take(&mut state.pending),
trailing: None,
blank_before,
});
}
}
}
/// Hang a comment off the token before it, merging with one already there.
/// Handed back untouched when there is no token before it.
fn attach_trailing(tokens: &mut [Token], comment: Comment) -> Option<Comment> {
let Some(prev) = tokens.last_mut() else { return Some(comment) };
match &mut prev.trailing {
Some(existing) => {
// Two comments on one line become one node, so its span has to
// cover both — the merge normalizes the gap between them to a
// single space, which is why a merged comment is the one comment
// whose text can differ from `source[span]`.
existing.text.push(' ');
existing.text.push_str(&comment.text);
existing.span = TextRange::new(existing.span.start, comment.span.end);
}
None => prev.trailing = Some(comment),
}
None
}
#[cfg(test)]
mod tests {
use super::*;
fn kinds(src: &str) -> Vec<(TokenKind, String)> {
tokenize(src).unwrap().into_iter().map(|t| (t.kind, t.text)).collect()
}
#[test]
fn basic_tokens() {
let toks = kinds("module foo; endmodule");
assert_eq!(toks[0], (TokenKind::Keyword, "module".to_string()));
assert_eq!(toks[1], (TokenKind::Ident, "foo".to_string()));
assert_eq!(toks[2], (TokenKind::Symbol, ";".to_string()));
assert_eq!(toks[3], (TokenKind::Keyword, "endmodule".to_string()));
}
#[test]
fn based_literals() {
let toks = kinds("8'hFF 4'b10_10 'd10 32 'shA5 'x 1.5e-3 10ns");
let texts: Vec<&str> = toks.iter().map(|(_, t)| t.as_str()).collect();
assert_eq!(texts, ["8'hFF", "4'b10_10", "'d10", "32'shA5", "'x", "1.5e-3", "10ns", ""]);
assert!(toks[..7].iter().all(|(k, _)| *k == TokenKind::Number));
}
// ------------------------------------------------------------------
// `define formal-argument continuation — TODO.md §22
// ------------------------------------------------------------------
#[test]
fn a_define_formal_list_continues_across_lines_without_a_backslash() {
// opentitan `cip_base_vseq__tl_errors.svh:8` — no backslash on the
// line that opens the list, and every tool accepts it.
let src = "`define A(x,\n y = 3,\n z) body\nwire w;\n";
let toks = tokenize(src).unwrap();
assert_eq!(toks[0].kind, TokenKind::Directive);
assert_eq!(toks[0].text, "`define A(x,\n y = 3,\n z) body");
assert_eq!(&src[toks[0].span.as_range()], toks[0].text);
assert!(toks[1].is_kw("wire"), "the next line is ordinary code again");
}
#[test]
fn a_closed_formal_list_stops_the_directive_at_end_of_line() {
// The body still needs its backslashes: the paren rule is about the
// *formal list* and nothing else.
let toks = tokenize("`define A(x) foo(\nwire w;\n").unwrap();
assert_eq!(toks[0].text, "`define A(x) foo(");
assert!(toks[1].is_kw("wire"));
}
#[test]
fn only_a_paren_touching_the_name_opens_a_formal_list() {
// `define A (x) is object-like (IEEE 1800 §22.5.1): its body merely
// starts with a paren, so end of line ends the directive.
let toks = tokenize("`define A (x,\nwire w;\n").unwrap();
assert_eq!(toks[0].text, "`define A (x,");
assert!(toks[1].is_kw("wire"));
// And a macro *usage* is not a `define at all.
let toks = tokenize("`uvm_info(a,\n b)\n").unwrap();
assert_eq!(toks[0].kind, TokenKind::Ident);
}
#[test]
fn a_string_or_a_comment_inside_a_formal_list_does_not_close_it() {
let toks = tokenize("`define A(s = \")\",\n t) body\nwire w;\n").unwrap();
assert_eq!(toks[0].text, "`define A(s = \")\",\n t) body");
assert!(toks[1].is_kw("wire"));
// A comment written inside the list rides along with the directive,
// exactly as one on a backslash-continued line does.
let toks = tokenize("`define A(x, // why\n y) body\nwire w;\n").unwrap();
assert_eq!(toks[0].text, "`define A(x, // why\n y) body");
assert!(toks[1].is_kw("wire"));
}
#[test]
fn a_formal_list_that_never_closes_stops_at_end_of_file() {
// Degenerate input, pinned so it cannot loop or panic.
let toks = tokenize("`define A(x,\n y\n").unwrap();
assert_eq!(toks[0].text, "`define A(x,\n y");
assert_eq!(toks[1].kind, TokenKind::Eof);
}
#[test]
fn a_nested_paren_inside_a_formal_list_does_not_close_it() {
// opentitan's real shape: a default value whose type is
// parameterized, so the list's own `)` is the *second* one.
let src = "`define A(x,\n t = seq #(item),\n y) body\nwire w;\n";
let toks = tokenize(src).unwrap();
assert_eq!(toks[0].text, "`define A(x,\n t = seq #(item),\n y) body");
assert!(toks[1].is_kw("wire"));
// A block comment spanning the line break is carried too.
let src = "`define A(x, /* one\n two */ y) body\nwire w;\n";
let toks = tokenize(src).unwrap();
assert_eq!(toks[0].text, "`define A(x, /* one\n two */ y) body");
assert!(toks[1].is_kw("wire"));
}
// ------------------------------------------------------------------
// `DefineParams` is incremental — QA finding, 2026-09-02
//
// The tracker is asked once per line the formal list stays open on. It
// must answer from the bytes added since the last question, never by
// re-deriving the depth from the directive's first byte: an *unclosed*
// list never stops asking, so a from-scratch rescan is quadratic in the
// number of lines and one dropped `)` in a vendor file stalls the editor.
// Two pins: the answers still match a from-scratch scan exactly, and the
// work really is one pass.
// ------------------------------------------------------------------
/// The from-scratch scan the incremental tracker replaced, kept as the
/// reference the tracker is held to. Deliberately the naive shape.
fn params_open_rescan(text: &[u8]) -> bool {
let Some(at) = define_params_start(text) else {
return false;
};
let mut depth = 0u32;
let mut mode = ScanMode::Code;
let mut i = at;
while i < text.len() {
match mode {
ScanMode::String => match text[i] {
b'\\' => i += 1,
b'"' => mode = ScanMode::Code,
_ => {}
},
ScanMode::LineComment => {
if text[i] == b'\n' {
mode = ScanMode::Code;
}
}
ScanMode::BlockComment => {
if text[i] == b'*' && text.get(i + 1) == Some(&b'/') {
mode = ScanMode::Code;
i += 1;
}
}
ScanMode::Code => match text[i] {
b'"' => mode = ScanMode::String,
b'/' if text.get(i + 1) == Some(&b'/') => {
mode = ScanMode::LineComment;
i += 1;
}
b'/' if text.get(i + 1) == Some(&b'*') => {
mode = ScanMode::BlockComment;
i += 1;
}
b'(' => depth += 1,
b')' => {
depth = depth.saturating_sub(1);
if depth == 0 {
return false;
}
}
_ => {}
},
}
i += 1;
}
depth > 0
}
/// Every directive shape the scan has to get right, as a whole source.
const PARAM_SHAPES: &[&str] = &[
"`define A(x, y) body",
"`define A(x,\n y) body",
"`define A(x,\n t = seq #(item),\n y) body",
"`define A(s = \")\", t) body",
"`define A(s = \"a\\\"b)\", t) body",
"`define A(x, // why\n y) body",
"`define A(x, /* one\n two */ y) body",
"`define A(x,\n y",
"`define A (x, y) body",
"`define A body(x, y)",
"`define A",
"`uvm_info(a,\n b)",
"`ifdef X",
"`define A() body",
];
/// Where the lexer actually asks the question: at every end of line, and
/// at every `//` or `/*` start, plus once at the end of the text. Driving
/// the tracker anywhere else would be testing a call pattern that does not
/// happen — in particular a question asked before the macro name is
/// complete, which the lexer can never ask.
fn question_points(src: &[u8]) -> Vec<usize> {
let mut out = Vec::new();
for (i, &b) in src.iter().enumerate() {
let comment = b == b'/' && matches!(src.get(i + 1), Some(b'/') | Some(b'*'));
if b == b'\n' || comment {
out.push(i);
}
}
out.push(src.len());
out
}
#[test]
fn the_incremental_tracker_answers_exactly_what_a_rescan_would() {
for shape in PARAM_SHAPES {
let src = shape.as_bytes();
let mut params = DefineParams::new();
for end in question_points(src) {
assert_eq!(
params.open(src, 0, end),
params_open_rescan(&src[..end]),
"{shape:?} at {end}: incremental and rescan disagree"
);
}
}
}
#[test]
fn the_incremental_tracker_visits_each_byte_at_most_once() {
// The structural half of the fix. `walked` is the real loop count, so
// a regression to a from-scratch rescan fails here with a number
// rather than with a stopwatch — and it fails on a 20-byte fixture,
// long before it is slow enough for anyone to notice.
for shape in PARAM_SHAPES {
let src = shape.as_bytes();
let mut params = DefineParams::new();
let mut last = 0usize;
for end in question_points(src) {
params.open(src, 0, end);
assert!(params.scanned >= last, "{shape:?}: the scan moved backwards");
last = params.scanned;
}
assert!(
params.walked <= src.len(),
"{shape:?}: walked {} bytes of a {}-byte directive",
params.walked,
src.len()
);
}
}
#[test]
fn the_work_stays_one_pass_however_many_lines_the_list_spans() {
// The same structural pin at the size that made the bug visible: a
// rescan walks ~n^2/2 bytes here, which is over 17 billion.
let mut src = String::from("`define A(x,\n");
for i in 0..20_000 {
src.push_str(" p");
src.push_str(&i.to_string());
src.push_str(",\n");
}
let bytes = src.as_bytes();
let mut params = DefineParams::new();
for end in question_points(bytes) {
assert!(params.open(bytes, 0, end), "the list never closes, so it is always open");
}
assert!(
params.walked <= bytes.len(),
"walked {} bytes of a {}-byte directive",
params.walked,
bytes.len()
);
}
#[test]
fn a_formal_list_that_never_closes_lexes_in_linear_time() {
// The regression this guards, end to end and through `tokenize`: one
// dropped `)` in a vendored macro. With the from-scratch rescan this
// took 2.5 s in release and far worse in debug; it is now well under a
// millisecond in release, so the bound is generous by three orders of
// magnitude in either build and cannot flake.
let mut src = String::from("`define A(x,\n");
for i in 0..20_000 {
src.push_str(" p");
src.push_str(&i.to_string());
src.push_str(",\n");
}
let started = std::time::Instant::now();
let toks = tokenize(&src).expect("lex");
let took = started.elapsed();
// The whole file really is the one directive, so the scan did not stop
// early and the timing means what it says.
assert_eq!(toks[0].kind, TokenKind::Directive);
assert_eq!(toks[0].text, src.trim_end());
assert_eq!(toks[1].kind, TokenKind::Eof);
assert!(took.as_secs() < 5, "20 000 unclosed formal-argument lines took {took:?}");
}
#[test]
fn trailing_comment_attaches() {
let toks = tokenize("assign x = y; // comment\nwire z;").unwrap();
let semi = toks.iter().find(|t| t.is_sym(";")).unwrap();
let trailing = semi.trailing.as_ref().expect("trailing comment");
assert_eq!(trailing.text, "// comment");
assert_eq!((trailing.line, trailing.col), (1, 15));
}
#[test]
fn leading_comment_attaches() {
let toks = tokenize("// header\n\n// second\nmodule m; endmodule").unwrap();
assert_eq!(toks[0].leading.len(), 2);
assert!(toks[0].leading[1].blank_before);
assert_eq!((toks[0].leading[1].line, toks[0].leading[1].col), (3, 1));
}
#[test]
fn comment_records_its_own_column() {
let toks = tokenize("module m;\n /* doc\n more */\n wire w;\nendmodule").unwrap();
let wire = toks.iter().find(|t| t.is_kw("wire")).unwrap();
let doc = &wire.leading[0];
assert_eq!((doc.line, doc.col), (2, 3));
assert!(doc.text.starts_with("/* doc"));
}
#[test]
fn directives_and_macros() {
let toks = kinds("`timescale 1ns / 1ps\nwire [`WIDTH-1:0] w;");
assert_eq!(toks[0], (TokenKind::Directive, "`timescale 1ns / 1ps".to_string()));
assert!(toks.iter().any(|(k, t)| *k == TokenKind::Ident && t == "`WIDTH"));
}
#[test]
fn a_blank_continuation_line_ends_a_directive_and_stays_a_blank_line() {
// The `\` on the last body line continues onto an *empty* line, which
// is what ends the directive. That empty line is not part of the
// token, and the comment after it must still see a blank line before
// it — otherwise the formatter prints the comment directly under a
// line ending in `\` and it re-lexes as part of the directive.
let toks = tokenize("`define A \\\n x \\\n\n// c\nwire w;\n").unwrap();
assert_eq!(toks[0].kind, TokenKind::Directive);
assert_eq!(toks[0].text, "`define A \\\n x \\");
let comment = &toks[1].leading[0];
assert_eq!(comment.text, "// c");
assert!(comment.blank_before, "the blank line before the comment was swallowed");
}
#[test]
fn a_nonblank_continuation_line_is_still_part_of_the_directive() {
let toks = tokenize("`define A \\\n x \\\n y\nwire w;\n").unwrap();
assert_eq!(toks[0].text, "`define A \\\n x \\\n y");
}
#[test]
fn macro_call_captures_balanced_arguments() {
// Nested brackets of every flavour, a string and a comment holding
// unmatched brackets, and a call spread over two lines.
let src = "`A(f(g(1)), {b[3:0], '{c: 1}}, \"a )\", /* ) */ x, // )\n y) wire w;";
let toks = kinds(src);
assert_eq!(toks[0].0, TokenKind::Ident);
assert_eq!(toks[0].1, "`A(f(g(1)), {b[3:0], '{c: 1}}, \"a )\", /* ) */ x, // )\n y)");
assert_eq!(toks[1], (TokenKind::Keyword, "wire".to_string()));
}
#[test]
fn unterminated_macro_call_is_a_lex_error() {
let err = tokenize("`A(a, b").expect_err("expected a lex error");
assert!(err.message.contains("unterminated macro call"), "unexpected: {err}");
}
#[test]
fn deeply_nested_macro_arguments_are_a_lex_error() {
let src = format!("`A({}x{})", "(".repeat(400), ")".repeat(400));
let err = tokenize(&src).expect_err("expected a lex error");
assert!(err.message.contains("macro argument nesting too deep"), "unexpected: {err}");
}
#[test]
fn error_and_warning_are_line_directives() {
let toks = kinds("`error \"a b (c)\"\nwire w;");
assert_eq!(toks[0], (TokenKind::Directive, "`error \"a b (c)\"".to_string()));
assert_eq!(toks[1], (TokenKind::Keyword, "wire".to_string()));
let toks = kinds("`warning \"deprecated\"\nwire w;");
assert_eq!(toks[0], (TokenKind::Directive, "`warning \"deprecated\"".to_string()));
}
#[test]
fn the_directive_list_stays_closed_around_error() {
// Only the exact names are directives: a macro whose name merely
// starts with one is still a macro usage token.
let toks = kinds("`error_if(x) wire w;");
assert_eq!(toks[0], (TokenKind::Ident, "`error_if(x)".to_string()));
}
#[test]
fn bare_macro_does_not_swallow_the_next_line() {
let toks = kinds("`BARE\n(a);");
assert_eq!(toks[0], (TokenKind::Ident, "`BARE".to_string()));
assert_eq!(toks[1], (TokenKind::Symbol, "(".to_string()));
}
#[test]
fn a_macro_supplies_the_digits_of_a_based_number() {
// `parameter int unsigned DmBaseAddr = 32'h`DM_ADDR;` (corpus
// `ibex/dv/uvm/core_ibex/tb/core_ibex_tb_top.sv:75`): the number token
// ends at the base and the macro follows as its own token.
let toks = kinds("32'h`DM_ADDR;");
assert_eq!(toks[0], (TokenKind::Number, "32'h".to_string()));
assert_eq!(toks[1], (TokenKind::Ident, "`DM_ADDR".to_string()));
assert_eq!(toks[2], (TokenKind::Symbol, ";".to_string()));
// Unsized and signed spellings take the same path.
assert_eq!(kinds("'h`X")[0], (TokenKind::Number, "'h".to_string()));
assert_eq!(kinds("32'sh`X")[0], (TokenKind::Number, "32'sh".to_string()));
}
#[test]
fn a_space_before_the_macro_digits_is_still_a_lex_error() {
// The backtick has to touch the base. A space there is a typo, and
// accepting it would change what the source says.
let err = tokenize("32'h `DM_ADDR;").expect_err("expected a lex error");
assert!(err.message.contains("expected digits after number base"), "unexpected: {err}");
}
#[test]
fn a_base_followed_by_a_non_digit_is_still_a_lex_error() {
for src in ["32'h;", "32'h)", "32'h"] {
let err = tokenize(src).expect_err("expected a lex error");
assert!(err.message.contains("expected digits after number base"), "unexpected: {err}");
}
}
#[test]
fn attributes() {
let toks = kinds("(* keep = \"true\" *) wire w;");
assert_eq!(toks[0].0, TokenKind::Attribute);
}
#[test]
fn attribute_scan_backs_off_when_the_contents_are_just_a_star() {
// The `@(* )` family: `(*` then whitespace then `)` is an implicit
// sensitivity list, not the start of an attribute.
for src in ["@(* )", "@(* )", "@(*\t)", "@(*\n)", "@(* \n )"] {
let toks = kinds(src);
let texts: Vec<&str> = toks.iter().map(|(_, t)| t.as_str()).collect();
assert_eq!(texts, ["@", "(", "*", ")", ""], "for {src:?}");
}
}
#[test]
fn real_attributes_still_lex_as_attributes() {
// Whitespace after `(*` does not decide by itself; the first
// non-whitespace character does. `(* *)` is degenerate but was an
// attribute before the backoff and stays one.
for src in ["(* keep *)", "(*keep*)", "(* a = 1, b *)", "(* *)", "(* x=\")\" *)"] {
let toks = kinds(src);
assert_eq!(toks[0].0, TokenKind::Attribute, "for {src:?}");
assert_eq!(toks[0].1, *src, "for {src:?}");
}
}
#[test]
fn an_unterminated_attribute_is_still_an_error() {
let err = tokenize("(* keep").expect_err("expected a lex error");
assert!(err.message.contains("unterminated attribute"), "unexpected: {err}");
}
#[test]
fn a_leading_bom_is_skipped_like_whitespace() {
let toks = tokenize("\u{feff}module m; endmodule").unwrap();
assert_eq!(toks[0].kind, TokenKind::Keyword);
assert_eq!(toks[0].text, "module");
// Columns count bytes, so the first token sits past the 3-byte BOM.
assert_eq!((toks[0].line, toks[0].col), (1, 4));
assert_eq!(toks[0].span.start, 3);
}
#[test]
fn a_bom_only_source_lexes_to_eof() {
let toks = tokenize("\u{feff}").unwrap();
assert_eq!(toks.len(), 1);
assert_eq!(toks[0].kind, TokenKind::Eof);
}
#[test]
fn a_bom_after_the_start_is_a_clear_error() {
let err = tokenize("module m;\u{feff} endmodule").expect_err("expected a lex error");
assert!(err.message.contains("byte order mark (U+FEFF)"), "unexpected: {err}");
assert_eq!((err.line, err.col), (1, 10));
}
#[test]
fn a_non_ascii_character_names_the_whole_character() {
// The old message decoded one byte of the UTF-8 encoding ("'Ã'").
let err = tokenize("parameter int élan = 1;").expect_err("expected a lex error");
assert!(
err.message.contains("character 'é' (U+00E9) is not valid in Verilog source"),
"unexpected: {err}"
);
assert_eq!((err.line, err.col), (1, 15));
}
/// IEEE 1800-2017 §5.6.1: an escaped identifier runs from its `\` to the
/// next whitespace character, which is *not* part of the token. Everything
/// downstream depends on this split — the formatter has to write that
/// terminator back itself, because the token it is handed does not carry
/// it (see `docs/features/escaped-identifiers/README.md`).
#[test]
fn an_escaped_identifier_ends_before_its_terminating_whitespace() {
let toks = kinds("wire \\my-signal ;");
assert_eq!(toks[1], (TokenKind::Ident, "\\my-signal".to_string()));
assert_eq!(toks[2], (TokenKind::Symbol, ";".to_string()));
// Any whitespace ends it, and punctuation ends nothing: `\a;` is one
// identifier that has swallowed the semicolon.
let texts: Vec<String> = kinds("\\a\tb \\c\n\\d ;").into_iter().map(|(_, t)| t).collect();
assert_eq!(texts, ["\\a", "b", "\\c", "\\d", ";", ""]);
assert_eq!(kinds("wire \\a;")[1], (TokenKind::Ident, "\\a;".to_string()));
// A name may end the file: there is nothing left to terminate it.
assert_eq!(kinds("wire \\a")[1], (TokenKind::Ident, "\\a".to_string()));
// The span stops with the text, so `src[span] == text`.
let toks = tokenize("wire \\my-signal ;").unwrap();
let span = toks[1].span;
assert_eq!(&"wire \\my-signal ;"[span.start as usize..span.end as usize], "\\my-signal");
}
#[test]
fn operators() {
let toks = kinds("a <<< b === c !== d <= e");
let texts: Vec<&str> = toks.iter().map(|(_, t)| t.as_str()).collect();
assert!(texts.contains(&"<<<"));
assert!(texts.contains(&"==="));
assert!(texts.contains(&"!=="));
assert!(texts.contains(&"<="));
}
// ------------------------------------------------------------------
// TODO §63.2 QA: the fused attach phase, attacked
//
// These cover the shapes the two-phase code (a `Vec<RawTok>` fully
// built, then walked) could tell apart from the fused one-pass code
// (each raw token attached as it is produced) if the fusion were not a
// pure reordering: a comment with no token before it at all, comments
// that never see a "previous token" until much later, EOF immediately
// after a trailing comment, and so on. Every one of these was also
// cross-checked, file for file, against `tokenize` built from 1b8723c
// (the pre-fusion tree) with a throwaway digest tool in the QA
// scratchpad — token-for-token identical, hash and manual `Debug`
// inspection alike; the assertions below pin that result durably.
// ------------------------------------------------------------------
#[test]
fn a_comment_as_the_very_first_thing_in_the_file_is_the_first_token_s_leading() {
let toks = tokenize("// only thing before the module\nmodule m;\nendmodule").unwrap();
assert_eq!(toks[0].leading.len(), 1);
assert_eq!(toks[0].leading[0].text, "// only thing before the module");
assert!(!toks[0].leading[0].blank_before);
}
#[test]
fn two_comments_on_the_first_line_before_any_token_both_lead_it() {
// Two *separate* comments here means two lines, each its own line
// comment (a line comment always runs to end of line, so "two
// comments on one line" before any token is only possible with
// block comments — covered by `two_block_comments_on_one_line_merge`
// below).
let toks = tokenize("// one\n// two\nmodule m;\nendmodule").unwrap();
assert_eq!(toks[0].leading.len(), 2);
assert_eq!(toks[0].leading[0].text, "// one");
assert_eq!(toks[0].leading[1].text, "// two");
assert!(!toks[0].leading[1].blank_before);
}
#[test]
fn a_trailing_comment_after_the_last_real_token_reaches_eof() {
let toks = tokenize("module m;\nendmodule // trailing at eof\n").unwrap();
let end = toks.iter().find(|t| t.is_kw("endmodule")).unwrap();
let trailing = end.trailing.as_ref().expect("trailing comment on endmodule");
assert_eq!(trailing.text, "// trailing at eof");
assert_eq!(toks.last().unwrap().kind, TokenKind::Eof);
}
#[test]
fn two_block_comments_on_one_line_merge_into_one_trailing_comment() {
let toks = tokenize("wire w; /* one */ /* two */\nendmodule").unwrap();
let semi = toks.iter().find(|t| t.is_sym(";")).unwrap();
let trailing = semi.trailing.as_ref().expect("merged trailing comment");
assert_eq!(trailing.text, "/* one */ /* two */");
}
#[test]
fn a_blank_line_between_a_comment_and_its_token_marks_both() {
let toks = tokenize("// lead\n\nmodule m;\nendmodule").unwrap();
assert_eq!(toks[0].leading.len(), 1);
// The comment itself is not blank-separated from what came before it
// (nothing did); the blank line sits between the comment and the
// token, so the *token* carries the flag.
assert!(!toks[0].leading[0].blank_before);
assert!(toks[0].blank_before);
}
#[test]
fn crlf_line_endings_lex_like_lf_with_the_same_comment_attachment() {
let toks = tokenize("module m; // c\r\nendmodule\r\n").unwrap();
let semi = toks.iter().find(|t| t.is_sym(";")).unwrap();
assert_eq!(semi.trailing.as_ref().unwrap().text, "// c");
let end = toks.iter().find(|t| t.is_kw("endmodule")).unwrap();
assert_eq!(end.line, 2);
}
#[test]
fn a_block_comment_spanning_lines_still_leads_a_same_line_token() {
let toks = tokenize("/* block\n spanning\n lines */ module m;\nendmodule").unwrap();
assert_eq!(toks[0].leading.len(), 1);
assert!(toks[0].leading[0].text.starts_with("/* block"));
assert!(toks[0].leading[0].text.ends_with("lines */"));
// The module keyword itself sits on the block comment's last line.
assert_eq!(toks[0].line, 3);
}
#[test]
fn a_comment_between_a_macro_invocation_and_its_arguments_trails_the_macro() {
let toks = tokenize("module m;\n`MYMACRO /*c*/ (a, b);\nendmodule").unwrap();
let mac = toks.iter().find(|t| t.text == "`MYMACRO").unwrap();
assert_eq!(mac.trailing.as_ref().unwrap().text, "/*c*/");
// The macro call's parenthesized arguments are unaffected — still
// ordinary tokens right after, comment or not.
let open_paren_idx = toks.iter().position(|t| t.is_sym("(")).unwrap();
assert_eq!(toks[open_paren_idx + 1].text, "a");
}
#[test]
fn a_file_that_is_only_comments_attaches_them_all_to_the_synthetic_eof() {
let toks = tokenize("// only a comment, nothing else\n").unwrap();
assert_eq!(toks.len(), 1);
assert_eq!(toks[0].kind, TokenKind::Eof);
assert_eq!(toks[0].leading.len(), 1);
assert_eq!(toks[0].leading[0].text, "// only a comment, nothing else");
}
#[test]
fn an_empty_file_lexes_to_a_lone_eof_with_no_comments() {
let toks = tokenize("").unwrap();
assert_eq!(toks.len(), 1);
assert_eq!(toks[0].kind, TokenKind::Eof);
assert!(toks[0].leading.is_empty());
}
// ------------------------------------------------------------------
// TODO §63.2 QA: the operator table's first-byte test
// ------------------------------------------------------------------
#[test]
fn every_operator_s_first_byte_is_a_single_ascii_byte() {
// `op.as_bytes()[0] != c` compares one byte of `c: u8` against the
// table entry's first *byte*. If any entry's first character were
// multi-byte UTF-8, its first byte alone would not identify it and
// the guard could reject a spelling it should have let through. Every
// entry here is pure ASCII punctuation, so the byte comparison is the
// whole character.
for op in OPERATORS {
let first = op.chars().next().expect("no empty operator spellings");
assert!(first.is_ascii(), "{op:?} does not start with an ASCII byte");
assert_eq!(
op.as_bytes()[0],
first as u8,
"{op:?}'s first byte does not match its first char"
);
}
}
#[test]
fn the_operator_table_has_no_duplicate_or_empty_entries() {
// A duplicate wastes a comparison; an empty entry would make
// `op.as_bytes()[0]` panic before ever reaching `starts_with`.
for op in OPERATORS {
assert!(!op.is_empty());
}
let mut sorted = OPERATORS.to_vec();
sorted.sort_unstable();
sorted.dedup();
assert_eq!(sorted.len(), OPERATORS.len(), "OPERATORS has a duplicate entry");
}
#[test]
fn every_operator_followed_by_every_other_operator_still_lexes_without_a_gap() {
// The first-byte test must not change *which* entry `starts_with`
// picks — only how many entries are tried before it does. Lexing
// every `op1 op2` concatenation (no space) and requiring the token
// stream to account for every byte with no lex error is the
// regression gate: a wrong short-circuit would either misplace the
// split point or leave a byte unconsumed. Cross-checked pair for
// pair against `tokenize` built from 1b8723c (pre-first-byte-test)
// in the QA scratchpad: 1 764 pairs, 0 differ.
for &op1 in OPERATORS {
for &op2 in OPERATORS {
let src = format!("{op1}{op2} ;");
let toks = tokenize(&src)
.unwrap_or_else(|e| panic!("lexing {op1:?} followed by {op2:?} failed: {e}"));
// Everything up to the space must be Symbol tokens whose
// texts concatenate back to exactly op1 followed by op2,
// with no gap and no overlap.
let mut consumed = String::new();
let mut i = 0;
while toks[i].kind == TokenKind::Symbol && toks[i].text != ";" {
consumed.push_str(&toks[i].text);
i += 1;
}
assert_eq!(
consumed,
format!("{op1}{op2}"),
"{op1:?} followed by {op2:?} did not round-trip"
);
}
}
}
}