TODO §36 (docs/features/small-items-3). Closes topo §2.9-24 and §2.9-25 and the §1 atomic-writes item. 36.1 `ItemKind::GenBlock(Box<GenBlock>)`: in tolerant mode a `begin … end` at module scope or straight inside a generate region is parsed as an unnamed generate block with a diagnostic at the keyword, so the items inside and after it survive; strict mode is untouched. Consumers walk its items; `module-begin-block`, `v2001-generate-begin` and `mismatched-labels` read the node. The formatter's `gen_block` is split by a pure extraction into `begin_block`. One server test that parsed a 3 000-deep begin nest on libtest's thread now runs on PARSE_STACK_SIZE. 36.2 `Parser::value_runs_into_next_instance`, a tolerant-mode lookahead in `parse_connection`: an unclosed `.NAME(` whose value would swallow the next instance as a call fails the element instead; `recover_element` takes the bracket the element stopped on before skipping so the skip stays at the list's level. The balanced-parens spelling stays greedy. 36.3 `lucisv_core::atomic::write_atomic`: sibling temp file + rename, permissions preserved, symlink target replaced, read-only target refused as `fs::write` refused it; used by format, `check --fix` and the cache. Also: TODO housekeeping (QA lines of §27–§35 ticked as recorded in their QA logs; the §27 P6 line and the sva-bodies README checkbox annotated as delivered by §29), topo §2.9-24/25 struck. Co-Authored-By: Claude Fable 5.1 <[email protected]>
562 lines
24 KiB
Rust
562 lines
24 KiB
Rust
//! `// verilog_format: off` / `// verilog_format: on` fences.
|
|
//!
|
|
//! A fenced region is emitted as the exact source bytes it was written with,
|
|
//! so nothing inside it is ever laid out. This module answers the two
|
|
//! questions that makes possible: which comments are fences, and which byte
|
|
//! ranges they select. Full spec: `docs/features/format-fences/README.md`,
|
|
//! plus `docs/features/statement-fences/README.md` for the class-body and
|
|
//! statement-list scopes.
|
|
//!
|
|
//! [`protected_regions`] and [`is_protected`] are the same answer for the
|
|
//! tools that only *edit* fenced bytes rather than lay them out — the CLI's
|
|
//! `lucisv check --fix` and the language server's quick fixes. They live here so
|
|
//! there is one definition of "what is fenced": see
|
|
//! `docs/features/shared-fence-filter/README.md`.
|
|
|
|
use vlog_parser::ast::{
|
|
Fragment, GenBlock, GenElse, GenIf, Item, ItemKind, SourceFile, Stmt, StmtKind,
|
|
};
|
|
use vlog_parser::span::TextRange;
|
|
use vlog_parser::token::Comment;
|
|
use vlog_parser::LineIndex;
|
|
|
|
/// Which side of a fence a comment spells.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub enum Fence {
|
|
/// `// verilog_format: off` — stop formatting here.
|
|
Off,
|
|
/// `// verilog_format: on` — resume formatting here.
|
|
On,
|
|
}
|
|
|
|
/// The fence a comment spells, if it spells one exactly.
|
|
///
|
|
/// The match is exact after trimming, not a prefix: a comment that merely
|
|
/// starts with a fence (`// lucisv: off-by-one`) is an ordinary comment, because
|
|
/// a fence firing by accident is worse than one that never fires.
|
|
pub fn fence_of(text: &str) -> Option<Fence> {
|
|
match text.strip_prefix("//")?.trim() {
|
|
"verilog_format: off" | "lucisv: off" => Some(Fence::Off),
|
|
"verilog_format: on" | "lucisv: on" => Some(Fence::On),
|
|
_ => None,
|
|
}
|
|
}
|
|
|
|
/// A range of source bytes to emit exactly as written.
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
pub struct Region {
|
|
/// First byte of the `off` fence comment itself — the region's identity,
|
|
/// and what tells the one comment that *opens* a region from the ones it
|
|
/// merely contains.
|
|
pub fence: usize,
|
|
/// First byte emitted: the start of the fence's line, so the region keeps
|
|
/// its own indentation on its first line too.
|
|
pub start: usize,
|
|
/// One past the last byte emitted.
|
|
pub end: usize,
|
|
}
|
|
|
|
/// Every fenced region in `file`, sorted and non-overlapping.
|
|
pub fn collect(src: &str, file: &SourceFile) -> Vec<Region> {
|
|
let mut found = Vec::new();
|
|
match &file.fragment {
|
|
// A statement fragment is one statement list standing at file scope,
|
|
// its dangling comments ending it exactly as a file's items' do. The
|
|
// other fragment shapes are element lists, which are not fenceable.
|
|
Some(Fragment::Statements(stmts)) => {
|
|
scan_stmt_scope(src, stmts, &file.dangling, &mut found)
|
|
}
|
|
_ => scan_scope(src, &file.items, &file.dangling, &mut found),
|
|
}
|
|
found.sort_by_key(|r| r.fence);
|
|
// A region inside an already-fenced range never runs: the items holding
|
|
// it are emitted as source bytes, so they are never formatted. Dropping
|
|
// those leaves a list sorted by both ends, which is what makes the
|
|
// lookup below a binary search.
|
|
let mut regions: Vec<Region> = Vec::new();
|
|
for r in found {
|
|
if regions.last().is_none_or(|prev| r.fence >= prev.end) {
|
|
regions.push(r);
|
|
}
|
|
}
|
|
regions
|
|
}
|
|
|
|
/// The region containing byte `pos`, if any. `regions` must come from
|
|
/// [`collect`].
|
|
pub fn region_at(regions: &[Region], pos: usize) -> Option<&Region> {
|
|
let i = regions.partition_point(|r| r.end <= pos);
|
|
regions.get(i).filter(|r| r.fence <= pos)
|
|
}
|
|
|
|
/// Every byte range in `src` that no tool may edit automatically.
|
|
///
|
|
/// `off` means hands-off across all of lucisv, not just the layout engine, so
|
|
/// the CLI's `--fix` and the server's quick fixes both ask this question here
|
|
/// rather than each answering it themselves. The answer is deliberately
|
|
/// wider than [`collect`]'s: it is the union of
|
|
///
|
|
/// 1. `collect` over a tolerant parse — the formatter's own item-scoped
|
|
/// answer, authoritative wherever the tree is good, and
|
|
/// 2. a line scan, the backstop for the broken files only the linter and the
|
|
/// server see, where error recovery can swallow the item structure a
|
|
/// region hangs on and `collect` then reports no region at all.
|
|
///
|
|
/// The regions may overlap and are not sorted; [`is_protected`] is the only
|
|
/// thing that reads them, and protecting a little more than the formatter
|
|
/// emits verbatim only ever declines an edit, which is the harmless
|
|
/// direction.
|
|
pub fn protected_regions(src: &str) -> Vec<Region> {
|
|
let (parsed, _) = vlog_parser::parse_source_tolerant(src);
|
|
let mut regions = collect(src, &parsed);
|
|
regions.extend(scanned_regions(src));
|
|
regions
|
|
}
|
|
|
|
/// Whether the byte range `start..end` overlaps any protected region.
|
|
///
|
|
/// An empty range is an insertion; it covers the byte it would land in front
|
|
/// of, so nothing can be spliced into a region. The protected extent is the
|
|
/// whole [`Region::start`]`..`[`Region::end`] the formatter emits verbatim,
|
|
/// the fence line's own indentation included — not just what [`region_at`]
|
|
/// calls "inside".
|
|
pub fn is_protected(regions: &[Region], start: usize, end: usize) -> bool {
|
|
let end = end.max(start + 1);
|
|
regions.iter().any(|region| start < region.end && region.start < end)
|
|
}
|
|
|
|
/// Fenced regions found by reading lines, without a parse.
|
|
///
|
|
/// A fence is by definition a line comment alone on its line whose text
|
|
/// matches exactly, so [`fence_of`] — the formatter's own grammar — is all
|
|
/// this needs. Pairing is cruder than [`collect`]'s: an `off` runs to the next
|
|
/// `on` or to the end of the file, with no notion of the enclosing scope. It
|
|
/// can therefore protect a little more than the formatter emits verbatim, and
|
|
/// would be fooled by a fence spelled inside a block comment; both err toward
|
|
/// declining an edit.
|
|
fn scanned_regions(src: &str) -> Vec<Region> {
|
|
let index = LineIndex::new(src);
|
|
let mut regions = Vec::new();
|
|
let mut open: Option<usize> = None;
|
|
for line in 1..=index.line_count() {
|
|
let Some(range) = index.line_range(line) else { continue };
|
|
let Some(spelling) = src.get(range.as_range()).and_then(|l| fence_of(l.trim())) else {
|
|
continue;
|
|
};
|
|
match (spelling, open) {
|
|
(Fence::Off, None) => open = Some(range.start as usize),
|
|
(Fence::On, Some(start)) => {
|
|
regions.push(Region { fence: start, start, end: range.end as usize });
|
|
open = None;
|
|
}
|
|
// A second `off`, or an `on` with nothing open, is just text.
|
|
_ => {}
|
|
}
|
|
}
|
|
if let Some(start) = open {
|
|
regions.push(Region { fence: start, start, end: src.len() });
|
|
}
|
|
regions
|
|
}
|
|
|
|
/// Scan one flat stream of units — each unit's leading comments, then its own
|
|
/// code extent — followed by the scope's dangling comments.
|
|
///
|
|
/// A region opens at the first `off` in that stream and closes at the first
|
|
/// `on` after it; anything else, including a second `off`, is just text. An
|
|
/// item list and a statement list have exactly this shape, and it is the only
|
|
/// shape a fence pairs inside, which is why both scan through here.
|
|
fn scan_units<'u>(
|
|
src: &str,
|
|
units: impl Iterator<Item = (&'u [Comment], TextRange)>,
|
|
dangling: &[Comment],
|
|
out: &mut Vec<Region>,
|
|
) {
|
|
let mut open: Option<Region> = None;
|
|
let mut scope_end = 0usize;
|
|
for (leading, span) in units {
|
|
for c in leading {
|
|
// An attribute followed by a comment puts a "leading" comment
|
|
// *after* the unit's span starts. Opening a region there would
|
|
// emit the attribute twice, so such comments are not fences.
|
|
if c.span.start < span.start {
|
|
step(src, c, &mut open, out);
|
|
}
|
|
}
|
|
// A leading comment always ends before its unit's code does, so the
|
|
// unit's own end is the scope's high-water mark.
|
|
scope_end = span.end as usize;
|
|
}
|
|
for c in dangling {
|
|
step(src, c, &mut open, out);
|
|
scope_end = c.span.end as usize;
|
|
}
|
|
if let Some(mut r) = open {
|
|
// An unmatched `off` runs to the end of the scope. The last unit's
|
|
// span stops before the comment trailing it on the same line, and
|
|
// `Meta.trailing` has no span to consult, so that comment has to be
|
|
// picked up from the source or it would be dropped.
|
|
r.end = with_trailing_comments(src, scope_end);
|
|
out.push(r);
|
|
}
|
|
}
|
|
|
|
/// Scan one item-list scope, then its nested scopes.
|
|
fn scan_scope(src: &str, items: &[Item], dangling: &[Comment], out: &mut Vec<Region>) {
|
|
scan_units(src, items.iter().map(|i| (i.meta.leading.as_slice(), i.span)), dangling, out);
|
|
for item in items {
|
|
scan_nested(src, item, out);
|
|
}
|
|
}
|
|
|
|
/// Scan one statement-list scope, then its nested scopes.
|
|
///
|
|
/// The statement twin of [`scan_scope`], unit for unit — which is what keeps a
|
|
/// region aligned with statement boundaries and stops an unmatched `off` at the
|
|
/// list's end rather than at the `end`, `join` or `endfunction` past it.
|
|
fn scan_stmt_scope(src: &str, stmts: &[Stmt], dangling: &[Comment], out: &mut Vec<Region>) {
|
|
scan_units(src, stmts.iter().map(|s| (s.meta.leading.as_slice(), s.span)), dangling, out);
|
|
for stmt in stmts {
|
|
scan_nested_stmt(src, stmt, out);
|
|
}
|
|
}
|
|
|
|
/// Advance the open/closed state by one comment unit.
|
|
fn step(src: &str, c: &Comment, open: &mut Option<Region>, out: &mut Vec<Region>) {
|
|
let start = c.span.start as usize;
|
|
match (fence_of(&c.text), open.is_some()) {
|
|
(Some(Fence::Off), false) if opens_line(src, start) => {
|
|
*open = Some(Region { fence: start, start: line_start(src, start), end: 0 })
|
|
}
|
|
(Some(Fence::On), true) => {
|
|
if let Some(mut r) = open.take() {
|
|
r.end = c.span.end as usize;
|
|
out.push(r);
|
|
}
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
/// Scopes nested inside one item: the item lists, and the statement lists an
|
|
/// item's body reaches.
|
|
fn scan_nested(src: &str, item: &Item, out: &mut Vec<Region>) {
|
|
match &item.kind {
|
|
ItemKind::Module(m) => scan_scope(src, &m.items, &m.dangling, out),
|
|
ItemKind::Package { items, dangling, .. } => scan_scope(src, items, dangling, out),
|
|
ItemKind::GenerateRegion { items, dangling } => scan_scope(src, items, dangling, out),
|
|
ItemKind::GenBlock(b) => scan_gen_block(src, b, out),
|
|
ItemKind::GenIf(g) => scan_gen_if(src, g, out),
|
|
ItemKind::GenFor(g) => scan_gen_block(src, &g.body, out),
|
|
ItemKind::GenCase(g) => {
|
|
for i in &g.items {
|
|
scan_gen_block(src, &i.body, out);
|
|
}
|
|
}
|
|
ItemKind::Class(c) => scan_scope(src, &c.items, &c.dangling, out),
|
|
ItemKind::Function(f) => scan_stmt_scope(src, &f.stmts, &f.dangling, out),
|
|
ItemKind::Task(t) => scan_stmt_scope(src, &t.stmts, &t.dangling, out),
|
|
ItemKind::Always { stmt, .. } | ItemKind::Initial(stmt) | ItemKind::Final(stmt) => {
|
|
scan_nested_stmt(src, stmt, out)
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
/// Statement scopes nested inside one statement.
|
|
///
|
|
/// A statement *list* is a scope — `begin`…`end`, `fork`…`join*`. A
|
|
/// single-statement body is not, for the reason [`scan_gen_block`] refuses a
|
|
/// block-less generate item: there is no list for a fence to end in, and the
|
|
/// formatter lays that statement out inside a `Group`. So the bodies below are
|
|
/// walked into rather than scanned, and only the block one of them holds opens
|
|
/// a scope.
|
|
fn scan_nested_stmt(src: &str, stmt: &Stmt, out: &mut Vec<Region>) {
|
|
match &stmt.kind {
|
|
StmtKind::Block { stmts, dangling, .. } | StmtKind::ForkJoin { stmts, dangling, .. } => {
|
|
scan_stmt_scope(src, stmts, dangling, out)
|
|
}
|
|
StmtKind::If { then, els, .. } => {
|
|
scan_nested_stmt(src, then, out);
|
|
if let Some(e) = els {
|
|
scan_nested_stmt(src, e, out);
|
|
}
|
|
}
|
|
StmtKind::Assert { then, els, .. } => {
|
|
for s in then.iter().chain(els.iter()) {
|
|
scan_nested_stmt(src, s, out);
|
|
}
|
|
}
|
|
// A case item's *labels* are not a fenceable stream (see the feature
|
|
// README); the block one of them may hold is.
|
|
StmtKind::Case { items, .. } | StmtKind::RandCase { items, .. } => {
|
|
for i in items {
|
|
scan_nested_stmt(src, &i.stmt, out);
|
|
}
|
|
}
|
|
StmtKind::For { body, .. }
|
|
| StmtKind::While { body, .. }
|
|
| StmtKind::DoWhile { body, .. }
|
|
| StmtKind::Repeat { body, .. }
|
|
| StmtKind::Forever { body }
|
|
| StmtKind::Foreach { body, .. }
|
|
| StmtKind::Labeled { stmt: body, .. } => scan_nested_stmt(src, body, out),
|
|
StmtKind::Timing { stmt: Some(inner), .. } | StmtKind::Wait { stmt: Some(inner), .. } => {
|
|
scan_nested_stmt(src, inner, out)
|
|
}
|
|
_ => {}
|
|
}
|
|
}
|
|
|
|
fn scan_gen_if(src: &str, g: &GenIf, out: &mut Vec<Region>) {
|
|
scan_gen_block(src, &g.then, out);
|
|
match g.els.as_deref() {
|
|
Some(GenElse::If(_, inner)) => scan_gen_if(src, inner, out),
|
|
Some(GenElse::Block(b)) => scan_gen_block(src, b, out),
|
|
None => {}
|
|
}
|
|
}
|
|
|
|
/// A generate `begin`…`end` is an item scope; a bodyless `if (X) item;` is
|
|
/// not — its one item has no list for a fence to end in, and the formatter
|
|
/// lays it out inside a `Group`. Its nested scopes are still scanned.
|
|
fn scan_gen_block(src: &str, b: &GenBlock, out: &mut Vec<Region>) {
|
|
if b.is_block {
|
|
scan_scope(src, &b.items, &b.dangling, out);
|
|
} else {
|
|
for item in &b.items {
|
|
scan_nested(src, item, out);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Whether a fence written at `at` begins the *content* of its line: nothing
|
|
/// but whitespace and finished block comments precedes it there.
|
|
///
|
|
/// This is what makes `begin // lucisv: off` an ordinary comment. The parser
|
|
/// hands a comment written after `begin` to the next *statement* as a leading
|
|
/// one, so without this test a region would open in the middle of a line and
|
|
/// take its first line's bytes from the wrong column. A fence preceded only by
|
|
/// another comment (`/* a */ // lucisv: off`) still opens one: that comment is
|
|
/// a unit of the same stream and prints on the line above.
|
|
fn opens_line(src: &str, at: usize) -> bool {
|
|
let bol = src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1);
|
|
let Some(mut before) = src.get(bol..at) else { return false };
|
|
loop {
|
|
before = before.trim_start();
|
|
if before.is_empty() {
|
|
return true;
|
|
}
|
|
match before.strip_prefix("/*").and_then(|b| b.split_once("*/")) {
|
|
Some((_, rest)) => before = rest,
|
|
None => return false,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The start of the line `at` sits on, when nothing but whitespace precedes it
|
|
/// there — otherwise `at` itself, so a fence sharing its line with another
|
|
/// comment does not swallow it.
|
|
pub(crate) fn line_start(src: &str, at: usize) -> usize {
|
|
let bol = src.get(..at).and_then(|s| s.rfind('\n')).map_or(0, |i| i + 1);
|
|
match src.get(bol..at) {
|
|
Some(before) if before.chars().all(char::is_whitespace) => bol,
|
|
_ => at,
|
|
}
|
|
}
|
|
|
|
/// Extend `end` over the comments written after it on the same line.
|
|
pub(crate) fn with_trailing_comments(src: &str, end: usize) -> usize {
|
|
let mut at = end;
|
|
loop {
|
|
let Some(rest) = src.get(at..) else { return at };
|
|
let spaces = rest.len() - rest.trim_start_matches([' ', '\t']).len();
|
|
let rest = &rest[spaces..];
|
|
if let Some(body) = rest.strip_prefix("//") {
|
|
// A line comment ends the line, so nothing else can follow it.
|
|
let len = body.find('\n').unwrap_or(body.len());
|
|
return trim_end(src, at + spaces + 2 + len);
|
|
}
|
|
match rest.strip_prefix("/*").and_then(|b| b.find("*/")) {
|
|
Some(i) => at += spaces + 2 + i + 2,
|
|
None => return at,
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Walk `end` back over spaces and tabs, so a region never ends in whitespace
|
|
/// the comment's own span would have dropped.
|
|
fn trim_end(src: &str, end: usize) -> usize {
|
|
let bytes = src.as_bytes();
|
|
let mut end = end.min(bytes.len());
|
|
while end > 0 && (bytes[end - 1] == b' ' || bytes[end - 1] == b'\t') {
|
|
end -= 1;
|
|
}
|
|
end
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn both_spellings_and_both_sides_are_fences() {
|
|
assert_eq!(fence_of("// verilog_format: off"), Some(Fence::Off));
|
|
assert_eq!(fence_of("// verilog_format: on"), Some(Fence::On));
|
|
assert_eq!(fence_of("// lucisv: off"), Some(Fence::Off));
|
|
assert_eq!(fence_of("// lucisv: on"), Some(Fence::On));
|
|
}
|
|
|
|
#[test]
|
|
fn surrounding_whitespace_is_trimmed() {
|
|
assert_eq!(fence_of("//lucisv: off"), Some(Fence::Off));
|
|
assert_eq!(fence_of("// verilog_format: on"), Some(Fence::On));
|
|
assert_eq!(fence_of("//\tlucisv: off"), Some(Fence::Off));
|
|
assert_eq!(fence_of("// lucisv: on "), Some(Fence::On));
|
|
}
|
|
|
|
#[test]
|
|
fn anything_else_is_an_ordinary_comment() {
|
|
// Trailing text disqualifies a fence: an accidental switch is worse
|
|
// than one that never fires.
|
|
assert_eq!(fence_of("// lucisv: off (for now)"), None);
|
|
assert_eq!(fence_of("// lucisv: off-by-one bug here"), None);
|
|
// The match is exact, not fuzzy.
|
|
assert_eq!(fence_of("// lucisv:off"), None);
|
|
assert_eq!(fence_of("// lucisv : off"), None);
|
|
assert_eq!(fence_of("// verilog_format off"), None);
|
|
assert_eq!(fence_of("// LUCISV: OFF"), None);
|
|
assert_eq!(fence_of("// verilog_lint: waive x"), None);
|
|
// Block comments are not fences.
|
|
assert_eq!(fence_of("/* lucisv: off */"), None);
|
|
assert_eq!(fence_of("/* verilog_format: off */"), None);
|
|
assert_eq!(fence_of("// lucisv: off\n// lucisv: on"), None);
|
|
assert_eq!(fence_of(""), None);
|
|
assert_eq!(fence_of("// off"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn a_fence_only_opens_a_region_at_the_start_of_its_line() {
|
|
// Whitespace before it, at any depth, and at the very first byte.
|
|
assert!(opens_line("// lucisv: off\n", 0));
|
|
assert!(opens_line("module m;\n // lucisv: off\n", 12));
|
|
assert!(opens_line("module m;\n\t\t// lucisv: off\n", 12));
|
|
// Another comment before it is still the start of the line's content.
|
|
let src = "module m;\n /* a */ // lucisv: off\n";
|
|
assert!(opens_line(src, src.find("//").expect("fence")));
|
|
let src = "module m;\n /* a */ /* b */ // lucisv: off\n";
|
|
assert!(opens_line(src, src.find("//").expect("fence")));
|
|
// Code before it is not — the two shapes the parser hands to the next
|
|
// node as a *leading* comment even though they trail code.
|
|
let src = "module m;\n always @(*) begin // lucisv: off\n x = 1;\n";
|
|
assert!(!opens_line(src, src.find("//").expect("fence")));
|
|
let src = "module m; // lucisv: off\n wire a;\n";
|
|
assert!(!opens_line(src, src.find("//").expect("fence")));
|
|
// An unterminated block comment before it is not a finished comment.
|
|
let src = "module m;\n /* a // lucisv: off\n";
|
|
assert!(!opens_line(src, src.find("// lucisv").expect("fence")));
|
|
}
|
|
|
|
#[test]
|
|
fn a_fence_line_starts_at_its_indentation() {
|
|
let src = "module m;\n // lucisv: off\n";
|
|
let at = src.find("//").expect("fence");
|
|
assert_eq!(line_start(src, at), src.find(" //").expect("indent"));
|
|
// Not when another comment shares the line.
|
|
let src = "module m;\n /* a */ // lucisv: off\n";
|
|
let at = src.find("//").expect("fence");
|
|
assert_eq!(line_start(src, at), at);
|
|
// At the very start of the file.
|
|
assert_eq!(line_start("// lucisv: off\n", 0), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn trailing_comments_extend_a_scope_end() {
|
|
let src = "wire a; // note\nendmodule\n";
|
|
let end = src.find(" //").expect("comment");
|
|
assert_eq!(&src[..with_trailing_comments(src, end)], "wire a; // note");
|
|
// Block comments, including several, and multi-line ones.
|
|
let src = "wire a; /* x */ /* y */\n";
|
|
let end = src.find(" /*").expect("comment");
|
|
assert_eq!(&src[..with_trailing_comments(src, end)], "wire a; /* x */ /* y */");
|
|
let src = "wire a; /* x\n y */\nendmodule\n";
|
|
let end = src.find(" /*").expect("comment");
|
|
assert_eq!(&src[..with_trailing_comments(src, end)], "wire a; /* x\n y */");
|
|
// Code on the same line is not absorbed.
|
|
let src = "wire a; endmodule\n";
|
|
let end = src.find(" endmodule").expect("kw");
|
|
assert_eq!(with_trailing_comments(src, end), end);
|
|
}
|
|
|
|
/// A region covering bytes 10..20, as `collect` would report one.
|
|
fn ten_to_twenty() -> Vec<Region> {
|
|
vec![Region { fence: 10, start: 10, end: 20 }]
|
|
}
|
|
|
|
#[test]
|
|
fn protection_is_decided_exactly_at_the_region_boundaries() {
|
|
let regions = ten_to_twenty();
|
|
// First byte inside, last byte inside, and the whole span.
|
|
assert!(is_protected(®ions, 10, 11), "first byte inside");
|
|
assert!(is_protected(®ions, 19, 20), "last byte inside");
|
|
assert!(is_protected(®ions, 10, 20), "the whole region");
|
|
// Adjacent on both ends, touching nothing inside.
|
|
assert!(!is_protected(®ions, 9, 10), "ends where the region starts");
|
|
assert!(!is_protected(®ions, 20, 21), "starts where the region ends");
|
|
// Straddling either edge is still a hit.
|
|
assert!(is_protected(®ions, 9, 11), "straddles the start");
|
|
assert!(is_protected(®ions, 19, 21), "straddles the end");
|
|
// An insertion (empty range) inside must not be spliced in either,
|
|
// while one at the far edge is outside.
|
|
assert!(is_protected(®ions, 15, 15), "insertion inside");
|
|
assert!(is_protected(®ions, 10, 10), "insertion at the first byte");
|
|
assert!(!is_protected(®ions, 20, 20), "insertion just past the end");
|
|
// Nothing is protected without a region.
|
|
assert!(!is_protected(&[], 10, 11));
|
|
}
|
|
|
|
#[test]
|
|
fn a_fence_in_a_good_tree_protects_its_whole_region() {
|
|
// The fenced content must be a valid module item, or this test only
|
|
// exercises the scan half it claims not to test (QA find): `\ta = 1;`
|
|
// bare at item position does not parse, and `collect` then hangs no
|
|
// region on the tree. `wire` declarations parse cleanly.
|
|
let src = "module m;\n// lucisv: off\n\twire a;\n// lucisv: on\n\twire b;\nendmodule\n";
|
|
let (parsed, diagnostics) = vlog_parser::parse_source_tolerant(src);
|
|
assert!(diagnostics.is_empty(), "the tree must be clean for this test to mean anything");
|
|
assert!(!collect(src, &parsed).is_empty(), "the TREE path must find the region");
|
|
let regions = protected_regions(src);
|
|
let fenced = src.find("\twire a").expect("fenced tab");
|
|
let free = src.find("\twire b").expect("free tab");
|
|
assert!(is_protected(®ions, fenced, fenced + 1), "{regions:?}");
|
|
assert!(!is_protected(®ions, free, free + 1), "{regions:?}");
|
|
}
|
|
|
|
#[test]
|
|
fn the_line_scan_backstops_a_file_that_does_not_parse() {
|
|
// Error recovery can swallow the structure `collect` hangs a region
|
|
// on; the scan still finds it.
|
|
let src = "module m;\n@@@ junk;\n// lucisv: off\n\ta = 1;\n// lucisv: on\nendmodule\n";
|
|
let (parsed, _) = vlog_parser::parse_source_tolerant(src);
|
|
assert!(collect(src, &parsed).is_empty(), "the premise: no tree region here");
|
|
let tab = src.find("\ta = 1").expect("tab");
|
|
assert!(is_protected(&protected_regions(src), tab, tab + 1));
|
|
}
|
|
|
|
#[test]
|
|
fn an_unclosed_fence_runs_to_the_end_of_the_file() {
|
|
let src = "module m;\n@@@ junk;\n// lucisv: off\n\ta = 1;\nendmodule\n";
|
|
let regions = scanned_regions(src);
|
|
assert_eq!(regions.len(), 1);
|
|
assert_eq!(regions[0].end, src.len());
|
|
}
|
|
|
|
#[test]
|
|
fn an_ordinary_comment_protects_nothing() {
|
|
assert!(scanned_regions("// lucisv: off-by-one\n\ta = 1;\n").is_empty());
|
|
assert!(scanned_regions("// just a note\n\ta = 1;\n").is_empty());
|
|
assert!(scanned_regions("// lucisv: on\n\ta = 1;\n").is_empty(), "a stray `on`");
|
|
assert!(protected_regions("module m;\n\ta = 1;\nendmodule\n").is_empty());
|
|
}
|
|
}
|