Files
lucisv/crates/vlog_parser/src/token.rs
T
lucioandClaude Fable 5 d8e37086df Refactoring M5: keyword + project-wide identifier completion; v0.3.0
Five completion tiers in one response: module skeletons (M4, unchanged
gate), scope-visible symbols with real kinds, workspace-index names and
`define macros (backtick-aware, never inventing punctuation), Verilog/SV
keywords (single-source KEYWORDS list factored from the lexer's table,
lexing unchanged), and token-harvested project words — comments and
strings contribute nothing and get no completions. Candidate tables build
with the index over the M1 scope ladder (94 ms / 860 files, ~1.4 MiB);
a keystroke answers in ~300 µs, budget-tested. Version 0.3.0 across the
workspace and extension, CHANGELOG covers the M1-M5 refactoring layer.

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

347 lines
8.8 KiB
Rust

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