//! The `` `define`` table: every macro definition a file writes, recorded so //! an editor can show it. //! //! This is bookkeeping, not preprocessing. Nothing here expands a macro and //! the formatter never calls it, so TODO.md §7's "no preprocessor expansion" //! non-goal stands. It is a pure post-lex pass: a `` `define`` already arrives //! as one [`TokenKind::Directive`] token carrying its whole text and span, so //! the table is read off the token stream a second time and the lexer needs no //! change at all. See `docs/features/define-table/README.md`. use crate::span::TextRange; use crate::token::{Token, TokenKind}; /// What a recorded directive did to a macro name. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DefineKind { /// `` `define NAME ... `` Define, /// `` `undef NAME `` — recorded so that a later position-aware lookup can /// see where a name stopped being defined. Nothing resolves it yet. Undef, } /// One `` `define`` or `` `undef`` directive, as written. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Define { /// Whether this entry defines the name or undefines it. pub kind: DefineKind, /// The macro name, without the leading backtick. pub name: String, /// `None` for an object-like macro, `Some` for a function-like one: one /// entry per parameter as written, edges trimmed (`"a"`, `"b = 8"`). /// `` `define NAME() `` gives `Some(vec![])`. Always `None` for an /// [`DefineKind::Undef`] entry. pub params: Option>, /// The replacement text, line continuations joined (see /// [`join_continuations`]). Empty for a body-less `` `define`` and for /// every `` `undef``. pub body: String, /// Extent of the whole directive: the backtick through the last byte the /// lexer kept. pub span: TextRange, /// Extent of the name alone, so an editor can highlight exactly it. pub name_span: TextRange, } /// Every `` `define``/`` `undef`` in one file, in source order. /// /// Redefinition is legal Verilog, so a name can have several definitions; they /// are all kept and [`DefineTable::latest`] picks the last one. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct DefineTable { entries: Vec, } impl DefineTable { /// A table from entries that are already known, in source order. /// /// The inverse of [`DefineTable::entries`], for the one caller that has a /// file's directives without the file's tokens: the workspace index's /// persistent cache, which stores what a parse found and restores it /// (`docs/features/index-persistence/README.md`). Nothing is re-derived /// here — `collect_defines` is still the only thing that *reads* a table /// out of a file. pub fn from_entries(entries: Vec) -> DefineTable { DefineTable { entries } } /// Every recorded directive, `` `undef``s included, in source order. pub fn entries(&self) -> &[Define] { &self.entries } /// Every definition of `name`, in source order. `` `undef`` entries are /// not definitions and are not returned. pub fn all(&self, name: &str) -> Vec<&Define> { self.entries.iter().filter(|d| d.kind == DefineKind::Define && d.name == name).collect() } /// The last definition of `name` in the file, or `None` if it has none. pub fn latest(&self, name: &str) -> Option<&Define> { self.entries.iter().rev().find(|d| d.kind == DefineKind::Define && d.name == name) } } /// Read the `` `define``/`` `undef`` table off an already-lexed token stream. /// /// Never fails: a directive too malformed to read a name out of is skipped, /// because an editor asking for hover text must not be told the file is /// broken. pub fn collect_defines(tokens: &[Token]) -> DefineTable { let mut entries = Vec::new(); for tok in tokens { if tok.kind != TokenKind::Directive { continue; } match directive_word(&tok.text) { "define" => entries.extend(parse_define(tok)), "undef" => entries.extend(parse_undef(tok)), _ => {} } } DefineTable { entries } } /// The directive's keyword: `` `define FOO `` → `define`. Matching on the /// whole word rather than a prefix is what keeps `` `undefineall`` out of the /// `` `undef`` arm. fn directive_word(text: &str) -> &str { let rest = text.strip_prefix('`').unwrap_or(text); let end = rest.find(|c: char| !is_name_char(c)).unwrap_or(rest.len()); rest.get(..end).unwrap_or("") } fn parse_define(tok: &Token) -> Option { let text = &tok.text; let after_keyword = 1 + directive_word(text).len(); let name_start = skip_separators(text, after_keyword); let (name, name_end) = read_name(text, name_start)?; // A parameter list counts only when its `(` touches the name (LRM 22.5.1): // `` `define A (x) `` is an object-like macro whose body starts with `(`. // An unbalanced list is not an error either — the text is recorded as an // object-like body rather than dropped. let (params, body_start) = match text.as_bytes().get(name_end) { Some(b'(') => match read_params(text, name_end) { Some((params, after)) => (Some(params), after), None => (None, name_end), }, _ => (None, name_end), }; Some(Define { kind: DefineKind::Define, name: name.to_string(), params, body: join_continuations(text.get(body_start..).unwrap_or("")).trim().to_string(), span: tok.span, name_span: sub_span(tok, name_start, name_end), }) } fn parse_undef(tok: &Token) -> Option { let text = &tok.text; let name_start = skip_separators(text, 1 + directive_word(text).len()); let (name, name_end) = read_name(text, name_start)?; Some(Define { kind: DefineKind::Undef, name: name.to_string(), params: None, body: String::new(), span: tok.span, name_span: sub_span(tok, name_start, name_end), }) } /// A range inside the directive's own text, translated to source offsets. /// /// Sound because a `Directive` token's text *is* its source slice: the lexer /// only trims its end, and gives the token the span of what it kept /// (`docs/features/spans/README.md`). fn sub_span(tok: &Token, start: usize, end: usize) -> TextRange { let base = tok.span.start; TextRange::new(base + start as u32, base + end as u32) } /// Skip the whitespace between a directive's words, line continuations /// included: a `\` before a newline joins two lines, it is not text. fn skip_separators(text: &str, mut i: usize) -> usize { let b = text.as_bytes(); while i < b.len() { match b[i] { b' ' | b'\t' | b'\r' | b'\n' => i += 1, b'\\' => match continuation_len(b, i) { Some(n) => i += n, None => break, }, _ => break, } } i } /// The macro name starting at `start`, and the offset just past it. fn read_name(text: &str, start: usize) -> Option<(&str, usize)> { let b = text.as_bytes(); let mut end = start; while end < b.len() && is_name_byte(b[end]) { end += 1; } if end == start { None } else { text.get(start..end).map(|name| (name, end)) } } /// Split a function-like macro's parameter list. `start` is its `(`; the /// result is the parameters as written and the offset just past the `)`. /// `None` when the list never closes. fn read_params(text: &str, start: usize) -> Option<(Vec, usize)> { let b = text.as_bytes(); let mut depth = 0usize; let mut piece_start = start + 1; let mut params: Vec = Vec::new(); let mut i = start; while i < b.len() { match b[i] { // A default value may hold a string, and a string may hold a // comma or a bracket. b'"' => { i = skip_string(b, i); continue; } b'(' | b'[' | b'{' => depth += 1, b')' | b']' | b'}' => { depth = depth.saturating_sub(1); if depth == 0 { let piece = text.get(piece_start..i).unwrap_or(""); // `NAME()` is a function-like macro with no parameters, // not one empty parameter. if !(params.is_empty() && piece.trim().is_empty()) { params.push(normalize_param(piece)); } return Some((params, i + 1)); } } b',' if depth == 1 => { params.push(normalize_param(text.get(piece_start..i).unwrap_or(""))); piece_start = i + 1; } _ => {} } i += 1; } None } fn normalize_param(piece: &str) -> String { join_continuations(piece).trim().to_string() } /// Join a directive's continued lines the way a preprocessor does: a `\` that /// ends a line is not part of the macro text, and neither is the newline it /// ends. /// /// Nothing else is touched — in particular the indentation of a continued line /// is kept byte for byte, because inside a string literal that whitespace is /// the value, not layout. So a three-line body becomes one line whose pieces /// are separated by exactly the spaces that were written around the joins. fn join_continuations(text: &str) -> String { let b = text.as_bytes(); let mut out = String::with_capacity(text.len()); let mut copied = 0; let mut i = 0; while i < b.len() { match continuation_len(b, i) { Some(n) => { out.push_str(text.get(copied..i).unwrap_or("")); i += n; copied = i; } None => i += 1, } } out.push_str(text.get(copied..).unwrap_or("")); out } /// The length of a line continuation starting at `i` — the `\`, the /// horizontal whitespace after it and the newline — or `None` when this /// backslash is ordinary text. /// /// Horizontal whitespace is allowed between the two because the lexer allows /// it when it decides to keep reading (`text_ends_with_continuation`); the two /// must agree or a stray `\` would survive into a body. fn continuation_len(b: &[u8], i: usize) -> Option { if b.get(i) != Some(&b'\\') { return None; } let mut j = i + 1; while matches!(b.get(j), Some(b' ' | b'\t' | b'\r')) { j += 1; } if b.get(j) == Some(&b'\n') { Some(j + 1 - i) } else { None } } /// The offset just past the string literal starting at `start`, or the end of /// the text if it never closes. fn skip_string(b: &[u8], start: usize) -> usize { let mut i = start + 1; while i < b.len() { match b[i] { b'\\' => i += 2, b'"' => return i + 1, _ => i += 1, } } b.len() } fn is_name_byte(c: u8) -> bool { c == b'_' || c == b'$' || c.is_ascii_alphanumeric() } fn is_name_char(c: char) -> bool { c == '_' || c == '$' || c.is_ascii_alphanumeric() }