directive-split: recover conditional-split constructs as verbatim items
An `ifdef/`else region whose arms are each an incomplete fragment of one declaration (alternative heads sharing a body; alternative struct bodies sharing a closing) no longer refuses: the strict parser recovers the whole construct as a verbatim item, exact source bytes, the constraint/covergroup precedent. The trigger requires an unmatched open bracket inside a region genuinely open at item scope — `Parser::open_conds` counts only at the single ItemKind::Directive producer, so opaque verbatim walks cannot perturb it, and a recovered block hands back the nesting it swallows. Corpus: 800 -> 813 / 820 (97.6% -> 99.1%), +13 files (12x riscv_core_setting.sv, riscv_instr_pkg.sv), pass set a strict superset. verify.rs untouched. Three dev passes, two adversarial QA rejections (stray-`endif laundering; open_conds pollution via opaque bodies), QA round 5 PASS. 26+12 new tests; workspace 1672 passed / 0 failed. Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
1 parent
22cfa91732
commit
b77b61e7de
4 files changed
+2297
-2
No files matched your search
@@ -0,0 +1,320 @@
|
||||
# alternative declaration heads sharing one body: the whole construct is one
|
||||
# verbatim block, so it comes back byte for byte
|
||||
# corpus/ibex/vendor/google_riscv-dv/target/rv32imc/riscv_core_setting.sv:98
|
||||
`ifdef DSIM
|
||||
privileged_reg_t implemented_csr[] = {
|
||||
`else
|
||||
const privileged_reg_t implemented_csr[] = {
|
||||
`endif
|
||||
MVENDORID, // Vendor ID
|
||||
MARCHID // Architecture ID
|
||||
};
|
||||
|
||||
parameter int AFTER = 1;
|
||||
----
|
||||
`ifdef DSIM
|
||||
privileged_reg_t implemented_csr[] = {
|
||||
`else
|
||||
const privileged_reg_t implemented_csr[] = {
|
||||
`endif
|
||||
MVENDORID, // Vendor ID
|
||||
MARCHID // Architecture ID
|
||||
};
|
||||
|
||||
parameter int AFTER = 1;
|
||||
====
|
||||
# alternative struct bodies sharing one closing brace, inside a package
|
||||
# corpus/ibex/vendor/google_riscv-dv/src/riscv_instr_pkg.sv:1236
|
||||
package p;
|
||||
`ifdef _VCP
|
||||
typedef struct packed {
|
||||
bit l;
|
||||
`else
|
||||
typedef struct{
|
||||
rand bit l;
|
||||
`endif
|
||||
} pmp_cfg_reg_t;
|
||||
|
||||
parameter int AFTER = 1;
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
`ifdef _VCP
|
||||
typedef struct packed {
|
||||
bit l;
|
||||
`else
|
||||
typedef struct{
|
||||
rand bit l;
|
||||
`endif
|
||||
} pmp_cfg_reg_t;
|
||||
|
||||
parameter int AFTER = 1;
|
||||
endpackage
|
||||
====
|
||||
# the block's *relative* layout is what survives: only the first line is
|
||||
# re-indented to the item's level, the rest is dedented by the block's start
|
||||
# column and indented back -- the fixed-point trick `constraint` uses
|
||||
module m;
|
||||
`ifdef A
|
||||
logic [3:0] x[] = {
|
||||
`else
|
||||
const logic [3:0] x[] = {
|
||||
`endif
|
||||
4'h1,
|
||||
4'h2
|
||||
};
|
||||
assign y = 1;
|
||||
endmodule
|
||||
----
|
||||
module m;
|
||||
`ifdef A
|
||||
logic [3:0] x[] = {
|
||||
`else
|
||||
const logic [3:0] x[] = {
|
||||
`endif
|
||||
4'h1,
|
||||
4'h2
|
||||
};
|
||||
assign y = 1;
|
||||
endmodule
|
||||
====
|
||||
# `ifndef and an `elsif chain: three rival spellings of one head, one body.
|
||||
# Only the first arm's `{` is counted, so the scan does not go looking for
|
||||
# two more closing braces.
|
||||
`ifndef A
|
||||
int x[] = {
|
||||
`elsif B
|
||||
const int x[] = {
|
||||
`else
|
||||
static int x[] = {
|
||||
`endif
|
||||
1
|
||||
};
|
||||
----
|
||||
`ifndef A
|
||||
int x[] = {
|
||||
`elsif B
|
||||
const int x[] = {
|
||||
`else
|
||||
static int x[] = {
|
||||
`endif
|
||||
1
|
||||
};
|
||||
====
|
||||
# a *balanced* region inside the shared tail is ordinary conditional text and
|
||||
# does not end the block early -- the item after it is still its own item
|
||||
`ifdef A
|
||||
int x[] = {
|
||||
`else
|
||||
const int x[] = {
|
||||
`endif
|
||||
1,
|
||||
`ifdef B
|
||||
2,
|
||||
`endif
|
||||
3
|
||||
};
|
||||
|
||||
parameter int AFTER=1;
|
||||
----
|
||||
`ifdef A
|
||||
int x[] = {
|
||||
`else
|
||||
const int x[] = {
|
||||
`endif
|
||||
1,
|
||||
`ifdef B
|
||||
2,
|
||||
`endif
|
||||
3
|
||||
};
|
||||
|
||||
parameter int AFTER = 1;
|
||||
====
|
||||
# comments: the one before the region leads the `ifdef, the ones written on
|
||||
# the directives and inside the arms are part of the verbatim bytes, and the
|
||||
# one after the terminating `;` stays outside the block and trails it
|
||||
// head
|
||||
`ifdef A // which
|
||||
int x[] = { // open
|
||||
`else // other
|
||||
const int x[] = {
|
||||
`endif
|
||||
// why
|
||||
1
|
||||
}; // done
|
||||
int y;
|
||||
----
|
||||
// head
|
||||
`ifdef A // which
|
||||
int x[] = { // open
|
||||
`else // other
|
||||
const int x[] = {
|
||||
`endif
|
||||
// why
|
||||
1
|
||||
}; // done
|
||||
int y;
|
||||
====
|
||||
# NEGATIVE: a region whose arms are each a whole item is not a split -- both
|
||||
# arms are parsed and laid out normally, as they always were
|
||||
`ifdef A
|
||||
wire x;
|
||||
`else
|
||||
wire y ;
|
||||
`endif
|
||||
----
|
||||
`ifdef A
|
||||
wire x;
|
||||
`else
|
||||
wire y;
|
||||
`endif
|
||||
====
|
||||
# NEGATIVE: a bracket that opens *and closes* inside one arm leaves nothing
|
||||
# open, so the region is ordinary text around ordinary items
|
||||
`ifdef A
|
||||
int x[] = {1, 2};
|
||||
`else
|
||||
int x[] = {3, 4};
|
||||
`endif
|
||||
----
|
||||
`ifdef A
|
||||
int x [] = {1, 2};
|
||||
`else
|
||||
int x [] = {3, 4};
|
||||
`endif
|
||||
====
|
||||
# a genuine split nested INSIDE a legitimately-open outer region: the guard
|
||||
# added for QA's stray-`endif finding is "a region is live", not "exactly one
|
||||
# region is live", so this still recovers
|
||||
`ifdef OUTER
|
||||
`ifdef DSIM
|
||||
privileged_reg_t csr[] = {
|
||||
`else
|
||||
const privileged_reg_t csr[] = {
|
||||
`endif
|
||||
MVENDORID
|
||||
};
|
||||
`endif
|
||||
parameter int AFTER = 1;
|
||||
----
|
||||
`ifdef OUTER
|
||||
`ifdef DSIM
|
||||
privileged_reg_t csr[] = {
|
||||
`else
|
||||
const privileged_reg_t csr[] = {
|
||||
`endif
|
||||
MVENDORID
|
||||
};
|
||||
`endif
|
||||
parameter int AFTER = 1;
|
||||
====
|
||||
# the same, shape B, inside a package inside an outer region
|
||||
package p;
|
||||
`ifdef OUTER
|
||||
`ifdef _VCP
|
||||
typedef struct packed {
|
||||
bit l;
|
||||
`else
|
||||
typedef struct{
|
||||
rand bit l;
|
||||
`endif
|
||||
} pmp_cfg_reg_t;
|
||||
`endif
|
||||
parameter int AFTER = 1;
|
||||
endpackage
|
||||
----
|
||||
package p;
|
||||
`ifdef OUTER
|
||||
`ifdef _VCP
|
||||
typedef struct packed {
|
||||
bit l;
|
||||
`else
|
||||
typedef struct{
|
||||
rand bit l;
|
||||
`endif
|
||||
} pmp_cfg_reg_t;
|
||||
`endif
|
||||
parameter int AFTER = 1;
|
||||
endpackage
|
||||
====
|
||||
# NEGATIVE: a stray `endif closes nothing, so the declaration next to it is
|
||||
# not a split -- and, since neither is a parse error on its own, both stay
|
||||
# ordinary items (lucisv does not validate directive nesting, and did not
|
||||
# before this work either)
|
||||
wire a;
|
||||
`endif
|
||||
int x[] = {1};
|
||||
----
|
||||
wire a;
|
||||
`endif
|
||||
int x [] = {1};
|
||||
====
|
||||
# over-suppression guard: directives written inside an opaque `constraint`
|
||||
# body no longer touch item-scope nesting, but the region around the body
|
||||
# still counts, so a genuine split after it still recovers
|
||||
class c;
|
||||
constraint co {
|
||||
`ifdef X
|
||||
x < 10;
|
||||
`endif
|
||||
}
|
||||
endclass
|
||||
|
||||
`ifdef DSIM
|
||||
int y[] = {
|
||||
`else
|
||||
const int y[] = {
|
||||
`endif
|
||||
1
|
||||
};
|
||||
parameter int AFTER = 1;
|
||||
----
|
||||
class c;
|
||||
constraint co {
|
||||
`ifdef X
|
||||
x < 10;
|
||||
`endif
|
||||
}
|
||||
endclass
|
||||
|
||||
`ifdef DSIM
|
||||
int y[] = {
|
||||
`else
|
||||
const int y[] = {
|
||||
`endif
|
||||
1
|
||||
};
|
||||
parameter int AFTER = 1;
|
||||
====
|
||||
# under-suppression guard: an earlier verbatim item (a constraint) inside the
|
||||
# very region the split sits in -- the outer `ifdef must still be counted
|
||||
`ifdef OUTER
|
||||
class c;
|
||||
constraint co {x < 10;}
|
||||
endclass
|
||||
|
||||
`ifdef DSIM
|
||||
int y[] = {
|
||||
`else
|
||||
const int y[] = {
|
||||
`endif
|
||||
1
|
||||
};
|
||||
`endif
|
||||
parameter int AFTER = 1;
|
||||
----
|
||||
`ifdef OUTER
|
||||
class c;
|
||||
constraint co {x < 10;}
|
||||
endclass
|
||||
|
||||
`ifdef DSIM
|
||||
int y[] = {
|
||||
`else
|
||||
const int y[] = {
|
||||
`endif
|
||||
1
|
||||
};
|
||||
`endif
|
||||
parameter int AFTER = 1;
|
||||
@@ -1129,3 +1129,131 @@ fn a_property_declarations_local_variable_may_not_be_dropped() {
|
||||
let output = "module m;\n property p;\n a |-> b;\n endproperty\nendmodule\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------
|
||||
// Split conditional regions (`docs/features/directive-split/README.md`)
|
||||
//
|
||||
// The recovery adds no forgiveness to the safety net -- verbatim bytes need
|
||||
// none -- but the capture is forgiveness-*adjacent* in exactly the way the
|
||||
// assertions above are: the block is re-lexed as ordinary tokens on both
|
||||
// sides, so every token inside it must still match. These are the crafted
|
||||
// (input, corrupted output) pairs CLAUDE.md's invariant #4 asks for, plus the
|
||||
// legitimate transformation that keeps the rejections from being vacuous.
|
||||
// ----------------------------------------------------------------------
|
||||
|
||||
/// The one shape all of these attack: alternative declaration heads sharing a
|
||||
/// body (`riscv_core_setting.sv:98`).
|
||||
fn split_region() -> String {
|
||||
"`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] = {\n\
|
||||
`endif\n // vendor\n MVENDORID\n};\n"
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_conditional_region_may_be_reindented() {
|
||||
let input = format!("module m;\n{}endmodule\n", split_region());
|
||||
let output = format_source(&input, &Config::default()).expect("must format");
|
||||
verify_equivalence(&input, &output).expect("only indentation changed");
|
||||
// ... and the second pass is a fixed point, which is what makes a
|
||||
// verbatim block safe to re-indent at all.
|
||||
let twice = format_source(&output, &Config::default()).expect("must format again");
|
||||
verify_convergence(&output, &twice).expect("idempotent");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_arm_of_a_split_region_is_rejected() {
|
||||
let input = split_region();
|
||||
let output = "`ifdef DSIM\nprivileged_reg_t csr[] = {\n`endif\n // vendor\n MVENDORID\n};\n";
|
||||
expect_divergence(&input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_endif_of_a_split_region_is_rejected() {
|
||||
let input = split_region();
|
||||
let output = "`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] = {\n // vendor\n MVENDORID\n};\n";
|
||||
expect_divergence(&input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_comment_inside_a_split_region_is_rejected() {
|
||||
let input = split_region();
|
||||
let output = "`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] = {\n`endif\n MVENDORID\n};\n";
|
||||
expect_divergence(&input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_regions_arms_may_not_be_swapped() {
|
||||
// Both arms are still there and the bytes still balance -- only which
|
||||
// one the `else selects has changed, which is a semantic rewrite.
|
||||
let input = split_region();
|
||||
let output = "`ifdef DSIM\nconst privileged_reg_t csr[] = {\n`else\nprivileged_reg_t csr[] = {\n`endif\n // vendor\n MVENDORID\n};\n";
|
||||
expect_divergence(&input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_ifdef_condition_is_rejected() {
|
||||
let input = split_region();
|
||||
let output = "`ifdef VCS\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] = {\n`endif\n // vendor\n MVENDORID\n};\n";
|
||||
expect_divergence(&input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dropped_element_of_a_split_regions_shared_body_is_rejected() {
|
||||
let input = "`ifdef DSIM\nint x[] = {\n`else\nconst int x[] = {\n`endif\n 1,\n 2\n};\n";
|
||||
let output = "`ifdef DSIM\nint x[] = {\n`else\nconst int x[] = {\n`endif\n 1\n};\n";
|
||||
expect_divergence(input, output);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_region_keeps_a_multiline_string_byte_for_byte() {
|
||||
let input = "`ifdef DSIM\nstring x[] = {\n`else\nconst string x[] = {\n`endif\n \"line one\n line two indented\"\n};\n";
|
||||
let output = format_source(input, &Config::default()).expect("must format");
|
||||
assert!(
|
||||
output.contains("\"line one\n line two indented\""),
|
||||
"the string's bytes changed:\n{output}"
|
||||
);
|
||||
verify_equivalence(input, &output).expect("nothing but indentation moved");
|
||||
}
|
||||
|
||||
/// QA repro (2026-08-26): a `` `endif `` with no region open is broken input,
|
||||
/// not a split. Recovering it would have `format_source` accept and rewrite
|
||||
/// invalid Verilog that a real toolchain rejects at preprocessing.
|
||||
#[test]
|
||||
fn a_stray_endif_next_to_an_open_bracket_is_refused_not_reformatted() {
|
||||
for input in [
|
||||
"int x[] = {\n`endif\n1\n};\n",
|
||||
"module m;\n int x[] = {\n`endif\n 1\n};\nendmodule\n",
|
||||
"module m;\n`ifdef FOO\n wire a;\n`endif\n`endif\n int x[] = {\n`else\n const int x[] = {\n`endif\n 1\n};\nendmodule\n",
|
||||
] {
|
||||
match format_source(input, &Config::default()) {
|
||||
Err(FormatError::Source(e)) => {
|
||||
assert!(e.to_string().contains('`'), "the directive is named: {e}");
|
||||
}
|
||||
Ok(out) => panic!("invalid input was accepted and rewritten as:\n{out}"),
|
||||
Err(e) => panic!("expected a parse refusal, got {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// QA repro (2026-08-26, round 4): an unbalanced `` `ifdef `` written inside a
|
||||
/// construct lucisv keeps as opaque bytes must not leak into the file's
|
||||
/// item-scope conditional nesting, where it would launder an unrelated stray
|
||||
/// `` `endif `` into a split and get invalid input reformatted with exit 0.
|
||||
#[test]
|
||||
fn an_opaque_body_cannot_launder_a_stray_endif_into_a_split() {
|
||||
for input in [
|
||||
// constraint, covergroup, property: all three walk their bodies token
|
||||
// by token to find their closer.
|
||||
"class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n }\nendclass\nint y[] = {\n`endif\n1\n};\n",
|
||||
"covergroup cg;\n`ifdef FAKE\n cp: coverpoint x;\nendgroup\nint y[] = {\n`endif\n1\n};\n",
|
||||
"module m;\n property p;\n`ifdef FAKE\n a |-> b;\n endproperty\n int y[] = {\n`endif\n1\n};\nendmodule\n",
|
||||
// Control: the inner directive balanced. The tail is still stray.
|
||||
"class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n`endif\n }\nendclass\nint y[] = {\n`endif\n1\n};\n",
|
||||
] {
|
||||
match format_source(input, &Config::default()) {
|
||||
Err(FormatError::Source(_)) => {}
|
||||
Ok(out) => panic!("invalid input was accepted and rewritten as:\n{out}"),
|
||||
Err(e) => panic!("expected a parse refusal, got {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -215,6 +215,17 @@ pub struct Parser<'a> {
|
||||
depth: u32,
|
||||
/// Chain links open on the current path; see [`MAX_CHAIN_LENGTH`].
|
||||
links: u32,
|
||||
/// Conditional-compilation regions open **at item scope** at the cursor:
|
||||
/// one per `` `ifdef `` / `` `ifndef `` that stood as an item and has not
|
||||
/// been closed by an `` `endif `` standing as an item.
|
||||
///
|
||||
/// Kept as running state because the split-conditional recovery must know
|
||||
/// whether a closing directive closes anything at all — a stray
|
||||
/// `` `endif `` is broken input, not a split. Maintained by exactly two
|
||||
/// places, [`Parser::note_item_conditional`] and
|
||||
/// [`Parser::split_conditional_item`]; see the former's doc for why it is
|
||||
/// *not* maintained in [`Parser::bump`].
|
||||
open_conds: u32,
|
||||
/// Recover from errors instead of returning them; see [`parse_tolerant`].
|
||||
tolerant: bool,
|
||||
/// The text the tokens were lexed from, in both modes: recovery copies a
|
||||
@@ -273,6 +284,44 @@ fn is_drive_strength(t: &Token) -> bool {
|
||||
t.kind == TokenKind::Keyword && DRIVE_STRENGTHS.contains(&t.text.as_str())
|
||||
}
|
||||
|
||||
/// Where an item started, for the recovery that may have to replace it whole.
|
||||
struct ItemMark {
|
||||
/// Index of the item's first token, past its attributes.
|
||||
pos: usize,
|
||||
/// Conditional regions open at that token.
|
||||
conds: u32,
|
||||
/// Diagnostics recorded before the item ran; a replaced parse's notes are
|
||||
/// dropped back to this length (tolerant mode only — strict has none).
|
||||
diags: usize,
|
||||
}
|
||||
|
||||
/// The word a compiler-directive token spells, without its backtick and
|
||||
/// without its argument: `` `ifndef FOO `` is `"ifndef"`. The empty string for
|
||||
/// anything that is not a directive token.
|
||||
fn directive_word(t: &Token) -> &str {
|
||||
if t.kind != TokenKind::Directive {
|
||||
return "";
|
||||
}
|
||||
let rest = t.text.strip_prefix('`').unwrap_or("");
|
||||
let end = rest.find(|c: char| !c.is_ascii_alphanumeric() && c != '_').unwrap_or(rest.len());
|
||||
rest.get(..end).unwrap_or("")
|
||||
}
|
||||
|
||||
/// `` `ifdef `` / `` `ifndef ``: opens a conditional-compilation region.
|
||||
fn opens_conditional(t: &Token) -> bool {
|
||||
matches!(directive_word(t), "ifdef" | "ifndef")
|
||||
}
|
||||
|
||||
/// `` `else `` / `` `elsif ``: starts the next arm of the region already open.
|
||||
fn continues_conditional(t: &Token) -> bool {
|
||||
matches!(directive_word(t), "else" | "elsif")
|
||||
}
|
||||
|
||||
/// `` `endif ``: closes the region already open.
|
||||
fn closes_conditional(t: &Token) -> bool {
|
||||
directive_word(t) == "endif"
|
||||
}
|
||||
|
||||
/// Split an optional [`Name`] into the `(text, span)` pair the nodes that keep
|
||||
/// a name in a `String` field store it as.
|
||||
fn split_label(name: Option<Name>) -> (Option<String>, Option<TextRange>) {
|
||||
@@ -291,6 +340,7 @@ impl<'a> Parser<'a> {
|
||||
pending_trailing: Vec::new(),
|
||||
depth: 0,
|
||||
links: 0,
|
||||
open_conds: 0,
|
||||
tolerant,
|
||||
source,
|
||||
diagnostics: Vec::new(),
|
||||
@@ -1118,7 +1168,12 @@ impl<'a> Parser<'a> {
|
||||
let tok = &mut self.tokens[self.pos];
|
||||
meta.leading.append(&mut tok.leading);
|
||||
}
|
||||
let kind = self.parse_item_kind()?;
|
||||
let mark =
|
||||
ItemMark { pos: self.pos, conds: self.open_conds, diags: self.diagnostics.len() };
|
||||
let kind = match self.parse_item_kind() {
|
||||
Ok(kind) => kind,
|
||||
Err(e) => self.split_conditional_item(&mark, e)?,
|
||||
};
|
||||
let span = self.span_from(start);
|
||||
if meta.trailing.is_none() {
|
||||
meta.trailing = self.take_trailing();
|
||||
@@ -1132,7 +1187,10 @@ impl<'a> Parser<'a> {
|
||||
}
|
||||
let t = self.cur();
|
||||
match t.kind {
|
||||
TokenKind::Directive => Ok(ItemKind::Directive(self.take_raw_text())),
|
||||
TokenKind::Directive => {
|
||||
self.note_item_conditional();
|
||||
Ok(ItemKind::Directive(self.take_raw_text()))
|
||||
}
|
||||
TokenKind::Keyword => self.parse_keyword_item(),
|
||||
TokenKind::Ident if self.at_bind_directive() => self.parse_bind().map(ItemKind::Bind),
|
||||
// `NoNMI: assume property (...)` and `restrict property (...)`:
|
||||
@@ -1765,6 +1823,206 @@ impl<'a> Parser<'a> {
|
||||
Ok(self.verbatim_since(start, col))
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Conditional-directive split recovery
|
||||
//
|
||||
// An `ifdef region whose arms are each an *incomplete fragment* of one
|
||||
// construct — two spellings of a declaration head sharing one body, two
|
||||
// struct bodies sharing one closing brace — is not a tree. There is no
|
||||
// AST for it and no layout to apply, so it joins `constraint`,
|
||||
// `covergroup` and the concurrent assertions in the verbatim bucket: the
|
||||
// exact source bytes, re-indented on the first line only.
|
||||
//
|
||||
// The recovery is deliberately hard to reach. It fires only after a real
|
||||
// parse failure, and only when that failure is the grammar refusing a
|
||||
// `else / `elsif / `endif that closes a region which is genuinely open
|
||||
// and which the failed item did not open, with a bracket the arm left
|
||||
// open. Everything else — a plain syntax error that merely sits near a
|
||||
// directive, a garbage token run with directives in it, an unterminated
|
||||
// region, a stray closer with nothing open — still refuses.
|
||||
// See `docs/features/directive-split/README.md`.
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// Count the conditional-compilation directive standing at the cursor,
|
||||
/// which the caller is about to consume as an `ItemKind::Directive`.
|
||||
///
|
||||
/// This is the **only** place [`Parser::open_conds`] grows, and the whole
|
||||
/// reason it is here rather than in [`Parser::bump`] is that `bump` cannot
|
||||
/// tell item scope from anything else. The constructs lucisv keeps as
|
||||
/// opaque bytes — `constraint`, `covergroup`, `property` / `sequence`,
|
||||
/// concurrent assertions, and the split regions this module produces —
|
||||
/// walk their bodies token by token *through* `bump` to find their closer,
|
||||
/// so counting there let a `` `ifdef `` written inside a constraint body
|
||||
/// leak into the file's item-scope nesting (QA round 4). Counting here
|
||||
/// instead makes "not item scope, does not count" the **default**: a new
|
||||
/// verbatim construct inherits the right behaviour by doing nothing, and
|
||||
/// there is no flag anyone can forget to set.
|
||||
///
|
||||
/// Saturating on the way down, so a stray closer near the top of a file
|
||||
/// cannot make a later, genuine region look unopened.
|
||||
fn note_item_conditional(&mut self) {
|
||||
let t = self.cur();
|
||||
if opens_conditional(t) {
|
||||
self.open_conds += 1;
|
||||
} else if closes_conditional(t) {
|
||||
self.open_conds = self.open_conds.saturating_sub(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn an item that is really one arm of a split conditional region into
|
||||
/// a verbatim block, or hand `err` back untouched.
|
||||
fn split_conditional_item(&mut self, mark: &ItemMark, err: ParseError) -> PResult<ItemKind> {
|
||||
if !self.at_split_conditional(mark) {
|
||||
return Err(err);
|
||||
}
|
||||
let Some((end_pos, conds_after)) = self.scan_split_extent(mark) else {
|
||||
return Err(err);
|
||||
};
|
||||
self.diagnostics.truncate(mark.diags);
|
||||
let start = self.tokens[mark.pos].span.start;
|
||||
let col = self.tokens[mark.pos].col;
|
||||
// Walk the span from the top rather than jumping the cursor: `bump`
|
||||
// is what moves a token's trailing comment into the pending bucket,
|
||||
// and the comment written after the construct's last token must end
|
||||
// up there for the next node to harvest. The copies that fall *inside*
|
||||
// the span — including the duplicates of the ones the failed parse
|
||||
// already moved — are dropped by `verbatim_since`.
|
||||
self.pos = mark.pos;
|
||||
while self.pos < end_pos && !self.at_eof() {
|
||||
self.bump();
|
||||
}
|
||||
// The block swallowed the region's own `else / `endif, which *are*
|
||||
// item-scope nesting even though they now sit inside opaque bytes.
|
||||
// The extent scan already worked out what they leave open, so this is
|
||||
// the second and last place `open_conds` moves.
|
||||
self.open_conds = conds_after;
|
||||
Ok(ItemKind::Verbatim(self.verbatim_since(start, col)))
|
||||
}
|
||||
|
||||
/// True when the item that began at `mark` failed *because* it is one arm
|
||||
/// of a conditional region it did not open.
|
||||
///
|
||||
/// Four things must hold at once:
|
||||
///
|
||||
/// 1. the cursor — where the failure was raised — stands on a
|
||||
/// `` `else `` / `` `elsif `` / `` `endif ``;
|
||||
/// 2. a conditional region was already open when the item started, so
|
||||
/// that directive has something to close. A stray closer opens nothing
|
||||
/// and ends nothing: it is broken input, and the parse error stands;
|
||||
/// 3. the item's own conditional nesting is back to zero there, so the
|
||||
/// live region is one opened *before* the item rather than by it;
|
||||
/// 4. the arm left a bracket open, i.e. it is structurally a fragment.
|
||||
/// A missing `;` leaves nothing open and is indistinguishable from a
|
||||
/// typo, so it is refused.
|
||||
fn at_split_conditional(&self, mark: &ItemMark) -> bool {
|
||||
let at = self.cur();
|
||||
if !continues_conditional(at) && !closes_conditional(at) {
|
||||
return false;
|
||||
}
|
||||
if mark.conds == 0 {
|
||||
return false;
|
||||
}
|
||||
let mut cond = 0i32;
|
||||
let mut brackets = 0i32;
|
||||
for t in self.tokens.get(mark.pos..self.pos).unwrap_or_default() {
|
||||
if t.kind == TokenKind::Directive {
|
||||
if opens_conditional(t) {
|
||||
cond += 1;
|
||||
} else if closes_conditional(t) {
|
||||
cond -= 1;
|
||||
}
|
||||
} else if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
|
||||
brackets += 1;
|
||||
} else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") {
|
||||
brackets -= 1;
|
||||
}
|
||||
}
|
||||
cond == 0 && brackets > 0
|
||||
}
|
||||
|
||||
/// One past the last token of the construct the split region belongs to,
|
||||
/// paired with the item-scope conditional nesting left open after it — or
|
||||
/// `None` when the file holds no such end.
|
||||
///
|
||||
/// The scan follows the *first* arm and skips the alternatives whole: the
|
||||
/// arms are rival spellings of the same thing, so counting all of their
|
||||
/// brackets would demand as many closers as there are arms. It ends where
|
||||
/// all three of (a) the regions the scan itself opened are closed, (b) the
|
||||
/// region that was already open has been closed — conditional nesting is
|
||||
/// back to the level it stood at where that region began — and (c) the
|
||||
/// brackets the chosen scan opened are closed: at the first `;` that sees
|
||||
/// all three.
|
||||
///
|
||||
/// A `` `else `` / `` `elsif `` / `` `endif `` met at scan level zero with
|
||||
/// no region live is a stray closer, not a split, and gives up — the same
|
||||
/// refusal the trigger makes, repeated here because the scan walks past
|
||||
/// the point the trigger looked at.
|
||||
fn scan_split_extent(&self, mark: &ItemMark) -> Option<(usize, u32)> {
|
||||
// Regions this scan opened, and regions that were already open when
|
||||
// it started. A directive at scan level zero belongs to the latter.
|
||||
let mut cond = 0i32;
|
||||
let mut live = mark.conds;
|
||||
let mut closed_outer = false;
|
||||
let mut brackets = 0i32;
|
||||
let mut i = mark.pos;
|
||||
while let Some(t) = self.tokens.get(i) {
|
||||
if t.kind == TokenKind::Eof {
|
||||
return None;
|
||||
}
|
||||
if t.kind == TokenKind::Directive {
|
||||
if opens_conditional(t) {
|
||||
cond += 1;
|
||||
} else if closes_conditional(t) {
|
||||
if cond > 0 {
|
||||
cond -= 1;
|
||||
} else {
|
||||
live = live.checked_sub(1)?;
|
||||
closed_outer = true;
|
||||
}
|
||||
} else if continues_conditional(t) && cond == 0 {
|
||||
live = live.checked_sub(1)?;
|
||||
closed_outer = true;
|
||||
i = self.skip_conditional_arms(i + 1)?;
|
||||
continue;
|
||||
}
|
||||
} else if t.is_sym("(") || t.is_sym("[") || t.is_sym("{") {
|
||||
brackets += 1;
|
||||
} else if t.is_sym(")") || t.is_sym("]") || t.is_sym("}") {
|
||||
brackets -= 1;
|
||||
if brackets < 0 {
|
||||
return None;
|
||||
}
|
||||
} else if t.is_sym(";") && brackets == 0 && cond == 0 && closed_outer {
|
||||
return Some((i + 1, live));
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Skip from `from` — just past a `` `else `` / `` `elsif `` — through the
|
||||
/// `` `endif `` that closes the region that directive belongs to, nested
|
||||
/// regions included. `None` if the file ends first.
|
||||
fn skip_conditional_arms(&self, from: usize) -> Option<usize> {
|
||||
let mut nested = 0i32;
|
||||
let mut i = from;
|
||||
while let Some(t) = self.tokens.get(i) {
|
||||
if t.kind == TokenKind::Eof {
|
||||
return None;
|
||||
}
|
||||
if opens_conditional(t) {
|
||||
nested += 1;
|
||||
} else if closes_conditional(t) {
|
||||
if nested == 0 {
|
||||
return Some(i + 1);
|
||||
}
|
||||
nested -= 1;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// True when the cursor opens a parameterized type's `#( ... )`.
|
||||
fn at_type_params(&self) -> bool {
|
||||
self.cur().is_sym("#") && self.nth(1).is_sym("(")
|
||||
@@ -6833,4 +7091,331 @@ mod tests {
|
||||
// The else-branch itself did not also take the comment.
|
||||
assert!(els.as_ref().expect("an else").meta.leading.is_empty());
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Split conditional regions (`docs/features/directive-split/README.md`)
|
||||
// ------------------------------------------------------------------
|
||||
|
||||
/// The verbatim item a split conditional region collapsed into, with the
|
||||
/// items that came before and after it, so every test can also assert
|
||||
/// that nothing around the region was swallowed.
|
||||
fn split_items(file: &SourceFile) -> Vec<String> {
|
||||
file.items
|
||||
.iter()
|
||||
.map(|i| match &i.kind {
|
||||
ItemKind::Verbatim(raw) => format!("verbatim:{}", raw.text),
|
||||
ItemKind::Directive(raw) => format!("directive:{}", raw.text),
|
||||
ItemKind::DataDecl(_) => "decl".to_string(),
|
||||
ItemKind::ParamDecl(_) => "param".to_string(),
|
||||
ItemKind::Typedef(_) => "typedef".to_string(),
|
||||
_ => "other".to_string(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alternative_declaration_heads_sharing_one_body_are_captured_verbatim() {
|
||||
// corpus/ibex/vendor/google_riscv-dv/target/rv32imc/riscv_core_setting.sv:98
|
||||
let src = "`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst privileged_reg_t csr[] \
|
||||
= {\n`endif\n MVENDORID\n};\n\nparameter int AFTER = 1;\n";
|
||||
let f = parse_ok(src);
|
||||
let kinds = split_items(&f);
|
||||
assert_eq!(kinds.len(), 3, "{kinds:?}");
|
||||
assert_eq!(kinds[0], "directive:`ifdef DSIM");
|
||||
assert_eq!(kinds[2], "param", "the item after the region was not swallowed");
|
||||
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") };
|
||||
assert_eq!(raw.text, src[raw.span.as_range()]);
|
||||
assert!(raw.text.starts_with("privileged_reg_t"), "{:?}", raw.text);
|
||||
assert!(raw.text.ends_with("};"), "{:?}", raw.text);
|
||||
assert!(raw.text.contains("`else") && raw.text.contains("`endif"), "{:?}", raw.text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alternative_struct_bodies_sharing_one_closing_are_captured_verbatim() {
|
||||
// corpus/ibex/vendor/google_riscv-dv/src/riscv_instr_pkg.sv:1236
|
||||
let src = "package p;\n`ifdef _VCP\n typedef struct packed {\n bit l;\n`else\n \
|
||||
typedef struct{\n rand bit l;\n`endif\n } pmp_cfg_reg_t;\n\n parameter \
|
||||
int AFTER = 1;\nendpackage\n";
|
||||
let f = parse_ok(src);
|
||||
let ItemKind::Package { items, .. } = &f.items[0].kind else { panic!("expected package") };
|
||||
assert_eq!(items.len(), 3, "{:?}", items.len());
|
||||
let ItemKind::Verbatim(raw) = &items[1].kind else { panic!("expected a verbatim block") };
|
||||
assert_eq!(raw.text, src[raw.span.as_range()]);
|
||||
assert!(raw.text.starts_with("typedef struct packed {"), "{:?}", raw.text);
|
||||
assert!(raw.text.ends_with("} pmp_cfg_reg_t;"), "{:?}", raw.text);
|
||||
assert!(matches!(items[2].kind, ItemKind::ParamDecl(_)), "the next item survived");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_ifndef_and_an_elsif_chain_are_the_same_shape() {
|
||||
let src = "`ifndef A\nint x[] = {\n`elsif B\nconst int x[] = {\n`else\nstatic int x[] = \
|
||||
{\n`endif\n 1\n};\n";
|
||||
let f = parse_ok(src);
|
||||
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") };
|
||||
// Every arm is inside the one block, and only the first arm's `{` was
|
||||
// counted -- otherwise the scan would still be looking for two more.
|
||||
assert!(raw.text.contains("`elsif B") && raw.text.contains("`else"), "{:?}", raw.text);
|
||||
assert!(raw.text.ends_with("};"), "{:?}", raw.text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_balanced_region_inside_the_shared_tail_does_not_end_the_scan() {
|
||||
let src = "`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n 1,\n`ifdef B\n \
|
||||
2,\n`endif\n 3\n};\n\nparameter int AFTER = 1;\n";
|
||||
let f = parse_ok(src);
|
||||
let kinds = split_items(&f);
|
||||
assert_eq!(kinds.len(), 3, "{kinds:?}");
|
||||
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") };
|
||||
assert!(raw.text.contains("`ifdef B"), "the nested region is inside: {:?}", raw.text);
|
||||
assert_eq!(kinds[2], "param", "the item after the region was not swallowed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn comments_inside_a_split_region_are_kept_and_the_one_after_it_is_not() {
|
||||
let src = "// head\n`ifdef A // which\nint x[] = { // open\n`else // other\nconst int \
|
||||
x[] = {\n`endif\n // why\n 1\n}; // done\nint y;\n";
|
||||
let f = parse_ok(src);
|
||||
assert_eq!(texts(&f.items[0].meta.leading), ["// head"]);
|
||||
assert_eq!(
|
||||
f.items[0].meta.trailing.as_ref().expect("`ifdef's own comment").text,
|
||||
"// which"
|
||||
);
|
||||
let ItemKind::Verbatim(raw) = &f.items[1].kind else { panic!("expected a verbatim block") };
|
||||
for c in ["// open", "// other", "// why"] {
|
||||
assert!(raw.text.contains(c), "{c} was dropped from {:?}", raw.text);
|
||||
}
|
||||
assert!(!raw.text.contains("// done"), "the trailing comment was swallowed");
|
||||
assert_eq!(
|
||||
f.items[1].meta.trailing.as_ref().expect("the comment survived").text,
|
||||
"// done"
|
||||
);
|
||||
}
|
||||
|
||||
// -- the trigger refuses everything that is not a split ---------------
|
||||
|
||||
#[test]
|
||||
fn a_plain_syntax_error_inside_a_complete_arm_is_still_an_error() {
|
||||
// Both arms are whole declarations; the `= ;` is an ordinary typo
|
||||
// that merely happens to sit inside a conditional region.
|
||||
let msg = parse_err("`ifdef A\nwire x = ;\n`else\nwire x = 1;\n`endif\n");
|
||||
assert!(msg.contains("expected expression"), "{msg}");
|
||||
// ... and the same typo with a bracket open before it, so the only
|
||||
// thing missing is the `else`/`endif` at the cursor.
|
||||
let msg = parse_err("`ifdef A\nint x[] = {1, };\nwire y = ;\n`else\n`endif\n");
|
||||
assert!(msg.contains("expected expression"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_garbage_token_run_between_directives_is_still_an_error() {
|
||||
let msg = parse_err("`ifdef A\n) ] }\n`else\n(\n`endif\n;\n");
|
||||
assert!(msg.contains("expected item"), "{msg}");
|
||||
let msg = parse_err("module m;\n`ifdef A\n = = =\n`else\n ;\n`endif\nendmodule\n");
|
||||
assert!(!msg.is_empty(), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unterminated_region_with_broken_code_is_still_an_error() {
|
||||
// No `endif at all: the scan finds no end for the region and the
|
||||
// original error stands.
|
||||
let msg = parse_err("`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n 1\n};\n");
|
||||
assert!(msg.contains("`else"), "{msg}");
|
||||
// An `endif but no terminating `;` before the end of the file.
|
||||
let msg = parse_err("`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n 1\n");
|
||||
assert!(msg.contains("`else"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_semicolon_is_not_a_split() {
|
||||
// The arm left no bracket open, so it is a fragment of nothing: the
|
||||
// shape is indistinguishable from a forgotten `;` and is refused.
|
||||
let msg = parse_err("`ifdef A\nwire x\n`else\nwire y\n`endif\n;\n");
|
||||
assert!(msg.contains("`else"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stray_endif_is_never_a_split() {
|
||||
// QA repro (2026-08-26): nothing opened a region, so the `endif
|
||||
// closes nothing and the arm before it is a fragment of nothing.
|
||||
// Recovering here would reformat invalid Verilog and exit 0.
|
||||
let msg = parse_err("int x[] = {\n`endif\n1\n};\n");
|
||||
assert!(msg.contains("expected expression") && msg.contains("`endif"), "{msg}");
|
||||
let msg = parse_err("module m;\n int x[] = {\n`endif\n 1\n};\nendmodule\n");
|
||||
assert!(msg.contains("`endif"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_closed_region_does_not_leave_a_later_endif_something_to_close() {
|
||||
// QA repro (2026-08-26): a legitimately closed region, then an
|
||||
// accidental duplicate closer, then a bracket-opening declaration.
|
||||
// The duplicate re-opens nothing, so the `else below is still stray.
|
||||
let msg = parse_err(
|
||||
"module m;\n`ifdef FOO\n wire a;\n`endif\n`endif\n int x[] = {\n`else\n const int \
|
||||
x[] = {\n`endif\n 1\n};\nendmodule\n",
|
||||
);
|
||||
assert!(msg.contains("`else"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stray_endif_with_no_item_to_break_is_left_exactly_as_it_was() {
|
||||
// lucisv has never validated directive nesting -- a lone `endif at
|
||||
// item position is an ordinary `ItemKind::Directive`, before this
|
||||
// work and after it. What matters is that no bracket-opening item
|
||||
// near it gets swallowed into a verbatim block.
|
||||
let f = parse_ok("wire a;\n`endif\nwire b;\n`endif\nint x[] = {1};\n");
|
||||
let kinds = split_items(&f);
|
||||
assert_eq!(
|
||||
kinds,
|
||||
["decl", "directive:`endif", "decl", "directive:`endif", "decl"],
|
||||
"nothing was collapsed into a verbatim block"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_split_nested_inside_an_open_region_is_still_recovered() {
|
||||
// The guard is "a region is live", not "exactly one region is live":
|
||||
// both corpus shapes still recover when they sit inside an outer
|
||||
// `ifdef that stays open across them.
|
||||
let a = parse_ok(
|
||||
"`ifdef OUTER\n`ifdef DSIM\nprivileged_reg_t csr[] = {\n`else\nconst \
|
||||
privileged_reg_t csr[] = {\n`endif\n MVENDORID\n};\n`endif\nparameter int AFTER = \
|
||||
1;\n",
|
||||
);
|
||||
let ItemKind::Verbatim(raw) = &a.items[2].kind else { panic!("expected a verbatim block") };
|
||||
assert!(raw.text.ends_with("};"), "{:?}", raw.text);
|
||||
// The outer region's own `endif is still its own directive item, and
|
||||
// the item past it was not swallowed.
|
||||
let kinds = split_items(&a);
|
||||
assert_eq!(kinds[3], "directive:`endif", "{kinds:?}");
|
||||
assert_eq!(kinds[4], "param", "{kinds:?}");
|
||||
|
||||
let b = parse_ok(
|
||||
"package p;\n`ifdef OUTER\n`ifdef _VCP\n typedef struct packed {\n bit l;\n\
|
||||
`else\n typedef struct{\n rand bit l;\n`endif\n } pmp_cfg_reg_t;\n`endif\n \
|
||||
parameter int AFTER = 1;\nendpackage\n",
|
||||
);
|
||||
let ItemKind::Package { items, .. } = &b.items[0].kind else { panic!("expected package") };
|
||||
let ItemKind::Verbatim(raw) = &items[2].kind else { panic!("expected a verbatim block") };
|
||||
assert!(raw.text.ends_with("} pmp_cfg_reg_t;"), "{:?}", raw.text);
|
||||
assert!(matches!(items[4].kind, ItemKind::ParamDecl(_)), "the next item survived");
|
||||
}
|
||||
|
||||
/// `Parser::open_conds` once the whole file has parsed. The invariant it
|
||||
/// pins: this is the number of `` `ifdef ``/`` `ifndef `` regions opened
|
||||
/// **at item scope** and not closed at item scope — nothing consumed
|
||||
/// inside an opaque verbatim body may move it.
|
||||
fn open_conds_after(src: &str) -> u32 {
|
||||
let toks = tokenize(src).expect("lex error");
|
||||
let mut p = Parser::new(toks, src, false);
|
||||
p.parse_source_file().expect("parse error");
|
||||
p.open_conds
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn item_scope_conditional_nesting_ignores_opaque_bodies() {
|
||||
// QA repro (2026-08-26, round 4): an unbalanced `ifdef written inside
|
||||
// a construct lucisv keeps as opaque bytes used to leak into the
|
||||
// file's item-scope nesting, because those bodies are walked token by
|
||||
// token through `bump`. Every one of them must leave the count alone.
|
||||
assert_eq!(open_conds_after("wire x;\n"), 0);
|
||||
assert_eq!(open_conds_after("`ifdef A\nwire x;\n"), 1, "an item-scope region does count");
|
||||
assert_eq!(open_conds_after("`ifdef A\nwire x;\n`endif\n"), 0);
|
||||
for body in [
|
||||
"class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n }\nendclass\n",
|
||||
"covergroup cg;\n`ifdef FAKE\n cp: coverpoint x;\nendgroup\n",
|
||||
"module m;\n property p;\n`ifdef FAKE\n a |-> b;\n endproperty\nendmodule\n",
|
||||
"module m;\n assert property (\n`ifdef FAKE\n a |-> b);\nendmodule\n",
|
||||
] {
|
||||
assert_eq!(open_conds_after(body), 0, "an opaque body leaked: {body:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unbalanced_ifdef_inside_an_opaque_body_cannot_launder_a_later_stray_endif() {
|
||||
// The end-to-end shape of the leak above: the polluted count used to
|
||||
// make an unrelated stray `endif look like a live region's closer.
|
||||
let msg = parse_err(
|
||||
"class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n }\nendclass\nint y[] = \
|
||||
{\n`endif\n1\n};\n",
|
||||
);
|
||||
assert!(msg.contains("`endif"), "{msg}");
|
||||
let msg = parse_err(
|
||||
"covergroup cg;\n`ifdef FAKE\n cp: coverpoint x;\nendgroup\nint y[] = \
|
||||
{\n`endif\n1\n};\n",
|
||||
);
|
||||
assert!(msg.contains("`endif"), "{msg}");
|
||||
let msg = parse_err(
|
||||
"module m;\n property p;\n`ifdef FAKE\n a |-> b;\n endproperty\n int y[] = \
|
||||
{\n`endif\n1\n};\nendmodule\n",
|
||||
);
|
||||
assert!(msg.contains("`endif"), "{msg}");
|
||||
// Control: the same shape with the inner directive balanced. The tail
|
||||
// is still a stray `endif with no live region, so it still refuses --
|
||||
// the count was never the thing making the tail legal.
|
||||
let msg = parse_err(
|
||||
"class c;\n constraint co {\n`ifdef FAKE\n x < 10;\n`endif\n }\nendclass\nint \
|
||||
y[] = {\n`endif\n1\n};\n",
|
||||
);
|
||||
assert!(msg.contains("`endif"), "{msg}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suppressing_opaque_bodies_does_not_suppress_the_regions_around_them() {
|
||||
// Over-suppression guard: balanced directives inside an opaque body,
|
||||
// then a genuine split later in the same file.
|
||||
let f = parse_ok(
|
||||
"class c;\n constraint co {\n`ifdef X\n x < 10;\n`endif\n }\nendclass\n`ifdef \
|
||||
DSIM\nint y[] = {\n`else\nconst int y[] = {\n`endif\n 1\n};\nparameter int AFTER = \
|
||||
1;\n",
|
||||
);
|
||||
assert!(matches!(f.items[2].kind, ItemKind::Verbatim(_)), "{:?}", split_items(&f));
|
||||
|
||||
// Under-suppression guard: an earlier verbatim item (a constraint)
|
||||
// inside the very region the split sits in.
|
||||
let f = parse_ok(
|
||||
"`ifdef OUTER\nclass c;\n constraint co {x < 10;}\nendclass\n`ifdef DSIM\nint y[] = \
|
||||
{\n`else\nconst int y[] = {\n`endif\n 1\n};\n`endif\nparameter int AFTER = 1;\n",
|
||||
);
|
||||
let kinds = split_items(&f);
|
||||
assert_eq!(kinds[3], "verbatim:int y[] = {\n`else\nconst int y[] = {\n`endif\n 1\n};");
|
||||
assert_eq!(kinds[4], "directive:`endif");
|
||||
assert_eq!(kinds[5], "param");
|
||||
assert_eq!(open_conds_after(
|
||||
"`ifdef OUTER\nclass c;\n constraint co {x < 10;}\nendclass\n`ifdef DSIM\nint y[] = \
|
||||
{\n`else\nconst int y[] = {\n`endif\n 1\n};\n`endif\nparameter int AFTER = 1;\n"
|
||||
), 0, "the recovered block accounted for the `endif it swallowed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recovered_block_leaves_the_right_nesting_behind_it() {
|
||||
// The block swallows the region's own `endif, so the count has to come
|
||||
// down with it -- otherwise the next `endif looks like it closes
|
||||
// something and the stray after it gets laundered.
|
||||
let src = "`ifdef OUTER\n`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n \
|
||||
1\n};\n`endif\nparameter int AFTER = 1;\n";
|
||||
assert_eq!(open_conds_after(src), 0);
|
||||
let msg = parse_err(
|
||||
"`ifdef OUTER\n`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n \
|
||||
1\n};\n`endif\nint z[] = {\n`endif\n 1\n};\n",
|
||||
);
|
||||
assert!(msg.contains("`endif"), "{msg}");
|
||||
// Two splits under one outer region both recover, and the outer region
|
||||
// is still open between them.
|
||||
let f = parse_ok(
|
||||
"`ifdef OUTER\n`ifdef A\nint x[] = {\n`else\nconst int x[] = {\n`endif\n \
|
||||
1\n};\n`ifdef B\nint y[] = {\n`else\nconst int y[] = {\n`endif\n \
|
||||
2\n};\n`endif\nparameter int AFTER = 1;\n",
|
||||
);
|
||||
let kinds = split_items(&f);
|
||||
assert_eq!(kinds.iter().filter(|k| k.starts_with("verbatim:")).count(), 2, "{kinds:?}");
|
||||
assert_eq!(kinds[kinds.len() - 1], "param", "{kinds:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_region_whose_arms_are_whole_items_still_parses_arm_by_arm() {
|
||||
let f = parse_ok("`ifdef A\nwire x;\n`else\nwire y;\n`endif\n");
|
||||
assert_eq!(
|
||||
split_items(&f),
|
||||
["directive:`ifdef A", "decl", "directive:`else", "decl", "directive:`endif"]
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user