Fragment mode and define continuation: the three .svh shapes that did not parse, and the define that was blamed on its class body

TODO section 22, coverage_gaps H4 corrected. Class-body and module-item
include fragments already parsed - the file-scope item loop is the
class-item loop. The three shapes that did not - a bare statement list,
an enum-member list (riscv-dv's CUSTOM_1, file, included between enum
members), a covergroup-item list - become SourceFile::fragment, detected
by a whole-file rule that cannot misfire on a valid file: the first
structural item failed (directives, macros and null items do not count;
a tolerant Ok that recorded a diagnostic counts as failed - an existing
parity test caught if/else reading as a generate-if to one parser and a
statement to the other), the file does not open with a design-unit
keyword, and a shape consumes the file to EOF, tried narrowest-first.
Each shape re-lexes a fresh token stream - Rewind does not restore the
tokens' comment buckets and the first draft lost comments on
non-fragment files. A fragment formats at indent zero through the
existing printers; its declarations bind; its enum variants are not
exported (pkg::CUSTOM_1 must not resolve to a name that does not
exist). FACTS stays 12.

The other .svh was never a fragment problem: a define whose formal
argument list spans two lines with no backslash. The lexer continues
such a directive until the list closes - incrementally, after QA found
the first cut quadratic on an unclosed list (20000 lines: 2.5 s ->
0.56 ms), pinned by a byte-visit counter.

Opentitan 12 -> 10 failing files, exactly the two predicted; corpus
813 -> 814 of 820; every remaining comment-gap failure proven to fail
identically outside a fragment.

docs/features/fragment-mode/README.md.

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
lucioandClaude Fable 5 committed 2026-09-02 07:34:31 -07:00
1 parent cbb80e884f
commit 4e62a14af6
23 files changed
+2786 -42

No files matched your search

+214 -12
View File
@@ -351,6 +351,80 @@ pub fn parse_tolerant(tokens: Vec<Token>, source: &str) -> (SourceFile, Vec<Pars
}
}
/// The three fragment shapes, in the order [`fragment_file`] tries them:
/// narrowest grammar first, so the shape that can only be one thing gets to
/// claim it before the shape that could read it as something else.
#[derive(Clone, Copy)]
enum Shape {
CoverItems,
EnumMembers,
Statements,
}
/// Design-unit keywords. A file that opens with one is a unit being written,
/// however broken the rest of it is, and is never re-read as a fragment — the
/// cheap guard that keeps mid-edit files off the retry path entirely.
const UNIT_OPENERS: &[&str] = &[
"module",
"macromodule",
"interface",
"program",
"package",
"class",
"primitive",
"checker",
"config",
"bind",
];
/// True for an item that says nothing about what kind of body it stands in: a
/// compiler directive, a macro invocation, a null `;`. All three are legal
/// wherever an item, a statement, an enum member or a cover item is, so a file
/// that has only these so far is still an open question.
fn is_prelude(kind: &ItemKind) -> bool {
matches!(kind, ItemKind::Directive(_) | ItemKind::MacroItem(_) | ItemKind::Empty)
}
/// Re-read `source` as a fragment: a whole file that is the bare middle of
/// some larger construct's body, `` `include``d at exactly that point.
///
/// Reached only when the file's **first** item failed to parse, so nothing
/// that is an item list today can change shape. A shape wins only if it
/// consumes the file to end of file, trailing comments included.
///
/// The shapes are tried narrowest first — cover items, enum members,
/// statements — because the wider grammars can read the narrower ones as
/// something else and would then bind the wrong symbols. `cp: coverpoint a;`
/// is a labelled `coverpoint a` declaration to the statement grammar and
/// `option.weight = 5;` is an assignment to it; an enum-member list is never a
/// statement list, because a statement ends at a `;` and a member list stops
/// in front of one. So the order is not a tie-break between equals: it is the
/// rule that the most specific reading of the same bytes wins.
///
/// Each shape gets its own freshly-lexed token stream rather than a rewind,
/// because a `Rewind` deliberately does not restore the tokens' own comment
/// buckets (see [`Rewind`]) and a fragment — unlike the verbatim captures the
/// rewind serves — has to print every comment back where it was written. The
/// re-lex costs nothing that matters: it only ever runs on a file whose first
/// item is already broken, and the guard above keeps design units out.
fn fragment_file(source: &str) -> Option<SourceFile> {
let tokens = crate::tokenize(source).ok()?;
if tokens
.first()
.is_some_and(|t| t.kind == TokenKind::Keyword && UNIT_OPENERS.contains(&t.text.as_str()))
{
return None;
}
for shape in [Shape::CoverItems, Shape::EnumMembers, Shape::Statements] {
// A clone rather than the same vector, for the reason above; strict in
// both modes, for the reason in [`Parser::read_fragment`].
if let Some(file) = Parser::new(tokens.clone(), source, false).read_fragment(shape) {
return Some(file);
}
}
None
}
/// A `SourceFile` that is one error item covering the whole text — what a
/// caller gets when the text cannot even be tokenized.
pub(crate) fn error_file(source: &str) -> SourceFile {
@@ -364,6 +438,7 @@ pub(crate) fn error_file(source: &str) -> SourceFile {
constraint_fallbacks: 0,
covergroups: 0,
covergroup_fallbacks: 0,
fragment: None,
}
}
@@ -1460,8 +1535,57 @@ impl<'a> Parser<'a> {
fn parse_source_file(&mut self) -> PResult<SourceFile> {
let mut items = Vec::new();
// The first item that carries structure decides what kind of file this
// is. One that parses settles it: this is an item list — a design
// unit, a package, a class body, a run of module items — and nothing
// re-reads it as anything else. One that fails is the only door to
// fragment mode; see [`fragment_file`]. Directives, macro invocations
// and null items do not settle it, because they are legal in *every*
// body, and a fragment routinely opens with one (`` `ifdef `` around
// the enum members it contributes).
let mut prelude_only = true;
while !self.at_eof() {
items.push(self.item_or_recover()?);
let start_pos = self.pos;
let start = self.here();
let diags_before = self.diagnostics.len();
match self.parse_item() {
Ok(item) => {
// A tolerant parse that recovered *inside* the item did not
// read it, it patched it — and the strict parse of the same
// bytes failed outright. Both must ask the fragment
// question at the same point or the editor would report
// errors on a file the formatter formats: `if (a) begin x =
// 1; end` is a generate-if whose body holds a statement.
let patched = self.diagnostics.len() > diags_before;
if prelude_only && patched {
if let Some(file) = fragment_file(self.source) {
self.diagnostics.truncate(diags_before);
return Ok(file);
}
}
prelude_only &= is_prelude(&item.kind) && !patched;
items.push(item);
}
Err(e) => {
if prelude_only {
if let Some(file) = fragment_file(self.source) {
self.diagnostics.truncate(diags_before);
return Ok(file);
}
}
if !self.tolerant {
return Err(e);
}
// Exactly what `item_or_recover` would have done, on the
// cursor the failure left behind — re-running the item to
// get there would move the comments it already drained.
// Asked once: a file that is not a fragment stays one.
prelude_only = false;
let raw = self.recover(start_pos, start, e);
let span = raw.span;
items.push(Item { meta: Meta::default(), kind: ItemKind::Error(raw), span });
}
}
}
let dangling = self.take_dangling();
// The cursor is on the EOF token, whose empty span sits at the end of
@@ -1474,9 +1598,51 @@ impl<'a> Parser<'a> {
constraint_fallbacks: self.constraint_fallbacks,
covergroups: self.covergroups,
covergroup_fallbacks: self.covergroup_fallbacks,
fragment: None,
})
}
/// Read the whole file as `shape`, and only accept it if the shape
/// consumed every token.
///
/// Nothing here recovers, in either mode: a shape that does not fit must
/// fail so the next one gets its turn, and a file that fits none keeps the
/// single error node — and the single diagnostic — a broken file has
/// always had.
fn read_fragment(&mut self, shape: Shape) -> Option<SourceFile> {
let fragment = match shape {
Shape::Statements => self.parse_stmts_to_eof().ok().map(Fragment::Statements)?,
Shape::EnumMembers => {
let (members, directives) = self.parse_enum_members(true).ok()?;
Fragment::EnumMembers { members, directives }
}
Shape::CoverItems => self.parse_cover_items(true).ok().map(Fragment::CoverItems)?,
};
if !self.at_eof() {
return None;
}
Some(SourceFile {
items: Vec::new(),
// Comments after the last element land in the slot they hold for
// every other file.
dangling: self.take_dangling(),
span: TextRange::new(0, self.cur().span.end),
constraint_fallbacks: self.constraint_fallbacks,
covergroups: self.covergroups,
covergroup_fallbacks: self.covergroup_fallbacks,
fragment: Some(fragment),
})
}
/// Statements up to end of file: the body of a statement fragment.
fn parse_stmts_to_eof(&mut self) -> PResult<Vec<Stmt>> {
let mut stmts = Vec::new();
while !self.at_eof() {
stmts.push(self.parse_stmt()?);
}
Ok(stmts)
}
/// Items nest through generate blocks and package bodies. Gated.
fn parse_item(&mut self) -> PResult<Item> {
self.enter()?;
@@ -2555,13 +2721,7 @@ impl<'a> Parser<'a> {
let event = self.parse_coverage_event()?;
let before_semi = self.gap_before(";");
self.expect_sym(";")?;
let mut items = Vec::new();
while !self.cur().is_kw("endgroup") {
if self.at_eof() {
return self.error("expected `endgroup`");
}
items.push(self.parse_cover_item()?);
}
let items = self.parse_cover_items(false)?;
let dangling = self.take_dangling();
// Strict, not [`Parser::expect_closer`]: an unclosed covergroup must
// *fail* here so the rewind puts the old flat scan back, which is what
@@ -2587,6 +2747,29 @@ impl<'a> Parser<'a> {
})
}
/// A covergroup's item list — coverpoints, crosses, options, directives.
///
/// Stops on `endgroup`; end of file before one is an error, which is what
/// makes an unclosed covergroup rewind to the verbatim capture rather than
/// swallow the rest of the file. `to_eof` swaps that closer for end of
/// file, which is a cover-item fragment.
fn parse_cover_items(&mut self, to_eof: bool) -> PResult<Vec<CoverItem>> {
let mut items = Vec::new();
loop {
if self.at_eof() {
if to_eof {
break;
}
return self.error("expected `endgroup`");
}
if !to_eof && self.cur().is_kw("endgroup") {
break;
}
items.push(self.parse_cover_item()?);
}
Ok(items)
}
/// The `coverage_event` of a covergroup header: `with function sample
/// (...)` or a clocking event. `sample` is matched by text, for the
/// reason `soft` and `dist` are.
@@ -4444,10 +4627,30 @@ impl<'a> Parser<'a> {
// (`typedef enum action_mask_t {...}`, prim_count_pkg.sv:10).
let base = if self.cur().is_sym("{") { None } else { Some(self.parse_type_ref()?) };
self.expect_sym("{")?;
let (members, directives) = self.parse_enum_members(false)?;
let dangling = self.take_dangling();
self.expect_sym("}")?;
Ok(EnumType { base, members, directives, dangling })
}
/// An `enum`'s member list, with the `` `ifdef``-style directives written
/// between the members.
///
/// The cursor starts just past the `{` and stops on the `}` that closes
/// it. `to_eof` swaps that closer for end of file, which is the only
/// difference between an enum body and an enum-member fragment — one
/// grammar, read by both (`docs/features/fragment-mode/README.md`).
fn parse_enum_members(
&mut self,
to_eof: bool,
) -> PResult<(Vec<EnumMember>, Vec<ListDirective>)> {
let mut members = Vec::new();
let mut directives = Vec::new();
self.take_list_directives(&mut directives, 0);
loop {
if to_eof && self.at_eof() {
break;
}
let start = self.here();
let mut meta = self.take_meta();
let Name { text: name, span: name_span } = self.expect_name()?;
@@ -4461,13 +4664,12 @@ impl<'a> Parser<'a> {
meta.trailing = self.take_trailing();
members.push(EnumMember { meta, name, name_span, range, value, comma, span });
let dirs = self.take_list_directives(&mut directives, members.len());
if (!comma && !dirs.any) || (dirs.any && self.cur().is_sym("}")) {
let at_close = if to_eof { self.at_eof() } else { self.cur().is_sym("}") };
if (!comma && !dirs.any) || (dirs.any && at_close) {
break;
}
}
let dangling = self.take_dangling();
self.expect_sym("}")?;
Ok(EnumType { base, members, directives, dangling })
Ok((members, directives))
}
/// `struct|union [packed] [signing] { members }` — the cursor is on the