Add class-semantics and lexer-cleanup (round 20)
class-semantics: classes are first-class in vlog_semantic -- class
scopes and symbols, member/method/prototype binding, this.x
(nearest-class-only), super.x, cls::x with lexical unit heads,
out-of-body cls::method bound into the class's scope with the extern
prototype as the definition (rule 10), and the honest
InheritedCandidate{base, paths} shape: a member miss in an extending
class records what the unknown base might supply (import paths
included) and is never chased, not even in-file -- the future
inheritance round's worklist, measured at 1303 candidates. Unit-name
misses stay ExternalCandidate (QA-found, lead-ruled: bases supply
members, not package names; +170 recovered navigations, pinned).
Workspace index gains classes as units (246) and their members
(11399). scan.rs migrated to parser name-spans: 26 call sites down
to the 2 documented consumers. 114044 spans, 0 unplaced, 0 panics;
UVM code now has hover/definition/references/outline.
lexer-cleanup: the three filed gaps -- @(* ) lexes via a
starts_attribute backoff (an attribute cannot begin with `)`; real
attributes pinned, no misfire on legal expressions), a leading BOM
is accepted as a named losslessness exception (mid-file BOM errors
clearly; 20k-case position fuzz clean), and non-ASCII lex errors now
decode the full character AND surface through vfmt check's error
slot (exit 2, matching format, text-rule findings still reported --
the silent-pass hole closed). The macro space-before-paren item is
parked with a QA-hardened analysis: the reading depends on a
definition vfmt cannot see, any fixed answer is provably wrong for
one population, and today's behavior fails safe.
827 workspace tests. Dev: 2 Fable agents; QA: 2 Opus agents; reviews
in docs/features/{class-semantics,lexer-cleanup}/README.md.
Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
da1448ecd0
commit
54b0ca3896
27 files changed
+2825
-231
No files matched your search
@@ -30,10 +30,12 @@ Legend: **[V]** = practice from Verible, **[R]** = from ruff, **[V+R]** = both.
|
||||
- [x] **[R] Panic containment.** ruff catches panics per-file and reports
|
||||
them as errors instead of killing the whole run. Wrap per-file work in
|
||||
`crates/vfmt/src/main.rs` with `std::panic::catch_unwind`.
|
||||
- [ ] **`@(* )` fails to lex** (bug-fix QA find): `(*` followed by anything
|
||||
- [x] **`@(* )` fails to lex** (bug-fix QA find): `(*` followed by anything
|
||||
but `)` is unconditionally lexed as an attribute (`lexer.rs`), so a bare
|
||||
space inside `@( * )`-style spellings errors out. Make the attribute
|
||||
scan back off when the contents are just `*`.
|
||||
→ `docs/features/lexer-cleanup/README.md`, with the BOM and non-ASCII
|
||||
message fixes and the `vfmt check` lex-error silence fix.
|
||||
- [x] **Recursion-depth limit in the parser.** Found by cli-polish QA:
|
||||
~150 levels of expression nesting overflow the stack and abort the whole
|
||||
process — uncatchable by `catch_unwind`, so mid-batch files after the
|
||||
@@ -378,6 +380,16 @@ later:
|
||||
simplifications and the corpus baseline (79.5% of uses resolved in-file on
|
||||
cleanly-parsed corpus files, 19.6% external, 0.9% unresolved) in
|
||||
`docs/features/vlog-semantic/README.md`.
|
||||
→ The crate's biggest named gap — "no name declared inside a class body
|
||||
is indexed, hovered or navigable" (the classes round's handshake) — has
|
||||
since closed: `docs/features/class-semantics/README.md` binds classes
|
||||
(`SymbolKind::Class`, `ScopeKind::Class`, members, `extends`,
|
||||
`this`/`super`, out-of-body methods, the honest
|
||||
`Resolution::InheritedCandidate` for what only a base class could
|
||||
supply), indexes classes and their members in the workspace layer, and
|
||||
grows the corpus tables by +4 232 symbols / +16 631 references (clean
|
||||
files: 74.0 % in-file, 17.9 % external, 7.1 % inherited, 1.0 %
|
||||
unresolved, 0 unplaced).
|
||||
- [x] **`` `define`` table for hover expansion.** Record every
|
||||
`` `define`` (name, params, body text, source span) during lexing
|
||||
instead of treating it as fully opaque — no expansion during
|
||||
|
||||
+27
-15
@@ -31,12 +31,14 @@ struct Report {
|
||||
violations: Vec<Violation>,
|
||||
/// Violations whose fix was applied and written back.
|
||||
fixed: usize,
|
||||
/// Set when the file could not be read or written; nothing was changed.
|
||||
/// Set when the file could not be fully checked: unreadable, unwritable,
|
||||
/// or — because the lexer is all-or-nothing — unlexable, in which case
|
||||
/// only the text-level rules saw it.
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
/// Lints every gathered file and reports. Exit 1 if anything is left over,
|
||||
/// 2 if a file could not be read or written.
|
||||
/// 2 if a file could not be read, written, or lexed.
|
||||
pub fn check_files(
|
||||
opts: &Options,
|
||||
jobs: &[(PathBuf, Config)],
|
||||
@@ -61,11 +63,11 @@ pub fn check_stdin(
|
||||
) -> ExitCode {
|
||||
let name = opts.stdin_filename.clone().unwrap_or_else(|| "<stdin>".to_string());
|
||||
let path = opts.stdin_filename.as_ref().map(PathBuf::from);
|
||||
let violations = run_rules(src, path, config, rules);
|
||||
let (violations, lex_error) = run_rules(src, path, config, rules);
|
||||
// Nothing is ever written back for stdin, so `--fix` has nothing to do
|
||||
// here; the violations are reported as they are.
|
||||
let report =
|
||||
Report { path: name, index: LineIndex::new(src), violations, fixed: 0, error: None };
|
||||
let error = lex_error.map(|e| format!("{name}: {e}"));
|
||||
let report = Report { path: name, index: LineIndex::new(src), violations, fixed: 0, error };
|
||||
finish(opts, vec![report])
|
||||
}
|
||||
|
||||
@@ -88,10 +90,11 @@ fn check_one(file: &Path, config: &Config, opts: &Options, rules: &[&'static dyn
|
||||
if opts.fix {
|
||||
fix_source(&src, file, config, opts, rules)
|
||||
} else {
|
||||
(run_rules(&src, Some(file.to_path_buf()), config, rules), None, 0)
|
||||
let (violations, lex_error) = run_rules(&src, Some(file.to_path_buf()), config, rules);
|
||||
(violations, None, 0, lex_error)
|
||||
}
|
||||
});
|
||||
let (violations, rewritten, fixed) = match outcome {
|
||||
let (violations, rewritten, fixed, lex_error) = match outcome {
|
||||
Ok(outcome) => outcome,
|
||||
Err(msg) => return failed(format!("{path}: panicked while linting: {msg}")),
|
||||
};
|
||||
@@ -101,26 +104,35 @@ fn check_one(file: &Path, config: &Config, opts: &Options, rules: &[&'static dyn
|
||||
return failed(format!("{path}: {e}"));
|
||||
}
|
||||
}
|
||||
Report { path, index, violations, fixed, error: None }
|
||||
// A file that does not lex still gets its text-level findings — those
|
||||
// rules ran — but every token- and AST-level rule silently saw nothing,
|
||||
// so the file must not pass as checked. It is an error (exit 2), exactly
|
||||
// as `vfmt format` treats the same file.
|
||||
let error = lex_error.map(|e| format!("{path}: {e}"));
|
||||
Report { path, index, violations, fixed, error }
|
||||
}
|
||||
|
||||
/// Runs the rules over one text.
|
||||
/// Runs the rules over one text. The second half of the answer is the lex
|
||||
/// error when the text does not lex — rendered `line:col: message`, ready
|
||||
/// for a path prefix — because a file with no tokens was only text-linted
|
||||
/// and must be reported as an error, not passed off as clean.
|
||||
fn run_rules(
|
||||
src: &str,
|
||||
path: Option<PathBuf>,
|
||||
config: &Config,
|
||||
rules: &[&'static dyn Rule],
|
||||
) -> Vec<Violation> {
|
||||
) -> (Vec<Violation>, Option<String>) {
|
||||
// One parse per file (TODO §4): the products are built here, once, and
|
||||
// lent to the context. Under `--fix` each *round* re-enters through this
|
||||
// function with rewritten text — that re-parse is inherent (the old
|
||||
// products describe text that no longer exists), so only the first round
|
||||
// saves a parse; a plain `vfmt check` always does.
|
||||
let parsed = ParsedSource::parse(src);
|
||||
let lex_error = parsed.lex_error().map(|e| format!("lex error: {e}"));
|
||||
// The indent width the formatter would use is also the width a tab
|
||||
// expands to, so `--indent 4` fixes tabs into four spaces.
|
||||
let ctx = parsed.context(path).with_tab_width(config.indent_width);
|
||||
lint(&ctx, rules)
|
||||
(lint(&ctx, rules), lex_error)
|
||||
}
|
||||
|
||||
/// The violations whose fix may be applied: everything except a fix that
|
||||
@@ -162,10 +174,10 @@ fn fix_source(
|
||||
config: &Config,
|
||||
opts: &Options,
|
||||
rules: &[&'static dyn Rule],
|
||||
) -> (Vec<Violation>, Option<String>, usize) {
|
||||
) -> (Vec<Violation>, Option<String>, usize, Option<String>) {
|
||||
let mut text = src.to_string();
|
||||
let mut fixed = 0;
|
||||
let mut violations = run_rules(&text, Some(file.to_path_buf()), config, rules);
|
||||
let (mut violations, mut lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules);
|
||||
for _ in 0..MAX_FIX_ROUNDS {
|
||||
let round =
|
||||
apply_fixes(&text, &fixable_outside_fences(&text, &violations), opts.unsafe_fixes);
|
||||
@@ -174,10 +186,10 @@ fn fix_source(
|
||||
}
|
||||
fixed += round.applied;
|
||||
text = round.output;
|
||||
violations = run_rules(&text, Some(file.to_path_buf()), config, rules);
|
||||
(violations, lex_error) = run_rules(&text, Some(file.to_path_buf()), config, rules);
|
||||
}
|
||||
let rewritten = (text != src).then_some(text);
|
||||
(violations, rewritten, fixed)
|
||||
(violations, rewritten, fixed, lex_error)
|
||||
}
|
||||
|
||||
/// Prints the run and turns it into an exit code.
|
||||
|
||||
@@ -808,6 +808,45 @@ fn check_fix_leaves_unfixable_findings_reported() {
|
||||
assert!(stdout(&out).contains("[module-filename]"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_reports_a_file_that_does_not_lex_instead_of_passing_it() {
|
||||
// A non-ASCII identifier fails to lex, so token- and AST-level rules see
|
||||
// nothing. That must be a loud error (exit 2), never a silent exit 0 —
|
||||
// the file was not actually checked.
|
||||
let dir = TempDir::new("check-nolex");
|
||||
let path = dir.write("bad.sv", "module bad;\n parameter int élan = 1;\nendmodule\n");
|
||||
|
||||
let out = run(&["check", &path]);
|
||||
assert_eq!(code(&out), 2, "a file that does not lex is an error: {}", stderr(&out));
|
||||
let err = stderr(&out);
|
||||
assert!(err.contains("lex error"), "{err}");
|
||||
assert!(err.contains("character 'é' (U+00E9) is not valid in Verilog source"), "{err}");
|
||||
assert!(err.contains("2:17"), "the position names the character: {err}");
|
||||
assert!(err.contains("could not be checked"), "{err}");
|
||||
|
||||
// Text-level findings on the same file are still reported alongside.
|
||||
dir.write("bad.sv", "module bad;\n\tparameter int élan = 1;\nendmodule\n");
|
||||
let out = run(&["check", "--select", "no-tabs", &path]);
|
||||
assert_eq!(code(&out), 2, "the error outranks the violation exit");
|
||||
assert!(stdout(&out).contains("[no-tabs]"), "{}", stdout(&out));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bom_prefixed_file_formats_and_checks_like_a_plain_one() {
|
||||
// The BOM is accepted like leading whitespace and not preserved: the
|
||||
// formatter writes the file back without it.
|
||||
let dir = TempDir::new("bom");
|
||||
let path = dir.write("m.sv", "\u{feff}module m;endmodule\n");
|
||||
|
||||
let out = run(&["check", &path]);
|
||||
assert_eq!(code(&out), 0, "a BOM'd file checks clean: {}", stderr(&out));
|
||||
assert_eq!(stdout(&out), "", "{}", stdout(&out));
|
||||
|
||||
let out = run(&["format", &path]);
|
||||
assert_eq!(code(&out), 0, "{}", stderr(&out));
|
||||
assert_eq!(dir.read("m.sv"), FORMATTED, "formatted, BOM dropped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_select_and_ignore_pick_the_rule_set() {
|
||||
let dir = TempDir::new("check-select");
|
||||
|
||||
@@ -25,6 +25,7 @@ pub fn kind_label(kind: SymbolKind) -> &'static str {
|
||||
SymbolKind::Instance => "instance",
|
||||
SymbolKind::Block => "block",
|
||||
SymbolKind::StructMember => "struct member",
|
||||
SymbolKind::Class => "class",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,6 +45,7 @@ pub fn lsp_kind(kind: SymbolKind) -> LspKind {
|
||||
SymbolKind::Instance => LspKind::OBJECT,
|
||||
SymbolKind::Block => LspKind::MODULE,
|
||||
SymbolKind::StructMember => LspKind::FIELD,
|
||||
SymbolKind::Class => LspKind::CLASS,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -146,7 +146,7 @@ fn identifier_type(offset: u32, semantics: &Semantics) -> Highlight {
|
||||
|
||||
fn symbol_type(kind: SymbolKind) -> Highlight {
|
||||
match kind {
|
||||
SymbolKind::Module => Highlight::Class,
|
||||
SymbolKind::Module | SymbolKind::Class => Highlight::Class,
|
||||
SymbolKind::Package => Highlight::Namespace,
|
||||
SymbolKind::Typedef => Highlight::Type,
|
||||
SymbolKind::EnumVariant => Highlight::EnumMember,
|
||||
|
||||
@@ -197,8 +197,9 @@ fn lex_stream(source: &str, side: Side) -> Result<Vec<Item>, VerificationError>
|
||||
/// Rewrite `@ ( * )` to `@ *` so the two spellings of an implicit sensitivity
|
||||
/// list compare equal. The parser folds both into `SensList::Star` and the
|
||||
/// formatter always prints `@(*)`, which is a deliberate canonicalization, not
|
||||
/// corruption. `(*` followed by anything other than `)` lexes as an attribute
|
||||
/// token, so this sequence has no other meaning.
|
||||
/// corruption. An adjacent `(*` followed by anything but whitespace-then-`)`
|
||||
/// lexes as an attribute token (lexer-cleanup's `starts_attribute` backoff),
|
||||
/// so this token sequence still has no other meaning.
|
||||
fn collapse_implicit_sensitivity(items: &mut Vec<Item>) {
|
||||
let is_sym = |item: &Item, sym: &str| {
|
||||
item.kind == ItemKind::Token(TokenKind::Symbol) && item.text == sym
|
||||
|
||||
@@ -411,6 +411,35 @@ module m;
|
||||
always_latch if (en) q <= d;
|
||||
endmodule
|
||||
====
|
||||
# implicit sensitivity spelled with spaces inside the parens canonicalizes
|
||||
module m;
|
||||
always @(* ) y = a;
|
||||
always @( * ) z = a;
|
||||
always @( *) w = a;
|
||||
always @(* ) v = a;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
always @(*) y = a;
|
||||
always @(*) z = a;
|
||||
always @(*) w = a;
|
||||
always @(*) v = a;
|
||||
endmodule
|
||||
====
|
||||
# a spaced @(* ) with a line break inside, as a statement-level event control
|
||||
module m;
|
||||
initial begin
|
||||
@(*
|
||||
) x = 1;
|
||||
end
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
initial begin
|
||||
@(*) x = 1;
|
||||
end
|
||||
endmodule
|
||||
====
|
||||
# disable, event trigger and immediate assertion
|
||||
module m;
|
||||
initial begin
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::path::{Path, PathBuf};
|
||||
use vlog_parser::ast::SourceFile;
|
||||
use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::{Comment, Token, TokenKind};
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LineIndex};
|
||||
use vlog_parser::{parse_source_tolerant, parse_tolerant, tokenize, LexError, LineIndex};
|
||||
|
||||
/// The default tab stop used when a fix expands a tab, matching vfmt's
|
||||
/// default indent. `LintContext::with_tab_width` follows `--indent`.
|
||||
@@ -24,6 +24,7 @@ pub struct ParsedSource {
|
||||
tokens: Vec<Token>,
|
||||
file: SourceFile,
|
||||
line_index: LineIndex,
|
||||
lex_error: Option<LexError>,
|
||||
}
|
||||
|
||||
impl ParsedSource {
|
||||
@@ -41,24 +42,34 @@ impl ParsedSource {
|
||||
/// and the one consumer that publishes them (the language server) holds
|
||||
/// its own.
|
||||
pub fn parse(source: &str) -> ParsedSource {
|
||||
let (tokens, file) = match tokenize(source) {
|
||||
let (tokens, file, lex_error) = match tokenize(source) {
|
||||
Ok(tokens) => {
|
||||
let (file, _diagnostics) = parse_tolerant(tokens.clone(), source);
|
||||
(tokens, file)
|
||||
(tokens, file, None)
|
||||
}
|
||||
// A lex error leaves no tokens (the lexer is all-or-nothing) and
|
||||
// the whole file becomes one error leaf. Text rules still work,
|
||||
// which is the point of not failing here.
|
||||
Err(_) => (Vec::new(), parse_source_tolerant(source).0),
|
||||
// which is the point of not failing here — but the error is kept
|
||||
// so a caller can say the token- and AST-level rules saw nothing.
|
||||
Err(error) => (Vec::new(), parse_source_tolerant(source).0, Some(error)),
|
||||
};
|
||||
ParsedSource {
|
||||
source: source.to_string(),
|
||||
tokens,
|
||||
file,
|
||||
line_index: LineIndex::new(source),
|
||||
lex_error,
|
||||
}
|
||||
}
|
||||
|
||||
/// The lex error, when the text does not lex. The tokens are empty then
|
||||
/// and every token- and AST-level rule silently saw nothing, so a caller
|
||||
/// that reports per-file errors must surface this rather than let the
|
||||
/// file pass as clean.
|
||||
pub fn lex_error(&self) -> Option<&LexError> {
|
||||
self.lex_error.as_ref()
|
||||
}
|
||||
|
||||
/// A lint context borrowing this parse. `path` is the file the text came
|
||||
/// from, or `None` for a buffer (stdin) — rules that need a filename skip.
|
||||
pub fn context(&self, path: Option<PathBuf>) -> LintContext<'_> {
|
||||
@@ -260,6 +271,14 @@ mod tests {
|
||||
assert_eq!(borrowed.strings, owned.strings);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_that_does_not_lex_exposes_its_lex_error() {
|
||||
let parsed = ParsedSource::parse("module m; parameter int élan = 1; endmodule\n");
|
||||
let error = parsed.lex_error().expect("a lex error");
|
||||
assert!(error.message.contains("not valid in Verilog source"), "unexpected: {error}");
|
||||
assert!(ParsedSource::parse("module m;\nendmodule\n").lex_error().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_text_that_does_not_lex_still_parses_to_the_error_tree() {
|
||||
// The lex-error fallback must produce the same all-error tree the old
|
||||
|
||||
@@ -66,9 +66,18 @@ const SINGLE_OPS: &[u8] = b"+-*/%&|^~!<>=?:;,.#@()[]{}'$";
|
||||
/// 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 {
|
||||
RawLexer { src, pos: 0, line: 1, col: 1 }
|
||||
// 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 {
|
||||
@@ -252,7 +261,7 @@ impl<'a> RawLexer<'a> {
|
||||
}
|
||||
|
||||
// Attribute instance `(* ... *)`.
|
||||
if c == b'(' && self.peek_at(1) == b'*' && self.peek_at(2) != b')' {
|
||||
if self.starts_attribute() {
|
||||
self.bump();
|
||||
self.bump();
|
||||
loop {
|
||||
@@ -400,7 +409,41 @@ impl<'a> RawLexer<'a> {
|
||||
});
|
||||
}
|
||||
|
||||
Err(self.error(format!("unexpected character {:?}", c as char)))
|
||||
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
|
||||
@@ -852,6 +895,70 @@ mod tests {
|
||||
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");
|
||||
|
||||
@@ -540,6 +540,32 @@ fn truncating_a_file_anywhere_never_panics() {
|
||||
println!("{checked} byte prefixes of the fixtures parsed");
|
||||
}
|
||||
|
||||
/// A BOM'd buffer truncated anywhere: the BOM is skipped like whitespace, so
|
||||
/// every prefix must obey the same invariants a plain file's prefixes do —
|
||||
/// including the prefix that is nothing but the BOM itself.
|
||||
#[test]
|
||||
fn truncating_a_bom_prefixed_file_never_panics() {
|
||||
let src = "\u{feff}module m;\n wire w;\n always @(* ) y = a;\nendmodule\n";
|
||||
for cut in 0..=src.len() {
|
||||
if !src.is_char_boundary(cut) {
|
||||
continue;
|
||||
}
|
||||
let prefix = &src[..cut];
|
||||
let (file, diags) = parse_source_tolerant(prefix);
|
||||
assert_eq!(file.span.as_range(), 0..prefix.len(), "cut at {cut}");
|
||||
assert_diagnostics_fit(prefix, &diags);
|
||||
for (span, text) in error_nodes(&file) {
|
||||
assert_eq!(text, &prefix[span.as_range()], "cut at {cut}");
|
||||
}
|
||||
}
|
||||
// A BOM anywhere else stays a lex error, which tolerant parsing turns
|
||||
// into one diagnostic and one file-wide error item like any other.
|
||||
let (file, diags) = parse_source_tolerant("module m;\u{feff}\nendmodule\n");
|
||||
assert_eq!(diags.len(), 1);
|
||||
assert!(diags[0].message.contains("byte order mark"), "unexpected: {}", diags[0].message);
|
||||
assert!(matches!(file.items[0].kind, ItemKind::Error(_)));
|
||||
}
|
||||
|
||||
/// Token-boundary truncation of the small case-table sources: same idea,
|
||||
/// different (much wider) set of constructs.
|
||||
#[test]
|
||||
|
||||
@@ -48,6 +48,14 @@ const SOURCES: &[&str] = &[
|
||||
"// λ αβγ — em dash\nmodule m;\n initial $display(\"λ = %d ünïcode\", x); // träiling ✓\nendmodule\n",
|
||||
// CRLF.
|
||||
"module m;\r\n wire w; // comment\r\nendmodule\r\n",
|
||||
// A leading BOM: skipped like whitespace, so it lives in the gap before
|
||||
// the first token. Anywhere else it is a lex error.
|
||||
"\u{feff}module m;\n wire w;\nendmodule\n",
|
||||
"\u{feff}// only a comment\n",
|
||||
"\u{feff}",
|
||||
// Implicit sensitivity lists spelled with spaces inside the parens: the
|
||||
// attribute scan backs off and `(` `*` `)` are three plain tokens.
|
||||
"module m;\n always @(* ) y = a;\n always @( * ) z = a;\n always @(*\n ) w = a;\nendmodule\n",
|
||||
// A string literal that spans a physical line.
|
||||
"module m;\n initial $display(\"line one\n line two\");\nendmodule\n",
|
||||
"module m;\n assign y = a inside {[0:3], 4} ? int'(b) + {2{c}} : '{default: 0};\n assign z = pkg::t'(v.field[3:0][2 +: 2]);\nendmodule\n",
|
||||
@@ -114,8 +122,11 @@ fn assert_covers_source(src: &str) {
|
||||
p.span
|
||||
);
|
||||
let gap = &src[at as usize..p.span.start as usize];
|
||||
// A leading BOM is the one non-whitespace character the lexer skips;
|
||||
// it can only ever sit in the very first gap (anywhere else it is a
|
||||
// lex error, so it never reaches this walk).
|
||||
assert!(
|
||||
gap.chars().all(char::is_whitespace),
|
||||
gap.chars().all(|c| c.is_whitespace() || (c == '\u{feff}' && at == 0)),
|
||||
"non-whitespace {gap:?} is not covered by any token in {src:?}"
|
||||
);
|
||||
let slice = &src[p.span.as_range()];
|
||||
|
||||
+421
-170
@@ -8,7 +8,7 @@ use vlog_parser::span::TextRange;
|
||||
use vlog_parser::token::is_keyword;
|
||||
|
||||
use crate::model::{Import, Scope, ScopeId, ScopeKind, Symbol, SymbolId, SymbolKind};
|
||||
use crate::scan::{name_after_kw, name_span, NameScanner};
|
||||
use crate::scan::{name_after_kw, NameScanner};
|
||||
|
||||
/// A recorded use, waiting for pass two to say what it names.
|
||||
pub(crate) struct Pending {
|
||||
@@ -22,14 +22,32 @@ pub(crate) struct Pending {
|
||||
pub(crate) enum Target {
|
||||
/// The lexical chain from `scope` outward, imports included.
|
||||
Lexical,
|
||||
/// A package name: the `p` of `p::x` or of `import p::x`.
|
||||
/// A package name: the `p` of `import p::x`. Only a package can be
|
||||
/// imported, so this stays narrower than [`Target::Unit`].
|
||||
Package,
|
||||
/// A module name: the type of an instantiation.
|
||||
Module,
|
||||
/// The `x` of `p::x`: looked up in package `p`'s scope only.
|
||||
PackageMember(String),
|
||||
/// A unit name — package or class (or a `typedef class` forward
|
||||
/// declaration): the head of `p::x`, an `extends`/`implements` base, the
|
||||
/// `cls` of an out-of-body method definition.
|
||||
Unit,
|
||||
/// The `x` of `p::x` (and an `extends base #(.x(...))` override): looked
|
||||
/// up inside the named unit's scope only, never in the lexical chain.
|
||||
UnitMember(String),
|
||||
/// The `.port` of a connection to the named module.
|
||||
Port(String),
|
||||
/// The `x` of `this.x`: the enclosing class's scope only.
|
||||
ThisMember,
|
||||
/// The `x` of `super.x`: always the base class's business.
|
||||
SuperMember,
|
||||
}
|
||||
|
||||
/// An out-of-body method definition (`function void cls::method(...)`), held
|
||||
/// until the whole file is bound so `cls` can be looked up wherever it is
|
||||
/// declared — before or after the definition.
|
||||
enum Deferred<'a> {
|
||||
Function(&'a FunctionDecl, TextRange, ScopeId),
|
||||
Task(&'a TaskDecl, TextRange, ScopeId),
|
||||
}
|
||||
|
||||
pub(crate) struct Binder<'a> {
|
||||
@@ -37,6 +55,7 @@ pub(crate) struct Binder<'a> {
|
||||
pub(crate) scopes: Vec<Scope>,
|
||||
pub(crate) symbols: Vec<Symbol>,
|
||||
pub(crate) pending: Vec<Pending>,
|
||||
deferred: Vec<Deferred<'a>>,
|
||||
}
|
||||
|
||||
impl<'a> Binder<'a> {
|
||||
@@ -49,9 +68,16 @@ impl<'a> Binder<'a> {
|
||||
symbols: Vec::new(),
|
||||
children: Vec::new(),
|
||||
imports: Vec::new(),
|
||||
extends: None,
|
||||
names: HashMap::new(),
|
||||
};
|
||||
Binder { src, scopes: vec![file], symbols: Vec::new(), pending: Vec::new() }
|
||||
Binder {
|
||||
src,
|
||||
scopes: vec![file],
|
||||
symbols: Vec::new(),
|
||||
pending: Vec::new(),
|
||||
deferred: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn file_scope(&self) -> ScopeId {
|
||||
@@ -72,6 +98,7 @@ impl<'a> Binder<'a> {
|
||||
symbols: Vec::new(),
|
||||
children: Vec::new(),
|
||||
imports: Vec::new(),
|
||||
extends: None,
|
||||
names: HashMap::new(),
|
||||
});
|
||||
self.scopes[parent.0 as usize].children.push(id);
|
||||
@@ -80,7 +107,8 @@ impl<'a> Binder<'a> {
|
||||
|
||||
/// Bind `name` in `scope`. A name already bound there becomes a reference
|
||||
/// to the first declaration instead of a second symbol — which is how a
|
||||
/// non-ANSI port's body declaration attaches to its header port.
|
||||
/// non-ANSI port's body declaration attaches to its header port, and how
|
||||
/// an out-of-body method definition attaches to its `extern` prototype.
|
||||
fn declare(
|
||||
&mut self,
|
||||
scope: ScopeId,
|
||||
@@ -132,41 +160,68 @@ impl<'a> Binder<'a> {
|
||||
|
||||
/// Record a use — unless it is not a name this crate can say anything
|
||||
/// about: a system task (`$display`), a macro standing where a name
|
||||
/// belongs (`` `PICORV32_REGS regs (...) ``), or a keyword the parser kept
|
||||
/// in an identifier slot.
|
||||
/// belongs (`` `PICORV32_REGS regs (...) ``), a keyword the parser kept
|
||||
/// in an identifier slot, or one of the four class words the lexer leaves
|
||||
/// as identifiers (`this`/`super` are modelled through their member
|
||||
/// accesses, `null` is a literal, and a bare `new` names the constructor
|
||||
/// of the *assigned* class, which needs types this crate does not have).
|
||||
fn use_name(&mut self, scope: ScopeId, name: &str, name_span: TextRange, target: Target) {
|
||||
if matches!(name, "this" | "super" | "null" | "new") {
|
||||
return;
|
||||
}
|
||||
self.use_member(scope, name, name_span, target);
|
||||
}
|
||||
|
||||
/// Like [`Binder::use_name`], but keeps `new`: the tail of `super.new(...)`
|
||||
/// really does name the base class's constructor.
|
||||
fn use_member(&mut self, scope: ScopeId, name: &str, name_span: TextRange, target: Target) {
|
||||
if name.is_empty() || name.starts_with('$') || name.starts_with('`') || is_keyword(name) {
|
||||
return;
|
||||
}
|
||||
self.pending.push(Pending { name: name.to_string(), name_span, scope, target });
|
||||
}
|
||||
|
||||
/// `span` when it slices to exactly `name`, else an empty range at its
|
||||
/// start. Guards the ranges this crate derives instead of receiving —
|
||||
/// a source spelling `pkg :: mod` must cost a span, never mislocate one.
|
||||
fn exact_or_empty(&self, span: TextRange, name: &str) -> TextRange {
|
||||
let range = span.as_range();
|
||||
if range.end <= self.src.len() && self.src.get(range.clone()).is_some_and(|s| s == name) {
|
||||
span
|
||||
} else {
|
||||
TextRange::empty(span.start)
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Items
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
pub(crate) fn bind_items(&mut self, items: &[Item], scope: ScopeId) {
|
||||
pub(crate) fn bind_items(&mut self, items: &'a [Item], scope: ScopeId) {
|
||||
for item in items {
|
||||
self.bind_item(item, scope);
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_item(&mut self, item: &Item, scope: ScopeId) {
|
||||
fn bind_item(&mut self, item: &'a Item, scope: ScopeId) {
|
||||
match &item.kind {
|
||||
ItemKind::Module(m) => self.bind_module(m, item.span, scope),
|
||||
ItemKind::Package { kw, name, items, .. } => {
|
||||
let ns = name_after_kw(self.src, item.span, kw, name);
|
||||
ItemKind::Package { name, name_span, items, .. } => {
|
||||
let inner = self.declare_with_scope(
|
||||
scope,
|
||||
name,
|
||||
SymbolKind::Package,
|
||||
ns,
|
||||
*name_span,
|
||||
item.span,
|
||||
ScopeKind::Package,
|
||||
);
|
||||
self.bind_items(items, inner);
|
||||
}
|
||||
ItemKind::Import(paths) => self.bind_imports(paths, item.span, scope),
|
||||
ItemKind::Import(paths) => {
|
||||
for path in paths {
|
||||
self.bind_import_path(path, scope);
|
||||
}
|
||||
}
|
||||
ItemKind::Typedef(t) => self.bind_typedef(t, item.span, scope),
|
||||
ItemKind::ParamDecl(p) => {
|
||||
self.bind_declarators(&p.declarators, SymbolKind::Param, &p.ty, item.span, scope)
|
||||
@@ -182,12 +237,11 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
ItemKind::Always { stmt, .. } => self.bind_stmt(stmt, scope),
|
||||
ItemKind::Initial(s) | ItemKind::Final(s) => self.bind_stmt(s, scope),
|
||||
ItemKind::Instantiation(i) => self.bind_instantiation(i, item.span, scope),
|
||||
ItemKind::Instantiation(i) => self.bind_instantiation(i, scope),
|
||||
ItemKind::GateInstantiation(g) => {
|
||||
self.bind_opt_expr(g.delay.as_ref(), scope);
|
||||
for inst in &g.instances {
|
||||
if let Some(name) = &inst.name {
|
||||
let ns = name_span(self.src, inst.span, name);
|
||||
if let (Some(name), Some(ns)) = (&inst.name, inst.name_span) {
|
||||
self.declare(scope, name, SymbolKind::Instance, ns, inst.span);
|
||||
}
|
||||
for a in &inst.args {
|
||||
@@ -196,10 +250,8 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
}
|
||||
ItemKind::Genvar(names) => {
|
||||
let mut scanner = NameScanner::new(self.src, item.span);
|
||||
for name in names {
|
||||
let ns = scanner.find(&name.text).unwrap_or(TextRange::empty(item.span.start));
|
||||
self.declare(scope, &name.text, SymbolKind::Genvar, ns, item.span);
|
||||
self.declare(scope, &name.text, SymbolKind::Genvar, name.span, item.span);
|
||||
}
|
||||
}
|
||||
ItemKind::GenerateRegion { items, .. } => {
|
||||
@@ -219,6 +271,7 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
ItemKind::Function(f) => self.bind_function(f, item.span, scope),
|
||||
ItemKind::Task(t) => self.bind_task(t, item.span, scope),
|
||||
ItemKind::Class(c) => self.bind_class(c, item.span, scope),
|
||||
ItemKind::Defparam(pairs) => {
|
||||
for (lhs, rhs) in pairs {
|
||||
self.bind_expr(lhs, scope);
|
||||
@@ -226,53 +279,41 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
}
|
||||
// Opaque leaves: verbatim text this crate makes no claims about.
|
||||
// `Verbatim` is a constraint or covergroup body — no symbol is
|
||||
// bound for its name and nothing inside it is scanned, the same
|
||||
// contract macro invocations have.
|
||||
ItemKind::Directive(_)
|
||||
| ItemKind::MacroItem(_)
|
||||
| ItemKind::Timeunit(_)
|
||||
| ItemKind::Error(_)
|
||||
| ItemKind::Verbatim(_) => {}
|
||||
// Classes are parsed and formatted but deliberately not modelled
|
||||
// here: their scoping rules (inheritance, `this`/`super`, static
|
||||
// vs. instance members) are a separate design question, and a
|
||||
// half-model would resolve names wrongly rather than not at all.
|
||||
// See `docs/features/classes/README.md`.
|
||||
ItemKind::Class(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_module(&mut self, m: &Module, span: TextRange, scope: ScopeId) {
|
||||
let ns = name_after_kw(self.src, span, &m.kw, &m.name);
|
||||
fn bind_module(&mut self, m: &'a Module, span: TextRange, scope: ScopeId) {
|
||||
let inner = self.declare_with_scope(
|
||||
scope,
|
||||
&m.name,
|
||||
SymbolKind::Module,
|
||||
ns,
|
||||
m.name_span,
|
||||
span,
|
||||
ScopeKind::Module,
|
||||
);
|
||||
// Header imports, then parameters, then ports: the order they are
|
||||
// written in, so one scanner walks the header left to right.
|
||||
let header = TextRange::new(ns.end, span.end);
|
||||
let mut scanner = NameScanner::new(self.src, header);
|
||||
for import in &m.imports {
|
||||
for path in &import.paths {
|
||||
self.bind_import_path(&path.text(), &mut scanner, inner);
|
||||
self.bind_import_path(path, inner);
|
||||
}
|
||||
}
|
||||
for p in m.param_ports.iter().flatten() {
|
||||
let name = self.decl_name(p.span, &p.ty, &p.unpacked, p.default.as_ref(), &p.name);
|
||||
self.bind_data_type(&p.ty, TextRange::new(p.span.start, name.start), inner);
|
||||
self.declare(inner, &p.name, SymbolKind::Param, name, p.span);
|
||||
self.bind_dims(&p.unpacked, inner);
|
||||
self.bind_opt_expr(p.default.as_ref(), inner);
|
||||
}
|
||||
self.bind_param_ports(m.param_ports.iter().flatten(), inner);
|
||||
match &m.ports {
|
||||
PortList::Ansi(ports) => {
|
||||
for p in ports {
|
||||
let name =
|
||||
self.decl_name(p.span, &p.ty, &p.unpacked, p.default.as_ref(), &p.name);
|
||||
self.bind_data_type(&p.ty, TextRange::new(p.span.start, name.start), inner);
|
||||
self.declare(inner, &p.name, SymbolKind::Port, name, p.span);
|
||||
self.bind_data_type(
|
||||
&p.ty,
|
||||
TextRange::new(p.span.start, p.name_span.start),
|
||||
inner,
|
||||
);
|
||||
self.declare(inner, &p.name, SymbolKind::Port, p.name_span, p.span);
|
||||
self.bind_dims(&p.unpacked, inner);
|
||||
self.bind_opt_expr(p.default.as_ref(), inner);
|
||||
}
|
||||
@@ -287,41 +328,40 @@ impl<'a> Binder<'a> {
|
||||
self.bind_items(&m.items, inner);
|
||||
}
|
||||
|
||||
fn bind_imports(&mut self, paths: &[ImportPath], span: TextRange, scope: ScopeId) {
|
||||
let mut scanner = NameScanner::new(self.src, span);
|
||||
for path in paths {
|
||||
self.bind_import_path(&path.text(), &mut scanner, scope);
|
||||
/// A `#( ... )` header parameter list — module and class headers share it.
|
||||
fn bind_param_ports(&mut self, ports: impl Iterator<Item = &'a ParamPort>, scope: ScopeId) {
|
||||
for p in ports {
|
||||
self.bind_data_type(&p.ty, TextRange::new(p.span.start, p.name_span.start), scope);
|
||||
self.declare(scope, &p.name, SymbolKind::Param, p.name_span, p.span);
|
||||
self.bind_dims(&p.unpacked, scope);
|
||||
self.bind_opt_expr(p.default.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
|
||||
/// Record one `pkg::item` / `pkg::*` path as an import of `scope`.
|
||||
fn bind_import_path(&mut self, path: &str, scanner: &mut NameScanner, scope: ScopeId) {
|
||||
let (package, item) = match path.split_once("::") {
|
||||
Some((p, i)) => (p, i),
|
||||
None => (path, "*"),
|
||||
};
|
||||
let pkg_span = scanner.find(package).unwrap_or(TextRange::empty(0));
|
||||
let item = if item == "*" {
|
||||
fn bind_import_path(&mut self, path: &ImportPath, scope: ScopeId) {
|
||||
let item = if path.item.text == "*" {
|
||||
None
|
||||
} else {
|
||||
// Consume the imported name so the next path starts after it.
|
||||
let item_span = scanner.find(item).unwrap_or(TextRange::empty(pkg_span.end));
|
||||
self.use_name(scope, item, item_span, Target::PackageMember(package.to_string()));
|
||||
Some(item.to_string())
|
||||
self.use_name(
|
||||
scope,
|
||||
&path.item.text,
|
||||
path.item.span,
|
||||
Target::UnitMember(path.pkg.text.clone()),
|
||||
);
|
||||
Some(path.item.text.clone())
|
||||
};
|
||||
self.use_name(scope, package, pkg_span, Target::Package);
|
||||
self.use_name(scope, &path.pkg.text, path.pkg.span, Target::Package);
|
||||
self.scopes[scope.0 as usize].imports.push(Import {
|
||||
package: package.to_string(),
|
||||
package: path.pkg.text.clone(),
|
||||
item,
|
||||
scope: None,
|
||||
name_span: pkg_span,
|
||||
name_span: path.pkg.span,
|
||||
});
|
||||
}
|
||||
|
||||
fn bind_typedef(&mut self, t: &Typedef, span: TextRange, scope: ScopeId) {
|
||||
// The typedef's own name is written last (`typedef enum {...} name;`),
|
||||
// so it is the last identifier of the construct, not the first.
|
||||
let ns = self.typedef_name_span(t, span);
|
||||
let ns = t.name_span;
|
||||
match &t.kind {
|
||||
TypedefKind::Alias(ty) => {
|
||||
self.bind_data_type(ty, TextRange::new(span.start, ns.start), scope);
|
||||
@@ -334,8 +374,7 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
// LRM: enum names belong to the scope holding the enum.
|
||||
for m in &e.members {
|
||||
let mns = name_span(self.src, m.span, &m.name);
|
||||
self.declare(scope, &m.name, SymbolKind::EnumVariant, mns, m.span);
|
||||
self.declare(scope, &m.name, SymbolKind::EnumVariant, m.name_span, m.span);
|
||||
self.bind_opt_expr(m.value.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
@@ -352,16 +391,15 @@ impl<'a> Binder<'a> {
|
||||
let first = m.declarators.first().map(|d| d.span.start).unwrap_or(m.span.end);
|
||||
self.bind_data_type(&m.ty, TextRange::new(m.span.start, first), scope);
|
||||
for d in &m.declarators {
|
||||
let dns = name_span(self.src, d.span, &d.name);
|
||||
self.declare(inner, &d.name, SymbolKind::StructMember, dns, d.span);
|
||||
self.declare(inner, &d.name, SymbolKind::StructMember, d.name_span, d.span);
|
||||
self.bind_dims(&d.unpacked, scope);
|
||||
self.bind_opt_expr(d.init.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
}
|
||||
// `typedef class c;` promises a class this crate does not model
|
||||
// (see `ItemKind::Class` above); the name is still declared, so a
|
||||
// reference to it resolves to the forward declaration.
|
||||
// `typedef class c;` promises a class declared elsewhere; the
|
||||
// name is declared here so a reference to it resolves to the
|
||||
// forward declaration.
|
||||
TypedefKind::ForwardClass => {
|
||||
self.declare(scope, &t.name, SymbolKind::Typedef, ns, span);
|
||||
}
|
||||
@@ -369,16 +407,6 @@ impl<'a> Binder<'a> {
|
||||
self.bind_dims(&t.unpacked, scope);
|
||||
}
|
||||
|
||||
/// The name of a `typedef` is the last identifier before its `;`.
|
||||
fn typedef_name_span(&self, t: &Typedef, span: TextRange) -> TextRange {
|
||||
let mut scanner = NameScanner::new(self.src, span);
|
||||
let mut last = TextRange::empty(span.start);
|
||||
while let Some(found) = scanner.find(&t.name) {
|
||||
last = found;
|
||||
}
|
||||
last
|
||||
}
|
||||
|
||||
fn bind_data_decl(&mut self, d: &DataDecl, span: TextRange, scope: ScopeId) {
|
||||
let kind = if d.net.is_some() { SymbolKind::Net } else { SymbolKind::Var };
|
||||
self.bind_opt_expr(d.delay.as_ref(), scope);
|
||||
@@ -404,22 +432,22 @@ impl<'a> Binder<'a> {
|
||||
let first = declarators.first().map(|d| d.span.start).unwrap_or(span.end);
|
||||
self.bind_data_type(ty, TextRange::new(span.start, first), scope);
|
||||
for d in declarators {
|
||||
let ns = name_span(self.src, d.span, &d.name);
|
||||
self.declare(scope, &d.name, kind, ns, d.span);
|
||||
self.declare(scope, &d.name, kind, d.name_span, d.span);
|
||||
self.bind_dims(&d.unpacked, scope);
|
||||
self.bind_opt_expr(d.init.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_instantiation(&mut self, i: &Instantiation, span: TextRange, scope: ScopeId) {
|
||||
let ns = name_span(self.src, span, &i.module);
|
||||
fn bind_instantiation(&mut self, i: &Instantiation, scope: ScopeId) {
|
||||
// `module_span` has the documented despace caveat for `pkg :: mod`,
|
||||
// so it is taken only when it slices back to the stored name.
|
||||
let ns = self.exact_or_empty(i.module_span, &i.module);
|
||||
self.use_name(scope, &i.module, ns, Target::Module);
|
||||
for c in i.params.iter().flatten() {
|
||||
self.bind_connection(c, &i.module, scope);
|
||||
}
|
||||
for inst in &i.instances {
|
||||
let ins = name_span(self.src, inst.span, &inst.name);
|
||||
self.declare(scope, &inst.name, SymbolKind::Instance, ins, inst.span);
|
||||
self.declare(scope, &inst.name, SymbolKind::Instance, inst.name_span, inst.span);
|
||||
self.bind_dims(&inst.dims, scope);
|
||||
match &inst.conns {
|
||||
Connections::Named(conns) => {
|
||||
@@ -438,13 +466,12 @@ impl<'a> Binder<'a> {
|
||||
|
||||
fn bind_connection(&mut self, c: &Connection, module: &str, scope: ScopeId) {
|
||||
if c.name != "*" {
|
||||
let ns = name_span(self.src, c.span, &c.name);
|
||||
self.use_name(scope, &c.name, ns, Target::Port(module.to_string()));
|
||||
self.use_name(scope, &c.name, c.name_span, Target::Port(module.to_string()));
|
||||
}
|
||||
self.bind_opt_expr(c.expr.as_ref(), scope);
|
||||
}
|
||||
|
||||
fn bind_gen_if(&mut self, g: &GenIf, scope: ScopeId) {
|
||||
fn bind_gen_if(&mut self, g: &'a GenIf, scope: ScopeId) {
|
||||
self.bind_expr(&g.cond, scope);
|
||||
self.bind_gen_block(&g.then, scope);
|
||||
match g.els.as_deref() {
|
||||
@@ -454,7 +481,7 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_gen_for(&mut self, g: &GenFor, span: TextRange, scope: ScopeId) {
|
||||
fn bind_gen_for(&mut self, g: &'a GenFor, span: TextRange, scope: ScopeId) {
|
||||
// The loop header opens a scope of its own so that `for (genvar i...)`
|
||||
// does not leak `i` into the enclosing module.
|
||||
let header = self.new_scope(ScopeKind::Generate, scope, span);
|
||||
@@ -478,34 +505,36 @@ impl<'a> Binder<'a> {
|
||||
self.bind_gen_block(&g.body, header);
|
||||
}
|
||||
|
||||
fn bind_gen_block(&mut self, b: &GenBlock, scope: ScopeId) {
|
||||
let inner = match &b.label {
|
||||
Some(label) => {
|
||||
let ns = name_span(self.src, b.span, label);
|
||||
self.declare_with_scope(
|
||||
scope,
|
||||
label,
|
||||
SymbolKind::Block,
|
||||
ns,
|
||||
b.span,
|
||||
ScopeKind::Generate,
|
||||
)
|
||||
}
|
||||
None => self.new_scope(ScopeKind::Generate, scope, b.span),
|
||||
fn bind_gen_block(&mut self, b: &'a GenBlock, scope: ScopeId) {
|
||||
let inner = match (&b.label, b.label_span) {
|
||||
(Some(label), Some(ls)) => self.declare_with_scope(
|
||||
scope,
|
||||
label,
|
||||
SymbolKind::Block,
|
||||
ls,
|
||||
b.span,
|
||||
ScopeKind::Generate,
|
||||
),
|
||||
_ => self.new_scope(ScopeKind::Generate, scope, b.span),
|
||||
};
|
||||
self.bind_items(&b.items, inner);
|
||||
}
|
||||
|
||||
fn bind_function(&mut self, f: &FunctionDecl, span: TextRange, scope: ScopeId) {
|
||||
let ns = name_after_kw(self.src, span, "function", &f.name);
|
||||
fn bind_function(&mut self, f: &'a FunctionDecl, span: TextRange, scope: ScopeId) {
|
||||
if f.scope.is_some() {
|
||||
// An out-of-body definition binds into its class's scope, which
|
||||
// may not exist yet — deferred until the whole file is bound.
|
||||
self.deferred.push(Deferred::Function(f, span, scope));
|
||||
return;
|
||||
}
|
||||
if let Some(ret) = &f.ret {
|
||||
self.bind_data_type(ret, TextRange::new(span.start, ns.start), scope);
|
||||
self.bind_data_type(ret, TextRange::new(span.start, f.name_span.start), scope);
|
||||
}
|
||||
let inner = self.declare_with_scope(
|
||||
scope,
|
||||
&f.name,
|
||||
SymbolKind::Function,
|
||||
ns,
|
||||
f.name_span,
|
||||
span,
|
||||
ScopeKind::Function,
|
||||
);
|
||||
@@ -513,50 +542,269 @@ impl<'a> Binder<'a> {
|
||||
self.bind_stmts(&f.stmts, inner);
|
||||
}
|
||||
|
||||
fn bind_task(&mut self, t: &TaskDecl, span: TextRange, scope: ScopeId) {
|
||||
let ns = name_after_kw(self.src, span, "task", &t.name);
|
||||
let inner =
|
||||
self.declare_with_scope(scope, &t.name, SymbolKind::Task, ns, span, ScopeKind::Task);
|
||||
fn bind_task(&mut self, t: &'a TaskDecl, span: TextRange, scope: ScopeId) {
|
||||
if t.scope.is_some() {
|
||||
self.deferred.push(Deferred::Task(t, span, scope));
|
||||
return;
|
||||
}
|
||||
let inner = self.declare_with_scope(
|
||||
scope,
|
||||
&t.name,
|
||||
SymbolKind::Task,
|
||||
t.name_span,
|
||||
span,
|
||||
ScopeKind::Task,
|
||||
);
|
||||
self.bind_tf_args(&t.args, inner);
|
||||
self.bind_stmts(&t.stmts, inner);
|
||||
}
|
||||
|
||||
fn bind_tf_args(&mut self, args: &[TfArg], scope: ScopeId) {
|
||||
fn bind_tf_args(&mut self, args: &'a [TfArg], scope: ScopeId) {
|
||||
for a in args {
|
||||
let name = self.decl_name(a.span, &a.ty, &a.unpacked, a.default.as_ref(), &a.name);
|
||||
self.bind_data_type(&a.ty, TextRange::new(a.span.start, name.start), scope);
|
||||
self.declare(scope, &a.name, SymbolKind::TfArg, name, a.span);
|
||||
self.bind_data_type(&a.ty, TextRange::new(a.span.start, a.name_span.start), scope);
|
||||
self.declare(scope, &a.name, SymbolKind::TfArg, a.name_span, a.span);
|
||||
self.bind_dims(&a.unpacked, scope);
|
||||
self.bind_opt_expr(a.default.as_ref(), scope);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Classes
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn bind_class(&mut self, c: &'a ClassDecl, span: TextRange, scope: ScopeId) {
|
||||
let inner = self.declare_with_scope(
|
||||
scope,
|
||||
&c.name,
|
||||
SymbolKind::Class,
|
||||
c.name_span,
|
||||
span,
|
||||
ScopeKind::Class,
|
||||
);
|
||||
// Header `#( ... )` parameters bind like a module's.
|
||||
self.bind_param_ports(c.param_ports.iter().flatten(), inner);
|
||||
if let Some(ext) = &c.extends {
|
||||
self.scopes[inner.0 as usize].extends = Some(ext.name.clone());
|
||||
// The base name resolves from the *enclosing* scope — a class is
|
||||
// not visible to its own header.
|
||||
self.use_scoped_unit(&ext.name, ext.name_span, scope);
|
||||
// Overrides: `.W` is the base's parameter; the value may name the
|
||||
// class's own parameters (`extends base #(.W(W))`), so it binds
|
||||
// in the class scope.
|
||||
let base = last_segment(&ext.name);
|
||||
for conn in ext.params.iter().flatten() {
|
||||
if conn.name != "*" {
|
||||
self.use_name(
|
||||
inner,
|
||||
&conn.name,
|
||||
conn.name_span,
|
||||
Target::UnitMember(base.to_string()),
|
||||
);
|
||||
}
|
||||
self.bind_opt_expr(conn.expr.as_ref(), inner);
|
||||
}
|
||||
}
|
||||
for n in &c.implements {
|
||||
self.use_scoped_unit(&n.text, n.span, scope);
|
||||
}
|
||||
// The body is an ordinary item list; everything the item walk already
|
||||
// does — declarations, typedefs, localparams, imports, methods,
|
||||
// nested classes — works here unchanged. Verbatim members
|
||||
// (constraints, covergroups) stay opaque through the item arm.
|
||||
self.bind_items(&c.items, inner);
|
||||
}
|
||||
|
||||
/// Record a unit name that may be scope-qualified: `base`, `pkg::base`.
|
||||
/// A qualified spelling records head and tail (middle segments of a
|
||||
/// longer chain are not recorded; the corpus has none). Both spans are
|
||||
/// derived from the glued text, so each is verified before use and the
|
||||
/// reference is skipped when the source spelled spaces around the `::`.
|
||||
fn use_scoped_unit(&mut self, name: &str, span: TextRange, scope: ScopeId) {
|
||||
match name.rsplit_once("::") {
|
||||
Some((head_path, tail)) => {
|
||||
let head = head_path.split("::").next().unwrap_or(head_path);
|
||||
let head_span = self.exact_or_empty(
|
||||
TextRange::new(span.start, span.start.saturating_add(head.len() as u32)),
|
||||
head,
|
||||
);
|
||||
if !head_span.is_empty() {
|
||||
self.use_name(scope, head, head_span, Target::Unit);
|
||||
}
|
||||
let tail_span = self.exact_or_empty(
|
||||
TextRange::new(span.end.saturating_sub(tail.len() as u32), span.end),
|
||||
tail,
|
||||
);
|
||||
let owner = head_path.rsplit("::").next().unwrap_or(head_path);
|
||||
if !tail_span.is_empty() {
|
||||
self.use_name(scope, tail, tail_span, Target::UnitMember(owner.to_string()));
|
||||
}
|
||||
}
|
||||
None => self.use_name(scope, name, span, Target::Unit),
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind the out-of-body method definitions collected during the walk.
|
||||
/// Runs after everything else is bound, so the class scope exists no
|
||||
/// matter where the class is written.
|
||||
pub(crate) fn bind_deferred(&mut self) {
|
||||
let deferred = std::mem::take(&mut self.deferred);
|
||||
for d in deferred {
|
||||
match d {
|
||||
Deferred::Function(f, span, scope) => {
|
||||
let path = f.scope.as_deref().unwrap_or("");
|
||||
self.bind_out_of_body(
|
||||
path,
|
||||
&f.name,
|
||||
f.name_span,
|
||||
span,
|
||||
scope,
|
||||
SymbolKind::Function,
|
||||
ScopeKind::Function,
|
||||
f.ret.as_ref(),
|
||||
&f.args,
|
||||
&f.stmts,
|
||||
);
|
||||
}
|
||||
Deferred::Task(t, span, scope) => {
|
||||
let path = t.scope.as_deref().unwrap_or("");
|
||||
self.bind_out_of_body(
|
||||
path,
|
||||
&t.name,
|
||||
t.name_span,
|
||||
span,
|
||||
scope,
|
||||
SymbolKind::Task,
|
||||
ScopeKind::Task,
|
||||
None,
|
||||
&t.args,
|
||||
&t.stmts,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One `function void cls::method(...)` definition: the method symbol
|
||||
/// binds into `cls`'s scope (an `extern` prototype already there makes
|
||||
/// the definition-site name a reference to it — the same
|
||||
/// redeclaration-becomes-reference rule non-ANSI ports use), and the body
|
||||
/// scope hangs under `cls`'s scope so properties resolve.
|
||||
// The allow: one call shape, two callers; a parameter struct would
|
||||
// outweigh the function.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn bind_out_of_body(
|
||||
&mut self,
|
||||
path: &str,
|
||||
name: &str,
|
||||
name_span: TextRange,
|
||||
span: TextRange,
|
||||
decl_scope: ScopeId,
|
||||
kind: SymbolKind,
|
||||
scope_kind: ScopeKind,
|
||||
ret: Option<&DataType>,
|
||||
args: &'a [TfArg],
|
||||
stmts: &'a [Stmt],
|
||||
) {
|
||||
// The written class path is a reference of its own — navigation from
|
||||
// `cls::method` to the class. Its span is derived (the parser glues
|
||||
// the path), so it is verified and skipped when inexact.
|
||||
let cls = last_segment(path);
|
||||
let cls_span = TextRange::new(
|
||||
name_span.start.saturating_sub(2).saturating_sub(cls.len() as u32),
|
||||
name_span.start.saturating_sub(2),
|
||||
);
|
||||
let cls_span = self.exact_or_empty(cls_span, cls);
|
||||
if !cls_span.is_empty() {
|
||||
self.use_name(decl_scope, cls, cls_span, Target::Unit);
|
||||
}
|
||||
|
||||
// The method's home: the class scope when the class is in this file,
|
||||
// else the scope the definition is written in.
|
||||
let home = self.find_unit_scope(decl_scope, path).unwrap_or(decl_scope);
|
||||
let sym = self.declare(home, name, kind, name_span, span);
|
||||
let body = self.new_scope(scope_kind, home, span);
|
||||
match sym {
|
||||
Some(sym) => {
|
||||
self.symbols[sym.0 as usize].child_scope = Some(body);
|
||||
self.scopes[body.0 as usize].owner = Some(sym);
|
||||
}
|
||||
// The prototype owns the name; mark the body scope as owned by it
|
||||
// (without touching the prototype's own scope) so method locals
|
||||
// do not spill into the class outline.
|
||||
None => {
|
||||
self.scopes[body.0 as usize].owner =
|
||||
self.scopes[home.0 as usize].lookup_local(name);
|
||||
}
|
||||
}
|
||||
// Return type, arguments and body all resolve from inside the class,
|
||||
// as the LRM says an out-of-body declaration does.
|
||||
if let Some(ret) = ret {
|
||||
self.bind_data_type(ret, TextRange::new(span.start, name_span.start), body);
|
||||
}
|
||||
self.bind_tf_args(args, body);
|
||||
self.bind_stmts(stmts, body);
|
||||
}
|
||||
|
||||
/// The scope of the unit `path` names, resolved lexically from `from` and
|
||||
/// descended segment by segment (`pkg::cls`).
|
||||
fn find_unit_scope(&self, from: ScopeId, path: &str) -> Option<ScopeId> {
|
||||
let mut segments = path.split("::");
|
||||
let mut scope = self.lookup_unit_scope(from, segments.next()?)?;
|
||||
for seg in segments {
|
||||
let sym = self.scopes[scope.0 as usize].lookup_local(seg)?;
|
||||
let s = self.symbols.get(sym.0 as usize)?;
|
||||
if !matches!(s.kind, SymbolKind::Class | SymbolKind::Package) {
|
||||
return None;
|
||||
}
|
||||
scope = s.child_scope?;
|
||||
}
|
||||
Some(scope)
|
||||
}
|
||||
|
||||
/// The scope of the class or package `name`, found on the lexical chain
|
||||
/// from `from`; non-unit shadowers are skipped.
|
||||
fn lookup_unit_scope(&self, from: ScopeId, name: &str) -> Option<ScopeId> {
|
||||
let mut current = Some(from);
|
||||
while let Some(id) = current {
|
||||
let scope = self.scopes.get(id.0 as usize)?;
|
||||
if let Some(sym) = scope.lookup_local(name) {
|
||||
if let Some(s) = self.symbols.get(sym.0 as usize) {
|
||||
if matches!(s.kind, SymbolKind::Class | SymbolKind::Package) {
|
||||
if let Some(child) = s.child_scope {
|
||||
return Some(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
current = scope.parent;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Statements
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
fn bind_stmts(&mut self, stmts: &[Stmt], scope: ScopeId) {
|
||||
fn bind_stmts(&mut self, stmts: &'a [Stmt], scope: ScopeId) {
|
||||
for s in stmts {
|
||||
self.bind_stmt(s, scope);
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_stmt(&mut self, stmt: &Stmt, scope: ScopeId) {
|
||||
fn bind_stmt(&mut self, stmt: &'a Stmt, scope: ScopeId) {
|
||||
match &stmt.kind {
|
||||
StmtKind::Block { label, stmts, .. } | StmtKind::ForkJoin { label, stmts, .. } => {
|
||||
let inner = match label {
|
||||
Some(label) => {
|
||||
let ns = name_span(self.src, stmt.span, label);
|
||||
self.declare_with_scope(
|
||||
scope,
|
||||
label,
|
||||
SymbolKind::Block,
|
||||
ns,
|
||||
stmt.span,
|
||||
ScopeKind::Block,
|
||||
)
|
||||
}
|
||||
None => self.new_scope(ScopeKind::Block, scope, stmt.span),
|
||||
StmtKind::Block { label, label_span, stmts, .. }
|
||||
| StmtKind::ForkJoin { label, label_span, stmts, .. } => {
|
||||
let inner = match (label, *label_span) {
|
||||
(Some(label), Some(ls)) => self.declare_with_scope(
|
||||
scope,
|
||||
label,
|
||||
SymbolKind::Block,
|
||||
ls,
|
||||
stmt.span,
|
||||
ScopeKind::Block,
|
||||
),
|
||||
_ => self.new_scope(ScopeKind::Block, scope, stmt.span),
|
||||
};
|
||||
self.bind_stmts(stmts, inner);
|
||||
}
|
||||
@@ -624,11 +872,8 @@ impl<'a> Binder<'a> {
|
||||
StmtKind::Foreach { target, vars, body } => {
|
||||
let inner = self.new_scope(ScopeKind::Block, scope, stmt.span);
|
||||
self.bind_expr(target, scope);
|
||||
let mut scanner =
|
||||
NameScanner::new(self.src, TextRange::new(target.span.end, stmt.span.end));
|
||||
for v in vars {
|
||||
let ns = scanner.find(&v.text).unwrap_or(TextRange::empty(target.span.end));
|
||||
self.declare(inner, &v.text, SymbolKind::Var, ns, ns);
|
||||
self.declare(inner, &v.text, SymbolKind::Var, v.span, v.span);
|
||||
}
|
||||
self.bind_stmt(body, inner);
|
||||
}
|
||||
@@ -663,6 +908,8 @@ impl<'a> Binder<'a> {
|
||||
StmtKind::PortDecl(p) => self.bind_port_decl(p, stmt.span, scope),
|
||||
StmtKind::Return(e) => self.bind_opt_expr(e.as_ref(), scope),
|
||||
StmtKind::Disable(name) => {
|
||||
// A use, not a declaration, so name-spans deliberately gave it
|
||||
// no range — the one statement still located by scanning.
|
||||
let ns = name_after_kw(self.src, stmt.span, "disable", name);
|
||||
self.use_name(scope, name, ns, Target::Lexical);
|
||||
}
|
||||
@@ -684,7 +931,7 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_timing(&mut self, t: &TimingControl, scope: ScopeId) {
|
||||
fn bind_timing(&mut self, t: &'a TimingControl, scope: ScopeId) {
|
||||
match t {
|
||||
TimingControl::Delay(e) => self.bind_expr(e, scope),
|
||||
TimingControl::Event(SensList::List(items)) => {
|
||||
@@ -752,8 +999,17 @@ impl<'a> Binder<'a> {
|
||||
self.bind_expr(msb, scope);
|
||||
self.bind_expr(lsb, scope);
|
||||
}
|
||||
// `a.b`: only the head is resolved — see the README.
|
||||
ExprKind::Member { base, .. } => self.bind_expr(base, scope),
|
||||
// `a.b`: only the head is resolved (see the README) — except
|
||||
// `this.b` and `super.b`, whose member is the whole point.
|
||||
ExprKind::Member { base, name } => match &base.kind {
|
||||
ExprKind::Ident(head) if head == "this" => {
|
||||
self.use_member(scope, name, member_tail(e.span, name), Target::ThisMember)
|
||||
}
|
||||
ExprKind::Ident(head) if head == "super" => {
|
||||
self.use_member(scope, name, member_tail(e.span, name), Target::SuperMember)
|
||||
}
|
||||
_ => self.bind_expr(base, scope),
|
||||
},
|
||||
ExprKind::Scope { base, name } => self.bind_scoped(base, name, e.span, scope),
|
||||
// The `#( ... )` is verbatim text this crate makes no claims
|
||||
// about; the name it parameterizes is still an ordinary use.
|
||||
@@ -801,13 +1057,14 @@ impl<'a> Binder<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `p::x`: the head names a package, the tail is looked up inside it.
|
||||
/// `p::x`: the head names a unit (package or class), the tail is looked
|
||||
/// up inside it.
|
||||
fn bind_scoped(&mut self, base: &Expr, name: &str, span: TextRange, scope: ScopeId) {
|
||||
let tail = TextRange::new(span.end.saturating_sub(name.len() as u32), span.end);
|
||||
match &base.kind {
|
||||
ExprKind::Ident(pkg) => {
|
||||
self.use_name(scope, pkg, base.span, Target::Package);
|
||||
self.use_name(scope, name, tail, Target::PackageMember(pkg.clone()));
|
||||
ExprKind::Ident(unit) => {
|
||||
self.use_name(scope, unit, base.span, Target::Unit);
|
||||
self.use_member(scope, name, tail, Target::UnitMember(unit.clone()));
|
||||
}
|
||||
_ => self.bind_expr(base, scope),
|
||||
}
|
||||
@@ -815,42 +1072,36 @@ impl<'a> Binder<'a> {
|
||||
|
||||
/// A user-defined type name is a use like any other. `window` is the
|
||||
/// source range the name was written in — everything before the declared
|
||||
/// name, which is where a data type always sits.
|
||||
/// name, which is where a data type always sits. A `DataType` has no span
|
||||
/// of its own (vlog-semantic handshake item 2, still open), so this is
|
||||
/// the one declaration surface still located by scanning.
|
||||
fn bind_data_type(&mut self, ty: &DataType, window: TextRange, scope: ScopeId) {
|
||||
if !ty.name.is_empty() && !is_keyword(&ty.name) {
|
||||
match ty.name.split_once("::") {
|
||||
Some((pkg, item)) => {
|
||||
Some((unit, item)) => {
|
||||
let mut scanner = NameScanner::new(self.src, window);
|
||||
let pkg_span = scanner.find(pkg).unwrap_or(TextRange::empty(window.start));
|
||||
let unit_span = scanner.find(unit).unwrap_or(TextRange::empty(window.start));
|
||||
let item_span = scanner.find(item).unwrap_or(TextRange::empty(window.start));
|
||||
self.use_name(scope, pkg, pkg_span, Target::Package);
|
||||
self.use_name(scope, item, item_span, Target::PackageMember(pkg.to_string()));
|
||||
self.use_name(scope, unit, unit_span, Target::Unit);
|
||||
self.use_name(scope, item, item_span, Target::UnitMember(unit.to_string()));
|
||||
}
|
||||
None => {
|
||||
let ns = name_span(self.src, window, &ty.name);
|
||||
let ns = crate::scan::name_span(self.src, window, &ty.name);
|
||||
self.use_name(scope, &ty.name, ns, Target::Lexical);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.bind_dims(&ty.packed, scope);
|
||||
}
|
||||
}
|
||||
|
||||
/// The range of a declared name that sits between its type and its
|
||||
/// dimensions/default (a port, a parameter port, a task/function argument).
|
||||
fn decl_name(
|
||||
&self,
|
||||
span: TextRange,
|
||||
ty: &DataType,
|
||||
unpacked: &[Dim],
|
||||
default: Option<&Expr>,
|
||||
name: &str,
|
||||
) -> TextRange {
|
||||
let start = ty.packed.last().map(|d| d.span.end).unwrap_or(span.start);
|
||||
let end = unpacked
|
||||
.first()
|
||||
.map(|d| d.span.start)
|
||||
.or_else(|| default.map(|e| e.span.start))
|
||||
.unwrap_or(span.end);
|
||||
name_span(self.src, TextRange::new(start, end), name)
|
||||
}
|
||||
/// The byte range of a member access's tail: the construct's last token, so
|
||||
/// its range is exactly the last `name.len()` bytes of the whole span.
|
||||
fn member_tail(span: TextRange, name: &str) -> TextRange {
|
||||
TextRange::new(span.end.saturating_sub(name.len() as u32), span.end)
|
||||
}
|
||||
|
||||
/// The last `::` segment of a possibly-qualified path (`pkg::cls` → `cls`).
|
||||
fn last_segment(path: &str) -> &str {
|
||||
path.rsplit("::").next().unwrap_or(path)
|
||||
}
|
||||
@@ -51,6 +51,9 @@ pub fn analyze(file: &SourceFile, src: &str) -> Semantics {
|
||||
let mut binder = bind::Binder::new(src, file.span);
|
||||
let file_scope = binder.file_scope();
|
||||
binder.bind_items(&file.items, file_scope);
|
||||
// Out-of-body method definitions bind into their class's scope, which is
|
||||
// only guaranteed to exist once the whole file is bound.
|
||||
binder.bind_deferred();
|
||||
|
||||
let bind::Binder { mut scopes, symbols, pending, .. } = binder;
|
||||
link_imports(&mut scopes, &symbols);
|
||||
|
||||
@@ -43,6 +43,8 @@ pub enum SymbolKind {
|
||||
Block,
|
||||
/// A member of a `struct`/`union` body.
|
||||
StructMember,
|
||||
/// A `class` declaration.
|
||||
Class,
|
||||
}
|
||||
|
||||
/// A declaration: a name bound in one scope.
|
||||
@@ -71,9 +73,17 @@ pub enum Resolution {
|
||||
/// package imported with `import p::*` / `import p::x`, a package written
|
||||
/// as `p::x`, or a module instantiated but declared in another file.
|
||||
/// `paths` names those units — a path containing `::` is a package path,
|
||||
/// a bare name is a module or package name. The workspace index
|
||||
/// a bare name is a module, package or class name. The workspace index
|
||||
/// (TODO.md §6) is what finishes these.
|
||||
ExternalCandidate { paths: Vec<String> },
|
||||
/// A use inside a class that nothing lexical binds, where the class's
|
||||
/// `extends` could: `base` is the base-class path as written
|
||||
/// (`uvm_component`, `pkg::base`), and `paths` are any import paths the
|
||||
/// lexical walk collected — either could supply the name. Nothing chases
|
||||
/// `base`, in this file or out of it; a future hover/index round can,
|
||||
/// without this crate pretending it did inheritance resolution. See
|
||||
/// `docs/features/class-semantics/README.md`.
|
||||
InheritedCandidate { base: String, paths: Vec<String> },
|
||||
/// Nothing in this file binds it and no external unit could.
|
||||
NotFound,
|
||||
}
|
||||
@@ -103,6 +113,11 @@ impl Reference {
|
||||
pub fn is_external_candidate(&self) -> bool {
|
||||
matches!(self.resolution, Resolution::ExternalCandidate { .. })
|
||||
}
|
||||
|
||||
/// True when the name could only come through the class's `extends`.
|
||||
pub fn is_inherited_candidate(&self) -> bool {
|
||||
matches!(self.resolution, Resolution::InheritedCandidate { .. })
|
||||
}
|
||||
}
|
||||
|
||||
/// What construct a [`Scope`] came from.
|
||||
@@ -120,6 +135,8 @@ pub enum ScopeKind {
|
||||
/// A `struct`/`union` body. Never searched by name lookup — members are
|
||||
/// reached through `x.field`, which this crate does not resolve.
|
||||
Struct,
|
||||
/// A `class` body.
|
||||
Class,
|
||||
}
|
||||
|
||||
/// One `import p::x;` / `import p::*;` recorded in the scope that wrote it.
|
||||
@@ -167,6 +184,9 @@ pub struct Scope {
|
||||
pub symbols: Vec<SymbolId>,
|
||||
pub children: Vec<ScopeId>,
|
||||
pub imports: Vec<Import>,
|
||||
/// For a [`ScopeKind::Class`] scope: the `extends` path as written, when
|
||||
/// the class has one. What an inheritance miss reports as its `base`.
|
||||
pub(crate) extends: Option<String>,
|
||||
/// Name → symbol, first declaration wins (see the README's shadowing
|
||||
/// rules). Kept separate from `symbols` so a redeclaration is still
|
||||
/// visible in the outline.
|
||||
|
||||
@@ -5,27 +5,16 @@
|
||||
//! requires at module scope and what an editor needs mid-edit.
|
||||
|
||||
use crate::bind::{Pending, Target};
|
||||
use crate::model::{Resolution, Scope, ScopeId, SymbolId, SymbolKind};
|
||||
use crate::model::{Resolution, Scope, ScopeId, Symbol, SymbolId, SymbolKind};
|
||||
|
||||
/// Resolve one pending use against the finished scope tree.
|
||||
pub(crate) fn resolve(
|
||||
scopes: &[Scope],
|
||||
symbols: &[crate::model::Symbol],
|
||||
p: &Pending,
|
||||
) -> Resolution {
|
||||
pub(crate) fn resolve(scopes: &[Scope], symbols: &[Symbol], p: &Pending) -> Resolution {
|
||||
match &p.target {
|
||||
Target::Lexical => lexical(scopes, p.scope, &p.name),
|
||||
Target::Package => named_at_file_scope(scopes, symbols, &p.name, SymbolKind::Package),
|
||||
Target::Module => named_at_file_scope(scopes, symbols, &p.name, SymbolKind::Module),
|
||||
Target::PackageMember(pkg) => {
|
||||
match owning_scope(scopes, symbols, pkg, SymbolKind::Package) {
|
||||
Some(scope) => match scopes[scope.0 as usize].lookup_local(&p.name) {
|
||||
Some(id) => Resolution::Resolved(id),
|
||||
None => Resolution::NotFound,
|
||||
},
|
||||
None => Resolution::ExternalCandidate { paths: vec![format!("{pkg}::{}", p.name)] },
|
||||
}
|
||||
}
|
||||
Target::Unit => unit(scopes, symbols, p.scope, &p.name),
|
||||
Target::UnitMember(unit) => unit_member(scopes, symbols, p.scope, unit, &p.name),
|
||||
Target::Port(module) => match owning_scope(scopes, symbols, module, SymbolKind::Module) {
|
||||
Some(scope) => match scopes[scope.0 as usize].lookup_local(&p.name) {
|
||||
Some(id) => Resolution::Resolved(id),
|
||||
@@ -34,11 +23,16 @@ pub(crate) fn resolve(
|
||||
// The port list lives in whatever file declares the module.
|
||||
None => Resolution::ExternalCandidate { paths: vec![module.clone()] },
|
||||
},
|
||||
Target::ThisMember => this_member(scopes, p.scope, &p.name),
|
||||
Target::SuperMember => super_member(scopes, p.scope),
|
||||
}
|
||||
}
|
||||
|
||||
/// Walk the scope chain outward: names declared in a scope first, then the
|
||||
/// packages that scope imports, then the enclosing scope.
|
||||
/// packages that scope imports, then the enclosing scope. A miss inside a
|
||||
/// class whose header says `extends` becomes an inheritance candidate — the
|
||||
/// base (which this crate never chases, in this file or out of it) could
|
||||
/// supply the name, and so could any import path collected on the way out.
|
||||
fn lexical(scopes: &[Scope], from: ScopeId, name: &str) -> Resolution {
|
||||
let mut external = Vec::new();
|
||||
let mut current = Some(from);
|
||||
@@ -69,6 +63,145 @@ fn lexical(scopes: &[Scope], from: ScopeId, name: &str) -> Resolution {
|
||||
}
|
||||
current = scope.parent;
|
||||
}
|
||||
miss(scopes, from, external, false)
|
||||
}
|
||||
|
||||
/// A unit name — package or class (or a `typedef class` forward declaration):
|
||||
/// the head of `p::x`, an `extends`/`implements` base, the `cls` of an
|
||||
/// out-of-body definition. Resolved on the lexical chain, non-unit shadowers
|
||||
/// skipped; imports are consulted because a class can arrive through
|
||||
/// `import p::*`. A miss always leaves at least the bare name as an external
|
||||
/// path, so `extends Base` reaches the workspace's unit table — and it stays
|
||||
/// an `ExternalCandidate` even inside an extending class, because a base
|
||||
/// class supplies members, not unit names (see [`miss`]).
|
||||
fn unit(scopes: &[Scope], symbols: &[Symbol], from: ScopeId, name: &str) -> Resolution {
|
||||
let mut external = Vec::new();
|
||||
let mut current = Some(from);
|
||||
while let Some(id) = current {
|
||||
let scope = &scopes[id.0 as usize];
|
||||
if let Some(sym) = scope.lookup_local(name) {
|
||||
if is_unit_kind(symbols, sym) {
|
||||
return Resolution::Resolved(sym);
|
||||
}
|
||||
}
|
||||
for import in &scope.imports {
|
||||
if !import.supplies(name) {
|
||||
continue;
|
||||
}
|
||||
match import.scope {
|
||||
Some(pkg) => {
|
||||
if let Some(sym) = scopes[pkg.0 as usize].lookup_local(name) {
|
||||
if is_unit_kind(symbols, sym) {
|
||||
return Resolution::Resolved(sym);
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
let path = import.path();
|
||||
if !external.contains(&path) {
|
||||
external.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
current = scope.parent;
|
||||
}
|
||||
external.push(name.to_string());
|
||||
miss(scopes, from, external, true)
|
||||
}
|
||||
|
||||
/// The `x` of `p::x`: looked up inside the named unit's scope only, never in
|
||||
/// the lexical chain. The unit itself is found lexically (a class nested in
|
||||
/// an in-file package is reachable from inside that package); in-file
|
||||
/// imports are not consulted here — a unit reached through one is answered
|
||||
/// by the head reference, and the member honestly stays external.
|
||||
fn unit_member(
|
||||
scopes: &[Scope],
|
||||
symbols: &[Symbol],
|
||||
from: ScopeId,
|
||||
unit: &str,
|
||||
name: &str,
|
||||
) -> Resolution {
|
||||
let mut current = Some(from);
|
||||
while let Some(id) = current {
|
||||
let scope = &scopes[id.0 as usize];
|
||||
if let Some(sym) = scope.lookup_local(unit) {
|
||||
match symbols[sym.0 as usize].kind {
|
||||
SymbolKind::Package | SymbolKind::Class => {
|
||||
if let Some(child) = symbols[sym.0 as usize].child_scope {
|
||||
if let Some(found) = scopes[child.0 as usize].lookup_local(name) {
|
||||
return Resolution::Resolved(found);
|
||||
}
|
||||
return match (
|
||||
symbols[sym.0 as usize].kind,
|
||||
&scopes[child.0 as usize].extends,
|
||||
) {
|
||||
// A static member may be inherited; the base is
|
||||
// recorded, never chased.
|
||||
(SymbolKind::Class, Some(base)) => Resolution::InheritedCandidate {
|
||||
base: base.clone(),
|
||||
paths: Vec::new(),
|
||||
},
|
||||
// A package fully known locally: no workspace
|
||||
// index could change the answer.
|
||||
_ => Resolution::NotFound,
|
||||
};
|
||||
}
|
||||
}
|
||||
// `typedef class c;` promises the class lives elsewhere: the
|
||||
// member is the workspace's to find.
|
||||
SymbolKind::Typedef => {
|
||||
return Resolution::ExternalCandidate { paths: vec![format!("{unit}::{name}")] }
|
||||
}
|
||||
// A non-unit shadower; keep walking outward.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
current = scope.parent;
|
||||
}
|
||||
Resolution::ExternalCandidate { paths: vec![format!("{unit}::{name}")] }
|
||||
}
|
||||
|
||||
/// `this.x`: the enclosing class's own scope only — a member access cannot
|
||||
/// name a method local or an enclosing module net.
|
||||
fn this_member(scopes: &[Scope], from: ScopeId, name: &str) -> Resolution {
|
||||
let Some(class) = nearest_class(scopes, from) else {
|
||||
return Resolution::NotFound;
|
||||
};
|
||||
if let Some(sym) = scopes[class.0 as usize].lookup_local(name) {
|
||||
return Resolution::Resolved(sym);
|
||||
}
|
||||
match &scopes[class.0 as usize].extends {
|
||||
Some(base) => Resolution::InheritedCandidate { base: base.clone(), paths: Vec::new() },
|
||||
None => Resolution::NotFound,
|
||||
}
|
||||
}
|
||||
|
||||
/// `super.x`: always the base class's business — recorded against it, never
|
||||
/// chased. A `super` in a class without `extends` is illegal anyway.
|
||||
fn super_member(scopes: &[Scope], from: ScopeId) -> Resolution {
|
||||
match nearest_class(scopes, from).and_then(|c| scopes[c.0 as usize].extends.clone()) {
|
||||
Some(base) => Resolution::InheritedCandidate { base, paths: Vec::new() },
|
||||
None => Resolution::NotFound,
|
||||
}
|
||||
}
|
||||
|
||||
/// How a full miss ends. `unit_lookup` is set for [`Target::Unit`], whose
|
||||
/// paths always hold at least the bare name — and whose misses stay
|
||||
/// `ExternalCandidate` even inside an extending class, because a base class
|
||||
/// supplies *members*, not package or class names (rules 5/8 of the
|
||||
/// class-semantics README; QA-found, lead-ruled). For a member miss, the
|
||||
/// nearest extends-carrying enclosing class's base could supply the name
|
||||
/// (the LRM even puts it ahead of the enclosing scopes this walk already
|
||||
/// searched — the deliberate inexactness the same README argues), so it
|
||||
/// becomes `InheritedCandidate`.
|
||||
fn miss(scopes: &[Scope], from: ScopeId, external: Vec<String>, unit_lookup: bool) -> Resolution {
|
||||
if unit_lookup {
|
||||
return Resolution::ExternalCandidate { paths: external };
|
||||
}
|
||||
if let Some(base) = nearest_extends(scopes, from) {
|
||||
return Resolution::InheritedCandidate { base, paths: external };
|
||||
}
|
||||
if external.is_empty() {
|
||||
Resolution::NotFound
|
||||
} else {
|
||||
@@ -76,9 +209,44 @@ fn lexical(scopes: &[Scope], from: ScopeId, name: &str) -> Resolution {
|
||||
}
|
||||
}
|
||||
|
||||
/// The innermost enclosing class scope, extends or not.
|
||||
fn nearest_class(scopes: &[Scope], from: ScopeId) -> Option<ScopeId> {
|
||||
let mut current = Some(from);
|
||||
while let Some(id) = current {
|
||||
let scope = &scopes[id.0 as usize];
|
||||
if scope.kind == crate::model::ScopeKind::Class {
|
||||
return Some(id);
|
||||
}
|
||||
current = scope.parent;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The `extends` path of the innermost enclosing class that has one.
|
||||
fn nearest_extends(scopes: &[Scope], from: ScopeId) -> Option<String> {
|
||||
let mut current = Some(from);
|
||||
while let Some(id) = current {
|
||||
let scope = &scopes[id.0 as usize];
|
||||
if scope.kind == crate::model::ScopeKind::Class {
|
||||
if let Some(base) = &scope.extends {
|
||||
return Some(base.clone());
|
||||
}
|
||||
}
|
||||
current = scope.parent;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn is_unit_kind(symbols: &[Symbol], sym: SymbolId) -> bool {
|
||||
matches!(
|
||||
symbols.get(sym.0 as usize).map(|s| s.kind),
|
||||
Some(SymbolKind::Package | SymbolKind::Class | SymbolKind::Typedef)
|
||||
)
|
||||
}
|
||||
|
||||
fn named_at_file_scope(
|
||||
scopes: &[Scope],
|
||||
symbols: &[crate::model::Symbol],
|
||||
symbols: &[Symbol],
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
) -> Resolution {
|
||||
@@ -90,7 +258,7 @@ fn named_at_file_scope(
|
||||
|
||||
fn owning_scope(
|
||||
scopes: &[Scope],
|
||||
symbols: &[crate::model::Symbol],
|
||||
symbols: &[Symbol],
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
) -> Option<ScopeId> {
|
||||
@@ -101,7 +269,7 @@ fn owning_scope(
|
||||
/// Modules and packages are file-scope names, so one lookup finds them.
|
||||
fn file_symbol(
|
||||
scopes: &[Scope],
|
||||
symbols: &[crate::model::Symbol],
|
||||
symbols: &[Symbol],
|
||||
name: &str,
|
||||
kind: SymbolKind,
|
||||
) -> Option<SymbolId> {
|
||||
|
||||
@@ -181,6 +181,14 @@ impl WorkspaceIndex {
|
||||
modules: self.units_of_kind(SymbolKind::Module),
|
||||
packages: self.units_of_kind(SymbolKind::Package),
|
||||
typedefs: self.units_of_kind(SymbolKind::Typedef),
|
||||
classes: self.units_of_kind(SymbolKind::Class)
|
||||
+ self
|
||||
.members
|
||||
.values()
|
||||
.flat_map(|m| m.values())
|
||||
.flatten()
|
||||
.filter(|d| d.kind == SymbolKind::Class)
|
||||
.count(),
|
||||
members: self.members.values().flat_map(|m| m.values()).map(Vec::len).sum(),
|
||||
defines: self.defines.iter().map(|t| t.entries().len()).sum(),
|
||||
}
|
||||
@@ -229,6 +237,13 @@ impl WorkspaceIndex {
|
||||
.entry(member.name.clone())
|
||||
.or_default()
|
||||
.push(Def { file, name_span: member.name_span, kind: member.kind });
|
||||
// A class nested in a package (the dominant UVM shape) is not a
|
||||
// unit, but an external `cls::x` candidate looks its members up
|
||||
// under the *class's* name — register them there too. The scope
|
||||
// tree is acyclic, so this recursion terminates.
|
||||
if member.kind == SymbolKind::Class {
|
||||
self.add_members(file, sem, member);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -244,7 +259,11 @@ pub struct IndexCounts {
|
||||
pub packages: usize,
|
||||
/// File-scope typedefs; a typedef inside a module or package is not one.
|
||||
pub typedefs: usize,
|
||||
/// Package and module member declarations, duplicates counted separately.
|
||||
/// Class declarations reachable in the index — file-scope units plus
|
||||
/// classes registered as members of a package or an enclosing class.
|
||||
pub classes: usize,
|
||||
/// Package, class and module member declarations, duplicates counted
|
||||
/// separately.
|
||||
pub members: usize,
|
||||
/// `` `define``/`` `undef`` directives recorded across all files.
|
||||
pub defines: usize,
|
||||
@@ -267,16 +286,20 @@ fn parse_and_collect(src: &str) -> (vlog_parser::ast::SourceFile, DefineTable) {
|
||||
|
||||
/// The file-scope kinds another file can name.
|
||||
fn is_unit(kind: SymbolKind) -> bool {
|
||||
matches!(kind, SymbolKind::Module | SymbolKind::Package | SymbolKind::Typedef)
|
||||
matches!(
|
||||
kind,
|
||||
SymbolKind::Module | SymbolKind::Package | SymbolKind::Typedef | SymbolKind::Class
|
||||
)
|
||||
}
|
||||
|
||||
/// What `unit::member` / `.member` may reach. A package exports everything
|
||||
/// declared at its top level; a module exports only what a connection list can
|
||||
/// name — its ports and its parameters — so an internal net is never reachable
|
||||
/// from another file.
|
||||
/// What `unit::member` / `.member` may reach. A package or class exports
|
||||
/// everything declared at its top level (a package's classes included — that
|
||||
/// is what lets `import uvm_pkg::*` answer `uvm_object`); a module exports
|
||||
/// only what a connection list can name — its ports and its parameters — so
|
||||
/// an internal net is never reachable from another file.
|
||||
fn is_exported(unit: SymbolKind, member: SymbolKind) -> bool {
|
||||
match unit {
|
||||
SymbolKind::Package => matches!(
|
||||
SymbolKind::Package | SymbolKind::Class => matches!(
|
||||
member,
|
||||
SymbolKind::Param
|
||||
| SymbolKind::Typedef
|
||||
@@ -285,6 +308,7 @@ fn is_exported(unit: SymbolKind, member: SymbolKind) -> bool {
|
||||
| SymbolKind::Task
|
||||
| SymbolKind::Net
|
||||
| SymbolKind::Var
|
||||
| SymbolKind::Class
|
||||
),
|
||||
SymbolKind::Module => matches!(member, SymbolKind::Port | SymbolKind::Param),
|
||||
_ => false,
|
||||
|
||||
@@ -0,0 +1,726 @@
|
||||
//! Class semantics: what a class body binds, how its members resolve, and
|
||||
//! the honest shapes for everything inheritance-flavored. The rules live in
|
||||
//! `docs/features/class-semantics/README.md`.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use vlog_parser::parse_source;
|
||||
use vlog_semantic::{
|
||||
analyze, resolve_external, Definition, Resolution, ScopeKind, Semantics, SymbolId, SymbolKind,
|
||||
WorkspaceIndex,
|
||||
};
|
||||
|
||||
fn sem(src: &str) -> Semantics {
|
||||
let file = parse_source(src).expect("fixture must parse");
|
||||
analyze(&file, src)
|
||||
}
|
||||
|
||||
/// Offset of the `n`th (0-based) occurrence of `needle`.
|
||||
fn nth(src: &str, needle: &str, n: usize) -> u32 {
|
||||
src.match_indices(needle).nth(n).expect("occurrence must exist").0 as u32
|
||||
}
|
||||
|
||||
fn symbol_named<'a>(s: &'a Semantics, name: &str) -> &'a vlog_semantic::Symbol {
|
||||
s.symbols().iter().find(|sym| sym.name == name).unwrap_or_else(|| panic!("no symbol {name}"))
|
||||
}
|
||||
|
||||
fn symbol_id(s: &Semantics, name: &str) -> SymbolId {
|
||||
let i = s.symbols().iter().position(|sym| sym.name == name).expect("symbol must exist");
|
||||
SymbolId(i as u32)
|
||||
}
|
||||
|
||||
fn resolution_at(s: &Semantics, offset: u32) -> Resolution {
|
||||
s.reference_at(offset).expect("a reference at the offset").resolution.clone()
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Binding
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_class_binds_a_symbol_a_scope_and_its_members() {
|
||||
let src = "\
|
||||
class c #(parameter int W = 8, type T = int);
|
||||
int prop;
|
||||
rand logic [W-1:0] bits;
|
||||
static int count;
|
||||
localparam int LP = 2;
|
||||
typedef enum { IDLE, BUSY } state_e;
|
||||
function new(int seed);
|
||||
endfunction
|
||||
virtual function int get(int idx);
|
||||
return prop + idx;
|
||||
endfunction
|
||||
extern task run(int cycles);
|
||||
endclass
|
||||
";
|
||||
let s = sem(src);
|
||||
let class = symbol_named(&s, "c");
|
||||
assert_eq!(class.kind, SymbolKind::Class);
|
||||
let scope = class.child_scope.and_then(|id| s.scope(id)).expect("a class scope");
|
||||
assert_eq!(scope.kind, ScopeKind::Class);
|
||||
|
||||
let expect = [
|
||||
("W", SymbolKind::Param),
|
||||
("T", SymbolKind::Param),
|
||||
("prop", SymbolKind::Var),
|
||||
("bits", SymbolKind::Var),
|
||||
("count", SymbolKind::Var),
|
||||
("LP", SymbolKind::Param),
|
||||
("state_e", SymbolKind::Typedef),
|
||||
("IDLE", SymbolKind::EnumVariant),
|
||||
("BUSY", SymbolKind::EnumVariant),
|
||||
("new", SymbolKind::Function),
|
||||
("get", SymbolKind::Function),
|
||||
("run", SymbolKind::Task),
|
||||
];
|
||||
for (name, kind) in expect {
|
||||
let member = symbol_named(&s, name);
|
||||
assert_eq!(member.kind, kind, "{name}");
|
||||
assert_eq!(member.scope, class.child_scope.expect("checked above"), "{name}");
|
||||
assert_eq!(&src[member.name_span.as_range()], name, "{name} span");
|
||||
}
|
||||
// The method body resolves the property and the header parameter.
|
||||
let prop = resolution_at(&s, nth(src, "prop + idx", 0));
|
||||
assert_eq!(prop, Resolution::Resolved(symbol_id(&s, "prop")));
|
||||
let w_use = resolution_at(&s, nth(src, "W-1", 0));
|
||||
assert_eq!(w_use, Resolution::Resolved(symbol_id(&s, "W")));
|
||||
// And the method argument.
|
||||
let idx = resolution_at(&s, nth(src, "prop + idx", 0) + 7);
|
||||
assert_eq!(idx, Resolution::Resolved(symbol_id(&s, "idx")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn member_definition_and_references_round_trip() {
|
||||
let src = "\
|
||||
class c;
|
||||
int counter;
|
||||
function void bump();
|
||||
counter = counter + 1;
|
||||
endfunction
|
||||
endclass
|
||||
";
|
||||
let s = sem(src);
|
||||
let id = symbol_id(&s, "counter");
|
||||
let uses = s.references_of(id);
|
||||
assert_eq!(uses.len(), 2, "both body uses, not the declaration");
|
||||
for r in &uses {
|
||||
assert_eq!(&src[r.name_span.as_range()], "counter");
|
||||
}
|
||||
// definition_of from a use lands on the declaration.
|
||||
let def = s.definition_of(nth(src, "counter + 1", 0)).expect("go to definition");
|
||||
assert_eq!(def.name, "counter");
|
||||
assert_eq!(def.kind, SymbolKind::Var);
|
||||
assert_eq!(def.name_span.start, nth(src, "counter", 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_method_arg_shadows_a_property_shadows_a_module_net() {
|
||||
let src = "\
|
||||
module m;
|
||||
wire x;
|
||||
class c;
|
||||
int x;
|
||||
function int f(int x);
|
||||
return x;
|
||||
endfunction
|
||||
function int g();
|
||||
return x;
|
||||
endfunction
|
||||
endclass
|
||||
assign x = 1;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
// Three distinct symbols named x, innermost wins at each use.
|
||||
let xs: Vec<_> = s.symbols().iter().filter(|sym| sym.name == "x").collect();
|
||||
assert_eq!(xs.len(), 3);
|
||||
let arg = resolution_at(&s, nth(src, "return x", 0) + 7);
|
||||
let prop = resolution_at(&s, nth(src, "return x", 1) + 7);
|
||||
let net = resolution_at(&s, nth(src, "assign x", 0) + 7);
|
||||
let kind_of = |r: &Resolution| match r {
|
||||
Resolution::Resolved(id) => s.symbol(*id).map(|sym| sym.kind),
|
||||
_ => None,
|
||||
};
|
||||
assert_eq!(kind_of(&arg), Some(SymbolKind::TfArg));
|
||||
assert_eq!(kind_of(&prop), Some(SymbolKind::Var));
|
||||
assert_eq!(kind_of(&net), Some(SymbolKind::Net));
|
||||
assert_ne!(arg, prop);
|
||||
assert_ne!(prop, net);
|
||||
// references_of splits cleanly per binding.
|
||||
for sym in &xs {
|
||||
let id = SymbolId(
|
||||
s.symbols().iter().position(|c| std::ptr::eq(*sym, c)).expect("from iteration") as u32,
|
||||
);
|
||||
assert!(s.references_of(id).len() <= 1);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// this / super
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn this_resolves_members_in_the_class_scope_only() {
|
||||
let src = "\
|
||||
module m;
|
||||
wire outside;
|
||||
class c;
|
||||
int prop;
|
||||
function void f(int prop);
|
||||
this.prop = prop;
|
||||
this.outside = 1;
|
||||
endfunction
|
||||
endclass
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
// this.prop names the property, not the shadowing argument.
|
||||
let via_this = resolution_at(&s, nth(src, "this.prop", 0) + 5);
|
||||
assert_eq!(via_this, Resolution::Resolved(symbol_id(&s, "prop")));
|
||||
let assigned = s.reference_at(nth(src, "this.prop = prop", 0) + 12).expect("the rhs");
|
||||
match &assigned.resolution {
|
||||
Resolution::Resolved(id) => {
|
||||
assert_eq!(s.symbol(*id).map(|sym| sym.kind), Some(SymbolKind::TfArg))
|
||||
}
|
||||
other => panic!("the bare rhs is the argument, got {other:?}"),
|
||||
}
|
||||
// this.outside cannot reach the module net, and c has no base to blame.
|
||||
let outside = resolution_at(&s, nth(src, "this.outside", 0) + 5);
|
||||
assert_eq!(outside, Resolution::NotFound);
|
||||
// `this` itself is never a recorded use.
|
||||
assert!(s.reference_at(nth(src, "this.prop", 0)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn super_and_inheritance_misses_record_the_base() {
|
||||
let src = "\
|
||||
class c extends uvm_object;
|
||||
function new(string name);
|
||||
super.new(name);
|
||||
super.whatever();
|
||||
set_name(name);
|
||||
endfunction
|
||||
endclass
|
||||
";
|
||||
let s = sem(src);
|
||||
let expect = Resolution::InheritedCandidate { base: "uvm_object".into(), paths: Vec::new() };
|
||||
assert_eq!(resolution_at(&s, nth(src, "super.new", 0) + 6), expect);
|
||||
assert_eq!(resolution_at(&s, nth(src, "super.whatever", 0) + 6), expect);
|
||||
// A plain call that misses the whole lexical chain blames the base too.
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "set_name", 0)),
|
||||
Resolution::InheritedCandidate { base: "uvm_object".into(), paths: Vec::new() }
|
||||
);
|
||||
// `super` itself is never a recorded use.
|
||||
assert!(s.reference_at(nth(src, "super.new", 0)).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inheritance_miss_keeps_the_import_paths_it_collected() {
|
||||
let src = "\
|
||||
class c extends uvm_component;
|
||||
import uvm_pkg::*;
|
||||
function void f();
|
||||
report(UVM_LOW);
|
||||
endfunction
|
||||
endclass
|
||||
";
|
||||
let s = sem(src);
|
||||
match resolution_at(&s, nth(src, "UVM_LOW", 0)) {
|
||||
Resolution::InheritedCandidate { base, paths } => {
|
||||
assert_eq!(base, "uvm_component");
|
||||
assert_eq!(paths, vec!["uvm_pkg::*".to_string()]);
|
||||
}
|
||||
other => panic!("expected an inherited candidate, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_and_new_are_never_plain_uses() {
|
||||
let src = "\
|
||||
class c;
|
||||
c next;
|
||||
function void f();
|
||||
next = new();
|
||||
next = null;
|
||||
endfunction
|
||||
endclass
|
||||
";
|
||||
let s = sem(src);
|
||||
assert!(s.reference_at(nth(src, "new()", 0)).is_none());
|
||||
assert!(s.reference_at(nth(src, "null", 0)).is_none());
|
||||
// The property use on the left still resolves.
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "next = new", 0)),
|
||||
Resolution::Resolved(symbol_id(&s, "next"))
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// extends
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn extends_resolves_to_an_in_file_class() {
|
||||
let src = "\
|
||||
class base #(parameter int W = 4);
|
||||
int held;
|
||||
endclass
|
||||
|
||||
class child extends base #(.W(8));
|
||||
endclass
|
||||
";
|
||||
let s = sem(src);
|
||||
let base_ref = resolution_at(&s, nth(src, "extends base", 0) + 8);
|
||||
assert_eq!(base_ref, Resolution::Resolved(symbol_id(&s, "base")));
|
||||
// The override name resolves into the base's scope.
|
||||
let w = resolution_at(&s, nth(src, ".W(8)", 0) + 1);
|
||||
assert_eq!(w, Resolution::Resolved(symbol_id(&s, "W")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extends_override_values_see_the_class_own_parameters() {
|
||||
let src = "\
|
||||
class base #(parameter int W = 4);
|
||||
endclass
|
||||
|
||||
class child #(parameter int CW = 16) extends base #(.W(CW));
|
||||
endclass
|
||||
";
|
||||
let s = sem(src);
|
||||
let cw = resolution_at(&s, nth(src, ".W(CW)", 0) + 3);
|
||||
assert_eq!(cw, Resolution::Resolved(symbol_id(&s, "CW")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extends_of_a_class_from_another_file_is_an_external_candidate() {
|
||||
let src = "\
|
||||
import uvm_pkg::*;
|
||||
|
||||
class c extends uvm_object;
|
||||
endclass
|
||||
";
|
||||
let s = sem(src);
|
||||
match resolution_at(&s, nth(src, "uvm_object", 0)) {
|
||||
Resolution::ExternalCandidate { paths } => {
|
||||
// The wildcard import and the bare unit name, in that order.
|
||||
assert_eq!(paths, vec!["uvm_pkg::*".to_string(), "uvm_object".to_string()]);
|
||||
}
|
||||
other => panic!("expected an external candidate, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_scoped_extends_records_head_and_tail() {
|
||||
let src = "\
|
||||
package p;
|
||||
class base;
|
||||
int held;
|
||||
endclass
|
||||
endpackage
|
||||
|
||||
class child extends p::base;
|
||||
endclass
|
||||
";
|
||||
let s = sem(src);
|
||||
let head = resolution_at(&s, nth(src, "p::base", 0));
|
||||
assert_eq!(head, Resolution::Resolved(symbol_id(&s, "p")));
|
||||
let tail = resolution_at(&s, nth(src, "p::base", 0) + 3);
|
||||
assert_eq!(tail, Resolution::Resolved(symbol_id(&s, "base")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_access_resolves_into_an_in_file_class() {
|
||||
let src = "\
|
||||
class c;
|
||||
localparam int K = 3;
|
||||
typedef logic [1:0] pair_t;
|
||||
endclass
|
||||
|
||||
module m;
|
||||
int x = c::K;
|
||||
c::pair_t y;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "c::K", 0) + 3),
|
||||
Resolution::Resolved(symbol_id(&s, "K"))
|
||||
);
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "c::pair_t", 0) + 3),
|
||||
Resolution::Resolved(symbol_id(&s, "pair_t"))
|
||||
);
|
||||
// A static miss on a class that extends blames the base.
|
||||
let src2 = "\
|
||||
class c extends base_c;
|
||||
endclass
|
||||
|
||||
module m;
|
||||
int x = c::MISSING;
|
||||
endmodule
|
||||
";
|
||||
let s2 = sem(src2);
|
||||
assert_eq!(
|
||||
resolution_at(&s2, nth(src2, "c::MISSING", 0) + 3),
|
||||
Resolution::InheritedCandidate { base: "base_c".into(), paths: Vec::new() }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_unit_miss_inside_an_extending_class_stays_external_a_member_miss_does_not() {
|
||||
// A base class supplies *members*, not package or class names (rules
|
||||
// 5/8): the head of `other_pkg::THING` and a nested class's own
|
||||
// `extends` base stay external candidates — the workspace's to answer —
|
||||
// while a plain member miss in the same position is the base's business.
|
||||
let src = "\
|
||||
class c extends base_c;
|
||||
function void f();
|
||||
int x = other_pkg::THING;
|
||||
member_miss();
|
||||
endfunction
|
||||
class inner extends other_base;
|
||||
endclass
|
||||
endclass
|
||||
";
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "other_pkg", 0)),
|
||||
Resolution::ExternalCandidate { paths: vec!["other_pkg".to_string()] }
|
||||
);
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "other_base", 0)),
|
||||
Resolution::ExternalCandidate { paths: vec!["other_base".to_string()] }
|
||||
);
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "member_miss", 0)),
|
||||
Resolution::InheritedCandidate { base: "base_c".into(), paths: Vec::new() }
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_member_of_an_in_file_package_is_not_found() {
|
||||
// The pinned rule 6 of the vlog-semantic README: the package is fully
|
||||
// known locally, so no workspace index could change the answer — and the
|
||||
// extends fallback must not leak into the package arm either.
|
||||
let src = "\
|
||||
package p;
|
||||
localparam int K = 1;
|
||||
endpackage
|
||||
|
||||
module m;
|
||||
int x = p::MISSING;
|
||||
endmodule
|
||||
|
||||
class c extends base_c;
|
||||
function void f();
|
||||
int y = p::ALSO_MISSING;
|
||||
endfunction
|
||||
endclass
|
||||
";
|
||||
let s = sem(src);
|
||||
assert_eq!(resolution_at(&s, nth(src, "p::MISSING", 0) + 3), Resolution::NotFound);
|
||||
assert_eq!(resolution_at(&s, nth(src, "p::ALSO_MISSING", 0) + 3), Resolution::NotFound);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Out-of-body definitions
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn an_out_of_body_definition_binds_into_the_class_and_round_trips() {
|
||||
let src = "\
|
||||
class c;
|
||||
int size;
|
||||
extern function void configure(int s);
|
||||
endclass
|
||||
|
||||
function void c::configure(int s);
|
||||
size = s;
|
||||
endfunction
|
||||
";
|
||||
let s = sem(src);
|
||||
// One `configure` symbol — the prototype — living in c's scope.
|
||||
let protos: Vec<_> = s.symbols().iter().filter(|sym| sym.name == "configure").collect();
|
||||
assert_eq!(protos.len(), 1, "the prototype is the symbol; the definition site is a use");
|
||||
let class = symbol_named(&s, "c");
|
||||
assert_eq!(protos[0].scope, class.child_scope.expect("class scope"));
|
||||
// The definition-site name is a reference to the prototype.
|
||||
let def_site = resolution_at(&s, nth(src, "c::configure", 0) + 3);
|
||||
assert_eq!(def_site, Resolution::Resolved(symbol_id(&s, "configure")));
|
||||
// The `c::` head navigates to the class.
|
||||
let head = resolution_at(&s, nth(src, "c::configure", 0));
|
||||
assert_eq!(head, Resolution::Resolved(symbol_id(&s, "c")));
|
||||
// The body resolves the property through the class scope.
|
||||
let size_use = resolution_at(&s, nth(src, "size = s", 0));
|
||||
assert_eq!(size_use, Resolution::Resolved(symbol_id(&s, "size")));
|
||||
// And the definition's own argument.
|
||||
let arg = resolution_at(&s, nth(src, "size = s", 0) + 7);
|
||||
match arg {
|
||||
Resolution::Resolved(id) => {
|
||||
assert_eq!(s.symbol(id).map(|sym| sym.kind), Some(SymbolKind::TfArg))
|
||||
}
|
||||
other => panic!("expected the argument, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_out_of_body_definition_for_an_unknown_class_stays_navigable_outward() {
|
||||
let src = "\
|
||||
function void elsewhere::helper(int x);
|
||||
int y;
|
||||
y = x;
|
||||
endfunction
|
||||
";
|
||||
let s = sem(src);
|
||||
// The class is not in this file: the head is an external candidate...
|
||||
match resolution_at(&s, nth(src, "elsewhere", 0)) {
|
||||
Resolution::ExternalCandidate { paths } => {
|
||||
assert_eq!(paths, vec!["elsewhere".to_string()])
|
||||
}
|
||||
other => panic!("expected an external candidate, got {other:?}"),
|
||||
}
|
||||
// ...the method still binds (in the writing scope) and its body resolves.
|
||||
let helper = symbol_named(&s, "helper");
|
||||
assert_eq!(helper.kind, SymbolKind::Function);
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "y = x", 0) + 4),
|
||||
Resolution::Resolved(symbol_id(&s, "x"))
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Nesting and packaging
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn a_nested_class_binds_inside_its_outer_class() {
|
||||
let src = "\
|
||||
class outer;
|
||||
int shared;
|
||||
class inner;
|
||||
function int f();
|
||||
return shared;
|
||||
endfunction
|
||||
endclass
|
||||
endclass
|
||||
";
|
||||
let s = sem(src);
|
||||
let outer = symbol_named(&s, "outer");
|
||||
let inner = symbol_named(&s, "inner");
|
||||
assert_eq!(inner.kind, SymbolKind::Class);
|
||||
assert_eq!(inner.scope, outer.child_scope.expect("outer scope"));
|
||||
// The inner method reaches the outer property lexically (documented
|
||||
// simplification: static-vs-instance access is not modelled).
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "return shared", 0) + 7),
|
||||
Resolution::Resolved(symbol_id(&s, "shared"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_class_in_a_package_is_a_package_member() {
|
||||
let src = "\
|
||||
package p;
|
||||
class item;
|
||||
int len;
|
||||
endclass
|
||||
endpackage
|
||||
|
||||
module m;
|
||||
import p::*;
|
||||
item it;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
let item = symbol_named(&s, "item");
|
||||
let pkg = symbol_named(&s, "p");
|
||||
assert_eq!(item.scope, pkg.child_scope.expect("package scope"));
|
||||
// The type use in the importing module resolves through the wildcard.
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "item it", 0)),
|
||||
Resolution::Resolved(symbol_id(&s, "item"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_forward_declared_class_defers_its_members_to_the_workspace() {
|
||||
let src = "\
|
||||
typedef class later;
|
||||
|
||||
module m;
|
||||
int x = later::K;
|
||||
endmodule
|
||||
";
|
||||
let s = sem(src);
|
||||
assert_eq!(
|
||||
resolution_at(&s, nth(src, "later::K", 0) + 7),
|
||||
Resolution::ExternalCandidate { paths: vec!["later::K".to_string()] }
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Outline and opaque members
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn document_symbols_nest_class_members_under_the_class() {
|
||||
let src = "\
|
||||
class c;
|
||||
int prop;
|
||||
function void f();
|
||||
int local_v;
|
||||
endfunction
|
||||
endclass
|
||||
|
||||
function void c::g();
|
||||
int hidden;
|
||||
endfunction
|
||||
";
|
||||
let s = sem(src);
|
||||
let outline = s.document_symbols();
|
||||
assert_eq!(outline.len(), 1, "one top-level node: the class");
|
||||
let class = &outline[0];
|
||||
assert_eq!(s.symbol(class.symbol).map(|sym| sym.name.as_str()), Some("c"));
|
||||
let names: Vec<_> = class
|
||||
.children
|
||||
.iter()
|
||||
.filter_map(|d| s.symbol(d.symbol).map(|sym| sym.name.as_str()))
|
||||
.collect();
|
||||
assert_eq!(names, vec!["prop", "f", "g"], "members nest; method locals do not spill");
|
||||
let f = &class.children[1];
|
||||
let f_children: Vec<_> =
|
||||
f.children.iter().filter_map(|d| s.symbol(d.symbol).map(|sym| sym.name.as_str())).collect();
|
||||
assert_eq!(f_children, vec!["local_v"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verbatim_members_are_absent_but_nothing_crashes() {
|
||||
let src = "\
|
||||
class c;
|
||||
rand int x;
|
||||
constraint c_x { x inside {[0:7]}; }
|
||||
covergroup cg;
|
||||
coverpoint x;
|
||||
endgroup
|
||||
endclass
|
||||
";
|
||||
let s = sem(src);
|
||||
// No symbol for the constraint or covergroup names, no reference inside.
|
||||
assert!(s.symbols().iter().all(|sym| sym.name != "c_x" && sym.name != "cg"));
|
||||
assert!(s.reference_at(nth(src, "x inside", 0)).is_none());
|
||||
assert!(s.reference_at(nth(src, "coverpoint x", 0) + 11).is_none());
|
||||
// Queries at every offset stay panic-free.
|
||||
for offset in 0..=src.len() as u32 {
|
||||
let _ = s.definition_of(offset);
|
||||
let _ = s.symbol_at(offset);
|
||||
let _ = s.reference_at(offset);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Workspace index
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
fn index(files: &[(&str, &str)]) -> WorkspaceIndex {
|
||||
WorkspaceIndex::build(files.iter().map(|(p, s)| (PathBuf::from(p), *s)))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_scope_class_is_a_unit_and_cross_file_extends_resolves() {
|
||||
let sources = [
|
||||
("base.svh", "class base;\n int held;\n function void poke(); endfunction\nendclass\n"),
|
||||
("child.svh", "class child extends base;\nendclass\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let units = ws.units("base");
|
||||
assert_eq!(units.len(), 1);
|
||||
assert_eq!(units[0].kind, SymbolKind::Class);
|
||||
// Members are exported.
|
||||
assert_eq!(ws.member("base", "held").len(), 1);
|
||||
assert_eq!(ws.member("base", "poke").len(), 1);
|
||||
// The extends candidate resolves through the overlay.
|
||||
let file = parse_source(sources[1].1).expect("child parses");
|
||||
let s = analyze(&file, sources[1].1);
|
||||
let overlay = resolve_external(&s, &ws);
|
||||
let offset = nth(sources[1].1, "base", 0);
|
||||
match overlay.definition_of(&s, offset) {
|
||||
Some(Definition::External(defs)) => {
|
||||
assert_eq!(defs.len(), 1);
|
||||
assert_eq!(defs[0].kind, SymbolKind::Class);
|
||||
assert_eq!(&sources[0].1[defs[0].name_span.as_range()], "base");
|
||||
}
|
||||
other => panic!("expected the workspace answer, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_package_nested_class_reaches_through_imports_and_static_access() {
|
||||
let sources = [
|
||||
(
|
||||
"pkg.sv",
|
||||
"package p;\n class item;\n localparam int K = 9;\n endclass\nendpackage\n",
|
||||
),
|
||||
("use.sv", "import p::*;\n\nclass mine extends item;\n int x = item::K;\nendclass\n"),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
// The class is a package member, and its own members are registered
|
||||
// under the class's name (the nested-class recursion).
|
||||
assert_eq!(ws.member("p", "item").len(), 1);
|
||||
assert_eq!(ws.member("item", "K").len(), 1);
|
||||
assert_eq!(ws.counts().classes, 2, "one package member, one file-scope unit");
|
||||
|
||||
let file = parse_source(sources[1].1).expect("use.sv parses");
|
||||
let s = analyze(&file, sources[1].1);
|
||||
let overlay = resolve_external(&s, &ws);
|
||||
// extends item → through the wildcard import.
|
||||
match overlay.definition_of(&s, nth(sources[1].1, "extends item", 0) + 8) {
|
||||
Some(Definition::External(defs)) => assert_eq!(defs[0].kind, SymbolKind::Class),
|
||||
other => panic!("expected the class, got {other:?}"),
|
||||
}
|
||||
// item::K → through the member table keyed by the class name.
|
||||
match overlay.definition_of(&s, nth(sources[1].1, "item::K", 0) + 6) {
|
||||
Some(Definition::External(defs)) => {
|
||||
assert_eq!(defs[0].kind, SymbolKind::Param);
|
||||
assert_eq!(&sources[0].1[defs[0].name_span.as_range()], "K");
|
||||
}
|
||||
other => panic!("expected the param, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_symbols_list_classes_and_their_members() {
|
||||
let ws = index(&[(
|
||||
"p.sv",
|
||||
"package p;\n class driver;\n task run(); endtask\n endclass\nendpackage\n",
|
||||
)]);
|
||||
let hits = ws.workspace_symbols("driver");
|
||||
assert!(hits.iter().any(|h| h.name == "driver" && h.container == Some("p")));
|
||||
let runs = ws.workspace_symbols("run");
|
||||
assert!(runs.iter().any(|h| h.name == "run" && h.container == Some("driver")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inherited_candidates_are_not_the_workspace_overlays_business() {
|
||||
let sources = [
|
||||
("base.svh", "class base;\n int held;\nendclass\n"),
|
||||
(
|
||||
"child.svh",
|
||||
"class child extends base;\n function void f();\n held = 1;\n endfunction\nendclass\n",
|
||||
),
|
||||
];
|
||||
let ws = index(&sources);
|
||||
let file = parse_source(sources[1].1).expect("child parses");
|
||||
let s = analyze(&file, sources[1].1);
|
||||
// The miss on `held` is an inherited candidate — never chased, even
|
||||
// though the base is right there in the workspace (the documented
|
||||
// future round).
|
||||
let held = s.reference_at(nth(sources[1].1, "held = 1", 0)).expect("the use");
|
||||
assert_eq!(
|
||||
held.resolution,
|
||||
Resolution::InheritedCandidate { base: "base".into(), paths: Vec::new() }
|
||||
);
|
||||
let overlay = resolve_external(&s, &ws);
|
||||
let id = s.reference_id_at(nth(sources[1].1, "held = 1", 0)).expect("an id");
|
||||
assert!(overlay.get(id).is_none(), "the overlay holds external candidates only");
|
||||
}
|
||||
@@ -15,6 +15,9 @@ struct Totals {
|
||||
references: usize,
|
||||
resolved: usize,
|
||||
external: usize,
|
||||
/// Uses inside a class that only its `extends` (or an import) could
|
||||
/// supply — the honest third bucket class-semantics added.
|
||||
inherited: usize,
|
||||
/// Names the source scan could not place. Expected to stay at zero — a
|
||||
/// nonzero count means a construct whose name this crate cannot locate.
|
||||
unplaced: usize,
|
||||
@@ -35,22 +38,25 @@ impl Totals {
|
||||
self.references += total;
|
||||
self.resolved += resolved;
|
||||
self.external += sem.references().iter().filter(|r| r.is_external_candidate()).count();
|
||||
self.inherited += sem.references().iter().filter(|r| r.is_inherited_candidate()).count();
|
||||
}
|
||||
|
||||
fn unresolved(&self) -> usize {
|
||||
self.references - self.resolved - self.external
|
||||
self.references - self.resolved - self.external - self.inherited
|
||||
}
|
||||
|
||||
fn report(&self, label: &str) {
|
||||
let pct = |n: usize| 100.0 * n as f64 / self.references.max(1) as f64;
|
||||
println!(
|
||||
"{label}: {} files, {} symbols, {} references — {:.1}% resolved in-file, \
|
||||
{:.1}% external candidates, {:.1}% unresolved, {} names unplaced",
|
||||
{:.1}% external candidates, {:.1}% inherited candidates, {:.1}% unresolved, \
|
||||
{} names unplaced",
|
||||
self.files,
|
||||
self.symbols,
|
||||
self.references,
|
||||
pct(self.resolved),
|
||||
pct(self.external),
|
||||
pct(self.inherited),
|
||||
pct(self.unresolved()),
|
||||
self.unplaced,
|
||||
);
|
||||
|
||||
@@ -405,12 +405,13 @@ fn the_corpus_index_finishes_most_external_references() {
|
||||
let counts = ws.counts();
|
||||
println!(
|
||||
"workspace index: {} files in {:.2}s — {} modules, {} packages, {} file-scope typedefs, \
|
||||
{} exported members, {} define directives",
|
||||
{} classes, {} exported members, {} define directives",
|
||||
counts.files,
|
||||
build.as_secs_f64(),
|
||||
counts.modules,
|
||||
counts.packages,
|
||||
counts.typedefs,
|
||||
counts.classes,
|
||||
counts.members,
|
||||
counts.defines,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,598 @@
|
||||
# class-semantics
|
||||
|
||||
## Goal
|
||||
|
||||
Classes become first-class in `vlog_semantic`. The classes round
|
||||
(`docs/features/classes/README.md`) made class declarations parse and format,
|
||||
but filed the honest gap: *"no name declared inside a class body is indexed,
|
||||
hovered or navigable"* — a real LSP hole across the entire DV half of the
|
||||
corpus. This feature closes it: class declarations bind a `SymbolKind::Class`
|
||||
symbol and open a `ScopeKind::Class` scope; properties, methods, parameters,
|
||||
typedefs and nested classes bind inside it; references in method bodies
|
||||
resolve through the class scope chain; `extends`, `this.x`, `super.x`, static
|
||||
`cls::x` access and out-of-body `function void cls::method(...)` definitions
|
||||
all get honest resolutions; and the workspace index gains classes as units
|
||||
with their exported members, so cross-file `extends Base` resolves.
|
||||
|
||||
## Resolution rules as shipped
|
||||
|
||||
Numbered so the next round can cite them. LRM-informed, corpus-tempered —
|
||||
the deviations are stated where they happen.
|
||||
|
||||
1. **Binding.** `class c` binds a `Class` symbol in the enclosing scope and
|
||||
opens a `Class` scope. Header `#( ... )` parameters bind as `Param` in the
|
||||
class scope, exactly like module header parameters. Properties bind
|
||||
through the ordinary declarator path (`Var`, or `Net` for the never-seen
|
||||
net-typed member); `rand`/`static`/`local`/... qualifiers are irrelevant
|
||||
to binding. Methods bind as `Function`/`Task` with their own scopes and
|
||||
`TfArg`s; a prototype (`extern ...;`, `pure virtual ...;`) binds exactly
|
||||
like a full method with an empty body. Class-body typedefs, localparams,
|
||||
imports, enums (variants land in the class scope, per the same LRM rule
|
||||
as modules) and nested classes all ride the existing item walk — a class
|
||||
body is an item list, so no per-kind code was added.
|
||||
2. **Verbatim members stay opaque.** `constraint c { ... }` and
|
||||
`covergroup ... endgroup` are `ItemKind::Verbatim` leaves; no symbol is
|
||||
bound for a constraint or covergroup name and nothing inside one is
|
||||
scanned. Same contract as macro invocations and directives.
|
||||
3. **Lexical resolution.** A bare name in a method body walks the ordinary
|
||||
chain: method scope → class scope → enclosing (package/module/file),
|
||||
imports consulted per scope as everywhere else. *Deliberate LRM
|
||||
inexactness:* the LRM puts inherited members ahead of enclosing scopes;
|
||||
vfmt cannot see into a base class it does not model, so the full lexical
|
||||
chain is searched first and inheritance is the fallback. An in-file name
|
||||
therefore always wins over a hypothetical inherited one.
|
||||
4. **Inheritance is never chased — not even in-file.** `extends Base` itself
|
||||
is resolved as a reference (rule 5). But a member use that misses the
|
||||
whole lexical chain, written inside a class whose nearest
|
||||
extends-carrying enclosing class says `extends Base`, becomes
|
||||
`Resolution::InheritedCandidate { base, paths }` — `base` is the extends
|
||||
path as written (`uvm_component`, `pkg::base`), `paths` are the import
|
||||
paths the lexical walk collected on the way out (both could supply the
|
||||
name; recording both is the honest answer). Nothing chases `base`, in
|
||||
this file or out of it: a future hover/index round can, without this
|
||||
crate pretending it did inheritance resolution. The fallback applies to
|
||||
*member* uses only — a **unit-name** miss (a `p::x` head, an
|
||||
`extends`/`implements` base) stays `ExternalCandidate` even inside an
|
||||
extending class, because a base class supplies members, not package or
|
||||
class names (QA-found, lead-ruled; pinned by
|
||||
`a_unit_miss_inside_an_extending_class_stays_external_a_member_miss_does_not`).
|
||||
**Non-goals, stated:**
|
||||
no method-resolution-order, no override checking, no base-member lookup.
|
||||
5. **`extends Base` resolves as a unit reference** from the class's
|
||||
*enclosing* scope: the lexical chain is walked for a symbol of a unit
|
||||
kind (`Class`, `Package`, `Typedef` — the last so `typedef class c;`
|
||||
forward declarations answer), non-unit shadowers are skipped, and on a
|
||||
miss the reference is `ExternalCandidate` carrying every import path in
|
||||
the chain that could supply the name plus the bare name itself — so
|
||||
`import uvm_pkg::*; class c extends uvm_object;` offers
|
||||
`["uvm_pkg::*", "uvm_object"]` to the workspace. A scope-qualified base
|
||||
(`extends pkg::base`) records two references, head and tail, like
|
||||
`p::x` everywhere else; middle segments of a 3-deep chain are not
|
||||
recorded (none in the corpus).
|
||||
6. **`extends` parameter overrides** (`#(.W(8))`): `.W` resolves against the
|
||||
base class's scope when the base is in this file (its header params are
|
||||
ordinary class-scope symbols), else `ExternalCandidate { ["base::W"] }`
|
||||
— the last path segment names the unit, so the workspace member table
|
||||
answers it. Override *values* bind in the class's own scope: the LRM
|
||||
allows `extends base #(.W(W))` to reference the class's own parameters,
|
||||
and the corpus does it.
|
||||
7. **`this.x`** resolves `x` in the nearest enclosing class's scope only —
|
||||
a member access cannot name a method local or an enclosing module net.
|
||||
Miss → `InheritedCandidate { base }` when that class extends, else
|
||||
`NotFound`. **`super.x`** always records against the base, like an
|
||||
inheritance miss: `InheritedCandidate { base }` when the class extends,
|
||||
`NotFound` when it does not (super without a base is illegal anyway) —
|
||||
including `super.new(...)`. `this`, `super`, `null` and bare `new` are
|
||||
never recorded as plain uses: they are reserved words whose referent
|
||||
this crate either models specially (this/super) or cannot know without
|
||||
types (`new` names the constructor of the *assigned* class).
|
||||
8. **Static access `cls::x`.** The head of any `p::x` — expression or type
|
||||
position — is now a *unit* lookup (rule 5's walk), so it finds classes
|
||||
and packages alike, lexically, wherever they are declared (a class
|
||||
nested in an in-file package included). The tail is looked up in the
|
||||
unit's scope only: found → resolved; package miss → `NotFound` (the
|
||||
long-standing rule 6 of the vlog-semantic README: no index can change
|
||||
the answer); class miss → `InheritedCandidate { base }` when that class
|
||||
extends (a static member may be inherited), else `NotFound`; unit not
|
||||
in this file → `ExternalCandidate { ["cls::x"] }`. `import p::x` heads
|
||||
still resolve as packages only — only a package can be imported.
|
||||
9. **Out-of-body definitions** (`function void cls::method(...)`) are
|
||||
*deferred*: the whole file binds first, then each deferred method looks
|
||||
up `cls` (unit-kind lexical walk from the writing scope, descending
|
||||
through `::` segments) and binds the method symbol **into cls's scope**.
|
||||
When the extern prototype already declared the name there, the
|
||||
definition-site name becomes a *reference* to the prototype — the same
|
||||
redeclaration-becomes-reference rule non-ANSI ports use — so
|
||||
definition/references round-trip across the two sites. The body's scope
|
||||
hangs under cls's scope, so properties and params resolve from the
|
||||
body; the scope is marked as owned by the prototype symbol so method
|
||||
locals do not spill into the class outline. A reference is recorded for
|
||||
the `cls` segment itself (navigation to the class); when `cls` is not
|
||||
declared in this file the method binds in the writing scope instead and
|
||||
the `cls` reference becomes an external candidate.
|
||||
10. **Queries just work, zero API changes.** `definition_of`,
|
||||
`references_of`, `document_symbols` (classes nest their members; method
|
||||
bodies nest under methods), hover data and `workspace_symbols` all
|
||||
operate on class members through the existing code paths.
|
||||
|
||||
## Workspace index additions (all additive)
|
||||
|
||||
- Classes at file scope are **units**: `units("c")` returns them,
|
||||
`workspace_symbols` lists them, and a cross-file `extends Base` resolves
|
||||
through `follow_one`'s existing bare-name arm.
|
||||
- Class members (params, typedefs, enum variants, functions, tasks, vars,
|
||||
nets, nested classes) are **exported members**, and packages now also
|
||||
export the classes declared in them — so `import uvm_pkg::*` can answer
|
||||
`uvm_object` when the workspace holds it.
|
||||
- Member registration recurses through nested classes: a class inside a
|
||||
package (the dominant UVM shape) gets its members registered under the
|
||||
*class's* name, so an external `cls::x` candidate (`member("cls", "x")`)
|
||||
answers even though the class is not a file-scope unit.
|
||||
- `IndexCounts` gains a `classes` field (additive; all existing fields
|
||||
unchanged).
|
||||
- `resolve_external` does **not** chase `InheritedCandidate` — that is the
|
||||
documented future round, and the variant exists precisely so the index
|
||||
can do it without re-deriving anything.
|
||||
|
||||
## scan.rs status
|
||||
|
||||
Class binding introduces **zero** new `scan.rs` usage: every class-round AST
|
||||
node carries a parser `name_span` (the name-spans convention), and this round
|
||||
also completed the migration that feature left to us — module, package,
|
||||
function, task, genvar, import, foreach, typedef, declarator, enum member,
|
||||
instance, module-name, connection, gate-instance and block-label spans now
|
||||
come from the parser, and `typedef_name_span` / `decl_name` are deleted.
|
||||
`scan.rs` itself survives with exactly **two** consumers, both documented:
|
||||
|
||||
1. `bind_data_type` — a `DataType` has no span (vlog-semantic handshake
|
||||
item 2, still open with `vlog_parser`); the type-name window scan stays
|
||||
until it lands.
|
||||
2. `StmtKind::Disable` — deliberately given no span by name-spans (a use,
|
||||
not a declaration), so `name_after_kw` stays for it.
|
||||
|
||||
So the stretch goal (delete scan.rs) is **not** met, and honestly cannot be
|
||||
until handshake item 2 lands; the module is now ~40 lines of live use instead
|
||||
of the whole declaration surface. `Instantiation.module_span` has the
|
||||
documented despace caveat (`pkg :: mod`), so it is taken only when it slices
|
||||
back to the stored name exactly (`exact_or_empty`), preserving the
|
||||
"exact or empty" span contract and the corpus 0-unplaced assertion.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **Class scopes are ordinary lexical scopes for bare names.** The LRM
|
||||
restricts a nested class's access to its outer class's instance members;
|
||||
vfmt does not distinguish static from instance access and lets the chain
|
||||
through. More permissive, never corrupting, same argument as forward
|
||||
references everywhere.
|
||||
- **The nearest enclosing extends-carrying class supplies `base` for an
|
||||
inheritance miss**, even when the innermost class has no `extends` of its
|
||||
own. A nested class does not truly inherit its outer class's base; the
|
||||
corpus never nests a class inside an extending class, and the fallback
|
||||
only fires after the entire lexical chain already missed.
|
||||
- **`FunctionDecl::scope` / `TaskDecl::scope` and `ClassExtends::name` may
|
||||
glue `::` chains** whose source spelled spaces around the `::`. Every
|
||||
span derived from them is verified by slicing (`exact_or_empty` /
|
||||
skip-if-inexact), so a spaced spelling costs a reference, never a wrong
|
||||
span.
|
||||
- **`new` binds as a declaration** (`function new` is an ordinary `Function`
|
||||
symbol named `new`) but is never recorded as a use (rule 7).
|
||||
- The corpus test's populations shift: files with classes now contribute
|
||||
symbols and references they did not before, so the baseline table below
|
||||
is the honest new baseline, not comparable line-by-line with the old one
|
||||
beyond the stated before/after.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Consumed from `vlog_parser`** (no change requested): `ClassDecl`,
|
||||
`ClassExtends`, `Name`, `ImportPath`, `TypedefKind::ForwardClass`,
|
||||
`FunctionDecl`/`TaskDecl` `prefix`/`is_prototype`/`scope`, and every
|
||||
`name_span`/`label_span`/`module_span` the name-spans round added. Handshake
|
||||
item 2 (a `DataType` span) **remains open** — it is now the only thing
|
||||
keeping `scan.rs` alive (with the deliberate `Disable` exception).
|
||||
|
||||
**Promised to consumers** (additive, nothing renamed or removed):
|
||||
|
||||
- `SymbolKind::Class`, `ScopeKind::Class`,
|
||||
`Resolution::InheritedCandidate { base, paths }`,
|
||||
`Reference::is_inherited_candidate()`, `IndexCounts::classes`.
|
||||
- `analyze` still never panics or fails; every non-empty `name_span` still
|
||||
slices back to exactly the name (corpus-asserted, 0 unplaced).
|
||||
- `ExternalCandidate` semantics unchanged; `InheritedCandidate` is a new,
|
||||
third honest answer the workspace overlay currently leaves untouched.
|
||||
|
||||
**Compile-fixes outside this feature's scope, listed per the name-spans
|
||||
precedent** (`SymbolKind` is matched exhaustively downstream, so the new
|
||||
variant does not compile without them; each is one arm, no logic):
|
||||
|
||||
- `crates/vfmt_server/src/tokens.rs` — `SymbolKind::Class =>
|
||||
Highlight::Class` in `symbol_type`.
|
||||
- `crates/vfmt_server/src/symbols.rs` — `SymbolKind::Class => "class"` in
|
||||
`kind_label`, `SymbolKind::Class => LspKind::CLASS` in `lsp_kind`.
|
||||
|
||||
**Requested of a future round (not done here):** chasing
|
||||
`InheritedCandidate` — in-file via `Semantics`, cross-file via the
|
||||
workspace member table (`member(base_tail, name)` is already the right
|
||||
lookup); and hover text for "class c extends base".
|
||||
|
||||
## Corpus acceptance
|
||||
|
||||
`cargo test -p vlog_semantic --test corpus -- --nocapture`, same 860-file
|
||||
corpus, before → after this feature (both measured this round, same tree
|
||||
otherwise):
|
||||
|
||||
| population | | symbols | references | resolved in-file | external | inherited | unresolved | unplaced |
|
||||
|---|---|---:|---:|---:|---:|---:|---:|---:|
|
||||
| every file (860) | before | 21 243 | 71 938 | 76.3 % | 20.6 % | — | 3.1 % | 0 |
|
||||
| every file (860) | **after** | **25 475** | **88 569** | **72.1 %** | **17.8 %** | **7.6 %** | **2.5 %** | **0** |
|
||||
| clean files (671) | before | 15 202 | 56 220 | 78.3 % | 20.5 % | — | 1.3 % | 0 |
|
||||
| clean files (671) | **after** | **17 760** | **67 646** | **74.0 %** | **17.9 %** | **7.1 %** | **1.0 %** | **0** |
|
||||
|
||||
(The after rows include the 2026-08-20 QA fix: 198 clean-file / 359
|
||||
all-file unit-name misses moved from the inherited bucket back to the
|
||||
external bucket, where rules 5/8 always said they belonged.)
|
||||
|
||||
Reading it honestly:
|
||||
|
||||
- **+4 232 symbols and +16 631 references** (+2 558 / +11 426 on clean
|
||||
files) — the DV half of the corpus becoming navigable. That is the
|
||||
feature.
|
||||
- **The in-file rate drops** (78.3 % → 74.0 % clean), exactly as predicted:
|
||||
class code references UVM externals heavily. The drop is not lost
|
||||
resolution — the old denominator simply excluded every name inside a
|
||||
class. 7.1 % of all clean-file references are now `InheritedCandidate`
|
||||
(uses only a base class — almost always `uvm_pkg` machinery not in the
|
||||
corpus — could supply), reported as their own honest bucket, and the
|
||||
external-candidate share *fell* (20.5 % → 17.9 %) because many former
|
||||
wildcard-import candidates inside classes are now inherited candidates
|
||||
carrying those same paths.
|
||||
- **Unresolved *fell* too** (1.3 % → 1.0 % clean, 3.1 % → 2.5 % all): the
|
||||
this/super/null/new suppression removed noise, and names that used to
|
||||
dangle in class-bearing files now bind.
|
||||
- 0 panics, 0 unplaced names across 114 044 spans, both populations.
|
||||
|
||||
Workspace index over the same corpus
|
||||
(`cargo test -p vlog_semantic --test workspace -- --nocapture`): `530
|
||||
modules, 63 packages, 31 file-scope typedefs, 246 classes, 11 399 exported
|
||||
members` (9 202 members before — class members and package-exported classes
|
||||
are the growth), build ~0.8 s, determinism assertions green. The overlay
|
||||
now sees 12 111 clean-file external candidates and answers **11 009
|
||||
(90.9 %)** — before the QA fix it saw 11 913 and answered 10 839, so the
|
||||
fix handed the index 198 more candidates and it answered **170** of them,
|
||||
exactly the navigation QA measured as lost; the *rate* dips 0.1 pt only
|
||||
because the other 28 name units the corpus genuinely lacks. Against the
|
||||
pre-feature baseline (92.5 %) the remaining movement is population change:
|
||||
class code contributes candidates for units like `uvm_pkg` that no index
|
||||
over this corpus can answer. After-overlay unresolved-external rate:
|
||||
**1.6 %** of all clean-file references (1.5 % before, on the smaller
|
||||
pre-class denominator). The top misses are unchanged and all genuinely
|
||||
absent sources (`sail_ibexspec`, `SB_SPRAM256KA`, `PLLE2_ADV`, `uvm_pkg`).
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `SymbolKind::Class`, `ScopeKind::Class`, `Scope::extends` (crate-
|
||||
private), `Resolution::InheritedCandidate { base, paths }`
|
||||
- [x] `bind_class`: class symbol + scope, header params, extends refs +
|
||||
overrides, implements refs, body via the ordinary item walk
|
||||
- [x] this/super member targets; this/super/null/new never plain uses
|
||||
- [x] `Target::Unit` / `Target::UnitMember` (heads of `p::x` find classes;
|
||||
package behavior byte-identical); `Target::ThisMember` /
|
||||
`Target::SuperMember`
|
||||
- [x] Inheritance-miss shape: `InheritedCandidate` from the lexical walk,
|
||||
never chased
|
||||
- [x] Out-of-body methods deferred, bound into the class scope, prototype
|
||||
round-trip via redeclaration-becomes-reference
|
||||
- [x] bind.rs migrated off `scan.rs` for every parser-supplied span;
|
||||
`scan.rs` down to `bind_data_type` + `Disable` (documented)
|
||||
- [x] Workspace: classes as units, class members + package-exported classes
|
||||
+ nested-class recursion, `IndexCounts::classes`
|
||||
- [x] Corpus test reports the external/inherited breakdown (assertions kept:
|
||||
0 unplaced, < 3 % unresolved on clean files)
|
||||
- [x] 25 new behavior tests (`tests/classes.rs` — 23 from the dev round,
|
||||
plus the QA-fix pin for unit-vs-member misses and the permanent
|
||||
package-tail-miss `NotFound` pin); existing 46 green — corpus.rs
|
||||
reporting extended (inherited bucket + counter), the workspace corpus
|
||||
report prints the classes count, no existing assertion weakened or
|
||||
removed
|
||||
- [x] TODO.md §6 annotation; classes README handshake annotated delivered
|
||||
- [ ] Future round: chase `InheritedCandidate` (in-file + workspace);
|
||||
hover "extends base"
|
||||
- [ ] Still blocked on parser handshake item 2: delete `scan.rs`
|
||||
|
||||
## Work log
|
||||
|
||||
**2026-08-19 — dev agent.** Read CLAUDE.md, the vlog-semantic, classes,
|
||||
workspace-index and name-spans READMEs, and the five source files before
|
||||
touching anything. Baseline recorded first (test counts, corpus numbers —
|
||||
the "before" rows above). Key decisions:
|
||||
|
||||
- **`InheritedCandidate { base, paths }`, not just `{ base }`.** The task
|
||||
sketched `{ base }`; the walk already holds the import paths it collected
|
||||
when the miss happens, and dropping them would erase real candidates —
|
||||
`import uvm_pkg::*` and `extends uvm_component` can *both* supply
|
||||
`get_name`. Carrying both is the honest shape and costs a Vec that was
|
||||
already built.
|
||||
- **Full lexical chain before inheritance** (rule 3's stated LRM
|
||||
inexactness). The alternative — stopping at the class boundary because
|
||||
an invisible base *might* define the name — would turn every resolvable
|
||||
enclosing-scope reference in DV code into a guess. In-file facts win.
|
||||
- **Deferred binding for out-of-body methods.** Pass one cannot look up
|
||||
`cls` (it may not be bound yet — forward references are the point of the
|
||||
two-pass design), so out-of-body methods are collected during the walk
|
||||
and bound after it, when every class scope exists. This required the
|
||||
binder to borrow the tree (`Binder<'a>` now ties `src` and the item refs
|
||||
to one lifetime) — mechanical, no behavioral change elsewhere.
|
||||
- **The out-of-body body scope is marked owned by the prototype symbol**
|
||||
(without touching the prototype's own `child_scope`), purely so
|
||||
`document_symbols` does not spill method locals into the class outline —
|
||||
found by the nesting test, not predicted.
|
||||
- **Migrated bind.rs off scan.rs while in there.** The task required only
|
||||
"no new scan usage", but routing class names through parser spans while
|
||||
module names still went through the scanner would have left the crate
|
||||
half-and-half; the name-spans README explicitly left this migration "to
|
||||
vlog_semantic's next round", which is this one. `exact_or_empty` guards
|
||||
the one despace-caveat field (`module_span`). Corpus: 0 unplaced before,
|
||||
0 after, +20 863 spans.
|
||||
- **`Target::Package` kept for import heads** — only a package can be
|
||||
imported — while expression/type heads widened to `Target::Unit`. The
|
||||
existing package tests pass unmodified because the lexical unit walk
|
||||
finds file-scope packages exactly where `named_at_file_scope` did, and
|
||||
skips non-unit shadowers on the way.
|
||||
- **corpus.rs gained the inherited bucket.** Unavoidable: `InheritedCandidate`
|
||||
would otherwise count as "unresolved" and trip the < 3 % assertion the
|
||||
moment class files joined the clean population — the bucket is a new
|
||||
honest category, not a relaxation; both original assertions
|
||||
(0 unplaced, < 3 % unresolved on clean files) stand unweakened.
|
||||
- Ran the semantics suite, the full workspace suite, clippy and fmt at the
|
||||
end; exact results in the Status section and the final report.
|
||||
|
||||
**Checks at the end:** `cargo test -p vlog_semantic`: 69 passed, 0 failed
|
||||
(6 scan unit + 1 corpus + 19 semantics + 20 workspace + 23 classes).
|
||||
`cargo clippy --workspace --all-targets`: silent, 0 warnings.
|
||||
`cargo fmt --all -- --check`: clean. `cargo test --workspace`: **825
|
||||
passed, 0 failed** (summed over every `test result:` line). Corpus and
|
||||
workspace-index numbers above are from the final tree.
|
||||
|
||||
**2026-08-20 — dev agent, post-QA fix (lead-ruled).** Applied the QA log's
|
||||
LOW should-fix: a *unit-name* miss inside an extending class now stays
|
||||
`ExternalCandidate`, per rules 5/8 — a base class supplies members, not
|
||||
package or class names. Of the two offered fixes, took the first (honor the
|
||||
unit-lookup flag *before* the `nearest_extends` consult in `resolve.rs`'s
|
||||
`miss`, parameter renamed `always_external` → `unit_lookup` and the doc
|
||||
comment now states the ruling); member misses route to `InheritedCandidate`
|
||||
exactly as before. Also added the QA-recommended permanent pin for the
|
||||
package-tail-miss `NotFound` rule (it had only ever lived in deleted
|
||||
scratch suites). Two new tests in `classes.rs`:
|
||||
`a_unit_miss_inside_an_extending_class_stays_external_a_member_miss_does_not`
|
||||
(QA's exact repro, both shapes: a `p::x` head and a nested class's own
|
||||
`extends` base, plus the member-miss counterexample) and
|
||||
`a_missing_member_of_an_in_file_package_is_not_found` (from a module *and*
|
||||
from inside an extending class, so the extends fallback can never leak into
|
||||
the package arm again).
|
||||
|
||||
Measured effect (probe with exact counts, before → after the fix): clean
|
||||
files 11 913 → 12 111 external candidates (+198, inherited 4 980 → 4 782),
|
||||
overlay answered 10 839 → **11 009** (+170 — exactly the references QA
|
||||
measured as lost navigation; the answered *rate* dips 91.0 % → 90.9 %
|
||||
because all 198 join the denominator and the other 28 name units the
|
||||
corpus lacks). Every file: 15 433 → 15 792 external (+359, inherited
|
||||
7 057 → 6 698), answered 13 337 → 13 658 (+321). Resolved-in-file,
|
||||
unresolved and unplaced unchanged in every digit (74.0 % / 1.0 % / 0 clean;
|
||||
72.1 % / 2.5 % / 0 all). The measurement briefly reverted `miss` in the
|
||||
working tree to capture the "before" run; the fixed file was restored from
|
||||
a copy and byte-verified (`cmp`) before the final gates.
|
||||
|
||||
Checks after the fix: `cargo test -p vlog_semantic` **71 passed, 0 failed**
|
||||
(6 + 1 + 19 + 20 + 25); `cargo test --workspace` **827 passed, 0 failed**;
|
||||
`cargo clippy --workspace --all-targets` 0 warnings;
|
||||
`cargo fmt -p vlog_semantic -- --check` clean. Rule-4/5 prose and the
|
||||
acceptance tables above updated to the post-fix numbers.
|
||||
|
||||
## QA log
|
||||
|
||||
**2026-08-20 — QA agent.** Read CLAUDE.md, this README, the vlog-semantic
|
||||
README (rule 6, the pinned package-tail-miss rule) and the full diff of
|
||||
`model.rs` / `resolve.rs` / `bind.rs` / `lib.rs` / `workspace.rs` /
|
||||
`tests/{classes,corpus,workspace}.rs` and the three `vfmt_server` arms.
|
||||
Attacks ran as a 29-test scratch suite (`tests/qa_probe.rs`, deleted after
|
||||
the run) plus a baseline `git worktree` at `da1448e` used to re-measure the
|
||||
"before" rows independently. Scope was held to `-p vlog_semantic
|
||||
-p vfmt_server`; nothing outside this feature was touched.
|
||||
|
||||
**Gates re-run on the current tree.** `cargo test -p vlog_semantic`: **69
|
||||
passed, 0 failed** (6 lib + 23 classes + 1 corpus + 19 semantics + 20
|
||||
workspace) — the claimed split is exact. `cargo test -p vfmt_server`: 122
|
||||
passed (116 unit + 6 e2e), no test file modified. `cargo clippy
|
||||
-p vlog_semantic -p vfmt_server --all-targets`: **0 warnings**; the crates
|
||||
carry exactly one new `#[allow]` (`bind.rs:694`, `too_many_arguments`) and
|
||||
it is commented. `cargo fmt -p vlog_semantic -p vfmt_server -- --check`:
|
||||
clean. `cargo test --workspace`: **825 passed, 0 failed** (summed over 28
|
||||
`test result:` lines), reproducing the work log's number.
|
||||
|
||||
**Corpus, measured twice — byte-identical output both runs.** Every cell of
|
||||
the acceptance table reproduces exactly, and the "before" rows were
|
||||
re-measured in a clean worktree at `da1448e` rather than taken on trust:
|
||||
|
||||
| population | | symbols | references | resolved | external | inherited | unresolved | unplaced |
|
||||
|---|---|---:|---:|---:|---:|---:|---:|---:|
|
||||
| all (860) | before (re-measured) | 21 243 | 71 938 | 76.3 % | 20.6 % | — | 3.1 % | 0 |
|
||||
| all (860) | after | 25 475 | 88 569 | 72.1 % | 17.4 % | 8.0 % | 2.5 % | 0 |
|
||||
| clean (671) | before (re-measured) | 15 202 | 56 220 | 78.3 % | 20.5 % | — | 1.3 % | 0 |
|
||||
| clean (671) | after | 17 760 | 67 646 | 74.0 % | 17.6 % | 7.4 % | 1.0 % | 0 |
|
||||
|
||||
0 panics, 0 unplaced over 114 044 spans (25 475 + 88 569). Workspace index
|
||||
reproduces too: 860 files in 0.77 s, 530 modules / 63 packages / 31
|
||||
file-scope typedefs / **246 classes** / **11 399 members** / 502 defines
|
||||
(baseline: 9 202 members, no class count), determinism assertions green,
|
||||
clean-file overlay **91.0 %** answered and **1.6 %** after-overlay external
|
||||
(baseline **92.5 %** / **1.5 %**).
|
||||
|
||||
**The 92.5 % → 91.0 % explanation is correct — verified, not accepted.**
|
||||
Re-ran the overlay over the population that did *not* change (clean files
|
||||
containing no `class` keyword), in both trees:
|
||||
|
||||
- before: 529 files, 56 084 refs, 11 475 external candidates, 10 637
|
||||
answered = **92.7 %**
|
||||
- after: 56 063 refs, 11 460 external candidates, 10 640 answered =
|
||||
**92.8 %**
|
||||
|
||||
Flat. The whole move comes from class-bearing clean files, which went from
|
||||
136 to 11 583 recorded references; their ~453 external candidates answer at
|
||||
~44 % because they name `uvm_pkg` and friends the corpus genuinely lacks.
|
||||
The README's population-change wording is accurate.
|
||||
|
||||
**The `unresolved()` redefinition in `corpus.rs` is not a relaxation.**
|
||||
Both original assertions are textually intact (`all.unplaced == 0`,
|
||||
`100 * clean.unresolved() < 3 * clean.references`). The new bucket could
|
||||
only weaken the second if it absorbed misses from the pre-class population;
|
||||
it does not — over all 860 files, of 7 057 inherited candidates, **0** come
|
||||
from a file with no `class` keyword in it (probe q20). Inherited candidates
|
||||
are structurally reachable only under a `ScopeKind::Class` chain.
|
||||
|
||||
**Verified by attack (all green).**
|
||||
|
||||
- *Claim 2's crux.* An in-file base that really declares the member still
|
||||
yields `InheritedCandidate { base }`, never a resolution — for a property
|
||||
and for a method, with and without a competing wildcard import (q1, q4).
|
||||
A 3-level in-file chain `c extends b extends a` blames only `b` for both
|
||||
`from_a` and `from_b`: no chasing at any level (q2). Matches rules 3–4,
|
||||
which state the LRM inexactness as deliberate.
|
||||
- *UVM shape.* `import uvm_pkg::*; import my_pkg::*; class d extends
|
||||
uvm_component` — a miss carries the base **and** both paths in walk order
|
||||
(q3).
|
||||
- *this/super.* `this.x` is nearest-class-only even against an *outer*
|
||||
class's property: `NotFound`, not the outer `prop` (q5). A method arg
|
||||
shadowing a property loses to `this.x` while the bare name wins (q8,
|
||||
three distinct symbols). `super.x` in a non-extending inner class nested
|
||||
in an extending outer class is `NotFound` (q6); a plain lexical miss in
|
||||
the same position borrows the outer base (q7) — the documented
|
||||
nearest-extends-carrying assumption, behaving as written.
|
||||
- *`cls::`.* The pinned rule holds: an in-file package with no such member
|
||||
is `NotFound`, both from a module (q9) and from inside an extending class
|
||||
(q10) — the extends fallback does not leak into the package arm. Class
|
||||
tail-miss → `InheritedCandidate`; `cls::CONSTANT` and `cls::static_var`
|
||||
resolve from a module and from a sibling class (q29). A non-unit
|
||||
shadower (`int base;` in the way of `extends base`) is skipped (q27).
|
||||
`outer::inner` resolves to the nested class; a bare `inner::K` from
|
||||
outside is `ExternalCandidate { ["inner::K"] }`, which the member table
|
||||
(keyed by class name) answers — consistent, no gap.
|
||||
- *Out-of-body.* Prototyped and non-prototyped shapes both bind into the
|
||||
class scope (q14), including a definition written *before* the class
|
||||
(q28) and `task p::c::run` through a package-qualified path (q15). Method
|
||||
locals never reach the class outline in either shape (q16).
|
||||
- *Outline.* Nested classes nest their own members; method locals sit under
|
||||
the method, not the class (q25).
|
||||
- *Tolerant trees.* Six broken shapes (missing `endclass`, `extends;`,
|
||||
broken prototype arg list, `::`-leading definition, duplicate nested
|
||||
name, self-extends) analyze without panic at every byte offset, and every
|
||||
non-empty span still slices back to its own name (q17). Spaced `c :: f`
|
||||
and `extends base ;` cost a reference but never mislocate one (q18).
|
||||
- *Workspace.* Cross-file `extends p::item` resolves head → package, tail →
|
||||
class through the overlay (q19).
|
||||
- *scan.rs.* 26 call sites at `da1448e` → **3** now, in exactly the two
|
||||
documented consumers (`bind_data_type` at `bind.rs:1082,1089`;
|
||||
`StmtKind::Disable` at `bind.rs:913`). Zero new usage from class binding.
|
||||
Status section's wording is accurate.
|
||||
|
||||
**Sabotage check.** Rewrote `this_member` to try the full lexical chain
|
||||
first. Exactly one test caught it — `classes.rs:179`
|
||||
`this_resolves_members_in_the_class_scope_only` (`this.prop` resolved to
|
||||
the shadowing `TfArg` instead of the property). The corpus test did not.
|
||||
Reverted; `resolve.rs` verified byte-identical to the pre-sabotage copy and
|
||||
the diffstat back to 185/20.
|
||||
|
||||
**Findings.**
|
||||
|
||||
- *Should-fix, LOW.* **A unit-name miss inside an extending class returns
|
||||
`InheritedCandidate`, not the `ExternalCandidate` rules 5 and 8
|
||||
document.** `resolve.rs`'s `unit()` ends in `miss(scopes, from, external,
|
||||
true)`, and `miss` consults `nearest_extends` before honouring
|
||||
`always_external` — so any `p::x` head, or a nested class's own `extends`
|
||||
base, written inside a class that extends, lands in the inherited bucket.
|
||||
Repro:
|
||||
```systemverilog
|
||||
class c extends base_c;
|
||||
function void f();
|
||||
int x = other_pkg::THING; // head → InheritedCandidate
|
||||
endfunction // { base: "base_c",
|
||||
endclass // paths: ["other_pkg"] }
|
||||
module m;
|
||||
int y = other_pkg::THING; // head → ExternalCandidate
|
||||
endmodule // { paths: ["other_pkg"] }
|
||||
```
|
||||
The same happens to `class inner extends other_base` nested inside
|
||||
`class outer extends base_c` → `InheritedCandidate { base: "base_c",
|
||||
paths: ["other_base"] }`. The paths are still carried, so nothing is
|
||||
*wrong*, but `resolve_external` ignores the inherited bucket by design,
|
||||
so the workspace never gets to answer these. Measured cost: **170**
|
||||
clean-file references whose bare-name path the index *does* hold as a
|
||||
unit — real go-to-definition the LSP loses (0.25 % of clean references;
|
||||
it is also part of the 92.5 → 91.0 move, on top of the population
|
||||
change). Two honest fixes, dev's choice: thread `always_external`
|
||||
*through* to suppress the inheritance fallback for unit lookups (a base
|
||||
class cannot supply a package name), or state the deviation in rules 5/8
|
||||
and let the overlay chase `InheritedCandidate.paths`. Filed, not fixed —
|
||||
it is a design call, not a typo.
|
||||
- *Observation, no action.* The `InheritedCandidate` bucket is 4 980
|
||||
clean-file references; of those, **1 303** name a member the indexed base
|
||||
class genuinely has. That is the size of the documented future round, and
|
||||
it confirms the variant is carrying the right information for it.
|
||||
- *Observation, no action.* Class-free clean files show 21 fewer references
|
||||
and 15 fewer external candidates than at `da1448e` (56 084 → 56 063;
|
||||
11 475 → 11 460) with 3 *more* answered. Consistent with the
|
||||
`this`/`super`/`null`/`new` suppression and the `Target::Package` →
|
||||
`Target::Unit` widening reaching a little non-class code; immaterial and
|
||||
in the right direction. The Assumptions section already warns the
|
||||
populations are not line-by-line comparable — they are, to within 0.04 %,
|
||||
outside classes.
|
||||
- *Recommendation, no action taken (out of this QA's write scope).* The
|
||||
pinned package-tail-miss rule still has **no permanent test** — the
|
||||
vlog-semantic QA log records it living in a since-deleted scratch suite,
|
||||
and neither `semantics.rs` nor `classes.rs` pins it today. It survived
|
||||
this round's `Target::PackageMember` → `Target::UnitMember` rewrite (I
|
||||
re-checked it by probe, twice, including from inside an extending class),
|
||||
but a rewrite of that arm is exactly what would silently break it.
|
||||
Worth three lines in `classes.rs`.
|
||||
- **No BLOCKING findings.** No panic, no unplaced name, no wrong span, no
|
||||
wrong resolution: `this.x` never hit a shadow, inheritance was never
|
||||
chased, and the pinned `NotFound` rule held under every attack.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-20 — lead. Verdict: accepted after one directed fix; commits
|
||||
with round 20. The LSP navigation gap inside classes is closed: UVM
|
||||
code now has hover, definition, references and outline, with 114k
|
||||
spans bound and zero unplaced.**
|
||||
|
||||
Points reviewed and accepted:
|
||||
|
||||
1. **`InheritedCandidate` is the honest shape** — recording what an
|
||||
unknown base *might* supply (with the import paths widened in,
|
||||
rightly: extends and imports both compete to supply a member)
|
||||
instead of pretending inheritance resolution. QA confirmed the
|
||||
never-chased crux even for in-file bases, and its 1,303-candidate
|
||||
measurement is the precisely-sized backlog for the future chasing
|
||||
round.
|
||||
2. **The unit-vs-member routing fix** (QA-found, lead-ruled: a base
|
||||
class supplies members, not package or class names) recovered
|
||||
exactly the 170 lost navigations QA measured, is pinned by a test
|
||||
distinguishing both routes from inside one extending class, and is
|
||||
reported with the 198/170/28 accounting rather than a flattering
|
||||
rate claim. The pinned package-tail-miss rule finally has its
|
||||
permanent test — three lines that would have caught the exact
|
||||
rewrite that nearly broke it this round.
|
||||
3. **The scan.rs migration** (26 call sites → the 2 documented
|
||||
consumers, everything else on parser name-spans) was the stretch
|
||||
goal delivered as a side effect of doing the work properly.
|
||||
4. **The corpus movement is honest**: in-file resolution *dropped* as
|
||||
predicted (UVM externals entered the population), unresolved fell
|
||||
(this/super/null/new noise removed), and QA's flat-control check
|
||||
(class-free files: 92.7% → 92.8%) proved the rate move is entirely
|
||||
population, not regression.
|
||||
5. `this.x` nearest-class-only survived sabotage with exactly one test
|
||||
catching it — a reminder the corpus alone doesn't police scope
|
||||
subtleties; the unit suite does.
|
||||
|
||||
With this, round 20 closes and the owner's item-3 requirement is
|
||||
delivered. The inheritance-chasing round (1,303 candidates), DataType
|
||||
spans (scan.rs's last consumer), and Disable name-spans remain filed
|
||||
where they belong.
|
||||
@@ -181,7 +181,8 @@ added and nothing more:
|
||||
|
||||
Consequence, stated plainly: **no name declared inside a class body is
|
||||
indexed, hovered or navigable.** That is a real LSP gap, not an oversight, and
|
||||
it is the natural next round for that crate.
|
||||
it is the natural next round for that crate. **Delivered 2026-08-19 by
|
||||
`class-semantics`** — see `docs/features/class-semantics/README.md`.
|
||||
|
||||
**Requested of `vlog_formatter::fence` (out of this feature's scope):**
|
||||
`scan_nested` enumerates the item scopes a fence can live in — module,
|
||||
|
||||
@@ -463,6 +463,8 @@ is untouched by this diff (`git diff --stat` confirms), so this is
|
||||
pre-existing and out of this feature's scope — flagging for whoever next
|
||||
touches `lexer.rs`, since BOM'd files are a common artifact from
|
||||
Windows/VS Code and will reach the LSP path this feature exists to serve.
|
||||
*(2026-08-19: delivered by lexer-cleanup — a leading BOM now lexes, a
|
||||
mid-file BOM errors by name; `docs/features/lexer-cleanup/README.md`.)*
|
||||
|
||||
**CLAUDE.md compliance:** public items documented (`ParseDiagnostic` and its
|
||||
fields, `parse_tolerant`, `parse_source_tolerant`, `ItemKind::Error`,
|
||||
|
||||
@@ -0,0 +1,519 @@
|
||||
# lexer-cleanup
|
||||
|
||||
## Goal
|
||||
|
||||
Close the three lexer gaps filed by earlier QA rounds: (1) `@(* )` — an
|
||||
implicit sensitivity list with whitespace between `(*` and `)` — failed to
|
||||
lex because `(*` was unconditionally the start of an attribute (TODO §1);
|
||||
(2) a UTF-8 BOM at the start of a file was a lex error with a mojibake
|
||||
message (`unexpected character 'ï'` — one byte of the BOM's encoding,
|
||||
error-recovery QA log); (3) a non-ASCII character produced the same
|
||||
one-byte mojibake (`'Ã'` for `é`), and — the sneaky half — because the
|
||||
lexer is all-or-nothing, `vfmt check` on such a file reported *nothing*
|
||||
and exited 0 while `vfmt format` correctly refused (lint-rules-2 QA log).
|
||||
The fixes make the lexer's answers honest: real spellings lex, real errors
|
||||
name the actual character and position, and a file the linter could not
|
||||
tokenize is a loud per-file error instead of a silent pass.
|
||||
|
||||
## Assumptions
|
||||
|
||||
- **An attribute instance contains at least one attr_spec** (IEEE 1800
|
||||
§5.12), and an attr_spec cannot begin with `)`. That is what makes the
|
||||
backoff safe: `(*` followed — possibly after whitespace — by `)` cannot
|
||||
be an attribute, so it lexes as the three symbols `(` `*` `)` (the
|
||||
implicit sensitivity list). A file that really contained `(* )…*)` was
|
||||
invalid Verilog before and is a parse error now instead of an attribute
|
||||
token; `(* *)` (first non-whitespace after `(*` is `*`, not `)`) still
|
||||
lexes as an attribute, exactly as before.
|
||||
- **A leading BOM is treated like leading whitespace and is not
|
||||
preserved.** The formatter's output starts at the first token, so
|
||||
formatting a BOM'd file drops the BOM — a deliberate normalization, the
|
||||
same one `vfmt_core`'s config parser already applies to `vfmt.toml`. A
|
||||
BOM anywhere else in the file stays a lex error, now with a message that
|
||||
names it (`byte order mark (U+FEFF) is only allowed at the start of the
|
||||
file`).
|
||||
- **Columns are UTF-8 byte offsets** (the `LineIndex` convention), so the
|
||||
first token of a BOM'd file reports column 4. `LineIndex` is built over
|
||||
the same text and agrees.
|
||||
- **Non-ASCII characters remain invalid in Verilog source** outside
|
||||
comments, strings and escaped identifiers — the LRM allows only
|
||||
`[a-zA-Z_$0-9]` in simple identifiers. Only the *message* changed: it
|
||||
now decodes the whole character (`character 'é' (U+00E9) is not valid in
|
||||
Verilog source`) instead of the first byte of its encoding. The decode
|
||||
is defensive (`from_utf8_lossy` over at most 4 bytes) even though
|
||||
`tokenize` takes `&str` and the cursor always sits on a char boundary.
|
||||
- **A lex error under `vfmt check` is a per-file error (exit 2), matching
|
||||
`vfmt format` on the same file** — the frozen exit-code contract's
|
||||
"error" class. Text-level findings (tabs, trailing whitespace, line
|
||||
length) are still reported for such a file, because those rules really
|
||||
did run; the error says the token- and AST-level rules saw nothing, so
|
||||
the file must not pass as checked.
|
||||
|
||||
## Handshakes
|
||||
|
||||
**Changed in `vlog_parser::lexer` (consumed by everything downstream):**
|
||||
|
||||
- `(*` + whitespace + `)` now lexes as `(` `*` `)`. The parser already
|
||||
folds `@ ( * )` into `SensList::Star` (probed: `@( * )` — spaces on
|
||||
both sides of the star — lexed and formatted to `@(*)` before this
|
||||
round), so no parser change was needed.
|
||||
- A leading BOM is skipped; `tokenize` on `"\u{feff}…"` succeeds. The BOM
|
||||
bytes are covered by the losslessness suite's *gap* rule (see below).
|
||||
- Lex-error messages for non-ASCII bytes changed shape. Nothing parses
|
||||
messages today (grepped: callers only `Display` them), but tests that
|
||||
matched the old `unexpected character 'ï'` wording would break — none
|
||||
did.
|
||||
|
||||
**Promised to `vlog_formatter` — verify.rs untouched:** the `@`-collapse
|
||||
(`collapse_implicit_sensitivity`) already whitelists exactly the `@ ( * )`
|
||||
token sequence on both sides, which is what `@(* )` now lexes to on the
|
||||
input side and `@(*)` re-lexes to on the output side. Its comment's
|
||||
justification ("`(*` followed by anything other than `)` lexes as an
|
||||
attribute") now has one more exception — whitespace-then-`)` — but the
|
||||
conclusion it supports is unchanged: the `@ ( * )` sequence still has no
|
||||
meaning other than an implicit sensitivity list, so the collapse forgives
|
||||
nothing new. **No normalization in `verify.rs` was added, broadened or
|
||||
weakened** (hard invariant #4 does not apply; `git diff verify.rs` is
|
||||
empty). BOM: the formatter's output never contains one, and
|
||||
`verify_equivalence` re-lexes both sides with the same BOM-skipping lexer,
|
||||
so a BOM'd input verifies against BOM-less output with no forgiveness
|
||||
rule at all. Probed end to end: full format, format-twice fixed point, and
|
||||
`format_range` (verbatim splice starts at the first item's span, past the
|
||||
BOM) all converge.
|
||||
|
||||
**Changed in `vlog_linter::ParsedSource` (consumed by `vfmt check`):** a
|
||||
new field + accessor, `lex_error() -> Option<&LexError>`, kept from the
|
||||
`tokenize` failure that previously vanished into the error-tree fallback.
|
||||
Additive: `vfmt_server` builds contexts via `from_parse` with its own
|
||||
products and is untouched.
|
||||
|
||||
**Changed in `crates/vfmt/src/lint.rs`:** `run_rules` now also returns
|
||||
the rendered lex error; `check_one`/`check_stdin` put it in the report's
|
||||
`error` slot — the same slot unreadable files and panics use — so it
|
||||
prints `error: <path>: lex error: <line>:<col>: <message>` on stderr,
|
||||
counts into "N files could not be checked", and exits 2. Violations found
|
||||
by text rules on the same file are still printed.
|
||||
|
||||
**Requested of nobody.** The `vfmt_server` publishes lex errors through
|
||||
its own diagnostics path already; no change needed there.
|
||||
|
||||
## The macro space-before-paren item: assessed, PARKED
|
||||
|
||||
`docs/features/macro-items/README.md` (Assumptions) defers `` `M (a, b) ``
|
||||
— a macro call with a space before the argument list — because the lexer
|
||||
only attaches a `(` that immediately follows the name. The suggested fix
|
||||
is a whitespace skip before that `(`. Assessed here since this round was
|
||||
in the lexer anyway. **Verdict: not safe; parked.** The analysis:
|
||||
|
||||
1. **Expression position is live, not hypothetical.** Probed:
|
||||
`x = `A (b);` *parses today* as `ExprKind::Call { callee: `A, args:
|
||||
[b] }` — a valid tree, no error. Gluing the lexer would silently change
|
||||
that parse to a single opaque macro token. That is a *meaning* change
|
||||
candidate, not just an acceptance change, so "the fix only accepts
|
||||
previously-rejected input" — the argument that would have made it safe
|
||||
— is false.
|
||||
2. **Which reading is correct depends on the macro's definition, which
|
||||
the lexer cannot see.** A macro defined *with* formal arguments
|
||||
consumes the parenthesized list at usage; one defined *without* does
|
||||
not — `(b)` after it is ordinary source text (IEEE 1800 §22.5.1). The
|
||||
definition is routinely in another file (`include), so any fixed
|
||||
lexer-side answer is provably wrong for one of the two populations.
|
||||
`` `NOT (a) `` with `` `define NOT ~ `` is the counterexample: gluing
|
||||
turns a negation of `a` into a bogus one-argument invocation.
|
||||
3. ~~**The glue would also rewrite the text.**~~ *Struck by the lead per
|
||||
QA (premise probed false: the formatter reprints a macro token's text
|
||||
verbatim, internal spacing included, so under the hypothetical glue
|
||||
there is no text rewrite for the net to miss). The park does not rest
|
||||
on this argument — arguments 1, 2 and 4 carry it: the reading depends
|
||||
on a definition vfmt cannot see, a fixed answer is provably wrong for
|
||||
one population, and today's behavior fails safe.*
|
||||
4. **Today's behavior fails safe.** Item position: clean parse error
|
||||
(documented in macro-items). Expression position: the call parses, the
|
||||
formatter prints `` `A(b) ``, and `verify_equivalence` *refuses* the
|
||||
result (probed: "token stream diverges … input has identifier "`A" …
|
||||
output has identifier "`A(b)"") — the file is left untouched with an
|
||||
error, exit 2. Nothing corrupts. The workaround (write the call tight)
|
||||
stands; every corpus call site is already written tight.
|
||||
|
||||
Filed observation for a future round: that expression-position shape is
|
||||
a formatter *usability* gap (a parseable file that always errors out of
|
||||
formatting). A formatter-side fix — preserving the author's space
|
||||
between a macro identifier and a following `(` — would close it without
|
||||
touching the lexer, and is the direction to explore if it ever matters
|
||||
in practice.
|
||||
|
||||
## Status / TODO
|
||||
|
||||
- [x] `@(* )` family lexes: attribute scan backs off when the first
|
||||
non-whitespace after `(*` is `)`; real attributes unaffected.
|
||||
- [x] `@(* )` family through the formatter (`statements.cases`):
|
||||
canonicalizes to `@(*)`, verify + idempotency green.
|
||||
- [x] Leading BOM skipped like whitespace; spans suite's gap rule admits
|
||||
the leading BOM and BOM'd sources joined `SOURCES`; mid-file BOM is
|
||||
a clear, named error.
|
||||
- [x] Non-ASCII lex error names the character and codepoint.
|
||||
- [x] `vfmt check` on a file that does not lex: exit 2, stderr error,
|
||||
"could not be checked" summary; text-rule findings still reported.
|
||||
(`ParsedSource::lex_error` + `crates/vfmt/src/lint.rs`.)
|
||||
- [x] BOM'd file through format AND check (CLI tests); non-ASCII file
|
||||
through both (CLI test pins the no-longer-silent behavior).
|
||||
- [x] Losslessness/spans suites green with the BOM decision; error-recovery
|
||||
truncation fuzz green, plus a dedicated BOM'd-prefix truncation test.
|
||||
- [x] TODO §1 checkbox; annotations in error-recovery and lint-rules-2 QA
|
||||
logs.
|
||||
- [x] Macro space-before-paren: assessed, parked with analysis (above).
|
||||
|
||||
## Work log
|
||||
|
||||
### 2026-08-19 — dev agent
|
||||
|
||||
- Read CLAUDE.md, TODO §1, the error-recovery and lint-rules-2 QA logs,
|
||||
the macro-items Assumption, `lexer.rs`, `spans.rs`, `verify.rs`'s
|
||||
`@`-collapse, and `vfmt`'s check driver before touching code. Baseline:
|
||||
`cargo test --workspace` **791 passed**.
|
||||
- **Probed before designing** (scratchpad harness, deleted): `@( * )` and
|
||||
`@( *)` already lexed — only the adjacent-`(*` spellings (`@(* )`,
|
||||
`@(* )`, `@(*\n)`) failed, as "unterminated attribute" swallowing the
|
||||
rest of the file. That narrowed the fix to the attribute-scan backoff
|
||||
the TODO suggested and showed no parser work was needed.
|
||||
- **Backoff is a lookahead, not a rescan**: `starts_attribute()` peeks
|
||||
past whitespace after `(*`; first non-whitespace `)` ⇒ not an
|
||||
attribute. It also subsumes the old special case `(*)` (`peek_at(2) !=
|
||||
b')'`), so the branch condition got simpler, not hairier. EOF during
|
||||
the lookahead (`peek_at` returns 0) keeps the old "unterminated
|
||||
attribute" error.
|
||||
- **BOM: option (a) — accept it — chosen over erroring.** Consistency
|
||||
(`vfmt_core` already strips it from config files; editors add it
|
||||
silently; the LSP will see such buffers constantly) beat strictness.
|
||||
The losslessness invariant stays meaningful: the gap rule now reads
|
||||
"whitespace, or the file's leading BOM" — one named exception, only
|
||||
reachable in the first gap since a BOM anywhere else never lexes.
|
||||
Skipped in `RawLexer::new` (3 bytes, col 4), not in `skip_whitespace`,
|
||||
so mid-file BOMs stay errors rather than becoming invisible whitespace.
|
||||
- **Mojibake fix**: the fallback error arm decodes the full character
|
||||
(lossy, ≤4 bytes, `unwrap_or` — no `unwrap`) and names it with its
|
||||
codepoint; U+FEFF gets its own message since the character itself is
|
||||
invisible. ASCII errors keep their old wording.
|
||||
- **Check silence**: chose "per-file error, exit 2, keep text findings"
|
||||
over a synthetic violation. Reasons: it matches how check already
|
||||
reports unreadable files and panics (same `Report.error` slot, same
|
||||
stderr line shape, same "could not be checked" summary), it matches
|
||||
`vfmt format` on the same file (frozen contract: errors are exit 2),
|
||||
and a violation-shaped entry would imply a rule name and a waiver path
|
||||
that make no sense for "the file did not tokenize". The linter crate's
|
||||
only change is keeping the `LexError` it already caught
|
||||
(`ParsedSource::lex_error()`); rendering and exit policy live in the
|
||||
CLI, where the other per-file errors live.
|
||||
- `--fix` on a non-lexing file keeps its old behavior (text fixes still
|
||||
apply — they are span-based and safe) and now *also* reports the error;
|
||||
the lex error is re-read each round from `run_rules`, so a hypothetical
|
||||
fix that made the file lexable would clear it.
|
||||
- **Corpus verified before and after**: no corpus file contains
|
||||
`(*<ws>)` or a BOM (grepped), and the after-TSV md5
|
||||
`e6f12eb7964e22e452655cf517cae766` is byte-identical to the md5 already
|
||||
recorded by the round-17/18 READMEs — zero delta by path.
|
||||
- **Concurrency note:** another agent is mid-edit in `vlog_semantic`
|
||||
(`bind.rs`/`model.rs` currently do not compile), so the final gates are
|
||||
scoped to the four crates this feature touches; `cargo test --workspace`
|
||||
is re-run at the end only if their tree compiles. Nothing in this
|
||||
feature's scope overlaps theirs.
|
||||
- Did not touch `verify.rs`, `vfmt_server`, `vlog_semantic`. Did not run
|
||||
`git commit`/`git push`.
|
||||
|
||||
**Results:** `cargo test -p vlog_parser -p vlog_linter -p vlog_formatter
|
||||
-p vfmt`: **589 passed, 0 failed** (+11 tests: 7 lexer unit, 1
|
||||
error-recovery, 1 linter context, 2 CLI; plus 3 new spans sources and 6
|
||||
new `.cases` pairs inside existing tests). `cargo clippy -p vlog_parser
|
||||
-p vlog_linter -p vlog_formatter -p vfmt --all-targets` silent. `cargo
|
||||
fmt --check` clean on the same four crates. Corpus: 820 files, 77.6%
|
||||
formattable, 0 verification errors, 0 crashes, TSV byte-identical to the
|
||||
recorded baseline. Files touched: `crates/vlog_parser/src/lexer.rs`,
|
||||
`crates/vlog_parser/tests/{spans,error_recovery}.rs`,
|
||||
`crates/vlog_formatter/tests/cases/statements.cases`,
|
||||
`crates/vlog_linter/src/context.rs`, `crates/vfmt/src/lint.rs`,
|
||||
`crates/vfmt/tests/cli.rs`, `TODO.md` (§1 checkbox), two QA-log
|
||||
annotations, this README.
|
||||
|
||||
## QA log
|
||||
|
||||
### 2026-08-20 — QA agent
|
||||
|
||||
Verified against the working tree (four-crate scope; the concurrent
|
||||
class-semantics work in `vlog_semantic`/`vfmt_server` was finished and
|
||||
compiling by the end of the session, so the workspace gate was run too).
|
||||
All mutation experiments ran in a scratchpad copy of `crates/`; nothing
|
||||
outside this QA log was written.
|
||||
|
||||
**Gates (reproduced, not taken on trust)**
|
||||
|
||||
- `cargo test -p vlog_parser -p vlog_formatter -p vlog_linter -p vfmt`:
|
||||
**589 passed, 0 failed** — exactly the dev's number.
|
||||
- `cargo test --workspace`: **825 passed, 0 failed** (class-semantics
|
||||
landed in between; recorded for the lead, not claimed for this feature).
|
||||
- `cargo clippy -p vlog_parser -p vlog_formatter -p vlog_linter -p vfmt
|
||||
--all-targets` after touching the three changed sources to defeat the
|
||||
cache: **0 warnings, 0 errors**. `cargo fmt --check` on the same four:
|
||||
clean.
|
||||
- Corpus: `tools/corpus_check.sh corpus`, run **twice**. 820 files,
|
||||
636/820 (77.6%) formattable, 0 verification errors, 0 crashes, exit 0.
|
||||
TSV md5 **`e6f12eb7964e22e452655cf517cae766`** both times — byte-equal
|
||||
to the recorded baseline, zero delta.
|
||||
- Independently re-ran the dev's corpus grep over 860 `.v/.sv/.svh/.vh`
|
||||
files: **0** files with a leading BOM, **0** with a BOM anywhere, **0**
|
||||
matching `\(\*[ \t\r\n]+\)`. The corpus genuinely could not have moved.
|
||||
|
||||
**Claim 1 — attribute backoff: PASS.**
|
||||
|
||||
- `@(*)`, `@(* )`, `@(* )`, `@(*\t)`, `@(*\n)`, `@(*\r\n)` all lex to the
|
||||
four symbols `@ ( * )` with correct line/col on the `)`; `(*)` and
|
||||
`(* )` standalone lex to `( * )`. `@(*)` — the spelling the *old*
|
||||
`peek_at(2) != b')'` special case handled — goes through the new
|
||||
lookahead and comes out identical, so the subsumption claim holds.
|
||||
- Real attributes pinned unchanged: `(*keep*)`, `(* keep *)`,
|
||||
`(* a = 1, b *)`, `(* = *)`, `(**)`, `(* *)` (degenerate), `(*\n keep
|
||||
*)`, `(* x=")" *)` — all one `Attribute` token with the exact source
|
||||
text. `(* keep`, `(*`, `(* ` still error "unterminated attribute", so
|
||||
the EOF path (`peek_at` returning 0) is preserved.
|
||||
- **Legal-expression probe (the blocking risk): no misfire.** `a*(b)`,
|
||||
`a * (b)`, `assign y = a *(b);`, `assign y = a*( *b );`, `foo u1(.*);`,
|
||||
`foo u1(.* );` all lex to the same token streams they did before —
|
||||
confirmed the backoff can only fire on a *literally adjacent* `(*`,
|
||||
which the `*`-as-multiply shapes never produce (the `*` precedes the
|
||||
`(`). `a*(*b)` / `x = y*(*z);` still error "unterminated attribute" —
|
||||
unchanged from before the round, and not legal SV anyway.
|
||||
- The one behaviour that genuinely changed for previously-accepted text:
|
||||
a source where `(*<ws>)` opened an attribute that ran to a later `*)`
|
||||
(probed: `module m;\n (* )\n wire w; *)\nendmodule`) now lexes as
|
||||
symbols and becomes a parse error. Judged correct — IEEE 1800 §5.12
|
||||
requires at least one attr_spec and an attr_spec cannot begin with `)`,
|
||||
so every such text was already invalid Verilog. No legal input loses a
|
||||
parse.
|
||||
- **verify.rs untouched** (`git diff crates/vlog_formatter/src/verify.rs`
|
||||
empty), so invariant #4 does not fire. Re-attacked the `@`-collapse
|
||||
anyway with 10 crafted (input, corrupted-output) pairs, since the
|
||||
backoff widens the set of *inputs* that can produce the `@ ( * )`
|
||||
sequence it whitelists. The two benign canonicalizations (`@(* )` →
|
||||
`@(*)`, `@(* )` → `@*`) are accepted; all 8 corruptions are rejected —
|
||||
star dropped (`@()`), sens list narrowed (`@(a)`), `@` dropped, RHS
|
||||
changed under a forgiven `@(* )`, attribute→sens-list, sens-list→
|
||||
attribute, attribute inner spacing rewritten, a second `@(*)` invented.
|
||||
The collapse forgives nothing new.
|
||||
|
||||
**Claim 2 — BOM: PASS.**
|
||||
|
||||
- Leading BOM skipped; first token at `(1, 4)`, `span.start == 3`.
|
||||
BOM-only and BOM+whitespace-only sources lex to a lone `Eof`.
|
||||
BOM'd comment-only source lexes. Two BOMs: the second is a clean error
|
||||
at 1:4 with the named message, and both `check` and `format` exit 2
|
||||
leaving the file byte-identical (md5 compared).
|
||||
- Mid-file BOM positions are exact: `module m;\u{feff}` → 1:10,
|
||||
`module\u{feff}` → 1:7 — **no 3-byte skew**.
|
||||
- Tolerant parse of a BOM'd broken file (`\u{feff}module m;\n wire ;;;\n
|
||||
endmodule\n`): file span covers 0..len, both diagnostics slice back to
|
||||
the exact offending `;`. No skew.
|
||||
- Losslessness gap rule (`spans.rs:125`) judged **still meaningful**: the
|
||||
exception is `c == '\u{feff}' && at == 0`, i.e. one named character in
|
||||
the very first gap only. A BOM anywhere else never lexes, so it can
|
||||
never reach the walk — the rule cannot be widened accidentally by this
|
||||
wording. Sabotaging the skip makes
|
||||
`the_token_stream_covers_every_source_byte` fail (below), so the rule
|
||||
is load-bearing, not decorative.
|
||||
- **The drop-normalization reasoning checks out and is written down**
|
||||
(Handshakes ¶3). Confirmed live: `format_source` on a BOM'd file emits
|
||||
BOM-free text, `verify_equivalence(bom_input, bomless_output)` is
|
||||
`Ok`, format-twice is a fixed point, `verify_convergence` is `Ok`, and
|
||||
`format_range(..., "2-2")` also converges and is idempotent. The
|
||||
equivalence passes because the BOM never becomes a token, so both
|
||||
sides' streams are identical — not because of any forgiveness rule.
|
||||
Attacked that: with a BOM'd input, changing a token, dropping an item,
|
||||
and dropping a comment in the output are each rejected; a mid-file BOM
|
||||
in the *output* is rejected as "cannot re-lex the output". The only
|
||||
extra latitude is symmetric — an output that *added* a leading BOM
|
||||
would also verify — which is unreachable (the formatter never emits
|
||||
one) but noted as F6 below.
|
||||
- CLI: BOM'd file `check`s clean (exit 0, no output) and `format`s to
|
||||
BOM-free bytes, stable across two runs (md5 equal); `--lines 2-2` on a
|
||||
BOM'd file converges; BOM'd stdin formats and checks. Text-rule
|
||||
positions on a BOM'd file are byte-consistent with the `LineIndex`
|
||||
convention: tab at start of line 1 → `1:4`, trailing whitespace on line
|
||||
1 → `1:16`, tab on line 2 → `2:1`. That is the documented byte-offset
|
||||
convention, not a skew (see F3 for the LSP-facing consequence).
|
||||
- Truncation fuzz: the new `truncating_a_bom_prefixed_file_never_panics`
|
||||
passes. Note it survives the BOM sabotage (it only asserts no-panic and
|
||||
span coverage), so the BOM *acceptance* is pinned by the lexer unit
|
||||
tests, `spans.rs` and the CLI test rather than by this one — fine, but
|
||||
worth knowing which test guards what.
|
||||
- Extra 20 000-case randomized fuzz (scratchpad, deterministic seed) over
|
||||
a piece-pool including BOMs, `(*`, `(* )`, `*)`, `é`, escaped
|
||||
identifiers and macro calls: no panics; every token span in bounds and
|
||||
on a char boundary; **every token's `(line, col)` equal to
|
||||
`LineIndex::line_col(span.start)`** — the README's "`LineIndex` agrees"
|
||||
assumption verified over 11 294 lexing sources, BOM'd ones included;
|
||||
every one of 2 930 formattable sources idempotent and BOM-free.
|
||||
|
||||
**Claim 3 — non-ASCII message + check silence: PASS.**
|
||||
|
||||
- Full-character decode confirmed, no mojibake, no `unwrap`:
|
||||
`é` → `character 'é' (U+00E9) …` at 1:15; `日` → `(U+65E5)`; `😀` →
|
||||
`(U+1F600)` — the astral case proves the 4-byte window is right.
|
||||
Non-ASCII inside comments, string literals and escaped identifiers
|
||||
still lexes fine (not over-rejected).
|
||||
- Exit-code matrix, all reproduced live:
|
||||
| case | exit |
|
||||
|---|---|
|
||||
| lex-error file alone | 2, `error: …: lex error: 2:17: …`, "1 file could not be checked" |
|
||||
| lex-error + clean file | 2, clean file still checked |
|
||||
| lex-error + violation in another file | 2 (outranks 1), violation still printed, "found 1 violation, 1 file could not be checked" |
|
||||
| violation only | 1 |
|
||||
| clean only | 0 |
|
||||
- **The combination the brief asked for, verified live**: one file with a
|
||||
tab *and* a bad character (`tabbad.sv`) → `[no-tabs]` finding on
|
||||
**stdout**, `error: …: lex error: 2:7: …` plus the summary on
|
||||
**stderr**, **exit 2**. Streams confirmed separately with `2>/dev/null`
|
||||
and `1>/dev/null`.
|
||||
- `--fix` on a lex-error file with no text findings: file byte-identical
|
||||
(md5 before == after), error reported, exit 2. `--fix` on the tab+bad
|
||||
file: the tab fix is written back, the lex error is still reported, and
|
||||
the exit is **2** — the error survives the fix rounds as the work log
|
||||
claims.
|
||||
- `--output-format json`: stdout is still a single valid JSON array
|
||||
(parsed with `json.load`) containing only the real violations; the lex
|
||||
error goes to stderr and exit 2. See F5.
|
||||
- stdin: `vfmt check -` on non-lexing input → `error: <stdin>: lex error:
|
||||
…`, exit 2.
|
||||
- LSP spot-check (cheap, over stdio against `vfmt-server`): a BOM'd
|
||||
document containing `élan` publishes the new decoded message with a
|
||||
sane range on the right line, alongside the `no-tabs` warning;
|
||||
`textDocument/formatting` on it returns `[]` (fail-safe, no edit), and
|
||||
on a clean BOM'd document returns one whole-document edit starting at
|
||||
line 0 char 0 whose text is BOM-free. Positions sane throughout.
|
||||
|
||||
**Claim 4 — macro space-before-paren, PARKED: verdict PASS, one argument
|
||||
does not survive.** Every probe claim re-run independently:
|
||||
|
||||
- ✅ Argument 1: `assign x = `A (b);` parses **today** with **0
|
||||
diagnostics** into `Call { callee: Ident("`A"), args: [Ident("b")] }`.
|
||||
Live, not hypothetical — confirmed.
|
||||
- ✅ Argument 4: formatting it fails with exactly the quoted error —
|
||||
`verification failed: token stream diverges at index 6: input has
|
||||
identifier "`A" at 2:14, output has identifier "`A(b)" at 2:14` — and
|
||||
the file is left untouched, exit 2. Item position is a clean parse
|
||||
error (`expected declaration or instantiation (found "`A")`). Fails
|
||||
safe, confirmed.
|
||||
- ✅ Argument 2 is the load-bearing one and stands on its own: the
|
||||
correct reading depends on whether the macro was defined with formals,
|
||||
which lives in another file, so no fixed lexer-side answer is right for
|
||||
both populations.
|
||||
- ❌ **Argument 3's premise is false — see F2.** The formatter does *not*
|
||||
print a macro-with-args token "tight": it prints the captured text
|
||||
verbatim. Probed: `` `A( b , c ) `` and `` `A( b ) `` both format
|
||||
back **byte-identical**, and `` `A( b , c ) `` is one token whose
|
||||
text keeps every internal space. Under the hypothetical glue the token
|
||||
would be `` `A (b) `` (the text is taken from the backtick through the
|
||||
`)`, whitespace included), the formatter would reprint it verbatim, and
|
||||
the re-lex would match — so there would be no text rewrite for the
|
||||
equivalence net to mask. The "normalization that hides its own damage"
|
||||
framing does not apply. **The PARKED verdict is still correct** on
|
||||
arguments 1, 2 and 4; argument 3 asserts rather than proves and should
|
||||
be corrected or dropped so a future round does not rely on it.
|
||||
|
||||
**Claim 5 — gates: PASS** (numbers above; every figure in the work log's
|
||||
Results paragraph reproduced exactly).
|
||||
|
||||
**Sabotage + revert, diff-verified** (scratchpad copy of `crates/`, the
|
||||
repo tree never modified):
|
||||
|
||||
- Restoring the old special case (`c == b'(' && self.peek_at(1) == b'*'
|
||||
&& self.peek_at(2) != b')'`) fails, as it must:
|
||||
`lexer::tests::attribute_scan_backs_off_when_the_contents_are_just_a_star`,
|
||||
`spans::the_token_stream_covers_every_source_byte`, and
|
||||
`vlog_formatter tests/cases::case_tables` (the 6 new `.cases` pairs).
|
||||
- Reverting that and instead removing the BOM skip
|
||||
(`let pos = 0;`) fails `lexer::tests::a_leading_bom_is_skipped_like_whitespace`,
|
||||
`lexer::tests::a_bom_only_source_lexes_to_eof`,
|
||||
`spans::the_token_stream_covers_every_source_byte` and
|
||||
`cli::a_bom_prefixed_file_formats_and_checks_like_a_plain_one`.
|
||||
- Both pins are real. The repo tree is unchanged (`git diff --stat`
|
||||
identical to the session start apart from this QA log).
|
||||
|
||||
**Findings** — none blocking. No corruption, no backoff misfire on a real
|
||||
attribute or on legal expression code, no BOM position skew.
|
||||
|
||||
- **F1 (low, stale comment).** `crates/vlog_formatter/src/verify.rs:200`
|
||||
still reads "`(*` followed by anything other than `)` lexes as an
|
||||
attribute token". After this round that is only true modulo whitespace.
|
||||
The Handshakes section acknowledges it, but the comment itself — the
|
||||
justification a future reader will find when auditing the `@`-collapse
|
||||
— was not updated. Not fixed here: `verify.rs` is outside this
|
||||
feature's stated scope and outside my write scope. Suggested one-line
|
||||
amendment for the lead: "…anything other than (optional whitespace
|
||||
then) `)`…".
|
||||
- **F2 (should-fix, analysis accuracy).** README §"The macro
|
||||
space-before-paren item", argument 3 (lines ~127-130): "The formatter
|
||||
prints a macro-with-args token tight (`` `A(b) ``)". Probed false — the
|
||||
formatter reprints the token text verbatim, internal spacing included.
|
||||
The verdict does not depend on it; the argument does not support the
|
||||
conclusion it is offered for and should be corrected or removed.
|
||||
- **F3 (should-note, contract nuance).** `--lines`/`format_range` on a
|
||||
BOM'd file drops the BOM even when line 1 is not in any selected range
|
||||
(probed: `--lines 2-2` on a BOM'd file rewrote line 2 *and* removed the
|
||||
BOM). `vfmt --help`'s range-formatting text promises "emit every other
|
||||
byte exactly as written"; the leading BOM is now an unstated exception.
|
||||
Nothing corrupts (converges, verifies, idempotent), but an LSP range
|
||||
format will return an edit touching offset 0. One sentence in the help
|
||||
text or in Assumptions would close it.
|
||||
- **F4 (info).** `vfmt check` prints `error: <path>: lex error: …`;
|
||||
`vfmt format` prints `<path>: lex error: …` (no `error: ` prefix). Each
|
||||
is internally consistent with how that command reports its other
|
||||
per-file errors, and the exit class matches as the Assumptions claim —
|
||||
recorded only so the difference is not mistaken for a bug later.
|
||||
- **F5 (info).** `--output-format json` does not carry the lex error into
|
||||
the JSON array; a consumer reading only stdout sees the file as having
|
||||
no findings and must look at the exit code. This matches how unreadable
|
||||
files already behave, so it is consistent, but it is undocumented.
|
||||
- **F6 (info).** `verify_equivalence` also accepts an output that *adds*
|
||||
a leading BOM (the skip is symmetric). Unreachable — the formatter
|
||||
never emits one, and convergence would still hold — but it is a byte
|
||||
the net will not defend, so it is recorded.
|
||||
- **F7 (info, pre-existing).** `@(* /* c */ )` still fails with
|
||||
"unterminated attribute": the backoff skips whitespace, not comments.
|
||||
Behaviour is identical before and after this round (the old
|
||||
`peek_at(2)` test also saw `/`), so it is not a regression — just the
|
||||
remaining edge of the `@(*)` family.
|
||||
|
||||
## Review
|
||||
|
||||
**2026-08-19 — lead. Verdict: accepted; commits with round 20. Three
|
||||
old gaps closed the way filed items should be — narrowly, with the
|
||||
invariants consulted before the code.**
|
||||
|
||||
Points reviewed and accepted:
|
||||
|
||||
1. **`starts_attribute` as a lookahead, not a special case**: the
|
||||
backoff subsumes the old `@(*)` peek (QA verified the routing), and
|
||||
the misfire question — adjacent `(*` in legal expressions — came
|
||||
back clean across every multiplication shape probed. Eight
|
||||
corruption pairs re-attacked the `@`-collapse and all were
|
||||
rejected; invariant 4 never fired because nothing widened.
|
||||
2. **The BOM decision** (accept-as-named-exception) kept the
|
||||
losslessness invariant meaningful — QA sabotaged the exception and
|
||||
the suite caught it — and the drop-normalization argument is the
|
||||
right kind: equivalence passes because the BOM never becomes a
|
||||
token, not because anything forgives it. The 20k-case line/col
|
||||
fuzz settles the position-skew question conclusively.
|
||||
3. **The check-silence fix routes through the existing error slot**
|
||||
rather than inventing a violation shape — the frozen exit-code
|
||||
contract honored, and the tabs+bad-char combination verified live
|
||||
in both output streams at once.
|
||||
4. **The macro-paren park survives QA scrutiny minus one argument**:
|
||||
QA probed argument 3's premise false (macro tokens reprint
|
||||
verbatim, not tight), and the lead has struck it in the analysis
|
||||
above — the park stands on the definition-dependence,
|
||||
provably-wrong-for-one-population, and fails-safe arguments, which
|
||||
QA verified independently. An analysis that loses a bad argument
|
||||
and keeps its conclusion is stronger for it.
|
||||
|
||||
Lead fixes on acceptance: the struck argument 3; the stale
|
||||
`verify.rs:200` comment updated to name the backoff; the
|
||||
range-formatting README gained the BOM-drop edge note (QA's F3).
|
||||
F4-F7 stand as recorded info items.
|
||||
@@ -611,6 +611,9 @@ empty, confirmed byte-identical to the pre-sabotage state.
|
||||
wording "is reported" is not literally accurate for that case — pre-existing
|
||||
`context.rs` behavior, not introduced by this round, not worth a code
|
||||
change, just a one-clause wording fix if the README is touched again.
|
||||
*(2026-08-19: delivered by lexer-cleanup — `vfmt check` on a file that
|
||||
does not lex now reports the lex error and exits 2 instead of silently
|
||||
passing; `docs/features/lexer-cleanup/README.md`.)*
|
||||
- No preset false positive or false negative found on any probed shape.
|
||||
No panic on escaped, non-ASCII, or unparseable input.
|
||||
No corpus regression: diff is exactly and only additive.
|
||||
|
||||
@@ -57,6 +57,9 @@ already are, so support costs one AST leaf rather than a grammar.
|
||||
finding, 2026-08-19) — the fix is a whitespace skip in the lexer, but it
|
||||
would also make `` `WIDTH (a + b) `` in expression position swallow a
|
||||
following parenthesized expression, which needs its own thought.
|
||||
*(2026-08-19: assessed by lexer-cleanup and parked — the expression-position
|
||||
risk is real and the glue cannot be proven meaning-preserving; full
|
||||
analysis in `docs/features/lexer-cleanup/README.md`.)*
|
||||
- **Whitespace next to a line break inside a *string literal* is data, not
|
||||
layout.** This is the premise the first round of this feature got wrong; see
|
||||
the QA finding and the fix under Handshakes and Design. Everywhere else in a
|
||||
|
||||
@@ -237,6 +237,13 @@ settled on that second run** (checked to 12 iterations; none needed a third).
|
||||
point of the *whole-file* formatter. `vfmt` with no `--lines` afterwards will
|
||||
reformat more. That is the point of having formatted less.
|
||||
|
||||
*(Lead note, per lexer-cleanup QA: one more unstated exception to
|
||||
"every other byte exactly as written" — a leading BOM is dropped by
|
||||
`--lines`/`format_range` even when line 1 is not selected, because the
|
||||
lexer consumes it before any range logic runs. Benign: converges,
|
||||
verifies, and an LSP range edit at offset 0 is legal. Recorded here so
|
||||
the promise's edges are all in one place.)*
|
||||
|
||||
## CLI
|
||||
|
||||
```
|
||||
|
||||
@@ -181,7 +181,10 @@ region | generate block | for-generate header | for/foreach statement`.
|
||||
a name a macro would have produced is invisible to this crate, which is the
|
||||
same contract the formatter and the define table keep (TODO.md §7).
|
||||
- **No classes/constraints/UVM.** The parser does not accept them yet; when it
|
||||
does, they will need scope kinds of their own.
|
||||
does, they will need scope kinds of their own. *(Since closed for classes:
|
||||
`docs/features/class-semantics/README.md` — `ScopeKind::Class`, member
|
||||
binding, `extends`/`this`/`super`, `Resolution::InheritedCandidate`.
|
||||
Constraints and covergroups stay opaque verbatim leaves.)*
|
||||
|
||||
## Assumptions
|
||||
|
||||
@@ -296,7 +299,8 @@ anywhere, and under 3 % unresolved on cleanly-parsed files.
|
||||
- [x] Tests: 19 behavior tests + 6 scanner unit tests + corpus smoke test
|
||||
- [x] TODO.md §6 `vlog_semantic` checkbox
|
||||
- [ ] Deferred to the workspace index: resolving `ExternalCandidate`s
|
||||
- [ ] Deferred: interfaces/modports, classes — the parser does not accept them
|
||||
- [ ] Deferred: interfaces/modports — the parser does not accept them.
|
||||
Classes delivered 2026-08-19 by `class-semantics`
|
||||
- [ ] Deferred: `Symbol` type information (needed for hover text richer than
|
||||
"port, declared at line N")
|
||||
|
||||
|
||||
Reference in new issue
Block a user