Files
lucisv/crates/vlog_parser/src/lexer.rs
T
lucioandClaude Fable 5 f52beff48f Add item-misc: spaced macro calls, line-aware macro items, `error, elab tasks
Macro invocations with whitespace before the argument list, a bare macro on its own line followed by a declaration, `error/`warning directives, and $error/$fatal/$warning/$info as module/generate items.

Coverage loop round 1, cluster 1: 636 -> 661 / 820 (77.6% -> 80.6%).
Feature README: docs/features/item-misc/README.md

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-20 22:54:47 -07:00

999 lines
36 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'`' {
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' {
// 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.
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,
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);
// 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.
///
/// 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"
)
}
/// 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,
span: raw.span,
};
if same_line_as_prev {
// Trailing comment for the previous real token.
let prev = tokens.last_mut().unwrap();
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),
}
} 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,
span: raw.span,
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 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 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));
}
#[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(&"<="));
}
}