From e22192916045f29cc52520161d180b02ff3ddb4d Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 12:38:43 +0900 Subject: [PATCH] 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() + ); + } +}