Files
lucisv/crates/vlog_parser/src/lexer.rs
T
lucioandClaude Fable 5 9f1a6cf1d2 Fix six formatter bugs; case table grows to 200 with zero skips
All five briefed bugs fixed, plus a sixth found during the work:

1. Block-comment continuation drift: token::Comment gained line/col;
   continuation lines are dedented by the comment's original column
   before re-indenting, making reformatting a true fixed point while
   preserving the author's relative indentation inside the comment.
2. Comments inside expression groups (concat, parens, call args,
   assignment patterns, binary operands) now force the group to break
   instead of being lifted out.
3. Closing block labels preserved for end/join*/endfunction/endtask/
   endpackage, matching endmodule.
4. Multi-instance declarations fit on one line when they fit and
   indent their continuations when they break.
5. @( /* c */ * ) keeps its comments (SensList::Star before/after).
6. Multi-line `define/attribute bodies no longer drift (RawText.col).

verify.rs comparison logic untouched (diagnostic positions only) —
QA audited the diff to confirm the safety net was not weakened.
All four #SKIP cases un-skipped verbatim as spec; 17 cases added
(183 -> 200, 0 skipped). QA triple-formatted 204 inputs with zero
regressions. Clippy is now fully silent workspace-wide.

Remaining comment-placement refusals (4) and a pre-existing @(* )
lexer limitation are documented as open items, not hacked around.

Dev: Opus agent; QA: Sonnet agent; review in
docs/features/formatter-bug-fixes/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-19 00:15:50 -07:00

683 lines
22 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::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,
/// 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"+-*/%&|^~!<>=?:;,.#@()[]{}'$";
impl<'a> RawLexer<'a> {
fn new(src: &'a [u8]) -> Self {
RawLexer { src, pos: 0, line: 1, col: 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()
}
/// 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,
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();
return Ok(RawTok { kind: RawKind::LineComment, text, line, col, newlines_before });
}
if c == b'/' && self.peek_at(1) == b'*' {
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();
break;
}
self.bump();
}
let text = self.text_from(start);
return Ok(RawTok { kind: RawKind::BlockComment, text, line, col, newlines_before });
}
// Compiler directives: capture through end of line, honoring `\`
// continuations (used by `define).
if c == b'`' {
while self.pos < self.src.len() && self.peek() != b'\n' {
// Stop before a trailing comment on the same line.
if self.peek() == b'/' && (self.peek_at(1) == b'/' || self.peek_at(1) == b'*') {
break;
}
self.bump();
}
// Line continuation: `define FOO \ <next line>
while self.text_ends_with_continuation(start) && self.peek() == b'\n' {
self.bump();
while self.pos < self.src.len() && self.peek() != b'\n' {
self.bump();
}
}
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) {
return Ok(RawTok {
kind: RawKind::Real(TokenKind::Directive),
text,
line,
col,
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 parens.
if self.peek() == b'(' {
let mut depth = 0usize;
loop {
if self.pos >= self.src.len() {
return Err(self.error("unterminated macro call".to_string()));
}
let ch = self.bump();
if ch == b'(' {
depth += 1;
} else if ch == b')' {
depth -= 1;
if depth == 0 {
break;
}
}
}
}
let text = self.text_from(start);
return Ok(RawTok {
kind: RawKind::Real(TokenKind::Ident),
text,
line,
col,
newlines_before,
});
}
// Attribute instance `(* ... *)`.
if c == b'(' && self.peek_at(1) == b'*' && self.peek_at(2) != b')' {
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,
newlines_before,
});
}
// String literal.
if c == b'"' {
self.bump();
loop {
if self.pos >= self.src.len() {
return Err(self.error("unterminated string literal".to_string()));
}
match self.bump() {
b'\\' => {
self.bump();
}
b'"' => break,
_ => {}
}
}
let text = self.text_from(start);
return Ok(RawTok {
kind: RawKind::Real(TokenKind::String),
text,
line,
col,
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,
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,
newlines_before,
});
}
// Number literals.
if c.is_ascii_digit() {
let text = self.lex_number()?;
return Ok(RawTok {
kind: RawKind::Real(TokenKind::Number),
text,
line,
col,
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,
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 };
return Ok(RawTok { kind: RawKind::Real(kind), text, line, col, newlines_before });
}
// Operators, longest match first.
for op in OPERATORS {
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,
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,
newlines_before,
});
}
Err(self.error(format!("unexpected character {:?}", c as char)))
}
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);
// 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)
}
}
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.
fn is_line_directive(word: &str) -> bool {
matches!(
word,
"define"
| "undef"
| "undefineall"
| "ifdef"
| "ifndef"
| "elsif"
| "else"
| "endif"
| "include"
| "timescale"
| "default_nettype"
| "resetall"
| "celldefine"
| "endcelldefine"
| "line"
| "pragma"
| "unconnected_drive"
| "nounconnected_drive"
| "begin_keywords"
| "end_keywords"
)
}
/// Tokenize source text, attaching comments and blank-line info to tokens.
pub fn tokenize(source: &str) -> Result<Vec<Token>, LexError> {
let mut raw_lexer = RawLexer::new(source.as_bytes());
let mut raws: Vec<RawTok> = Vec::new();
loop {
let tok = raw_lexer.next_raw()?;
let is_eof = tok.kind == RawKind::Real(TokenKind::Eof);
raws.push(tok);
if is_eof {
break;
}
}
// Attachment phase.
let mut tokens: Vec<Token> = Vec::new();
let mut pending: Vec<Comment> = Vec::new();
let mut pending_blank = false;
for raw in raws {
match raw.kind {
RawKind::LineComment | RawKind::BlockComment => {
let same_line_as_prev =
raw.newlines_before == 0 && !tokens.is_empty() && pending.is_empty();
let comment = Comment {
text: raw.text,
blank_before: raw.newlines_before > 1 || pending_blank,
line: raw.line,
col: raw.col,
};
if same_line_as_prev {
// Trailing comment for the previous real token.
let prev = tokens.last_mut().unwrap();
match &mut prev.trailing {
Some(existing) => {
existing.text.push(' ');
existing.text.push_str(&comment.text);
}
None => prev.trailing = Some(comment),
}
} else {
pending.push(comment);
pending_blank = false;
}
}
RawKind::Real(kind) => {
let blank_before = if pending.is_empty() {
raw.newlines_before > 1
} else {
// 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.
raw.newlines_before > 1
};
tokens.push(Token {
kind,
text: raw.text,
line: raw.line,
col: raw.col,
leading: std::mem::take(&mut pending),
trailing: None,
blank_before,
});
}
}
}
Ok(tokens)
}
#[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));
}
#[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 attributes() {
let toks = kinds("(* keep = \"true\" *) wire w;");
assert_eq!(toks[0].0, TokenKind::Attribute);
}
#[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(&"<="));
}
}