From e22192916045f29cc52520161d180b02ff3ddb4d Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 12:38:43 +0900 Subject: [PATCH 1/2] perf(sv): analyze each scope in time proportional to its own size Per-scope analysis selected arena entries by token range by scanning the whole source file's arenas, so a design shipped as one file cost (analyses x file size). A per-file span index now orders each arena by first token; a scope visits only the entries starting inside its own ranges, in arena order, and applies the same predicates. Facts that are pure functions of the file (constant-value nodes, callees, exclusion ranges, override dimensions, qualified bases, pattern keys and the timescale source key with its hash) are computed once per file. Diagnostics and lowering are unchanged. Closes #1956 Change-Id: I283e94ab1244d6aa8c08bfb4af44b1bca00a8e4d --- crates/celox-sv-analyzer/src/ast.rs | 4 +- crates/celox-sv-analyzer/src/ast/generate.rs | 8 +- crates/celox-sv-analyzer/src/ast/imports.rs | 103 ++- .../celox-sv-analyzer/src/ast/timescales.rs | 45 +- .../src/ast/type_binding/binding.rs | 7 +- .../celox-sv-analyzer/src/ast/validation.rs | 690 +++++++++++------- crates/celox-sv-analyzer/src/ast/warnings.rs | 24 +- crates/celox-sv-analyzer/src/source_tree.rs | 23 +- .../src/source_tree/spans.rs | 284 +++++++ 9 files changed, 836 insertions(+), 352 deletions(-) create mode 100644 crates/celox-sv-analyzer/src/source_tree/spans.rs diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 019490d81eb..873be525655 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -120,7 +120,7 @@ mod expressions; mod ff_process; mod functions; mod generate; -mod imports; +pub(crate) mod imports; mod inlining; mod instances; mod interface_ast; @@ -147,7 +147,7 @@ mod subroutine_owners; pub(crate) mod timescales; pub(crate) mod type_parameters; mod types; -mod validation; +pub(crate) mod validation; pub(crate) mod warnings; use array_compatibility::selected_unpacked_shape; diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index f5b19ef58bf..bf92dba3033 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -692,10 +692,10 @@ fn parameter_literal_references( ranges.push(item.tokens); } let mut references = HashSet::default(); - for (_, expression) in native.expression_nodes() { - if !ranges.iter().any(|range| { - range.start <= expression.tokens.start && expression.tokens.end <= range.end - }) { + let scope = crate::source_tree::Ranges::new(ranges.iter().copied()); + for id in tree.spans().expressions.within(&ranges) { + let expression = native.expression(id); + if !scope.contains(expression.tokens) { continue; } if let ExprKind::Name(name) | ExprKind::Member { name, .. } = &expression.kind { diff --git a/crates/celox-sv-analyzer/src/ast/imports.rs b/crates/celox-sv-analyzer/src/ast/imports.rs index 9e7c4882027..84ce4d53c4e 100644 --- a/crates/celox-sv-analyzer/src/ast/imports.rs +++ b/crates/celox-sv-analyzer/src/ast/imports.rs @@ -103,7 +103,9 @@ impl ScopeImports { // Qualified expression and type names carry their package segment natively. let native = tree.declarations(); let ranges = active_ranges(tree)?; - for expression in &native.expressions { + let spans = tree.spans(); + for id in spans.expressions.within(&ranges) { + let expression = native.expression(id); if !in_ranges(expression.tokens.start, &ranges) { continue; } @@ -138,7 +140,8 @@ impl ScopeImports { } } } - for ty in &native.types { + for id in spans.types.within(&ranges) { + let ty = native.data_type(id); if in_ranges(ty.tokens.start, &ranges) && let celox_sv_syntax::DataTypeKind::Named(path) = &ty.kind && let [package, name] = path.as_slice() @@ -353,6 +356,59 @@ fn in_ranges(offset: usize, ranges: &[celox_sv_syntax::TokenRange]) -> bool { let next = ranges.partition_point(|range| range.start <= offset); next > 0 && offset < ranges[next - 1].end } +/// Whole-file facts the reference collection selects from, built once per +/// file so each scope costs what its own token ranges contain. +#[derive(Debug)] +pub(crate) struct Facts { + /// Token spans of the plain-name packages of qualified names. + qualified_bases: HashSet<(usize, usize)>, + /// First tokens of the bare-name keys of patterns. + pattern_keys: HashSet, +} + +impl Facts { + fn of(tree: &SyntaxTree) -> &Self { + use celox_sv_syntax::ExprKind; + tree.spans().imports.get_or_init(|| { + let native = tree.declarations(); + let name = |id| { + matches!(native.expression(id).kind, ExprKind::Name(_)) + .then_some(native.expression(id).tokens) + }; + let qualified_bases = native + .expressions + .iter() + .filter_map(|expression| match &expression.kind { + ExprKind::Member { + expression, + separator, + .. + } if separator == "::" => name(*expression), + _ => None, + }) + .map(|tokens| (tokens.start, tokens.end)) + .collect(); + // Bare pattern keys name members; they do not bind wildcard imports. + let pattern_keys = native + .expressions + .iter() + .flat_map(|expression| match &expression.kind { + ExprKind::Pattern { items, .. } => { + items.iter().filter_map(|item| item.key).collect::>() + } + _ => Vec::new(), + }) + .filter_map(name) + .map(|tokens| tokens.start) + .collect(); + Self { + qualified_bases, + pattern_keys, + } + }) + } +} + /// Unqualified expression and type references in the selected native scope. pub(super) fn unqualified_names(tree: &SyntaxTree) -> HashMap> { use celox_sv_syntax::{DataTypeKind, ExprKind}; @@ -361,33 +417,10 @@ pub(super) fn unqualified_names(tree: &SyntaxTree) -> HashMap return HashMap::default(); }; let nested = nested_declarations(tree); - let qualified: HashSet<_> = native - .expressions - .iter() - .filter_map(|expression| match &expression.kind { - ExprKind::Member { - expression, - separator, - .. - } if separator == "::" => Some(*expression), - _ => None, - }) - .collect(); - // Bare pattern keys name members; they do not bind wildcard imports. - let pattern_keys: HashSet<_> = native - .expressions - .iter() - .flat_map(|expression| match &expression.kind { - ExprKind::Pattern { items, .. } => { - items.iter().filter_map(|item| item.key).collect::>() - } - _ => Vec::new(), - }) - .filter_map(|id| { - matches!(native.expression(id).kind, ExprKind::Name(_)) - .then_some(native.expression(id).tokens.start) - }) - .collect(); + let Facts { + qualified_bases, + pattern_keys, + } = Facts::of(tree); let mut names: HashMap> = HashMap::default(); let mut add = |name: &str, offset| { let name = normalize_identifier(name); @@ -399,18 +432,18 @@ pub(super) fn unqualified_names(tree: &SyntaxTree) -> HashMap names.entry(name).or_default().push(offset); } }; - for expression in &native.expressions { + let spans = tree.spans(); + for id in spans.expressions.within(&ranges) { + let expression = native.expression(id); if let ExprKind::Name(name) = &expression.kind && !pattern_keys.contains(&expression.tokens.start) - && !qualified.iter().any(|base| { - native.expression(*base).tokens == expression.tokens - && matches!(&native.expression(*base).kind, ExprKind::Name(_)) - }) + && !qualified_bases.contains(&(expression.tokens.start, expression.tokens.end)) { add(&name.spelling, expression.tokens.start); } } - for ty in &native.types { + for id in spans.types.within(&ranges) { + let ty = native.data_type(id); if let DataTypeKind::Named(path) = &ty.kind && let [name] = path.as_slice() { diff --git a/crates/celox-sv-analyzer/src/ast/timescales.rs b/crates/celox-sv-analyzer/src/ast/timescales.rs index 7399cb91030..7e56ff00692 100644 --- a/crates/celox-sv-analyzer/src/ast/timescales.rs +++ b/crates/celox-sv-analyzer/src/ast/timescales.rs @@ -100,7 +100,7 @@ struct Unit { pub(super) struct Timescales { // Identical expanded tokens have identical native scope positions. Content keys // remain valid when ParsedSource values move or their trees are dropped. - units: HashMap>, + units: HashMap>, definitions: HashMap, packages: HashMap, precision: Option, @@ -210,12 +210,8 @@ fn install_context<'a>( } } -fn key(tree: &SyntaxTree) -> String { - tree.declarations() - .tokens - .iter() - .map(|token| token.text.as_str()) - .collect() +fn key(tree: &SyntaxTree) -> crate::source_tree::SourceText { + tree.source_text().clone() } fn exponent(number: &str, suffix: &str) -> Converted { @@ -384,34 +380,15 @@ pub(crate) fn generated_source_declarations( pub(super) fn validate_queries( tree: &AnalysisContext<'_>, ranges: &[celox_sv_syntax::TokenRange], - excluded: &[celox_sv_syntax::TokenRange], + excluded: &crate::source_tree::Ranges, ) -> Converted<()> { - use celox_sv_syntax::{ExprKind, StatementKind}; let native = tree.declarations(); - let callees: HashSet<_> = native - .expression_nodes() - .filter_map(|(_, node)| match node.kind { - ExprKind::Call { expression, .. } => Some(expression), - _ => None, - }) - .collect(); - let statements: HashSet<_> = native - .statements - .iter() - .filter_map(|statement| match statement.kind { - StatementKind::Expression(id) => Some(id), - _ => None, - }) - .collect(); - for (id, expression) in native.expression_nodes() { - let at = expression.tokens.start; - if !ranges - .iter() - .any(|range| range.start <= at && at < range.end) - || excluded - .iter() - .any(|range| range.start <= at && at < range.end) - { + let facts = validation::Facts::of(tree); + let (callees, statements) = (&facts.callees, &facts.expression_statements); + let scope = crate::source_tree::Ranges::new(ranges.iter().copied()); + for id in tree.spans().expressions.within(ranges) { + let at = native.expression(id).tokens.start; + if !scope.covers(at) || excluded.covers(at) { continue; } if callees.contains(&id) { @@ -743,7 +720,7 @@ impl Timescales { .insert(scopes[i].name.clone(), scopes[i].clone()); } design.units.insert( - key(tree).to_string(), + key(tree), Arc::new(Unit { scale: unit, scopes, diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs index 4f6d6b471c3..6d152b61b19 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -247,7 +247,12 @@ pub(in crate::ast) fn packed_ranges( // historical primitive/alias kernel includes nested datatype dimensions. // Aggregate fields use their own independently scheduled type ranges. let mut all = dimensions.to_vec(); - for data in &tree.declarations().types { + let bounds = dimensions + .iter() + .map(|dimension| dimension.tokens) + .collect::>(); + for id in tree.spans().types.within(&bounds) { + let data = tree.declarations().data_type(id); if dimensions.iter().any(|bound| { bound.tokens.start <= data.tokens.start && data.tokens.end <= bound.tokens.end }) { diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index f432f47c197..669af79e830 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -1,6 +1,8 @@ //! Unsupported-construct checks and bounded procedural-loop validation. use super::*; +use crate::source_tree::{Ranges, Starts}; +use celox_sv_syntax::ExprId; /// How an `always` construct is simulated. #[derive(Clone, Copy, PartialEq, Eq)] @@ -312,6 +314,319 @@ fn contains(outer: celox_sv_syntax::TokenRange, inner: celox_sv_syntax::TokenRan outer.start <= inner.start && inner.end <= outer.end } +/// Whole-file facts the scope validation selects from, built once per file +/// so each scope costs what its own token ranges contain. +#[derive(Debug)] +pub(crate) struct Facts { + /// Generate controls, whose bodies a module's own validation skips. + controls: Ranges, + /// The first token of the body item declaring each nested unit. + unit_starts: HashMap, + /// Unit and port positions of every header port, in arena order. + ports: Vec<(usize, usize)>, + port_starts: Starts, + /// Type and dimension positions of every packed dimension. + packed_dimensions: Vec<(usize, usize)>, + packed_dimension_starts: Starts, + /// Dimensions of type arguments naming an alias, with that name. + override_dimensions: Vec<(String, celox_sv_syntax::Dimension)>, + override_dimension_starts: Starts, + /// Value parameter defaults of declarations and unit headers. + parameter_defaults: Ranges, + /// Value parameter defaults of parameter declarations. + declared_defaults: Vec, + declared_default_ranges: Ranges, + /// Procedures and subroutines. + procedural: Ranges, + /// Subroutines, void casts of discarded calls and indexed widths. + cast_exclusions: Ranges, + pub(super) callees: HashSet, + /// Token spans of the callees of calls. + pub(super) callee_spans: HashSet<(usize, usize)>, + /// Expressions that are expression statements. + pub(super) expression_statements: HashSet, + /// Expressions that are constant values, and the roots they are under. + constant_roots: Vec, + constant_nodes: HashSet, + /// Callee and first argument of every call with one. + first_arguments: Vec<(ExprId, ExprId)>, + first_argument_ranges: Ranges, +} + +impl Facts { + fn new(native: &celox_sv_syntax::Declarations) -> Self { + use celox_sv_syntax::{BodyItemKind, ExprKind, ParameterKind, StatementKind}; + let controls = Ranges::new(native.body_items.iter().filter_map(|item| { + matches!( + item.kind, + BodyItemKind::Conditional { .. } + | BodyItemKind::Case { .. } + | BodyItemKind::Loop { .. } + ) + .then_some(item.tokens) + })); + let mut unit_starts = HashMap::default(); + for item in &native.body_items { + if let BodyItemKind::Unit(id) = item.kind { + unit_starts.entry(id).or_insert(item.tokens.start); + } + } + let units = || native.units.iter().chain(&native.nested_units); + let ports = units() + .enumerate() + .flat_map(|(unit, data)| (0..data.ports.len()).map(move |port| (unit, port))) + .collect::>(); + let port_starts = Starts::new( + units() + .flat_map(|unit| &unit.ports) + .map(|port| port.tokens) + .enumerate(), + ); + let packed_dimensions = native + .types + .iter() + .enumerate() + .flat_map(|(ty, data)| { + (0..data.packed_dimensions.len()).map(move |dimension| (ty, dimension)) + }) + .collect::>(); + let packed_dimension_starts = Starts::new( + native + .types + .iter() + .flat_map(|data| &data.packed_dimensions) + .map(|dimension| dimension.tokens) + .enumerate(), + ); + let override_dimensions = native + .instantiations + .iter() + .flat_map(|instance| instance.parameters.iter().flatten()) + .filter_map(|argument| argument.value) + .filter_map(|id| type_binding::argument_alias(id, native)) + .flat_map(|(name, dimensions)| { + dimensions + .into_iter() + .map(move |dimension| (name.clone(), dimension)) + }) + .collect::>(); + let override_dimension_starts = Starts::new( + override_dimensions + .iter() + .map(|(_, dimension)| dimension.tokens) + .enumerate(), + ); + let declared = || { + native + .parameter_declarations + .iter() + .flat_map(|declaration| &declaration.parameters) + }; + let headers = || units().flat_map(|unit| unit.parameters.iter().flatten()); + let parameter_defaults = Ranges::new( + declared() + .chain(headers()) + .filter_map(parameters::ownership::default) + .map(|id| native.expression(id).tokens), + ); + let declared_defaults = declared() + .filter_map(parameters::ownership::default) + .collect::>(); + let declared_default_ranges = Ranges::new( + declared_defaults + .iter() + .map(|id| native.expression(*id).tokens), + ); + let procedural = Ranges::new( + native + .procedures + .iter() + .map(|procedure| procedure.tokens) + .chain( + native + .subroutines + .iter() + .map(|subroutine| subroutine.tokens), + ), + ); + // Discarded calls own a void cast as statement syntax. The statement + // binder validates this wrapper; it is not an integral value cast. + let void_casts = native.statements.iter().filter_map(|statement| { + let StatementKind::Expression(root) = statement.kind else { + return None; + }; + let ExprKind::Cast { target, .. } = native.expression(root).kind else { + return None; + }; + let ExprKind::Type(id) = native.expression(target).kind else { + return None; + }; + matches!(&native.data_type(id).kind, celox_sv_syntax::DataTypeKind::Builtin(name) if name == "void") + .then_some(native.expression(root).tokens) + }); + let indexed_widths = + native + .expression_nodes() + .filter_map(|(_, expression)| match &expression.kind { + ExprKind::Select { dimension, .. } + if matches!( + dimension.kind, + celox_sv_syntax::DimensionKind::Indexed { .. } + ) => + { + Some(dimension.tokens) + } + _ => None, + }); + let cast_exclusions = Ranges::new( + native + .subroutines + .iter() + .map(|subroutine| subroutine.tokens) + .chain(void_casts) + .chain(indexed_widths), + ); + let callees = native + .expression_nodes() + .filter_map(|(_, expression)| match expression.kind { + ExprKind::Call { expression, .. } => Some(expression), + _ => None, + }) + .collect(); + let callee_spans = native + .expression_nodes() + .filter_map(|(_, expression)| match expression.kind { + ExprKind::Call { expression, .. } => { + let tokens = native.expression(expression).tokens; + Some((tokens.start, tokens.end)) + } + _ => None, + }) + .collect(); + let expression_statements = native + .statements + .iter() + .filter_map(|statement| match statement.kind { + StatementKind::Expression(id) => Some(id), + _ => None, + }) + .collect(); + let mut constant_roots = declared() + .chain(headers()) + .filter_map(|parameter| match parameter.kind { + ParameterKind::Value { default, .. } => default, + _ => None, + }) + .collect::>(); + for data in &native.types { + for dimension in &data.packed_dimensions { + dimension_expressions(dimension, &mut constant_roots); + } + if let celox_sv_syntax::DataTypeKind::Enum { items, .. } = &data.kind { + constant_roots.extend(items.iter().filter_map(|item| item.value)); + } + } + // Unpacked declaration bounds and expression forms retain their own + // constant-value operands, even inside otherwise runtime statements. + for unit in units() { + for port in &unit.ports { + for dimension in &port.dimensions { + dimension_expressions(dimension, &mut constant_roots); + } + } + } + for declaration in &native.data_declarations { + if let celox_sv_syntax::DataDeclaration::Variables(declaration) + | celox_sv_syntax::DataDeclaration::Constructed(declaration) = declaration + { + for dimension in declaration + .variables + .iter() + .flat_map(|variable| &variable.dimensions) + { + dimension_expressions(dimension, &mut constant_roots); + } + } + } + for declaration in &native.net_declarations { + for dimension in declaration + .variables + .iter() + .flat_map(|variable| &variable.dimensions) + { + dimension_expressions(dimension, &mut constant_roots); + } + } + for (_, expression) in native.expression_nodes() { + match &expression.kind { + ExprKind::Replication { count, .. } => constant_roots.push(*count), + ExprKind::Select { dimension, .. } | ExprKind::StreamSelect { dimension, .. } => { + match dimension.kind { + celox_sv_syntax::DimensionKind::Indexed { width, .. } => { + constant_roots.push(width) + } + celox_sv_syntax::DimensionKind::Range { left, right } => { + constant_roots.extend([left, right]) + } + _ => {} + } + } + _ => {} + } + } + let mut constant = constant_roots.clone(); + let mut constant_nodes = HashSet::default(); + while let Some(id) = constant.pop() { + if constant_nodes.insert(id) { + constant.extend(parameters::skipped::children(id, native)); + } + } + let first_arguments = native + .expression_nodes() + .filter_map(|(_, expression)| match &expression.kind { + ExprKind::Call { + expression: callee, + arguments, + } => Some((*callee, arguments.first()?.value?)), + _ => None, + }) + .collect::>(); + let first_argument_ranges = Ranges::new( + first_arguments + .iter() + .map(|(_, id)| native.expression(*id).tokens), + ); + Self { + controls, + unit_starts, + ports, + port_starts, + packed_dimensions, + packed_dimension_starts, + override_dimensions, + override_dimension_starts, + parameter_defaults, + declared_defaults, + declared_default_ranges, + procedural, + cast_exclusions, + callees, + callee_spans, + expression_statements, + constant_roots, + constant_nodes, + first_arguments, + first_argument_ranges, + } + } + + pub(super) fn of(tree: &SyntaxTree) -> &Self { + tree.spans() + .validation + .get_or_init(|| Self::new(tree.declarations())) + } +} + /// Validate authored native owners, excluding generate branches until their /// elaborated item carries the appropriate lexical environment. fn validate_scope( @@ -321,6 +636,8 @@ fn validate_scope( ) -> Converted<()> { use celox_sv_syntax::{BodyItemKind, DataTypeKind, DimensionKind, ExprKind}; let native = syntax_tree.declarations(); + let spans = syntax_tree.spans(); + let facts = Facts::of(syntax_tree); let owner = item.map(|item| item.id); let is_module = owner.is_none() && syntax_tree @@ -346,12 +663,7 @@ fn validate_scope( .then_some(item.tokens.start) }) } - crate::source_tree::ScopeHandle::Unit(id) => { - native.body_items.iter().find_map(|item| { - matches!(item.kind, BodyItemKind::Unit(owner) if owner == id) - .then_some(item.tokens.start) - }) - } + crate::source_tree::ScopeHandle::Unit(id) => facts.unit_starts.get(&id).copied(), } .ok_or_else(|| AnalyzerError::Parse("native root authored owner is absent".into()))?; ranges.push(celox_sv_syntax::TokenRange { @@ -359,46 +671,46 @@ fn validate_scope( end: unit.header.end, }); } + let scope = Ranges::new(ranges.iter().copied()); + let no_controls = Ranges::default(); let excluded = if is_module { - native - .body_items - .iter() - .filter_map(|item| { - matches!( - item.kind, - BodyItemKind::Conditional { .. } - | BodyItemKind::Case { .. } - | BodyItemKind::Loop { .. } - ) - .then_some(item.tokens) - }) - .collect::>() + &facts.controls } else { - Vec::new() - }; - let selected = |tokens| { - ranges.iter().any(|range| contains(*range, tokens)) - && !excluded.iter().any(|range| contains(*range, tokens)) + &no_controls }; - timescales::validate_queries(syntax_tree, &ranges, &excluded)?; - reject_constant_calls(native, &selected, syntax_tree, indexed_dimensions, item)?; - for unit in native.units.iter().chain(&native.nested_units) { - for port in &unit.ports { - if !selected(port.tokens) { - continue; - } - if port - .data_type - .is_some_and(|id| matches!(native.data_type(id).kind, DataTypeKind::Enum { .. })) - { - return Err(unsupported("enum port")); - } - if let Some(net_type) = &port.net_type { - validate_net_type(net_type)?; - } + let selected = |tokens| scope.contains(tokens) && !excluded.contains(tokens); + timescales::validate_queries(syntax_tree, &ranges, excluded)?; + reject_constant_calls( + native, + &selected, + &ranges, + syntax_tree, + indexed_dimensions, + item, + )?; + let units = native + .units + .iter() + .chain(&native.nested_units) + .collect::>(); + for index in facts.port_starts.within(&ranges) { + let (unit, port) = facts.ports[index]; + let port = &units[unit].ports[port]; + if !selected(port.tokens) { + continue; + } + if port + .data_type + .is_some_and(|id| matches!(native.data_type(id).kind, DataTypeKind::Enum { .. })) + { + return Err(unsupported("enum port")); + } + if let Some(net_type) = &port.net_type { + validate_net_type(net_type)?; } } - for net in &native.net_declarations { + for index in spans.net_declarations.within(&ranges) { + let net = &native.net_declarations[index]; if !selected(net.tokens) { continue; } @@ -411,7 +723,8 @@ fn validate_scope( return Err(unsupported("net declaration assignment")); } } - for item in &native.body_items { + for index in spans.body_items.within(&ranges) { + let item = &native.body_items[index]; if !selected(item.tokens) { continue; } @@ -450,7 +763,8 @@ fn validate_scope( } } } - for instance in &native.instantiations { + for index in spans.instantiations.within(&ranges) { + let instance = &native.instantiations[index]; if selected(instance.tokens) && instance .instances @@ -466,7 +780,8 @@ fn validate_scope( return Err(unsupported("wildcard port connection")); } } - for function in &native.subroutines { + for index in spans.subroutines.within(&ranges) { + let function = &native.subroutines[index]; if selected(function.tokens) && function .ports @@ -483,10 +798,11 @@ fn validate_scope( return Err(unsupported("ref function argument")); } } - for (id, data) in native - .type_nodes() - .filter(|(_, data)| selected(data.tokens)) - { + for id in spans.types.within(&ranges) { + let data = native.data_type(id); + if !selected(data.tokens) { + continue; + } if matches!(data.kind, DataTypeKind::Struct { .. }) && type_binding::bind(id, syntax_tree, indexed_dimensions)?.is_none() { @@ -495,20 +811,22 @@ fn validate_scope( )); } } - let override_dimensions = native - .instantiations - .iter() - .flat_map(|instance| instance.parameters.iter().flatten()) - .filter_map(|argument| argument.value) - .filter_map(|id| type_binding::argument_alias(id, native)) + let override_dimensions = facts + .override_dimension_starts + .within(&ranges) + .into_iter() + .map(|index| &facts.override_dimensions[index]) .filter(|(name, _)| type_aliases.contains_key(name)) - .flat_map(|(_, dimensions)| dimensions) - .collect::>(); - for dimension in native - .types - .iter() - .flat_map(|data| &data.packed_dimensions) - .chain(override_dimensions.iter()) + .map(|(_, dimension)| dimension); + for dimension in facts + .packed_dimension_starts + .within(&ranges) + .into_iter() + .map(|index| { + let (ty, dimension) = facts.packed_dimensions[index]; + &native.types[ty].packed_dimensions[dimension] + }) + .chain(override_dimensions) .filter(|dimension| selected(dimension.tokens)) { let DimensionKind::Range { left, right } = dimension.kind else { @@ -522,26 +840,11 @@ fn validate_scope( } } } - let parameter_ranges = native - .parameter_declarations - .iter() - .flat_map(|declaration| &declaration.parameters) - .filter_map(parameters::ownership::default) - .map(|id| native.expression(id).tokens) - .chain( - native - .units - .iter() - .chain(&native.nested_units) - .flat_map(|unit| unit.parameters.iter().flatten()) - .filter_map(parameters::ownership::default) - .map(|id| native.expression(id).tokens), - ) - .collect::>(); - for (_, expression) in native - .expression_nodes() - .filter(|(_, expression)| selected(expression.tokens)) - { + for id in spans.expressions.within(&ranges) { + let expression = native.expression(id); + if !selected(expression.tokens) { + continue; + } match &expression.kind { ExprKind::MinTypMax { .. } if !native.timing_controls.iter().any(|control| matches!(control.kind, celox_sv_syntax::TimingControlKind::Delay { value, .. } if contains(native.expression(value).tokens, expression.tokens))) => { @@ -549,7 +852,7 @@ fn validate_scope( } ExprKind::Select { dimension, .. } => { if let DimensionKind::Indexed { width, .. } = dimension.kind { - if parameter_ranges.iter().any(|range| contains(*range, dimension.tokens)) { continue; } + if facts.parameter_defaults.contains(dimension.tokens) { continue; } // IEEE 1800-2023 11.5.1 permits a variable base. Its // expression is bound after variable types are available; // only the width requires constant validation here. @@ -559,62 +862,9 @@ fn validate_scope( _ => {} } } - let procedural_ranges = native - .procedures - .iter() - .map(|procedure| procedure.tokens) - .chain( - native - .subroutines - .iter() - .map(|subroutine| subroutine.tokens), - ) - .collect::>(); - let mut cast_exclusions = native - .subroutines - .iter() - .map(|subroutine| subroutine.tokens) - .collect::>(); - // Discarded calls own a void cast as statement syntax. The statement - // binder validates this wrapper; it is not an integral value cast. - cast_exclusions.extend(native.statements.iter().filter_map(|statement| { - let celox_sv_syntax::StatementKind::Expression(root) = statement.kind else { - return None; - }; - let celox_sv_syntax::ExprKind::Cast { target, .. } = native.expression(root).kind else { - return None; - }; - let celox_sv_syntax::ExprKind::Type(id) = native.expression(target).kind else { - return None; - }; - matches!(&native.data_type(id).kind, celox_sv_syntax::DataTypeKind::Builtin(name) if name == "void") - .then_some(native.expression(root).tokens) - })); - cast_exclusions.extend(native.expression_nodes().filter_map(|(_, expression)| { - match &expression.kind { - celox_sv_syntax::ExprKind::Select { dimension, .. } - if matches!( - dimension.kind, - celox_sv_syntax::DimensionKind::Indexed { .. } - ) => - { - Some(dimension.tokens) - } - _ => None, - } - })); - cast_exclusions.extend( - native - .parameter_declarations - .iter() - .flat_map(|declaration| &declaration.parameters) - .filter_map(|parameter| { - let root = parameters::ownership::default(parameter)?; - parameters::skipped::needs_selected(&syntax_tree.state, root, native) - .then_some(native.expression(root).tokens) - }), - ); - for (_, expression) in native.expression_nodes() { + let candidates = spans.expressions.within(&ranges); + for id in &candidates { + let expression = native.expression(*id); let celox_sv_syntax::ExprKind::Cast { target, expression: operand, @@ -623,13 +873,20 @@ fn validate_scope( continue; }; let at = expression.tokens.start; - if ranges - .iter() - .any(|range| range.start <= at && at < range.end) - && !excluded - .iter() - .chain(&cast_exclusions) - .any(|range| range.start <= at && at < range.end) + if scope.covers(at) + && !excluded.covers(at) + && !facts.cast_exclusions.covers(at) + && !facts + .declared_default_ranges + .covering(at) + .into_iter() + .any(|index| { + parameters::skipped::needs_selected( + &syntax_tree.state, + facts.declared_defaults[index], + native, + ) + }) { expression_binding::cast_target_native( target, @@ -640,11 +897,12 @@ fn validate_scope( )?; } } - let mut native_bits = native.expression_nodes().filter_map(|(id, expression)| { - let celox_sv_syntax::ExprKind::Call { expression: callee, .. } = expression.kind else { return None; }; - if !matches!(&native.expression(callee).kind, celox_sv_syntax::ExprKind::Name(name) if matches!(name.spelling.as_str(),"$bits"|"$size"|"$dimensions"|"$unpacked_dimensions"|"$left"|"$right"|"$low"|"$high"|"$increment"|"$isunbounded")) { return None; } + let mut native_bits = candidates.into_iter().filter(|id| { + let expression = native.expression(*id); + let celox_sv_syntax::ExprKind::Call { expression: callee, .. } = expression.kind else { return false; }; + if !matches!(&native.expression(callee).kind, celox_sv_syntax::ExprKind::Name(name) if matches!(name.spelling.as_str(),"$bits"|"$size"|"$dimensions"|"$unpacked_dimensions"|"$left"|"$right"|"$low"|"$high"|"$increment"|"$isunbounded")) { return false; } let at = expression.tokens.start; - (ranges.iter().any(|range| range.start <= at && at < range.end) && !excluded.iter().chain(&procedural_ranges).any(|range| range.start <= at && at < range.end)).then_some(id) + scope.covers(at) && !excluded.covers(at) && !facts.procedural.covers(at) }).collect::>(); native_bits.sort_by_key(|id| native.expression(*id).tokens.start); for root in native_bits { @@ -691,31 +949,18 @@ fn dimension_expressions( fn reject_constant_calls( native: &celox_sv_syntax::Declarations, selected: &impl Fn(celox_sv_syntax::TokenRange) -> bool, + ranges: &[celox_sv_syntax::TokenRange], tree: &AnalysisContext<'_>, dimensions: &PackedDimensions, item: Option<&generate::Item>, ) -> Converted<()> { - use celox_sv_syntax::{ExprKind, ParameterKind}; - let mut constant = native - .parameter_declarations - .iter() - .flat_map(|declaration| &declaration.parameters) - .chain( - native - .units - .iter() - .chain(&native.nested_units) - .flat_map(|unit| unit.parameters.iter().flatten()), - ) - .filter_map(|parameter| match parameter.kind { - ParameterKind::Value { default, .. } => default, - _ => None, - }) - .collect::>(); + use celox_sv_syntax::ExprKind; + let facts = Facts::of(tree); // Specparams are inert timing declarations until used, but IEEE 1800-2023 // 6.20.5 explicitly forbids using them to assign value parameters. let mut specparams = HashSet::default(); - for body in &native.body_items { + for index in tree.spans().body_items.within(ranges) { + let body = &native.body_items[index]; if !selected(body.tokens) || !matches!(&body.kind, celox_sv_syntax::BodyItemKind::Unconverted { category, .. } if category == "specparam") { @@ -741,7 +986,7 @@ fn reject_constant_calls( } } if !specparams.is_empty() { - let mut pending = constant.clone(); + let mut pending = facts.constant_roots.clone(); let mut visited = HashSet::default(); while let Some(id) = pending.pop() { if !visited.insert(id) || !selected(native.expression(id).tokens) { @@ -755,97 +1000,24 @@ fn reject_constant_calls( pending.extend(parameters::skipped::children(id, native)); } } - for data in &native.types { - for dimension in &data.packed_dimensions { - dimension_expressions(dimension, &mut constant); - } - if let celox_sv_syntax::DataTypeKind::Enum { items, .. } = &data.kind { - constant.extend(items.iter().filter_map(|item| item.value)); - } - } - // Unpacked declaration bounds and expression forms retain their own - // constant-value operands, even inside otherwise runtime statements. - for unit in native.units.iter().chain(&native.nested_units) { - for port in &unit.ports { - for dimension in &port.dimensions { - dimension_expressions(dimension, &mut constant); - } - } - } - for declaration in &native.data_declarations { - if let celox_sv_syntax::DataDeclaration::Variables(declaration) - | celox_sv_syntax::DataDeclaration::Constructed(declaration) = declaration - { - for dimension in declaration - .variables - .iter() - .flat_map(|variable| &variable.dimensions) - { - dimension_expressions(dimension, &mut constant); - } - } - } - for declaration in &native.net_declarations { - for dimension in declaration - .variables - .iter() - .flat_map(|variable| &variable.dimensions) - { - dimension_expressions(dimension, &mut constant); - } - } - for (_, expression) in native.expression_nodes() { - match &expression.kind { - ExprKind::Replication { count, .. } => constant.push(*count), - ExprKind::Select { dimension, .. } | ExprKind::StreamSelect { dimension, .. } => { - match dimension.kind { - celox_sv_syntax::DimensionKind::Indexed { width, .. } => constant.push(width), - celox_sv_syntax::DimensionKind::Range { left, right } => { - constant.extend([left, right]) - } - _ => {} - } - } - _ => {} - } - } - let mut constant_nodes = HashSet::default(); - while let Some(id) = constant.pop() { - if constant_nodes.insert(id) { - constant.extend(parameters::skipped::children(id, native)); - } - } - let mut unevaluated = Vec::new(); - for (_, expression) in native.expression_nodes() { - let ExprKind::Call { - expression: callee, - arguments, - } = &expression.kind - else { - continue; - }; - let Some(name) = expression_binding::native_name(&tree.state, *callee, native) else { - continue; - }; - if SystemFunction::from_name(&name).is_some_and(SystemFunction::is_data_query) - && let Some(Some(id)) = arguments.first().map(|argument| argument.value) - { - unevaluated.push(native.expression(id).tokens); - } - } - let callees = native - .expression_nodes() - .filter_map(|(_, expression)| match expression.kind { - ExprKind::Call { expression, .. } => Some(expression), - _ => None, - }) - .collect::>(); - for (id, expression) in native.expression_nodes() { + // Operands of data queries, whose callee names may depend on the scope. + let unevaluated = |tokens| { + facts + .first_argument_ranges + .containing(tokens) + .into_iter() + .any(|index| { + expression_binding::native_name(&tree.state, facts.first_arguments[index].0, native) + .is_some_and(|name| { + SystemFunction::from_name(&name).is_some_and(SystemFunction::is_data_query) + }) + }) + }; + for id in tree.spans().expressions.within(ranges) { + let expression = native.expression(id); if !selected(expression.tokens) - || !constant_nodes.contains(&id) - || unevaluated - .iter() - .any(|range| contains(*range, expression.tokens)) + || !facts.constant_nodes.contains(&id) + || unevaluated(expression.tokens) { continue; } @@ -863,7 +1035,7 @@ fn reject_constant_calls( ExprKind::Name(name) if name.spelling.starts_with('$') && !matches!(name.spelling.as_str(), "$" | "$unit" | "$root") - && !callees.contains(&id) => + && !facts.callees.contains(&id) => { (name.spelling.clone(), &[][..]) } diff --git a/crates/celox-sv-analyzer/src/ast/warnings.rs b/crates/celox-sv-analyzer/src/ast/warnings.rs index 354e287cdf5..c4924e34220 100644 --- a/crates/celox-sv-analyzer/src/ast/warnings.rs +++ b/crates/celox-sv-analyzer/src/ast/warnings.rs @@ -36,9 +36,12 @@ fn functions(tree: &SyntaxTree, range: celox_sv_syntax::TokenRange) -> Vec = native + let spans = tree.spans(); + let functions: Vec<_> = spans .subroutines - .iter() + .within(&[range]) + .into_iter() + .map(|index| &native.subroutines[index]) .filter(|function| { function.kind == SubroutineKind::Function && range.start <= function.tokens.start @@ -46,19 +49,10 @@ fn functions(tree: &SyntaxTree, range: celox_sv_syntax::TokenRange) -> Vec>(); + let called_names = &validation::Facts::of(tree).callee_spans; let mut warnings = Vec::new(); - for expression in &native.expressions { + for id in spans.expressions.within(&functions) { + let expression = native.expression(id); let tokens = expression.tokens; if !functions .iter() @@ -78,7 +72,7 @@ fn functions(tree: &SyntaxTree, range: celox_sv_syntax::TokenRange) -> Vec name, + ExprKind::Name(name) if !called_names.contains(&(tokens.start, tokens.end)) => name, _ => continue, }; if name.spelling == "$exit" { diff --git a/crates/celox-sv-analyzer/src/source_tree.rs b/crates/celox-sv-analyzer/src/source_tree.rs index 5960cc2b2ba..a4a8acbf6d1 100644 --- a/crates/celox-sv-analyzer/src/source_tree.rs +++ b/crates/celox-sv-analyzer/src/source_tree.rs @@ -5,13 +5,19 @@ use std::path::Path; use crate::AnalyzerError; mod scopes; pub(crate) use scopes::ScopeHandle; +mod spans; +pub(crate) use spans::{Ranges, SourceText, Spans, Starts}; /// Shared native arena with copy-on-write support for ownership regressions. +/// The span index is built on first use and dropped when the arena changes. #[derive(Clone, Debug)] -pub(super) struct Shared(std::sync::Arc); +pub(super) struct Shared( + std::sync::Arc, + std::sync::Arc>, +); impl From for Shared { fn from(value: T) -> Self { - Self(std::sync::Arc::new(value)) + Self(std::sync::Arc::new(value), Default::default()) } } impl std::ops::Deref for Shared { @@ -22,6 +28,7 @@ impl std::ops::Deref for Shared { } impl std::ops::DerefMut for Shared { fn deref_mut(&mut self) -> &mut T { + self.1 = Default::default(); std::sync::Arc::make_mut(&mut self.0) } } @@ -129,6 +136,18 @@ impl SourceTree { pub(crate) fn declarations(&self) -> &celox_sv_syntax::Declarations { &self.declarations } + /// The token-order index of this file's arenas. + pub(crate) fn spans(&self) -> &Spans { + self.declarations + .1 + .get_or_init(|| Spans::new(&self.declarations)) + } + /// The expanded token text of this file. + pub(crate) fn source_text(&self) -> &SourceText { + self.spans() + .text + .get_or_init(|| SourceText::new(&self.declarations)) + } pub(crate) fn into_declarations(self) -> celox_sv_syntax::Declarations { std::sync::Arc::try_unwrap(self.declarations.0).unwrap_or_else(|shared| (*shared).clone()) diff --git a/crates/celox-sv-analyzer/src/source_tree/spans.rs b/crates/celox-sv-analyzer/src/source_tree/spans.rs new file mode 100644 index 00000000000..67a3af723e9 --- /dev/null +++ b/crates/celox-sv-analyzer/src/source_tree/spans.rs @@ -0,0 +1,284 @@ +//! Token-order indexes of the native arenas, built once per source file. +//! +//! Scope analyses select arena entries by token range. Visiting every entry of +//! the file for each scope makes a design shipped as one file quadratic, so +//! these indexes let a scope visit only the entries starting inside its own +//! ranges. Results keep arena order, so diagnostics are reported in the order +//! a whole-arena scan would report them. + +use celox_sv_syntax::{Declarations, ExprId, TokenRange, TypeId}; + +/// Arena entries ordered by their first token. +#[derive(Debug)] +pub(crate) struct Starts { + /// First token, arena position and handle of each entry. + sorted: Vec<(usize, usize, I)>, +} + +impl Starts { + pub(crate) fn new(entries: impl Iterator) -> Self { + let mut sorted = entries + .enumerate() + .map(|(index, (id, tokens))| (tokens.start, index, id)) + .collect::>(); + sorted.sort_unstable_by_key(|(start, index, _)| (*start, *index)); + Self { sorted } + } + + /// The entries whose first token lies in one of `ranges`, in arena + /// order. Every entry a range contains is among them. + pub(crate) fn within(&self, ranges: &[TokenRange]) -> Vec { + let mut entries = Vec::new(); + for range in merge(ranges) { + let first = self + .sorted + .partition_point(|(start, ..)| *start < range.start); + entries.extend( + self.sorted[first..] + .iter() + .take_while(|(start, ..)| *start <= range.end) + .map(|(_, index, id)| (*index, *id)), + ); + } + entries.sort_unstable_by_key(|(index, _)| *index); + entries.into_iter().map(|(_, id)| id).collect() + } +} + +/// Token ranges whose union is that of `ranges`, without overlaps. +fn merge(ranges: &[TokenRange]) -> Vec { + let mut sorted = ranges.to_vec(); + sorted.sort_unstable_by_key(|range| range.start); + let mut merged = Vec::::with_capacity(sorted.len()); + for range in sorted { + match merged.last_mut() { + Some(last) if range.start <= last.end => last.end = last.end.max(range.end), + _ => merged.push(range), + } + } + merged +} + +/// Token ranges answering which of them contain a range or a token. +#[derive(Debug, Default)] +pub(crate) struct Ranges { + /// Ranges ordered by start with their position in the input, each with + /// the largest end up to it. + sorted: Vec<(TokenRange, usize, usize)>, +} + +impl Ranges { + pub(crate) fn new(ranges: impl IntoIterator) -> Self { + let mut ranges = ranges.into_iter().enumerate().collect::>(); + ranges.sort_by_key(|(_, range)| range.start); + let mut end = 0; + Self { + sorted: ranges + .into_iter() + .map(|(index, range)| { + end = end.max(range.end); + (range, index, end) + }) + .collect(), + } + } + + /// Input positions of the ranges for which `keep` holds, in input order. + fn matching(&self, start: usize, keep: impl Fn(TokenRange) -> bool) -> Vec { + let count = self + .sorted + .partition_point(|(range, ..)| range.start <= start); + let mut indexes = self.sorted[..count] + .iter() + .rev() + .take_while(|(.., reach)| keep(TokenRange { start, end: *reach })) + .filter(|(range, ..)| keep(*range)) + .map(|(_, index, _)| *index) + .collect::>(); + indexes.sort_unstable(); + indexes + } + + /// Input positions of the ranges that contain `inner`. + pub(crate) fn containing(&self, inner: TokenRange) -> Vec { + self.matching(inner.start, |range| inner.end <= range.end) + } + + /// Input positions of the ranges that have token `at` before their end. + pub(crate) fn covering(&self, at: usize) -> Vec { + self.matching(at, |range| at < range.end) + } + + /// The largest end of the ranges starting at or before `start`. + fn reach(&self, start: usize) -> Option { + let count = self + .sorted + .partition_point(|(range, ..)| range.start <= start); + count.checked_sub(1).map(|last| self.sorted[last].2) + } + + /// Whether a range contains `inner`. + pub(crate) fn contains(&self, inner: TokenRange) -> bool { + self.reach(inner.start).is_some_and(|end| inner.end <= end) + } + + /// Whether a range has token `at` before its end. + pub(crate) fn covers(&self, at: usize) -> bool { + self.reach(at).is_some_and(|end| at < end) + } +} + +/// The arenas analyses select from by token range. +#[derive(Debug)] +pub(crate) struct Spans { + pub expressions: Starts, + pub types: Starts, + pub body_items: Starts, + pub net_declarations: Starts, + pub instantiations: Starts, + pub subroutines: Starts, + /// Facts the scope validation derives from the whole file. + pub validation: std::sync::OnceLock, + /// Facts the import analysis derives from the whole file. + pub imports: std::sync::OnceLock, + pub(super) text: std::sync::OnceLock, +} + +/// The expanded token text of a file, which identifies its source across +/// trees. Its hash is computed once, so lookups by it do not rehash the file. +#[derive(Clone, Debug)] +pub(crate) struct SourceText { + hash: u64, + text: std::sync::Arc, +} + +impl SourceText { + pub(super) fn new(native: &Declarations) -> Self { + use std::hash::{Hash, Hasher}; + let text = native + .tokens + .iter() + .map(|token| token.text.as_str()) + .collect::(); + let mut hasher = fxhash::FxHasher::default(); + text.hash(&mut hasher); + Self { + hash: hasher.finish(), + text: text.into(), + } + } +} + +impl PartialEq for SourceText { + fn eq(&self, other: &Self) -> bool { + std::sync::Arc::ptr_eq(&self.text, &other.text) + || (self.hash == other.hash && self.text == other.text) + } +} + +impl Eq for SourceText {} + +impl std::hash::Hash for SourceText { + fn hash(&self, state: &mut H) { + state.write_u64(self.hash); + } +} + +impl Spans { + pub(super) fn new(native: &Declarations) -> Self { + let indexed = + |tokens: &mut dyn Iterator| Starts::new(tokens.enumerate()); + Self { + expressions: Starts::new( + native + .expression_nodes() + .map(|(id, node)| (id, node.tokens)), + ), + types: Starts::new(native.type_nodes().map(|(id, node)| (id, node.tokens))), + body_items: indexed(&mut native.body_items.iter().map(|node| node.tokens)), + net_declarations: indexed(&mut native.net_declarations.iter().map(|node| node.tokens)), + instantiations: indexed(&mut native.instantiations.iter().map(|node| node.tokens)), + subroutines: indexed(&mut native.subroutines.iter().map(|node| node.tokens)), + validation: Default::default(), + imports: Default::default(), + text: Default::default(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn range(start: usize, end: usize) -> TokenRange { + TokenRange { start, end } + } + + /// Ranges of every length over a short token sequence, overlapping, + /// nested, empty and repeated. + fn all_ranges() -> Vec { + (0..8) + .flat_map(|start| (start..8).map(move |end| range(start, end))) + .collect() + } + + #[test] + fn selections_match_whole_arena_scans() { + let entries = all_ranges(); + let starts = Starts::new(entries.iter().copied().enumerate()); + let ranges = Ranges::new(entries.iter().copied()); + for scope in entries + .iter() + .flat_map(|a| entries.iter().map(move |b| [*a, *b])) + { + let contained = (0..entries.len()) + .filter(|index| { + scope.iter().any(|outer| { + outer.start <= entries[*index].start && entries[*index].end <= outer.end + }) + }) + .collect::>(); + let within = starts.within(&scope); + assert!(within.is_sorted(), "{scope:?}"); + assert!( + contained.iter().all(|index| within.contains(index)), + "{scope:?}" + ); + assert!( + within.iter().all(|index| scope + .iter() + .any(|outer| outer.start <= entries[*index].start + && entries[*index].start <= outer.end)), + "{scope:?}" + ); + } + for inner in all_ranges() { + let containing = (0..entries.len()) + .filter(|index| { + entries[*index].start <= inner.start && inner.end <= entries[*index].end + }) + .collect::>(); + assert_eq!(ranges.containing(inner), containing, "{inner:?}"); + assert_eq!(ranges.contains(inner), !containing.is_empty(), "{inner:?}"); + } + for at in 0..9 { + let covering = (0..entries.len()) + .filter(|index| entries[*index].start <= at && at < entries[*index].end) + .collect::>(); + assert_eq!(ranges.covering(at), covering, "{at}"); + assert_eq!(ranges.covers(at), !covering.is_empty(), "{at}"); + } + } + + #[test] + fn ranges_without_entries_select_nothing() { + let ranges = Ranges::default(); + assert!(!ranges.contains(range(0, 0))); + assert!(!ranges.covers(0)); + assert!( + Starts::::new(std::iter::empty()) + .within(&[range(0, 9)]) + .is_empty() + ); + } +} From 1d8b956b8f158e522ba1b668c95ffa5fdbeec91d Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 12:56:34 +0900 Subject: [PATCH 2/2] feat(sv)!: support bounded class randc randomization MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implement unconstrained randc for 1–8-bit two-state integers and scalar enums with up to 256 declared values. Draw uniformly without replacement using per-object, per-property cycle state, then start a new cycle once all values have been consumed. Preserve cycles across disabled modes, explicit member selection, aliases, inheritance and checkpoint restore. Reseeding changes the RNG without reintroducing consumed values. Add shared cycle/domain/control regressions, heap and checkpoint tests, and diagnostics for larger domains. Verilator passes the integer/direct-enum case; its inherited srandom compilation failure and enum alias mismatch, and Icarus's unsupported randomization methods, are recorded with narrow exclusions and reproduction evidence. Validation: analyzer 804 tests (3 existing ignores), frontend 6, heap 18, class regressions 198; NAPI build and JS tests 432; retained reports 4; affected crate/test Clippy, formatting and diff checks. Shared cases were exercised with Verilator and Icarus, with the limitations above retained. Rebased onto master and revalidated the class suite and retained-report checks. The optional xezim adapter was not run because xezim is not installed in this shell. BREAKING CHANGE: The public celox-sv-analyzer ObjectOp enum gains RandomCyclic; downstream exhaustive matches must handle this variant. Change-Id: I48859189cd57d25bb8c0df4773968b8e1534bf60 --- .../src/lowering/ff/objects.rs | 9 ++ crates/celox-heap/src/objects.rs | 80 +++++++++- crates/celox-heap/src/ops.rs | 3 + crates/celox-sv-analyzer/src/ast/classes.rs | 27 +++- .../src/ast/expression_binding/objects.rs | 4 +- .../src/ast/procedural/randomization.rs | 74 ++++++--- .../celox-sv-analyzer/src/system_functions.rs | 8 +- crates/celox-sv-analyzer/src/tests.rs | 25 ++- crates/celox-test-suite/LIMITATIONS.md | 8 + .../celox-test-suite/src/sv/cases/class.vtest | 144 ++++++++++++++++++ .../verification/repros/sv_randc_icarus.json | 44 ++++++ .../repros/sv_randc_verilator.json | 33 ++++ .../verification/sv/icarus/class.json | 69 +++++++++ .../verification/sv/limitations.json | 53 +++++++ .../verification/sv/verilator/class.json | 46 ++++++ .../tests/frontends/systemverilog/class.rs | 34 +++++ docs/guide/systemverilog-reference.md | 8 +- docs/ja/guide/systemverilog-reference.md | 7 +- 18 files changed, 638 insertions(+), 38 deletions(-) create mode 100644 crates/celox-test-suite/verification/repros/sv_randc_icarus.json create mode 100644 crates/celox-test-suite/verification/repros/sv_randc_verilator.json diff --git a/crates/celox-frontend-sv/src/lowering/ff/objects.rs b/crates/celox-frontend-sv/src/lowering/ff/objects.rs index ac966cb01e3..9f2026bb1c5 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/objects.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/objects.rs @@ -60,6 +60,14 @@ impl Ff<'_, '_> { let value = self.integer_of_width(&args[1], field.width as usize, field.signed)?; self.heap_call(ops::OBJECT_STORE, &[object, place, value]) } + ObjectOp::RandomCyclic { offset, count } => { + let object = self.handle(&args[0])?; + let count = self.constant64(u64::from(*count)); + self.heap_call( + ops::encode(ops::OBJECT_RANDOM_CYCLIC, u64::from(*offset)), + &[object, count], + ) + } ObjectOp::Random | ObjectOp::Check(_) | ObjectOp::ModeGet(..) @@ -121,6 +129,7 @@ impl Ff<'_, '_> { ObjectOp::Store(_) | ObjectOp::ClassOf | ObjectOp::Random + | ObjectOp::RandomCyclic { .. } | ObjectOp::Seed | ObjectOp::Check(_) | ObjectOp::ModeGet(..) diff --git a/crates/celox-heap/src/objects.rs b/crates/celox-heap/src/objects.rs index b7d294c8964..bace65434d6 100644 --- a/crates/celox-heap/src/objects.rs +++ b/crates/celox-heap/src/objects.rs @@ -17,6 +17,8 @@ pub(crate) struct Object { random_state: u64, random_modes: RandomModes, saved_random_modes: Vec, + /// Remaining domain indices for each randc property, keyed by byte offset. + random_cycles: fxhash::FxHashMap>, bytes: Box<[u8]>, /// Byte offsets of the handle properties, with what they refer to. pub(crate) handles: Vec<(u32, HandleKind)>, @@ -30,6 +32,14 @@ struct RandomModes { } impl Object { + fn random(&mut self) -> u64 { + self.random_state = self.random_state.wrapping_add(0x9e3779b97f4a7c15); + let mut word = self.random_state; + word = (word ^ (word >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); + word = (word ^ (word >> 27)).wrapping_mul(0x94d049bb133111eb); + word ^ (word >> 31) + } + pub(crate) fn size(&self) -> usize { self.bytes.len() } @@ -71,6 +81,7 @@ impl Heap { random_state: 0, random_modes: RandomModes::default(), saved_random_modes: Vec::new(), + random_cycles: Default::default(), bytes: vec![0; size].into(), handles: Vec::new(), }, @@ -92,11 +103,36 @@ impl Heap { let Some(object) = self.object_mut(handle) else { return 0; }; - object.random_state = object.random_state.wrapping_add(0x9e3779b97f4a7c15); - let mut word = object.random_state; - word = (word ^ (word >> 30)).wrapping_mul(0xbf58476d1ce4e5b9); - word = (word ^ (word >> 27)).wrapping_mul(0x94d049bb133111eb); - word ^ (word >> 31) + object.random() + } + + /// Draw without replacement from an immutable domain (IEEE 1800-2023 + /// 18.4.2). Lazy Fisher-Yates uses bounded storage and uniform draws. + /// Seeding changes the RNG, but does not discard an unfinished cycle. + pub(crate) fn random_cyclic_object(&mut self, handle: Handle, offset: u32, count: u64) -> u64 { + assert!((1..=256).contains(&count), "invalid randc domain size"); + let Some(object) = self.object_mut(handle) else { + return 0; + }; + let remaining = object.random_cycles.entry(offset).or_default(); + if remaining.is_empty() { + remaining.extend(0..count as u16); + } + let count = remaining.len() as u64; + let threshold = count.wrapping_neg() % count; + let index = loop { + let draw = object.random(); + if draw >= threshold { + break (draw % count) as usize; + } + }; + u64::from( + object + .random_cycles + .get_mut(&offset) + .unwrap() + .swap_remove(index), + ) } /// Random properties start enabled. Modes are shared by aliases of an @@ -287,6 +323,40 @@ mod tests { mod random_tests { use super::*; + #[test] + fn cyclic_domains_survive_reseeding_and_checkpoint_restore() { + for count in [1, 3, 256] { + let mut heap = Heap::new(); + let object = heap.new_object(1, 2); + let other = heap.new_object(1, 2); + heap.seed_object(object, 12); + heap.seed_object(other, 12); + let first = heap.random_cyclic_object(object, 0, count); + assert_eq!(first, heap.random_cyclic_object(other, 0, count)); + let mut saved = heap.clone(); + let mut seen = crate::HashSet::from_iter([first]); + for _ in 1..count { + // Seeding does not make consumed values eligible again. + heap.seed_object(object, 19); + saved.seed_object(object, 19); + let value = heap.random_cyclic_object(object, 0, count); + assert_eq!(value, saved.random_cyclic_object(object, 0, count)); + assert!(seen.insert(value)); + } + for offset in [0, 1, 0] { + let seen: crate::HashSet<_> = (0..count) + .map(|_| heap.random_cyclic_object(object, offset, count)) + .collect(); + assert_eq!(seen.len(), count as usize); + assert!(seen.iter().all(|&value| value < count)); + } + assert_eq!(heap.take_fault(), None); + } + let mut heap = Heap::new(); + assert_eq!(heap.random_cyclic_object(NULL, 0, 3), 0); + assert_eq!(heap.take_fault(), Some(Fault::NullDereference)); + } + #[test] fn random_streams_are_independent_and_checkpointed() { let mut heap = Heap::new(); diff --git a/crates/celox-heap/src/ops.rs b/crates/celox-heap/src/ops.rs index 9c38b6a00e0..d0485579576 100644 --- a/crates/celox-heap/src/ops.rs +++ b/crates/celox-heap/src/ops.rs @@ -79,6 +79,8 @@ pub const OBJECT_MODE_POP: u64 = 59; pub const OBJECT_MODE_SELECT: u64 = 60; /// Whether a non-rand property is temporarily random in the active scope. pub const OBJECT_MODE_SELECTED: u64 = 61; +/// Draw a randc domain index; parameter is the property offset, b its domain size. +pub const OBJECT_RANDOM_CYCLIC: u64 = 62; /// The opcode word of `op` with parameter `parameter`. pub const fn encode(op: u64, parameter: u64) -> u64 { @@ -187,6 +189,7 @@ impl Heap { } OBJECT_CLASS => self.class_of(a as Handle).into(), OBJECT_RANDOM => self.random_object(a as Handle), + OBJECT_RANDOM_CYCLIC => self.random_cyclic_object(a as Handle, parameter as u32, b), OBJECT_SEED => { self.seed_object(a as Handle, b as u32); 0 diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 4b92fe3940d..467292a8c8e 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -34,6 +34,25 @@ pub(super) struct Property { pub initializer: Option, } +impl Property { + pub fn cyclic_domain_size(&self) -> Option { + if self.field.handle.is_some() { + return None; + } + if self.r#type.is_enum { + self.r#type.enum_values.as_ref().and_then(|values| { + (1..=256) + .contains(&values.len()) + .then_some(values.len() as u16) + }) + } else { + (1..=8) + .contains(&self.field.width) + .then(|| 1u16 << self.field.width) + } + } +} + /// A static property of a class: one variable of the module that declares /// the class, shared by all of its objects (IEEE 1800-2023 8.9). #[derive(Debug, Clone, PartialEq, Eq)] @@ -119,10 +138,12 @@ impl Class { return Err(unsupported("class randomize with constraints")); } for property in &self.properties { - if property.randc { - return Err(unsupported("class randomize with randc properties")); + if property.randc && property.cyclic_domain_size().is_none() { + return Err(unsupported( + "randc requires a 1-8 bit integer or an enum with at most 256 declared values", + )); } - if property.rand + if (property.rand || property.randc) && (property.field.handle.is_some() || (property.r#type.is_enum && property.r#type.enum_values.is_none())) { diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs index 26d4e676a93..1c91118b142 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -557,10 +557,10 @@ pub(super) fn random_selection( } if property.field.handle.is_some() || (property.r#type.is_enum && property.r#type.enum_values.is_none()) - || property.randc + || (property.randc && property.cyclic_domain_size().is_none()) { return Err(unsupported( - "randomize arguments require integral, non-randc properties with a supported enum domain", + "randomize arguments require integral properties with a supported enum domain", )); } bits[index + 1] = '1'; diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index 597458d6c73..f92f50ec209 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -120,7 +120,10 @@ pub(super) fn lower( right: Box::new(Expr::Literal("1'b1".into())), }; select.push(Stmt::Eval(classes::object_call( - ObjectOp::ModeSelect(property.field.offset, property.rand), + ObjectOp::ModeSelect( + property.field.offset, + property.rand || property.randc, + ), vec![Expr::Ident(this.clone()), selected], ))); } @@ -146,7 +149,10 @@ pub(super) fn lower( }), op: BinaryOp::LogicAnd, right: Box::new(classes::object_call( - ObjectOp::ModeGet(property.field.offset, property.rand), + ObjectOp::ModeGet( + property.field.offset, + property.rand || property.randc, + ), vec![Expr::Ident(this.clone())], )), }, @@ -264,36 +270,56 @@ fn random_property( property: &classes::Property, this: &str, ) -> Vec { - let random = || classes::object_call(ObjectOp::Random, vec![Expr::Ident(this.into())]); + let random = || { + let op = if property.randc { + ObjectOp::RandomCyclic { + offset: property.field.offset, + count: property + .cyclic_domain_size() + .expect("validated randc domain"), + } + } else { + ObjectOp::Random + }; + classes::object_call(op, vec![Expr::Ident(this.into())]) + }; let mut body = Vec::new(); let value = if let Some(values) = &property.r#type.enum_values { let count = values.len() as u64; let threshold = count.wrapping_neg() % count; let draw = builder.declare("$enum_draw", classes::unsigned_type(64)); - body.push(Stmt::Loop { - kind: LoopKind::DoWhile, - init: Vec::new(), - condition: Some(Expr::Binary { - left: Box::new(Expr::Ident(draw.clone())), - op: BinaryOp::Lt, - right: Box::new(Expr::Literal(format!("64'd{threshold}"))), - }), - step: Vec::new(), - body: vec![Stmt::Assign { + if property.randc { + body.push(Stmt::Assign { lhs: LValue::Ident(draw.clone()), rhs: random(), nonblocking: false, - }], - }); - body.push(Stmt::Assign { - lhs: LValue::Ident(draw.clone()), - rhs: Expr::Binary { - left: Box::new(Expr::Ident(draw.clone())), - op: BinaryOp::Mod, - right: Box::new(Expr::Literal(format!("64'd{count}"))), - }, - nonblocking: false, - }); + }); + } else { + body.push(Stmt::Loop { + kind: LoopKind::DoWhile, + init: Vec::new(), + condition: Some(Expr::Binary { + left: Box::new(Expr::Ident(draw.clone())), + op: BinaryOp::Lt, + right: Box::new(Expr::Literal(format!("64'd{threshold}"))), + }), + step: Vec::new(), + body: vec![Stmt::Assign { + lhs: LValue::Ident(draw.clone()), + rhs: random(), + nonblocking: false, + }], + }); + body.push(Stmt::Assign { + lhs: LValue::Ident(draw.clone()), + rhs: Expr::Binary { + left: Box::new(Expr::Ident(draw.clone())), + op: BinaryOp::Mod, + right: Box::new(Expr::Literal(format!("64'd{count}"))), + }, + nonblocking: false, + }); + } let literal = |value| { Expr::Literal(format_typed_parameter_literal( value, diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index f8f63e9284b..e496c9871eb 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -793,6 +793,11 @@ pub enum ObjectOp { ClassOf, /// Advance the object's independent RNG, returning 64 random bits. Random, + /// Draw a domain index without replacement for the property at `offset`. + RandomCyclic { + offset: u32, + count: u16, + }, /// Seed the object's RNG from the second argument. Seed, /// Validate a receiver; a nonzero class also rejects unsupported dynamic @@ -811,7 +816,7 @@ impl ObjectOp { /// The width and signedness of the result. pub fn result_type(&self) -> (usize, bool) { match self { - Self::Random => (64, false), + Self::Random | Self::RandomCyclic { .. } => (64, false), Self::Seed | Self::Check(_) | Self::ModeSet(_) @@ -834,6 +839,7 @@ impl fmt::Display for ObjectOp { Self::Store(_) => "property write", Self::ClassOf => "class query", Self::Random => "object random bits", + Self::RandomCyclic { .. } => "object random cyclic index", Self::Seed => "object random seed", Self::Check(_) => "object receiver check", Self::ModeGet(..) => "random mode query", diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index bc7669ccad1..c3c271322e4 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -6592,7 +6592,7 @@ fn class_randomize_rejects_unsupported_semantics() { "c.randomize()", "constraints", ), - ("randc bit [1:0] x;", "c.randomize()", "randc"), + ("randc bit [8:0] x;", "c.randomize()", "randc"), ("rand int x;", "c.srandom()", "argument"), ("rand int x;", "c.srandom(1, 2)", "arguments"), ( @@ -6799,3 +6799,26 @@ endmodule assert_eq!(ir.modules()[0].parameters()[0].resolved_value(), None); } } + +#[test] +fn class_randc_checks_domain_limits() { + let values = (0..257) + .map(|i| format!("V{i}={i}")) + .collect::>() + .join(","); + for (declarations, members) in [ + (String::new(), "randc bit [8:0] x;"), + ( + format!("typedef enum bit [15:0] {{{values}}} E;"), + "randc E x;", + ), + ] { + for call in ["c.randomize()", "c.randomize(x)"] { + let source = format!( + "module Top; {declarations} class C; {members} endclass C c; initial begin c=new; void'({call}); end endmodule" + ); + let error = analyze_source(&source, Path::new("randc_limits.sv")).unwrap_err(); + assert!(error.to_string().contains("randc"), "{error}"); + } + } +} diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 94290b6f9ef..574be054d9b 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -725,6 +725,14 @@ without the enum domain, and draws undeclared values (`sv_verilator_scope_enum_r IEEE 1800-2023 18.3 and 18.12 require the declared enum domain. The shared assertions remain unchanged, including the direct-enum case without an alias. +Cyclic randomization (IEEE 1800-2023 18.4.2) retains narrow external +exclusions: Icarus 13.0 cannot elaborate the three `randomization_cyclic_*` +cases ([diagnostics](verification/repros/sv_randc_icarus.json)). Verilator +5.052 passes the integer and direct-enum domain case, but emits duplicate +`srandom` declarations for the inheritance/control case and draws undeclared +values for an enum typedef alias ([evidence](verification/repros/sv_randc_verilator.json)). +The original cycle, mode and domain assertions remain unchanged. + ## SystemVerilog packed unions The `unions` shared group covers hard and soft packed untagged unions. With diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index 06c4057355b..15ee5508f33 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -1067,3 +1067,147 @@ module Top(output bit done, output int errors); endmodule "#) (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_cyclic_domains + (source "randc_domains.sv" #" +module Top(output bit done, output int errors); + typedef enum bit signed [63:0] {NEG=-7, MID=2, HIGH=91} E; + typedef enum bit [63:0] {ONLY='1} Single; + class C; + randc bit [7:0] byte_value; + randc bit signed [1:0] signed_value; + randc E value; + randc Single single_value; + rand bit [7:0] ordinary; + endclass + C c; + bit [255:0] seen; + bit [3:0] signed_seen; + bit [2:0] enum_seen; + int index; + initial begin + c = new; + repeat (3) begin + seen = 0; + repeat (256) begin + if (!c.randomize(byte_value, single_value, ordinary)) errors++; + if (seen[c.byte_value]) errors++; + seen[c.byte_value] = 1; + if (c.single_value != 64'hffffffffffffffff) errors++; + end + if (seen != '1) errors++; + end + repeat (8) begin + signed_seen = 0; + repeat (4) begin + if (!c.randomize(signed_value)) errors++; + if (c.signed_value < -2 || c.signed_value > 1) errors++; + index = c.signed_value + 2; + if (signed_seen[index]) errors++; + signed_seen[index] = 1; + end + if (signed_seen != 15) errors++; + enum_seen = 0; + repeat (3) begin + if (!c.randomize(value)) errors++; + case (c.value) + NEG: index=0; + MID: index=1; + HIGH: index=2; + default: begin errors++; index=0; end + endcase + if (enum_seen[index]) errors++; + enum_seen[index] = 1; + end + if (enum_seen != 7) errors++; + end + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_cyclic_controls + (source "randc_controls.sv" #" +module Top(output bit done, output int errors); + class Base; + randc bit [2:0] x; + int calls; + function void post_randomize(); calls++; endfunction + endclass + class Derived extends Base; + randc bit [1:0] y; + endclass + Derived a, alias_a, b; + Base base_a; + bit [7:0] seen; + bit [3:0] seen_y; + bit [2:0] saved_x; + bit [1:0] saved_y; + initial begin + a = new; b = new; alias_a = a; base_a = a; + a.srandom(27); b.srandom(27); + if (!a.x.rand_mode() || !a.y.rand_mode()) errors++; + repeat (8) begin + if (!base_a.randomize() || !b.randomize()) errors++; + if (a.x != b.x || a.y != b.y) errors++; + if (seen[a.x]) errors++; + seen[a.x] = 1; + end + if (seen != 255) errors++; + seen = 0; seen_y = 0; + repeat (8) begin + if (!a.randomize(x)) errors++; + if (seen[a.x]) errors++; + seen[a.x] = 1; + saved_x = a.x; saved_y = a.y; + alias_a.rand_mode(0); + repeat (2) if (!a.randomize()) errors++; + if (!a.randomize(null)) errors++; + if (a.x != saved_x || a.y != saved_y) errors++; + if (!a.randomize(y)) errors++; + if (seen_y[a.y]) errors++; + seen_y[a.y] = 1; + if (a.x.rand_mode() || a.y.rand_mode()) errors++; + if (seen_y == 15) seen_y = 0; + alias_a.rand_mode(1); + end + if (seen != 255 || seen_y != 0) errors++; + if (a.calls != 48) errors++; + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) + +(case randomization_cyclic_enum_alias + (source "randc_enum_alias.sv" #" +module Top(output bit done, output int errors); + typedef enum bit signed [63:0] {NEG=-7, MID=2, HIGH=91} E; + typedef E Alias; + class C; randc Alias value; endclass + C c; + bit [2:0] seen; + int index; + initial begin + c = new; + repeat (8) begin + seen = 0; + repeat (3) begin + if (!c.randomize()) errors++; + case (c.value) + NEG: index=0; + MID: index=1; + HIGH: index=2; + default: begin errors++; index=0; end + endcase + if (seen[index]) errors++; + seen[index] = 1; + end + if (seen != 7) errors++; + end + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq errors 0)) diff --git a/crates/celox-test-suite/verification/repros/sv_randc_icarus.json b/crates/celox-test-suite/verification/repros/sv_randc_icarus.json new file mode 100644 index 00000000000..2a1d280dd49 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_randc_icarus.json @@ -0,0 +1,44 @@ +{ + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "exclude_stronger_than_sv": false, + "include_ignored": false, + "cases": [ + { + "category": "Types", + "detail": "Icarus build exit status: 31; see /build.log\n/source_0.sv:19: error: Can't find task srandom in class Derived\n/source_0.sv:19: error: Enable of unknown task ``a.srandom''.\n/source_0.sv:19: error: Can't find task srandom in class Derived\n/source_0.sv:19: error: Enable of unknown task ``b.srandom''.\n/source_0.sv:20: sorry: Method name nesting is not supported yet.\n/source_0.sv:20: : method path: x.rand_mode\n/source_0.sv:20: error: Object celox_suite_tb.dut.a has no method \"x.rand_mode(...)\".\n/source_0.sv:20: sorry: Method name nesting is not supported yet.\n/source_0.sv:20: : method path: y.rand_mode\n/source_0.sv:20: error: Object celox_suite_tb.dut.a has no method \"y.rand_mode(...)\".\n/source_0.sv:20: error: Unable to elaborate condition expression.\n/source_0.sv:22: Error: randomize is not a method of class Base.\n/source_0.sv:22: error: Object celox_suite_tb.dut.base_a has no method \"randomize(...)\".\n/source_0.sv:22: Error: randomize is not a method of class Derived.\n/source_0.sv:22: error: Object celox_suite_tb.dut.b has no method \"randomize(...)\".\n/source_0.sv:22: error: Unable to elaborate condition expression.\n/source_0.sv:30: Error: randomize is not a method of class Derived.\n/source_0.sv:30: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:30: error: Unable to elaborate condition expression.\n/source_0.sv:34: error: Can't find task rand_mode in class Derived\n/source_0.sv:34: error: Enable of unknown task ``alias_a.rand_mode''.\n/source_0.sv:35: Error: randomize is not a method of class Derived.\n/source_0.sv:35: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:35: error: Unable to elaborate condition expression.\n/source_0.sv:36: Error: randomize is not a method of class Derived.\n/source_0.sv:36: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:36: error: Unable to elaborate condition expression.\n/source_0.sv:38: Error: randomize is not a method of class Derived.\n/source_0.sv:38: error: Object celox_suite_tb.dut.a has no method \"randomize(...)\".\n/source_0.sv:38: error: Unable to elaborate condition expression.\n/source_0.sv:41: sorry: Method name nesting is not supported yet.\n/source_0.sv:41: : method path: x.rand_mode\n/source_0.sv:41: error: Object celox_suite_tb.dut.a has no method \"x.rand_mode(...)\".\n/source_0.sv:41: sorry: Method name nesting is not supported yet.\n/source_0.sv:41: : method path: y.rand_mode\n/source_0.sv:41: error: Object celox_suite_tb.dut.a has no method \"y.rand_mode(...)\".\n/source_0.sv:41: error: Unable to elaborate condition expression.\n/source_0.sv:43: error: Can't find task rand_mode in class Derived\n/source_0.sv:43: error: Enable of unknown task ``alias_a.rand_mode''.\n31 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_cyclic_controls", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 9; see /build.log\n/source_0.sv:22: Error: randomize is not a method of class C.\n/source_0.sv:22: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:22: error: Unable to elaborate condition expression.\n/source_0.sv:32: Error: randomize is not a method of class C.\n/source_0.sv:32: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:32: error: Unable to elaborate condition expression.\n/source_0.sv:41: Error: randomize is not a method of class C.\n/source_0.sv:41: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:41: error: Unable to elaborate condition expression.\n9 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_cyclic_domains", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 3; see /build.log\n/source_0.sv:14: Error: randomize is not a method of class C.\n/source_0.sv:14: error: Object celox_suite_tb.dut.c has no method \"randomize(...)\".\n/source_0.sv:14: error: Unable to elaborate condition expression.\n3 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "class::randomization_cyclic_enum_alias", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/repros/sv_randc_verilator.json b/crates/celox-test-suite/verification/repros/sv_randc_verilator.json new file mode 100644 index 00000000000..797443f1b7a --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_randc_verilator.json @@ -0,0 +1,33 @@ +{ + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "verilator", + "version": "Verilator 5.052 2026-09-05 rev v5.052", + "exclude_stronger_than_sv": false, + "include_ignored": false, + "cases": [ + { + "category": "Types", + "detail": "Verilator build exit status: 1; see /build.log\n%Warning-WIDTHTRUNC: /source_0.sv:20:13: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'rand_mode' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 20 | if (!a.x.rand_mode() || !a.y.rand_mode()) errors++;\n | ^\n ... For warning description see https://verilator.org/warn/WIDTHTRUNC?v=5.052\n ... Use \"/* verilator lint_off WIDTHTRUNC */\" and lint_on around source to disable this message.\n%Warning-WIDTHTRUNC: /source_0.sv:20:33: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'rand_mode' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 20 | if (!a.x.rand_mode() || !a.y.rand_mode()) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:22:17: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'randomize' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 22 | if (!base_a.randomize() || !b.randomize()) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:22:40: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'randomize' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 22 | if (!base_a.randomize() || !b.randomize()) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:30:17: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'randomize' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 30 | if (!a.randomize(x)) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:35:28: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'randomize' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 35 | repeat (2) if (!a.randomize()) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:36:17: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'randomize' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 36 | if (!a.randomize(null)) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:38:17: Logical operator LOGNOT expects 1 bit on the LHS, but LHS's METHODCALL 'randomize' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 38 | if (!a.randomize(y)) errors++;\n | ^\n%Warning-WIDTHTRUNC: /source_0.sv:41:33: Logical operator LOGOR expects 1 bit on the LHS, but LHS's METHODCALL 'rand_mode' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 41 | if (a.x.rand_mode() || a.y.rand_mode()) errors++;\n | ^~\n%Warning-WIDTHTRUNC: /source_0.sv:41:33: Logical operator LOGOR expects 1 bit on the RHS, but RHS's METHODCALL 'rand_mode' generates 32 bits.\n : ... note: In instance 'celox_suite_tb.dut'\n 41 | if (a.x.rand_mode() || a.y.rand_mode()) errors++;\n | ^~\n%Error: /source_0.sv:3:5: Duplicate declaration of member name: 'srandom'\n : ... note: In instance 'celox_suite_tb.dut'\n 3 | class Base;\n | ^~~~~\n ... See the manual at https://verilator.org/verilator_doc.html?v=5.052 for more assistance.\n%Error: /source_0.sv:3:5: Duplicate declaration of function: 'srandom'\n : ... note: In instance 'celox_suite_tb.dut'\n 3 | class Base;\n | ^~~~~\n /source_0.sv:3:5: ... Location of original declaration\n 3 | class Base;\n | ^~~~~\n%Error: Exiting due to 2 error(s)\n", + "expectation": "Simulation", + "name": "class::randomization_cyclic_controls", + "phase": "compile", + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "class::randomization_cyclic_enum_alias at 1213:46: assert_eq errors: expected 0x0, got 0x20", + "expectation": "Simulation", + "name": "class::randomization_cyclic_enum_alias", + "phase": "execute", + "status": "mismatch", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 96bafddf611..1cde7a83605 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -608,6 +608,75 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 cannot elaborate class randomize, srandom and rand_mode calls in the randc cases. IEEE 1800-2023 18.4.2, 18.6 and 18.8 define these operations. The unchanged assertions cover full cycles, signed and enum domains, modes and inheritance.", + "expectation": "Simulation", + "name": "class::randomization_cyclic_controls", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_icarus_randc", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 cannot elaborate class randomize, srandom and rand_mode calls in the randc cases. IEEE 1800-2023 18.4.2, 18.6 and 18.8 define these operations. The unchanged assertions cover full cycles, signed and enum domains, modes and inheritance.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } + }, + { + "category": "Types", + "detail": "Icarus 13.0 cannot elaborate class randomize, srandom and rand_mode calls in the randc cases. IEEE 1800-2023 18.4.2, 18.6 and 18.8 define these operations. The unchanged assertions cover full cycles, signed and enum domains, modes and inheritance.", + "expectation": "Simulation", + "name": "class::randomization_cyclic_domains", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_icarus_randc", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 cannot elaborate class randomize, srandom and rand_mode calls in the randc cases. IEEE 1800-2023 18.4.2, 18.6 and 18.8 define these operations. The unchanged assertions cover full cycles, signed and enum domains, modes and inheritance.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } + }, + { + "category": "Types", + "detail": "Icarus 13.0 cannot elaborate class randomize, srandom and rand_mode calls in the randc cases. IEEE 1800-2023 18.4.2, 18.6 and 18.8 define these operations. The unchanged assertions cover full cycles, signed and enum domains, modes and inheritance.", + "expectation": "Simulation", + "name": "class::randomization_cyclic_enum_alias", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_icarus_randc", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 cannot elaborate class randomize, srandom and rand_mode calls in the randc cases. IEEE 1800-2023 18.4.2, 18.6 and 18.8 define these operations. The unchanged assertions cover full cycles, signed and enum domains, modes and inheritance.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index fe1ffd7e92f..e90cd817cd0 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2386,5 +2386,58 @@ "program::programs_reject_instances" ] } + }, + { + "id": "sv_icarus_randc", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 cannot elaborate class randomize, srandom and rand_mode calls in the randc cases. IEEE 1800-2023 18.4.2, 18.6 and 18.8 define these operations. The unchanged assertions cover full cycles, signed and enum domains, modes and inheritance.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::randomization_cyclic_controls", + "class::randomization_cyclic_domains", + "class::randomization_cyclic_enum_alias" + ] + } + }, + { + "id": "sv_verilator_randc_inheritance", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 emits duplicate srandom declarations for the inherited randc control case using both base and derived handles. The shared assertions retain cyclic state and random-mode coverage under IEEE 1800-2023 18.4.2, 18.6.2 and 18.8.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::randomization_cyclic_controls" + ] + } + }, + { + "id": "sv_verilator_randc_enum_alias", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 treats the randc enum typedef alias as its underlying integer. Generated __VBasicRand assigns the cyclic integer draw directly without an enum value table, producing undeclared values. IEEE 1800-2023 18.3 and 18.4.2 require a permutation of declared values. The direct enum and integer cycle case passes unchanged.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "class::randomization_cyclic_enum_alias" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index 67802610550..0afd033620e 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -303,6 +303,52 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Types", + "detail": "Verilator 5.052 emits duplicate srandom declarations for the inherited randc control case using both base and derived handles. The shared assertions retain cyclic state and random-mode coverage under IEEE 1800-2023 18.4.2, 18.6.2 and 18.8.", + "expectation": "Simulation", + "name": "class::randomization_cyclic_controls", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_verilator_randc_inheritance", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 emits duplicate srandom declarations for the inherited randc control case using both base and derived handles. The shared assertions retain cyclic state and random-mode coverage under IEEE 1800-2023 18.4.2, 18.6.2 and 18.8.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } + }, + { + "category": "Types", + "detail": "Verilator 5.052 treats the randc enum typedef alias as its underlying integer. Generated __VBasicRand assigns the cyclic integer draw directly without an enum value table, producing undeclared values. IEEE 1800-2023 18.3 and 18.4.2 require a permutation of declared values. The direct enum and integer cycle case passes unchanged.", + "expectation": "Simulation", + "name": "class::randomization_cyclic_enum_alias", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "known_issue": { + "id": "sv_verilator_randc_enum_alias", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 treats the randc enum typedef alias as its underlying integer. Generated __VBasicRand assigns the cyclic integer draw directly without an enum value table, producing undeclared values. IEEE 1800-2023 18.3 and 18.4.2 require a permutation of declared values. The direct enum and integer cycle case passes unchanged.", + "upstream": [], + "evidence": [ + "verification/repros/sv_randc_verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ] + } } ] } diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index b2c81061d78..de50527500c 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -388,3 +388,37 @@ sv_backends! { sv_backends! { fn class_randomization_enum_fill_literals(sim) { @case "class::randomization_enum_fill_literals"; } } + +sv_backends! { + fn class_randomization_cyclic_enum_alias(sim) { @case "class::randomization_cyclic_enum_alias"; } + fn class_randomization_cyclic_domains(sim) { @case "class::randomization_cyclic_domains"; } + fn class_randomization_cyclic_controls(sim) { @case "class::randomization_cyclic_controls"; } + fn class_randomization_cyclic_checkpoint(sim) { + @setup { let source = r#" + module Top(output bit [63:0] value); + timeunit 1ps / 1ps; + class C; randc bit [2:0] x; endclass + C c; + initial begin + c = new; + c.srandom(41); + void'(c.randomize()); + #10; + repeat (16) begin + void'(c.randomize()); + value = (value << 3) | c.x; + end + end + endmodule + "#; } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("cyclic_checkpoint.sv"))], "Top").four_state(true); + sim.run_until(5).unwrap(); + let saved = sim.checkpoint().unwrap(); + let value = sim.signal("value"); + sim.run_until(15).unwrap(); + let expected = sim.get_four_state(value); + sim.restore(&saved).unwrap(); + sim.run_until(15).unwrap(); + assert_eq!(sim.get_four_state(value), expected); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index aa944c98e4d..cee9451f494 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -145,7 +145,13 @@ not supported even for this checker form. Each object has an independent random stream, seeded from its creating process. `object.srandom(seed)` resets it using a 32-bit seed; checkpoints preserve both RNG and mode state (18.13.3, 18.14.3). Random sequences are implementation-specific. -`randc` randomization, constraints, `with`, static random properties, and random +`randc` supports 1–8-bit two-state integers and scalar enums with up to 256 +members. Each property visits every value once before starting another cycle +(18.4.2), including inherited properties and explicit member selection. +Disabled properties retain their cycle; checkpoints restore it. `srandom` +reseeds the RNG without making already consumed values eligible again. + +Constraints, `with`, larger `randc` domains, static random properties, and random array/object/string properties remain unsupported. A constrained dynamic subclass is rejected rather than silently randomizing only its base properties. A call through `null` is a runtime error. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 22c756c2ce5..2ac2f662659 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -127,7 +127,12 @@ enumは宣言された値だけから均等に抽選し、飛び飛びの値や オブジェクトごとに独立した乱数列を持ち、生成元のプロセスから初期シードを取得します。 `object.srandom(seed)` で32ビットのシードを設定でき、チェックポイントは乱数状態とモードを保持します (18.13.3、18.14.3)。具体的な乱数列は処理系に依存します。 -`randc` の乱数化、制約、`with`、staticな乱数プロパティ、配列・オブジェクト・文字列の +`randc` は1〜8ビットの2値整数と、宣言値が256個以下のスカラーenumに対応します。 +各プロパティは全値を重複なく一巡してから次の循環に進みます(18.4.2)。継承、 +`rand_mode`、引数による対象選択とチェックポイント復元にも対応します。無効化中は +循環を進めず、`srandom` は消費済みの値を保持したまま乱数生成器を再シードします。 + +制約、`with`、上記の上限を超える `randc`、staticな乱数プロパティ、配列・オブジェクト・文字列の 乱数化は未対応です。実際の子クラスに制約がある場合は、親のプロパティだけを乱数化せず拒否します。 `null` を通した呼び出しは実行時エラーです。