From aa2e4aa5278190c32042247e9cf859b3d1ad6c0a Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 31 Oct 2026 02:58:31 +0900 Subject: [PATCH 1/2] refactor(sv): pass constant functions explicitly instead of installing them The constant functions visible in a scope were installed into the shared analysis state behind a RefCell, swapped by guards and tracked by a revision, and the evaluator kept its call depth and the fuel and two-state mode of runtime evaluation in Cells of the same state. The functions are now a value of the analysis context, which entering a module, a generate block or an interface scope derives with the functions it sees, and the constant evaluator takes them as an argument. The depth, fuel and mode are a budget each evaluation owns and lends to its frames, and a call's frame sees the constants of its caller's scope rather than the caller's frame. Code that evaluates constants of an analyzed module takes a context with the module's functions. Change-Id: Icbacebc1ba8721afe2ea0352b393fe06ff625091 --- crates/celox-sv-analyzer/src/analyze.rs | 19 +- crates/celox-sv-analyzer/src/ast.rs | 160 ++++--- .../src/ast/array_compatibility.rs | 18 +- .../src/ast/array_parameters.rs | 2 +- .../src/ast/array_reductions.rs | 4 +- .../src/ast/assignment_analysis.rs | 47 ++- .../src/ast/bound_patterns.rs | 43 +- .../src/ast/bound_patterns/binding.rs | 4 +- .../src/ast/bound_patterns/ports.rs | 16 +- crates/celox-sv-analyzer/src/ast/case.rs | 47 ++- crates/celox-sv-analyzer/src/ast/casts.rs | 15 +- crates/celox-sv-analyzer/src/ast/classes.rs | 17 +- .../src/ast/classes/foreign.rs | 1 + .../src/ast/classes/specializations.rs | 12 +- .../celox-sv-analyzer/src/ast/comb_process.rs | 12 +- .../celox-sv-analyzer/src/ast/comb_rewrite.rs | 45 +- .../src/ast/const_functions.rs | 392 +++++++++--------- .../src/ast/const_functions/runtime.rs | 84 ++-- .../src/ast/const_functions/tests.rs | 116 ++++-- .../src/ast/constant_binding.rs | 35 +- .../src/ast/constant_folding.rs | 85 ++-- .../src/ast/constant_folding/tests.rs | 21 +- crates/celox-sv-analyzer/src/ast/constants.rs | 162 ++++---- .../src/ast/constants/tests.rs | 10 +- .../celox-sv-analyzer/src/ast/containers.rs | 19 +- .../celox-sv-analyzer/src/ast/declarations.rs | 4 +- .../celox-sv-analyzer/src/ast/dimensions.rs | 16 +- .../src/ast/dimensions/discovery.rs | 35 +- .../src/ast/dimensions/queries.rs | 8 +- .../src/ast/dimensions/query_binding.rs | 32 +- .../src/ast/dimensions/tests.rs | 20 +- .../src/ast/expression_binding.rs | 8 +- .../src/ast/expression_binding/direct.rs | 123 +++--- .../src/ast/expression_binding/enums.rs | 8 +- .../src/ast/expression_binding/objects.rs | 2 +- .../src/ast/expression_binding/references.rs | 12 +- .../src/ast/expression_binding/selected.rs | 4 +- .../src/ast/expression_binding/streams.rs | 28 +- .../celox-sv-analyzer/src/ast/expressions.rs | 47 ++- .../celox-sv-analyzer/src/ast/ff_process.rs | 9 +- crates/celox-sv-analyzer/src/ast/functions.rs | 12 +- .../src/ast/functions/symbolic.rs | 3 +- crates/celox-sv-analyzer/src/ast/generate.rs | 139 ++++--- .../src/ast/generate/elaboration.rs | 39 +- .../src/ast/generate/memo.rs | 15 +- .../src/ast/generate/memo/sites.rs | 1 - crates/celox-sv-analyzer/src/ast/instances.rs | 31 +- .../src/ast/interface_ast.rs | 4 +- .../src/ast/interface_binding.rs | 57 +-- crates/celox-sv-analyzer/src/ast/lifetimes.rs | 85 ++-- .../src/ast/lifetimes/bit_result.rs | 24 +- crates/celox-sv-analyzer/src/ast/locators.rs | 17 +- crates/celox-sv-analyzer/src/ast/mailboxes.rs | 10 +- crates/celox-sv-analyzer/src/ast/packages.rs | 1 + .../src/ast/packed_structs/layout.rs | 17 +- .../src/ast/packed_structs/selects.rs | 15 +- .../src/ast/packed_structs/tagged.rs | 10 +- .../celox-sv-analyzer/src/ast/parameters.rs | 107 ++--- .../src/ast/parameters/declaration_types.rs | 4 +- .../src/ast/parameters/skipped.rs | 42 +- .../src/ast/parameters/tests.rs | 115 ++--- crates/celox-sv-analyzer/src/ast/patterns.rs | 66 +-- .../src/ast/patterns/binding.rs | 17 +- .../celox-sv-analyzer/src/ast/procedural.rs | 84 ++-- .../src/ast/procedural/effects.rs | 2 +- .../src/ast/procedural/randomization.rs | 2 +- .../src/ast/procedural/timing.rs | 2 +- crates/celox-sv-analyzer/src/ast/selects.rs | 222 +++++----- .../src/ast/semantic_types/conversion.rs | 24 +- .../src/ast/semantic_types/tests.rs | 4 +- .../celox-sv-analyzer/src/ast/statements.rs | 38 +- .../src/ast/type_binding/aggregates.rs | 11 +- .../src/ast/type_binding/binding.rs | 24 +- .../celox-sv-analyzer/src/ast/type_names.rs | 6 +- .../src/ast/type_parameters.rs | 18 +- crates/celox-sv-analyzer/src/ast/types.rs | 20 +- .../src/ast/unpacked_structs.rs | 10 +- .../celox-sv-analyzer/src/ast/validation.rs | 12 +- .../src/ast/virtual_interfaces.rs | 19 +- crates/celox-sv-analyzer/src/ir.rs | 2 +- crates/celox-sv-analyzer/src/source_tree.rs | 5 + .../source_tree/tests/function_symbolic.rs | 3 +- crates/celox-sv-analyzer/src/tests.rs | 5 +- crates/celox-sv-analyzer/src/typecheck.rs | 126 ++++-- .../celox-sv-analyzer/src/typecheck/real.rs | 36 +- 85 files changed, 1696 insertions(+), 1552 deletions(-) diff --git a/crates/celox-sv-analyzer/src/analyze.rs b/crates/celox-sv-analyzer/src/analyze.rs index e6b567e0dcf..2d24f7b20fd 100644 --- a/crates/celox-sv-analyzer/src/analyze.rs +++ b/crates/celox-sv-analyzer/src/analyze.rs @@ -16,7 +16,8 @@ fn analyze_source_impl(source: ast::Source) -> Result { let mut module_table = ModuleTable::default(); let mut modules = Vec::new(); for module in source.modules() { - let state = module.constant_function_state(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = &module.constant_context(&syntax); let id = module_table.insert(module)?; let mut constants = HashMap::default(); let mut parameter_types = HashMap::default(); @@ -42,7 +43,7 @@ fn analyze_source_impl(source: ast::Source) -> Result { } let value: Option = parameter.value().cloned().map(Into::into); let (resolved_value, literal) = parameter.resolved_value_and_literal( - &state, + tree, &constants, ¶meter_types, ¶meter_literals, @@ -79,7 +80,7 @@ fn analyze_source_impl(source: ast::Source) -> Result { .with_declaration( parameter.value().map(|value| { module - .declaration_expr(&state, value, ¶meter_signedness) + .declaration_expr(tree, value, ¶meter_signedness) .into() }), parameter @@ -88,10 +89,10 @@ fn analyze_source_impl(source: ast::Source) -> Result { .map(|range| { ir::PackedRange::new( module - .declaration_expr(&state, range.left(), ¶meter_signedness) + .declaration_expr(tree, range.left(), ¶meter_signedness) .into(), module - .declaration_expr(&state, range.right(), ¶meter_signedness) + .declaration_expr(tree, range.right(), ¶meter_signedness) .into(), ) }) @@ -116,7 +117,7 @@ fn analyze_source_impl(source: ast::Source) -> Result { port.r#type().clone(), &ast::const_functions::Environment { constants: &constants, - functions: &state.const_functions, + functions: &tree.functions, }, ), port.is_net(), @@ -126,7 +127,7 @@ fn analyze_source_impl(source: ast::Source) -> Result { .with_pattern_target(port.r#type().pattern_target( &ast::const_functions::Environment { constants: &constants, - functions: &state.const_functions, + functions: &tree.functions, }, )), ); @@ -162,7 +163,7 @@ fn analyze_source_impl(source: ast::Source) -> Result { ty, &ast::const_functions::Environment { constants: &constants, - functions: &state.const_functions, + functions: &tree.functions, }, ), port.is_net(), @@ -182,7 +183,7 @@ fn analyze_source_impl(source: ast::Source) -> Result { signal.r#type().clone(), &ast::const_functions::Environment { constants: &constants, - functions: &state.const_functions, + functions: &tree.functions, }, ), signal.is_net(), diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 2e539e6c113..05bef7d6f91 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -20,7 +20,6 @@ use crate::source_tree::SourceTree as SyntaxTree; /// State owned by one analysis session, shared explicitly with nested scopes. #[derive(Default)] pub(super) struct AnalysisState { - pub(crate) const_functions: const_functions::State, foreign: std::rc::Rc, foreign_arguments: RefCell>, foreign_names: RefCell>, @@ -75,7 +74,7 @@ pub(super) struct AnalysisState { /// Syntax and specialization bindings for one scope within an analysis session. /// Child modules share the session and receive their own parameter bindings. #[derive(Clone)] -struct AnalysisContext<'a> { +pub(crate) struct AnalysisContext<'a> { syntax_tree: &'a SyntaxTree, state: std::rc::Rc, parameter_overrides: Cow<'a, HashMap>, @@ -83,6 +82,9 @@ struct AnalysisContext<'a> { imported: Arc, /// The package being analyzed, inside which `p::x` names its own item. package: Option>, + /// The constant functions that calls in constant expressions of the + /// scope call (IEEE 1800-2023 13.4.3). + pub(crate) functions: const_functions::ConstantFunctions, } impl<'a> AnalysisContext<'a> { @@ -97,16 +99,18 @@ impl<'a> AnalysisContext<'a> { parameter_overrides: Cow::Borrowed(parameter_overrides), imported: Arc::default(), package: None, + functions: const_functions::ConstantFunctions::default(), } } - fn unspecialized(syntax_tree: &'a SyntaxTree) -> Self { + pub(crate) fn unspecialized(syntax_tree: &'a SyntaxTree) -> Self { Self { syntax_tree, state: std::rc::Rc::default(), parameter_overrides: Cow::Owned(HashMap::default()), imported: Arc::default(), package: None, + functions: const_functions::ConstantFunctions::default(), } } @@ -123,6 +127,7 @@ impl<'a> AnalysisContext<'a> { parameter_overrides: Cow::Owned(HashMap::default()), imported: Arc::default(), package: None, + functions: const_functions::ConstantFunctions::default(), } } @@ -137,6 +142,7 @@ impl<'a> AnalysisContext<'a> { parameter_overrides: Cow::Borrowed(parameter_overrides), imported: self.imported.clone(), package: self.package.clone(), + functions: self.functions.clone(), } } @@ -148,6 +154,14 @@ impl<'a> AnalysisContext<'a> { } } + /// This context with `functions` as its constant functions. + fn with_functions(&self, functions: const_functions::ConstantFunctions) -> Self { + Self { + functions, + ..self.clone() + } + } + /// This context analyzing package `name`, inside which `name::x` names /// its own item `x`. fn in_package(&self, name: &str) -> Self { @@ -679,7 +693,7 @@ pub struct Module { impl Module { pub(crate) fn declaration_expr( &self, - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: &ConstExpr, signedness: &HashMap, ) -> ConstExpr { @@ -690,7 +704,7 @@ impl Module { 0, true, ); - expr_to_index_const(state, expanded, &PackedDimensions::default()) + expr_to_index_const(tree, expanded, &PackedDimensions::default()) .unwrap_or_else(|| expr.clone()) } @@ -698,12 +712,11 @@ impl Module { &self.declaration_subroutines } - /// Make the module's constant functions available to the constant - /// evaluator until the guard is dropped. - pub(crate) fn constant_function_state(&self) -> AnalysisState { - let state = AnalysisState::default(); - const_functions::replace(&state.const_functions, self.constant_functions.clone()); - state + /// A context that calls the module's constant functions, for constant + /// expressions of the analyzed module, which no longer read its syntax: + /// `syntax` is an empty tree. + pub(crate) fn constant_context<'a>(&self, syntax: &'a SyntaxTree) -> AnalysisContext<'a> { + AnalysisContext::unspecialized(syntax).with_functions(self.constant_functions.clone()) } /// Analyze a module or a package. The scope starts from the `imported` @@ -831,15 +844,14 @@ impl Module { let mut type_aliases = type_aliases_from_scope(syntax_tree)?; // Constant functions see the module constants known so far; they are // collected again once the parameters are known. - let _constant_functions = const_functions::install( - &syntax_tree.state, - with_imported(const_functions::module_constant_functions( + let preliminary = + syntax_tree.with_functions(with_imported(const_functions::module_constant_functions( syntax_tree, &imported.const_env, &type_aliases, &imported.parameter_values, - )), - ); + ))); + let syntax_tree = &preliminary; let mut parameters = parameters_from_scope( syntax_tree, &type_aliases, @@ -860,7 +872,7 @@ impl Module { apply_parameter_overrides(&mut parameters, parameter_overrides)?; } let mut const_env = imported.const_env.clone(); - const_env.extend(const_env_from_parameters(&syntax_tree.state, ¶meters)); + const_env.extend(const_env_from_parameters(syntax_tree, ¶meters)); type_aliases = type_aliases_from_scope_with_env(syntax_tree, &const_env)?; let mut enum_constants = enum_member_constants_from_scope( syntax_tree, @@ -903,7 +915,7 @@ impl Module { if name == override_module_name { apply_parameter_overrides(&mut parameters, parameter_overrides)?; } - extend_const_env_with_parameters(&syntax_tree.state, &mut const_env, ¶meters); + extend_const_env_with_parameters(syntax_tree, &mut const_env, ¶meters); type_aliases = type_aliases_from_scope_with_env(syntax_tree, &const_env)?; // Contract dependency analysis must see module parameter references // before the normal procedural lowering substitutes default literals. @@ -922,21 +934,15 @@ impl Module { &symbolic_parameters, )) .declarations(); - const_functions::replace( - &syntax_tree.state.const_functions, - with_imported(const_functions::module_constant_functions( + let parameterized = + syntax_tree.with_functions(with_imported(const_functions::module_constant_functions( syntax_tree, &const_env, &type_aliases, - ¶meter_value_env_with_imported( - &syntax_tree.state, - ¶meters, - &const_env, - &imported, - ), - )), - ); - extend_const_env_with_parameters(&syntax_tree.state, &mut const_env, ¶meters); + ¶meter_value_env_with_imported(syntax_tree, ¶meters, &const_env, &imported), + ))); + let syntax_tree = ¶meterized; + extend_const_env_with_parameters(syntax_tree, &mut const_env, ¶meters); let mut array_parameters = array_parameters::array_parameters_from_scope(syntax_tree, &const_env, &type_aliases)?; @@ -953,12 +959,7 @@ impl Module { &const_env, &type_aliases, ¶meter_packed_dimensions_with_imported(¶meters, &imported).into(), - ¶meter_value_env_with_imported( - &syntax_tree.state, - ¶meters, - &const_env, - &imported, - ), + ¶meter_value_env_with_imported(syntax_tree, ¶meters, &const_env, &imported), ) { Ok(()) => {} // A parameter initializer may inspect a port or signal type @@ -973,7 +974,7 @@ impl Module { let preliminary_signals = signals_from_scope(syntax_tree, &const_env, &type_aliases)?; extend_const_env_with_variable_types( - &syntax_tree.state, + &syntax_tree.functions, &mut const_env, preliminary_ports .iter() @@ -1002,11 +1003,7 @@ impl Module { if name == override_module_name { apply_parameter_overrides(&mut parameters, parameter_overrides)?; } - extend_const_env_with_parameters( - &syntax_tree.state, - &mut const_env, - ¶meters, - ); + extend_const_env_with_parameters(syntax_tree, &mut const_env, ¶meters); type_aliases = type_aliases_from_scope_with_env(syntax_tree, &const_env)?; array_parameters = array_parameters::array_parameters_from_scope( syntax_tree, @@ -1019,7 +1016,7 @@ impl Module { &type_aliases, ¶meter_packed_dimensions_with_imported(¶meters, &imported).into(), ¶meter_value_env_with_imported( - &syntax_tree.state, + syntax_tree, ¶meters, &const_env, &imported, @@ -1066,7 +1063,7 @@ impl Module { .chain(signals.iter().map(Signal::r#type)) { validate_unpacked_dimension_sizes( - &syntax_tree.state, + &syntax_tree.functions, r#type.unpacked_ranges(), &const_env, )?; @@ -1084,13 +1081,9 @@ impl Module { packed_dimensions_from_ports_and_signals(&ports, &signals, &const_env, &type_aliases); // Four-state parameter values cannot be represented by the numeric // environment. Keep their expressions for constant case analysis. - packed_dimensions.parameter_values = parameter_value_env_with_imported( - &syntax_tree.state, - ¶meters, - &const_env, - &imported, - ) - .into(); + packed_dimensions.parameter_values = + parameter_value_env_with_imported(syntax_tree, ¶meters, &const_env, &imported) + .into(); packed_dimensions .parameter_values .retain(|name, _| !const_env.contains_key(name)); @@ -1188,7 +1181,7 @@ impl Module { let signed = shape.signed; let is_2state = shape.is_2state; let width = expr_static_width( - &syntax_tree.state, + syntax_tree, &Expr::Ident(name.to_string()), &packed_dimensions, ) @@ -1205,7 +1198,7 @@ impl Module { }; } let value = fold_const_integral_expr_preserving_mask( - &syntax_tree.state, + syntax_tree, value, &packed_dimensions.const_env, ); @@ -1226,7 +1219,7 @@ impl Module { instance .condition() .and_then(|condition| { - eval_ast_const_expr(&syntax_tree.state, condition, &const_env) + eval_ast_const_expr(&syntax_tree.functions, condition, &const_env) }) .is_none_or(|value| value != 0) }) @@ -1266,12 +1259,8 @@ impl Module { name: conflict.to_string(), }); } - let mut parameter_values = parameter_value_env_with_imported( - &syntax_tree.state, - ¶meters, - &const_env, - &imported, - ); + let mut parameter_values = + parameter_value_env_with_imported(syntax_tree, ¶meters, &const_env, &imported); parameter_values.extend(packed_pattern_values); for (name, value) in &enum_constants.exprs { parameter_values @@ -1358,7 +1347,7 @@ impl Module { connection.map_expressions(|expr| { let expr = expand_expr_calls(expr, &functions, &expression_signedness, 0, true); substitute_expr_constants_with_parameter_literals( - &syntax_tree.state, + syntax_tree, expr, &const_env, &enum_constants.exprs, @@ -1404,7 +1393,7 @@ impl Module { .into_iter() .map(|process| { substitute_process_constants_with_parameter_literals( - &syntax_tree.state, + syntax_tree, process, &const_env, ¶meter_values, @@ -1442,7 +1431,7 @@ impl Module { // of the module, initialized once with the declaration initializers. let statics: HashMap = body_state.statics.drain(..).collect(); let (mut kept, mut static_initializers) = lifetimes::keep_static_locals( - &syntax_tree.state, + syntax_tree, &statics, &subroutine_directions, comb_processes @@ -1589,7 +1578,7 @@ impl Module { enum_constants: enum_constants.clone(), functions: functions.clone(), function_return_types: (*packed_dimensions.function_return_types).clone(), - constant_functions: const_functions::installed(&syntax_tree.state.const_functions), + constant_functions: syntax_tree.functions.clone(), subroutine_params: subroutine_params.clone(), subroutine_shapes: subroutine_shapes.clone(), subroutines: subroutines.clone(), @@ -1662,12 +1651,11 @@ impl Module { let symbolic_type = subroutine .return_type .as_ref() - .is_some_and(|ty| ty.has_symbolic_ranges(&syntax_tree.state.const_functions)) - || subroutine.params.iter().any(|param| { - param - .r#type - .has_symbolic_ranges(&syntax_tree.state.const_functions) - }); + .is_some_and(|ty| ty.has_symbolic_ranges(&syntax_tree.functions)) + || subroutine + .params + .iter() + .any(|param| param.r#type.has_symbolic_ranges(&syntax_tree.functions)); if (selected_write || symbolic_type) && let Some(function) = functions.get_mut(&subroutine.name) { @@ -1712,7 +1700,7 @@ impl Module { locals, subroutines, dpi_imports, - constant_functions: const_functions::installed(&syntax_tree.state.const_functions), + constant_functions: syntax_tree.functions.clone(), symbolic_functions: functions, declaration_subroutines, imported_parameters, @@ -1850,7 +1838,7 @@ impl Parameter { pub(crate) fn resolved_value( &self, - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, constants: &HashMap, parameter_types: &HashMap, ) -> Option { @@ -1868,7 +1856,7 @@ impl Parameter { let value: crate::ir::ConstExpr = value.into(); let environment = const_functions::Environment { constants, - functions: &state.const_functions, + functions, }; let mut value = if self.has_declared_type && typecheck::const_expr_has_real_type(&value) { // An explicitly integral parameter supplies an integer assignment @@ -1889,23 +1877,29 @@ impl Parameter { /// literal after two-state conversion or dependency substitution. pub(crate) fn resolved_value_and_literal( &self, - state: &AnalysisState, + tree: &AnalysisContext<'_>, constants: &HashMap, parameter_types: &HashMap, literals: &HashMap, ) -> (Option, Option) { + let state = &*tree.state; + let functions = &tree.functions; if self.floating.is_some() { return ( None, - self.resolved_literal(state, constants, parameter_types, literals), + self.resolved_literal(tree, constants, parameter_types, literals), ); } - if let Some(value) = self.resolved_value(state, constants, parameter_types) { + if let Some(value) = self.resolved_value(&tree.functions, constants, parameter_types) { return (Some(value), None); } - let literal = self.resolved_literal(state, constants, parameter_types, literals); + let literal = self.resolved_literal(tree, constants, parameter_types, literals); let value = literal.as_ref().and_then(|literal| { - eval_ast_const_expr(state, &expr_to_const(state, literal.clone())?, constants) + eval_ast_const_expr( + functions, + &expr_to_const(state, literal.clone())?, + constants, + ) }); if value.is_some() { (value, None) @@ -1916,7 +1910,7 @@ impl Parameter { pub(crate) fn resolved_literal( &self, - state: &AnalysisState, + tree: &AnalysisContext<'_>, constants: &HashMap, parameter_types: &HashMap, literals: &HashMap, @@ -1952,13 +1946,13 @@ impl Parameter { parameter.declared_signed = Some(ty.signed); } let value = parameter_value_env( - state, + tree, std::slice::from_ref(¶meter), &evaluation_constants, ) .remove(self.name())?; let value = substitute_expr_idents(value, literals); - let value = fold_const_integral_expr_preserving_mask(state, value, &evaluation_constants); + let value = fold_const_integral_expr_preserving_mask(tree, value, &evaluation_constants); matches!(value, Expr::Literal(_)).then_some(value) } @@ -3152,12 +3146,12 @@ fn parameter_packed_dimensions_with_imported( /// The literal values of `parameters`, and of the package parameters and /// enum members a scope imports. fn parameter_value_env_with_imported( - state: &AnalysisState, + tree: &AnalysisContext<'_>, parameters: &[Parameter], const_env: &HashMap, imported: &scope::ScopeSymbols, ) -> HashMap { - let mut values = parameter_value_env(state, parameters, const_env); + let mut values = parameter_value_env(tree, parameters, const_env); let local_names: HashSet<_> = parameters.iter().map(Parameter::name).collect(); for (name, value) in &imported.parameter_values { if !local_names.contains(name.as_str()) { diff --git a/crates/celox-sv-analyzer/src/ast/array_compatibility.rs b/crates/celox-sv-analyzer/src/ast/array_compatibility.rs index c1e86b81168..0c176640c8a 100644 --- a/crates/celox-sv-analyzer/src/ast/array_compatibility.rs +++ b/crates/celox-sv-analyzer/src/ast/array_compatibility.rs @@ -50,7 +50,7 @@ fn element_identity(shape: &VariableDimensions) -> Option { /// The type of an unpacked array of `shape`, or `None` when `shape` is not an /// unpacked array or its type cannot be resolved. pub(super) fn unpacked_array_type( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, shape: &VariableDimensions, dims: &PackedDimensions, ) -> Option { @@ -58,7 +58,7 @@ pub(super) fn unpacked_array_type( return None; } let count = |width: &ConstExpr| { - eval_ast_const_expr(state, width, &dims.const_env) + eval_ast_const_expr(functions, width, &dims.const_env) .and_then(|width| usize::try_from(width).ok()) }; Some(UnpackedArrayType { @@ -101,12 +101,15 @@ fn incompatible_types( /// How fixed-size unpacked arrays of `actual` and `target` are spelled if /// the first may not be assigned to the second (see [`incompatible_types`]). pub(super) fn incompatible( - state: &AnalysisState, + tree: &AnalysisContext<'_>, actual: &VariableDimensions, target: &VariableDimensions, dims: &PackedDimensions, ) -> Option<(String, String)> { - let of_shape = |shape| semantic_types::of_shape(&state.types, state, shape, &dims.const_env); + let state = &*tree.state; + let functions = &tree.functions; + let of_shape = + |shape| semantic_types::of_shape(&state.types, functions, shape, &dims.const_env); incompatible_types(&state.types, of_shape(actual)?, of_shape(target)?) } @@ -147,7 +150,7 @@ fn native_selection( constant_binding::bind(id, tree, dims) .ok() .flatten() - .and_then(|value| eval_ast_const_expr(&tree.state, &value, &dims.const_env)) + .and_then(|value| eval_ast_const_expr(&tree.functions, &value, &dims.const_env)) }; let mut indices = 0; // A slice selects from the dimension that the indices inside it leave @@ -221,7 +224,8 @@ fn native_unpacked_type( use semantic_types::{ArrayKind, Range, TyData}; let (path, indices, slice) = native_selection(id, tree, dims)?; let table = &tree.state.types; - let mut ty = semantic_types::of_shape(table, &tree.state, dims.get(&path)?, &dims.const_env)?; + let mut ty = + semantic_types::of_shape(table, &tree.functions, dims.get(&path)?, &dims.const_env)?; for _ in 0..indices { let TyData::Array { element, .. } = table.data(ty) else { return None; @@ -297,7 +301,7 @@ fn check_assignment( } let table = &tree.state.types; let Some((actual, target)) = - semantic_types::of_shape(table, &tree.state, target, &dims.const_env) + semantic_types::of_shape(table, &tree.functions, target, &dims.const_env) .zip(native_unpacked_type(id, tree, dims)) .and_then(|(target, actual)| incompatible_types(table, actual, target)) else { diff --git a/crates/celox-sv-analyzer/src/ast/array_parameters.rs b/crates/celox-sv-analyzer/src/ast/array_parameters.rs index b0704239f47..ded8ee86e9e 100644 --- a/crates/celox-sv-analyzer/src/ast/array_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/array_parameters.rs @@ -197,7 +197,7 @@ impl ArrayParameter { let name = self.signal.name().to_string(); let shape = procedural::dimensions_from_type(self.signal.r#type()); let value = if let Some(bound) = &self.bound { - bound.lower(&tree.state, &shape, dims)? + bound.lower(tree, &shape, dims)? } else { match self.native_pattern { Some(root) => match patterns::native_expression(root, &shape, tree, dims)? { diff --git a/crates/celox-sv-analyzer/src/ast/array_reductions.rs b/crates/celox-sv-analyzer/src/ast/array_reductions.rs index 8481b2dbcad..bad87287527 100644 --- a/crates/celox-sv-analyzer/src/ast/array_reductions.rs +++ b/crates/celox-sv-analyzer/src/ast/array_reductions.rs @@ -95,7 +95,7 @@ pub(super) fn bind( .try_fold(1usize, |width, dim| { width.checked_mul( usize::try_from(eval_ast_const_expr( - &tree.state, + &tree.functions, &dim.width, &dims.const_env, )?) @@ -104,7 +104,7 @@ pub(super) fn bind( }) .ok_or_else(|| unsupported("array reduction element width"))?; let count = usize::try_from( - eval_ast_const_expr(&tree.state, &shape.unpacked[0].width, &dims.const_env) + eval_ast_const_expr(&tree.functions, &shape.unpacked[0].width, &dims.const_env) .ok_or_else(|| unsupported("array reduction length"))?, ) .map_err(|_| unsupported("array reduction length"))?; diff --git a/crates/celox-sv-analyzer/src/ast/assignment_analysis.rs b/crates/celox-sv-analyzer/src/ast/assignment_analysis.rs index 114cce60d6c..92e2911e7b9 100644 --- a/crates/celox-sv-analyzer/src/ast/assignment_analysis.rs +++ b/crates/celox-sv-analyzer/src/ast/assignment_analysis.rs @@ -3,14 +3,14 @@ use super::*; pub(super) fn two_state_conditions_are_complements( - state: &AnalysisState, + tree: &AnalysisContext<'_>, left: &Expr, right: &Expr, packed_dimensions: &PackedDimensions, ) -> bool { if let (Some((left, left_positive)), Some((right, right_positive))) = ( - normalized_two_state_boolean(state, left, packed_dimensions), - normalized_two_state_boolean(state, right, packed_dimensions), + normalized_two_state_boolean(tree, left, packed_dimensions), + normalized_two_state_boolean(tree, right, packed_dimensions), ) && left == right && left_positive != right_positive { @@ -22,7 +22,7 @@ pub(super) fn two_state_conditions_are_complements( Expr::Unary { op: UnaryOp::LogicNot, expr, - } if &**expr == other && expr_is_two_state(state, other, packed_dimensions) + } if &**expr == other && expr_is_two_state(tree, other, packed_dimensions) ) }; let are_inverse_equalities = |left: &Expr, right: &Expr| { @@ -48,8 +48,8 @@ pub(super) fn two_state_conditions_are_complements( } match (left_op, right_op) { (BinaryOp::Eq, BinaryOp::Ne) | (BinaryOp::Ne, BinaryOp::Eq) => { - expr_is_two_state(state, left_lhs, packed_dimensions) - && expr_is_two_state(state, left_rhs, packed_dimensions) + expr_is_two_state(tree, left_lhs, packed_dimensions) + && expr_is_two_state(tree, left_rhs, packed_dimensions) } (BinaryOp::EqCase, BinaryOp::NeCase) | (BinaryOp::NeCase, BinaryOp::EqCase) => true, _ => false, @@ -59,7 +59,7 @@ pub(super) fn two_state_conditions_are_complements( } fn normalized_two_state_boolean<'a>( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: &'a Expr, packed_dimensions: &PackedDimensions, ) -> Option<(&'a Expr, bool)> { @@ -68,27 +68,27 @@ fn normalized_two_state_boolean<'a>( expr: operand, width, .. - } if expr_static_width(state, operand, packed_dimensions) + } if expr_static_width(tree, operand, packed_dimensions) .is_some_and(|source| source <= *width) - && expr_is_two_state(state, operand, packed_dimensions) => + && expr_is_two_state(tree, operand, packed_dimensions) => { - return normalized_two_state_boolean(state, operand, packed_dimensions); + return normalized_two_state_boolean(tree, operand, packed_dimensions); } Expr::Unary { op: UnaryOp::ToTwoState, expr: operand, - } if expr_is_two_state(state, operand, packed_dimensions) => { - return normalized_two_state_boolean(state, operand, packed_dimensions); + } if expr_is_two_state(tree, operand, packed_dimensions) => { + return normalized_two_state_boolean(tree, operand, packed_dimensions); } _ => {} } if let Expr::Unary { op, expr } = expr && (*op == UnaryOp::LogicNot || (*op == UnaryOp::BitNot - && expr_static_width(state, expr, packed_dimensions) == Some(1) - && expr_is_two_state(state, expr, packed_dimensions))) + && expr_static_width(tree, expr, packed_dimensions) == Some(1) + && expr_is_two_state(tree, expr, packed_dimensions))) { - let (expr, positive) = normalized_two_state_boolean(state, expr, packed_dimensions)?; + let (expr, positive) = normalized_two_state_boolean(tree, expr, packed_dimensions)?; return Some((expr, !positive)); } if let Expr::Binary { left, op, right } = expr @@ -97,25 +97,28 @@ fn normalized_two_state_boolean<'a>( BinaryOp::Eq | BinaryOp::Ne | BinaryOp::EqCase | BinaryOp::NeCase ) { - let nonzero_side = if expr_is_constant_zero(state, left, &packed_dimensions.const_env) { + let nonzero_side = if expr_is_constant_zero(tree, left, &packed_dimensions.const_env) { &**right - } else if expr_is_constant_zero(state, right, &packed_dimensions.const_env) { + } else if expr_is_constant_zero(tree, right, &packed_dimensions.const_env) { &**left } else { - return expr_is_two_state(state, expr, packed_dimensions).then_some((expr, true)); + return expr_is_two_state(tree, expr, packed_dimensions).then_some((expr, true)); }; - if expr_is_two_state(state, nonzero_side, packed_dimensions) { + if expr_is_two_state(tree, nonzero_side, packed_dimensions) { return Some((nonzero_side, matches!(op, BinaryOp::Ne | BinaryOp::NeCase))); } } - expr_is_two_state(state, expr, packed_dimensions).then_some((expr, true)) + expr_is_two_state(tree, expr, packed_dimensions).then_some((expr, true)) } fn expr_is_constant_zero( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: &Expr, const_env: &HashMap, ) -> bool { - expr_to_const(state, expr.clone()).and_then(|expr| eval_ast_const_expr(state, &expr, const_env)) + let state = &*tree.state; + let functions = &tree.functions; + expr_to_const(state, expr.clone()) + .and_then(|expr| eval_ast_const_expr(functions, &expr, const_env)) == Some(0) } diff --git a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs index c6e34f29d59..a383049349b 100644 --- a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs @@ -61,20 +61,22 @@ pub(super) fn from_array_parameter( dims: &PackedDimensions, shape: &VariableDimensions, ) -> Converted { - let ty = array_compatibility::unpacked_array_type(&tree.state, shape, dims) + let ty = array_compatibility::unpacked_array_type(&tree.functions, shape, dims) .ok_or_else(|| unsupported("array parameter argument type"))?; let value = substitute_expr_idents( expression_binding::bind(root, tree, dims)?, &dims.array_parameter_values, ); - let value = frozen(&tree.state, value, dims)?; + let value = frozen(tree, value, dims)?; Ok(BoundPattern { items: Items::ArrayValue { value, ty }, }) } -fn frozen(state: &AnalysisState, expr: Expr, dims: &PackedDimensions) -> Converted { - let freeze = |expr| frozen(state, expr, dims).map(Box::new); +fn frozen(tree: &AnalysisContext<'_>, expr: Expr, dims: &PackedDimensions) -> Converted { + let state = &*tree.state; + let functions = &tree.functions; + let freeze = |expr| frozen(tree, expr, dims).map(Box::new); Ok(match expr { Expr::Literal(_) => expr, Expr::Unary { op, expr } => Expr::Unary { @@ -104,7 +106,7 @@ fn frozen(state: &AnalysisState, expr: Expr, dims: &PackedDimensions) -> Convert .into_iter() .map(|arg| { let expr = frozen( - state, + tree, arg.ok_or_else(|| { unsupported("default constant function argument in pattern") })?, @@ -115,13 +117,9 @@ fn frozen(state: &AnalysisState, expr: Expr, dims: &PackedDimensions) -> Convert .ok_or_else(|| unsupported("constant pattern function argument")) }) .collect::>>()?; - let literal = const_functions::eval_call_literal( - &state.const_functions, - &name, - &args, - &dims.const_env, - ) - .ok_or_else(|| unsupported("constant parameter pattern function"))?; + let literal = + const_functions::eval_call_literal(functions, &name, &args, &dims.const_env) + .ok_or_else(|| unsupported("constant parameter pattern function"))?; Expr::Literal(typecheck::format_integral_literal_binary(&literal)) } value => { @@ -132,12 +130,12 @@ fn frozen(state: &AnalysisState, expr: Expr, dims: &PackedDimensions) -> Convert .map(|(n, v)| (n.clone(), v.clone())) .collect(); let value = substitute_expr_constants_with_parameter_literals( - state, + tree, value, &dims.const_env, &values, ); - let folded = fold_const_integral_expr_preserving_mask(state, value, &dims.const_env); + let folded = fold_const_integral_expr_preserving_mask(tree, value, &dims.const_env); if !matches!(folded, Expr::Literal(_)) { return Err(unsupported("nonconstant parameter pattern element")); } @@ -154,13 +152,13 @@ impl Value { } fn lower( &self, - state: &AnalysisState, + tree: &AnalysisContext<'_>, shape: &VariableDimensions, dims: &PackedDimensions, default: bool, ) -> Converted { if let Self::Pattern(pattern) = self { - return pattern.lower(state, shape, dims); + return pattern.lower(tree, shape, dims); } let (value, signed, value_type) = match self { Self::Expression { @@ -174,19 +172,20 @@ impl Value { ), Self::Pattern(_) => unreachable!(), }; - patterns::assignment_value(state, value, signed, value_type, shape, dims, default) + patterns::assignment_value(tree, value, signed, value_type, shape, dims, default) } } impl BoundPattern { pub(super) fn lower( &self, - state: &AnalysisState, + tree: &AnalysisContext<'_>, shape: &VariableDimensions, dims: &PackedDimensions, ) -> Converted { + let functions = &tree.functions; if let Items::ArrayValue { value, ty } = &self.items { - let target = array_compatibility::unpacked_array_type(state, shape, dims) + let target = array_compatibility::unpacked_array_type(&tree.functions, shape, dims) .ok_or_else(|| unsupported("unpacked array parameter supplied to a scalar"))?; if !ty.is_assignment_compatible_with(&target) { return Err(AnalyzerError::IncompatibleUnpackedArray { @@ -201,7 +200,7 @@ impl BoundPattern { return Ok(value.clone()); } let eval = |expr| { - eval_ast_const_expr(state, expr, &dims.const_env) + eval_ast_const_expr(functions, expr, &dims.const_env) .ok_or_else(|| unsupported("assignment pattern target bounds")) }; let unpacked = !shape.unpacked.is_empty(); @@ -299,7 +298,7 @@ impl BoundPattern { .map(|m| procedural::dimensions_from_type(m.r#type())), ); } else { - let width = patterns::shape_width(state, shape, dims) + let width = patterns::shape_width(&tree.functions, shape, dims) .ok_or_else(|| unsupported("pattern target width"))?; shapes = vec![ VariableDimensions { @@ -388,7 +387,7 @@ impl BoundPattern { let mut parts = selected .into_iter() .zip(shapes) - .map(|((v, default), shape)| v.lower(state, &shape, dims, default)) + .map(|((v, default), shape)| v.lower(tree, &shape, dims, default)) .collect::>>()?; if unpacked { parts.reverse(); diff --git a/crates/celox-sv-analyzer/src/ast/bound_patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/bound_patterns/binding.rs index 8e1aabe5721..ce41af7fcda 100644 --- a/crates/celox-sv-analyzer/src/ast/bound_patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns/binding.rs @@ -25,7 +25,7 @@ pub(in crate::ast) fn prepare_native( }; let integer = |id| { constant_binding::bind(id, tree, dims)? - .and_then(|value| eval_ast_const_expr(&tree.state, &value, &dims.const_env)) + .and_then(|value| eval_ast_const_expr(&tree.functions, &value, &dims.const_env)) .ok_or_else(|| unsupported("nonconstant assignment pattern key or count")) }; if let [item] = items.as_slice() @@ -130,7 +130,7 @@ pub(super) fn value_mode( ); let signed = dimensions::expression_signedness(&expr, &types, &types.const_env); - let expr = frozen(&tree.state, expr, dims)?; + let expr = frozen(tree, expr, dims)?; let signed = Some(signed.unwrap_or_else(|| { dimensions::expression_signedness(&expr, &types, &types.const_env) .unwrap_or(false) diff --git a/crates/celox-sv-analyzer/src/ast/bound_patterns/ports.rs b/crates/celox-sv-analyzer/src/ast/bound_patterns/ports.rs index 9ef73a7f00f..b1c6f136eca 100644 --- a/crates/celox-sv-analyzer/src/ast/bound_patterns/ports.rs +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns/ports.rs @@ -132,18 +132,20 @@ impl BoundPattern { let aggregate = target .unpacked_struct() .ok_or_else(|| unsupported("unpacked structure port type"))?; - let state = AnalysisState::default(); + let syntax = SyntaxTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); let shape = procedural::dimensions_from_type(target); - let value = self.lower(&state, &shape, &PackedDimensions::default())?; + let value = self.lower(&tree, &shape, &PackedDimensions::default())?; unpacked_structs::leaf_parts(aggregate, &value) .ok_or_else(|| unsupported("unpacked structure port pattern layout")) .map(|parts| parts.into_iter().map(Into::into).collect()) } pub(crate) fn bind_port(&self, target: &Type) -> Converted { - let state = AnalysisState::default(); + let syntax = SyntaxTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); let shape = procedural::dimensions_from_type(target); - self.lower(&state, &shape, &PackedDimensions::default()) + self.lower(&tree, &shape, &PackedDimensions::default()) .map(Into::into) } } @@ -238,7 +240,7 @@ pub(super) fn native_value_type_plan( || !shape.unpacked.is_empty() || shape.packed.len() > 1 }) - .and_then(|shape| shape.pattern_type(&tree.state, dims)), + .and_then(|shape| shape.pattern_type(&tree.functions, dims)), )); } } @@ -262,7 +264,7 @@ pub(super) fn native_value_type_plan( impl VariableDimensions { pub(in crate::ast) fn pattern_type( &self, - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, dims: &PackedDimensions, ) -> Option { let mut ty = Type::new(if self.is_2state { @@ -286,7 +288,7 @@ impl VariableDimensions { ty.signed_element_depth = self.signed_element_depth; ty.pattern_target(&const_functions::Environment { constants: &*dims.const_env, - functions: &state.const_functions, + functions, }) } } diff --git a/crates/celox-sv-analyzer/src/ast/case.rs b/crates/celox-sv-analyzer/src/ast/case.rs index f3caa9d49f3..e767b5ed934 100644 --- a/crates/celox-sv-analyzer/src/ast/case.rs +++ b/crates/celox-sv-analyzer/src/ast/case.rs @@ -3,10 +3,12 @@ use super::*; pub(super) fn expr_is_two_state( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: &Expr, packed_dimensions: &PackedDimensions, ) -> bool { + let state = &*tree.state; + let functions = &tree.functions; match expr { Expr::Ident(name) => { packed_dimensions @@ -17,33 +19,33 @@ pub(super) fn expr_is_two_state( Expr::Literal(value) => typecheck::parse_integral_literal(value) .is_some_and(|literal| literal.mask == num_bigint::BigUint::default()), Expr::Select { expr, msb, lsb, .. } => { - expr_is_two_state(state, expr, packed_dimensions) - && select_bounds_are_statically_valid(state, expr, msb, lsb, packed_dimensions) + expr_is_two_state(tree, expr, packed_dimensions) + && select_bounds_are_statically_valid(tree, expr, msb, lsb, packed_dimensions) } - Expr::Resize { expr, .. } => expr_is_two_state(state, expr, packed_dimensions), + Expr::Resize { expr, .. } => expr_is_two_state(tree, expr, packed_dimensions), Expr::Concat(parts) | Expr::RepeatConcat { parts, .. } => parts .iter() - .all(|part| expr_is_two_state(state, part, packed_dimensions)), + .all(|part| expr_is_two_state(tree, part, packed_dimensions)), Expr::Unary { op, expr } => { - *op == UnaryOp::ToTwoState || expr_is_two_state(state, expr, packed_dimensions) + *op == UnaryOp::ToTwoState || expr_is_two_state(tree, expr, packed_dimensions) } Expr::Binary { left, op, right } => { matches!(op, BinaryOp::EqCase | BinaryOp::NeCase) - || (expr_is_two_state(state, left, packed_dimensions) - && expr_is_two_state(state, right, packed_dimensions) + || (expr_is_two_state(tree, left, packed_dimensions) + && expr_is_two_state(tree, right, packed_dimensions) && (!matches!(op, BinaryOp::Div | BinaryOp::Mod) || expr_to_const(state, (**right).clone()) .and_then(|right| { - eval_ast_const_expr(state, &right, &packed_dimensions.const_env) + eval_ast_const_expr(functions, &right, &packed_dimensions.const_env) }) .is_some_and(|right| right != 0))) } Expr::Inside { expr, items } => { - expr_is_two_state(state, expr, packed_dimensions) + expr_is_two_state(tree, expr, packed_dimensions) && items.iter().all(|item| { item.exprs() .into_iter() - .all(|operand| expr_is_two_state(state, operand, packed_dimensions)) + .all(|operand| expr_is_two_state(tree, operand, packed_dimensions)) }) } Expr::Mux { @@ -51,10 +53,10 @@ pub(super) fn expr_is_two_state( then_expr, else_expr, } => { - expr_is_two_state(state, then_expr, packed_dimensions) + expr_is_two_state(tree, then_expr, packed_dimensions) && (then_expr == else_expr - || (expr_is_two_state(state, condition, packed_dimensions) - && expr_is_two_state(state, else_expr, packed_dimensions))) + || (expr_is_two_state(tree, condition, packed_dimensions) + && expr_is_two_state(tree, else_expr, packed_dimensions))) } Expr::Call { callee: Callee::System(function), @@ -71,7 +73,7 @@ pub(super) fn expr_is_two_state( .. } => args.iter().all(|arg| { arg.as_ref() - .is_some_and(|arg| expr_is_two_state(state, arg, packed_dimensions)) + .is_some_and(|arg| expr_is_two_state(tree, arg, packed_dimensions)) }), // Properties are 2-state. Expr::Call { @@ -90,7 +92,7 @@ pub(super) fn expr_is_two_state( key(index) || arg .as_ref() - .is_some_and(|arg| expr_is_two_state(state, arg, packed_dimensions)) + .is_some_and(|arg| expr_is_two_state(tree, arg, packed_dimensions)) }) } Expr::Call { @@ -124,15 +126,16 @@ pub(super) fn expr_is_two_state( } fn select_bounds_are_statically_valid( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: &Expr, msb: &ConstExpr, lsb: &ConstExpr, packed_dimensions: &PackedDimensions, ) -> bool { + let functions = &tree.functions; let (Some(msb), Some(lsb)) = ( - eval_ast_const_expr(state, msb, &packed_dimensions.const_env), - eval_ast_const_expr(state, lsb, &packed_dimensions.const_env), + eval_ast_const_expr(functions, msb, &packed_dimensions.const_env), + eval_ast_const_expr(functions, lsb, &packed_dimensions.const_env), ) else { return false; }; @@ -142,14 +145,14 @@ fn select_bounds_are_statically_valid( return false; }; let (Some(msb), Some(lsb)) = ( - eval_ast_const_expr(state, &msb, &packed_dimensions.const_env), - eval_ast_const_expr(state, &lsb, &packed_dimensions.const_env), + eval_ast_const_expr(functions, &msb, &packed_dimensions.const_env), + eval_ast_const_expr(functions, &lsb, &packed_dimensions.const_env), ) else { return false; }; (msb.min(lsb), msb.max(lsb)) } else { - let Some(width) = expr_static_width(state, expr, packed_dimensions) + let Some(width) = expr_static_width(tree, expr, packed_dimensions) .and_then(|width| width.checked_sub(1)) .and_then(|high| i128::try_from(high).ok()) else { diff --git a/crates/celox-sv-analyzer/src/ast/casts.rs b/crates/celox-sv-analyzer/src/ast/casts.rs index f1819cdce52..1f6f99bfe0a 100644 --- a/crates/celox-sv-analyzer/src/ast/casts.rs +++ b/crates/celox-sv-analyzer/src/ast/casts.rs @@ -3,7 +3,7 @@ use super::*; pub(super) fn expr_type_from_type( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, r#type: &Type, const_env: &HashMap, ) -> Option { @@ -14,8 +14,8 @@ pub(super) fn expr_type_from_type( .packed_ranges() .iter() .try_fold(1usize, |width, range| { - let left = eval_ast_const_expr(state, range.left(), const_env)?; - let right = eval_ast_const_expr(state, range.right(), const_env)?; + let left = eval_ast_const_expr(functions, range.left(), const_env)?; + let right = eval_ast_const_expr(functions, range.right(), const_env)?; width.checked_mul(usize::try_from(left.abs_diff(right)).ok()?.checked_add(1)?) })?; Some(ExprType { @@ -48,7 +48,7 @@ pub(super) enum RuntimeCastTarget { /// an assignment to a variable of the target type. Casts to two-state types /// turn unknown bits into zero. pub(super) fn runtime_cast_target_expr( - state: &AnalysisState, + tree: &AnalysisContext<'_>, target: RuntimeCastTarget, expr: Expr, packed_dimensions: &PackedDimensions, @@ -84,7 +84,7 @@ pub(super) fn runtime_cast_target_expr( }); } RuntimeCastTarget::Signing(signed) => { - let width = expr_static_width(state, &expr, packed_dimensions).ok_or_else(|| { + let width = expr_static_width(tree, &expr, packed_dimensions).ok_or_else(|| { unsupported("signedness cast of an operand without a static width") })?; let operand_signed = @@ -137,11 +137,12 @@ pub(super) fn runtime_cast_target_expr( /// Constant sizing, source-sign preservation and mask conversion independent /// of the syntax adapter that supplied its target and operand. pub(super) fn cast_constant_target( - state: &AnalysisState, + tree: &AnalysisContext<'_>, operand: ConstExpr, target: RuntimeCastTarget, const_env: &HashMap, ) -> Option { + let state = &*tree.state; if let RuntimeCastTarget::Real { short } = target { let kind = if short { TypeKind::Shortreal @@ -215,7 +216,7 @@ pub(super) fn cast_constant_target( &ir_parameter_types, ) .or_else(|| { - let operand_value = eval_ast_const_expr(state, &operand, const_env)?; + let operand_value = eval_ast_const_expr(&tree.functions, &operand, const_env)?; let operand_literal = format_typed_parameter_literal( operand_value, operand_type.width, diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 883a15e77a7..35c81dc6221 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -420,7 +420,8 @@ pub(super) fn scope_classes(tree: &AnalysisContext<'_>, env: &HashMap, offset: u32, @@ -1273,7 +1274,7 @@ pub(super) fn field( TypeKind::Object => (HANDLE_WIDTH, false, Some(HandleProperty::Object)), TypeKind::Process | TypeKind::Event => (HANDLE_WIDTH, false, None), TypeKind::Bit | TypeKind::Logic | TypeKind::Reg | TypeKind::Implicit => { - let shape = casts::expr_type_from_type(state, ty, env) + let shape = casts::expr_type_from_type(functions, ty, env) .ok_or_else(|| unsupported("class property type"))?; (shape.width, shape.signed, None) } diff --git a/crates/celox-sv-analyzer/src/ast/classes/foreign.rs b/crates/celox-sv-analyzer/src/ast/classes/foreign.rs index f3fc72014fe..7b16bf02fc8 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/foreign.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/foreign.rs @@ -318,6 +318,7 @@ impl Registry { state: state.clone(), parameter_overrides: Cow::Owned(HashMap::default()), imported: Arc::default(), + functions: const_functions::ConstantFunctions::default(), // Inside the package, `p::x` names its own item `x`. package: Some(name.into()), }; diff --git a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs index be7d9df660e..c15c56883fa 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs @@ -497,7 +497,7 @@ pub(in crate::ast) fn export_member_types( } for (member, ty) in &specialization.declared_aliases { if let Some(ty) = - type_parameters::resolve(&tree.state, ty.clone(), &specialization.env) + type_parameters::resolve(&tree.functions, ty.clone(), &specialization.env) { members.insert(member.clone(), ty); } @@ -966,7 +966,7 @@ fn finish_specialization( // container (IEEE 1800-2023 7.5, 7.8, 7.10). let ty = containers::with_dimensions(ty, &alias.dimensions, tree, &context) .ok()?; - type_parameters::resolve(&tree.state, ty, &env) + type_parameters::resolve(&tree.functions, ty, &env) }); if let Some(mut ty) = ty { let alias = instances::normalize_identifier(&alias.name.spelling); @@ -1146,7 +1146,7 @@ impl Parameters { } }; // The type is fixed in the scope that assigns it. - let ty = type_parameters::resolve(&tree.state, ty, env) + let ty = type_parameters::resolve(&tree.functions, ty, env) .ok_or_else(|| unsupported(format!("type of type parameter `{name}`")))?; if port { self.spelled.push(format!("{name}={}", spelling(&ty))); @@ -1186,7 +1186,7 @@ impl Parameters { parameter.packed_ranges.len(), )); constants::bind_generate_parameter( - &tree.state, + tree, parameter, env, &mut self.literals, @@ -1381,7 +1381,7 @@ fn finish( ) -> Converted> { let ty = ty.ok_or_else(|| unsupported("class type parameter value"))?; // The bounds are those of the scope that assigns the type. - let Some(ty) = type_parameters::resolve(&tree.state, ty, &context.const_env) else { + let Some(ty) = type_parameters::resolve(&tree.functions, ty, &context.const_env) else { return Ok(None); }; // Each enumeration declaration is a type of its own (6.19), and so is @@ -1420,7 +1420,7 @@ fn value_argument( { return Ok(expr); } - let Some(value) = eval_ast_const_expr(&tree.state, &expr, &context.const_env) else { + let Some(value) = eval_ast_const_expr(&tree.functions, &expr, &context.const_env) else { // A string or four-state value is its literal, and so is the value // of a real expression, or of a parameter with such a value. return match expr { diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs index 4e9f9500cc8..41de23a3705 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_process.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs @@ -23,7 +23,7 @@ pub(super) fn comb_processes_from_scope( ) { continue; } - let _constant_functions = item.enter(); + let syntax_tree = &item.enter(syntax_tree); let start = processes.len(); let (dimensions, literals) = views.get(item); comb_processes_from_item( @@ -71,7 +71,7 @@ fn comb_processes_from_item( )? { process.condition = condition.clone(); processes.push(substitute_process_constants_with_parameter_literals( - &syntax_tree.state, + syntax_tree, process, const_env, parameter_literals, @@ -91,7 +91,7 @@ fn comb_processes_from_item( state, )? { processes.push(substitute_process_constants( - &syntax_tree.state, + syntax_tree, process, const_env, )); @@ -105,7 +105,7 @@ fn comb_processes_from_item( packed_dimensions, )? { let assignment = substitute_assignment_constants_with_parameter_literals( - &syntax_tree.state, + syntax_tree, assignment, const_env, parameter_literals, @@ -285,7 +285,7 @@ fn continuous_assignments( .. } ) { - coerce_procedural_assignment_rhs(&tree.state, rhs, &lhs, dimensions) + coerce_procedural_assignment_rhs(tree, rhs, &lhs, dimensions) } else { rhs }; @@ -324,7 +324,7 @@ fn comb_process_from_procedure( let mut body = builder.native_body(&[body], &procedure.authored_statements)?; for stmt in &mut body { procedural::substitute_stmt_constants( - &syntax_tree.state, + syntax_tree, stmt, &HashMap::default(), parameter_literals, diff --git a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs index d82b78b4d75..ddaeed52d3e 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs @@ -3,20 +3,23 @@ use super::*; pub(super) fn expr_static_width( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: &Expr, packed_dimensions: &PackedDimensions, ) -> Option { + let functions = &tree.functions; match expr { - Expr::Ident(name) => { - lvalue_expr_type(state, &LValue::Ident(name.clone()), packed_dimensions) + Expr::Ident(name) => lvalue_expr_type( + &tree.functions, + &LValue::Ident(name.clone()), + packed_dimensions, + ) + .map(|r#type| r#type.width) + .or_else(|| variable_size_function_width(&packed_dimensions.const_env, name, false)) + .or_else(|| { + parameter_type_from_const_env(&packed_dimensions.const_env, name) .map(|r#type| r#type.width) - .or_else(|| variable_size_function_width(&packed_dimensions.const_env, name, false)) - .or_else(|| { - parameter_type_from_const_env(&packed_dimensions.const_env, name) - .map(|r#type| r#type.width) - }) - } + }), Expr::Literal(literal) => { typecheck::integral_literal_type_metadata(literal).map(|(width, _)| width) } @@ -26,13 +29,13 @@ pub(super) fn expr_static_width( &packed_dimensions.const_env, ), Expr::Concat(parts) => parts.iter().try_fold(0usize, |width, part| { - width.checked_add(expr_static_width(state, part, packed_dimensions)?) + width.checked_add(expr_static_width(tree, part, packed_dimensions)?) }), Expr::RepeatConcat { count, parts } => { - let count = eval_ast_const_expr(state, count, &packed_dimensions.const_env)?; + let count = eval_ast_const_expr(functions, count, &packed_dimensions.const_env)?; let count = usize::try_from(count).ok()?; let width = parts.iter().try_fold(0usize, |width, part| { - width.checked_add(expr_static_width(state, part, packed_dimensions)?) + width.checked_add(expr_static_width(tree, part, packed_dimensions)?) })?; width.checked_mul(count) } @@ -44,7 +47,7 @@ pub(super) fn expr_static_width( ) { Some(1) } else { - expr_static_width(state, expr, packed_dimensions) + expr_static_width(tree, expr, packed_dimensions) } } Expr::Binary { left, op, right } => { @@ -52,8 +55,8 @@ pub(super) fn expr_static_width( // resolve the types of both original operands. if packed_dimensions.type_query && matches!(op, BinaryOp::LogicAnd | BinaryOp::LogicOr) { - expr_static_width(state, left, packed_dimensions)?; - expr_static_width(state, right, packed_dimensions)?; + expr_static_width(tree, left, packed_dimensions)?; + expr_static_width(tree, right, packed_dimensions)?; } if matches!( op, @@ -72,11 +75,11 @@ pub(super) fn expr_static_width( ) { Some(1) } else if matches!(op, BinaryOp::Shl | BinaryOp::Shr | BinaryOp::Sar) { - expr_static_width(state, left, packed_dimensions) + expr_static_width(tree, left, packed_dimensions) } else { Some( - expr_static_width(state, left, packed_dimensions)?.max(expr_static_width( - state, + expr_static_width(tree, left, packed_dimensions)?.max(expr_static_width( + tree, right, packed_dimensions, )?), @@ -90,15 +93,15 @@ pub(super) fn expr_static_width( else_expr, .. } if matches!(&**then_expr, Expr::Literal(text) if text == crate::DIV_ZERO_UNKNOWN_LITERAL) => { - expr_static_width(state, else_expr, packed_dimensions) + expr_static_width(tree, else_expr, packed_dimensions) } Expr::Mux { then_expr, else_expr, .. } => Some( - expr_static_width(state, then_expr, packed_dimensions)?.max(expr_static_width( - state, + expr_static_width(tree, then_expr, packed_dimensions)?.max(expr_static_width( + tree, else_expr, packed_dimensions, )?), diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index ea0efbecaca..08bafe6d978 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -13,7 +13,6 @@ mod runtime; pub use runtime::RuntimeConstantFunctions; use num_bigint::BigUint; -use std::cell::{Cell, RefCell}; use super::*; use crate::procedural::{CaseKind, CaseLabel, LoopKind}; @@ -45,45 +44,41 @@ pub(super) struct FunctionErrors { by_name: HashMap, } -/// Constant evaluator state owned by one explicit analysis session. +/// What one constant evaluation has spent and may still spend, owned by the +/// evaluation and lent to each frame it opens. #[derive(Default)] -pub(crate) struct State { - functions: RefCell, - revision: generate::Revision, - depth: Cell, - runtime_fuel: Cell>, - runtime_two_state: Cell>, - argument_names: RefCell<( - Arc, - Arc>>, - )>, +pub(crate) struct Budget { + /// How many calls the frame being evaluated is nested in. + depth: usize, + /// How many statements and loop iterations a runtime evaluation may + /// still run; `None` outside one. + fuel: Option, + /// Whether a runtime evaluation runs a two-state build; `None` outside + /// one. + two_state: Option, } -pub(super) struct Installed { - previous: ConstantFunctions, - revision: u64, - state: std::rc::Rc, -} - -impl Drop for Installed { - fn drop(&mut self) { - let functions = &self.state.const_functions; - replace(functions, std::mem::take(&mut self.previous)); - functions.revision.restore(self.revision); +impl Budget { + /// Spend one step of a runtime evaluation's fuel. + fn charge(&mut self) -> Option<()> { + if let Some(fuel) = &mut self.fuel { + *fuel = fuel.checked_sub(1)?; + } + Some(()) } } /// A numeric environment together with the functions visible at its call site. pub(crate) struct Environment<'a> { pub(crate) constants: &'a dyn ConstantEnvironment, - pub(crate) functions: &'a State, + pub(crate) functions: &'a ConstantFunctions, } impl ConstantEnvironment for Environment<'_> { fn get(&self, name: &str) -> Option<&i128> { self.constants.get(name) } - fn function_state(&self) -> Option<&State> { + fn functions(&self) -> Option<&ConstantFunctions> { Some(self.functions) } fn literal(&self, name: &str) -> Option<&typecheck::IntegralLiteral> { @@ -93,7 +88,7 @@ impl ConstantEnvironment for Environment<'_> { /// The functions of a module and the types of their locals. #[derive(Debug, Clone, Default, PartialEq, Eq)] -pub(super) struct ConstantFunctions { +pub(crate) struct ConstantFunctions { functions: Arc, locals: Arc>, /// Why the module's functions, or one of them by name, could not be @@ -101,37 +96,9 @@ pub(super) struct ConstantFunctions { errors: Arc, } -/// Make `functions` the constant functions until the guard is dropped. -pub(super) fn install( - state: &std::rc::Rc, - functions: ConstantFunctions, -) -> Installed { - let previous = installed(&state.const_functions); - let revision = state.const_functions.revision.get(); - replace(&state.const_functions, functions); - Installed { - previous, - revision, - state: state.clone(), - } -} - -pub(super) fn replace(state: &State, functions: ConstantFunctions) { - *state.functions.borrow_mut() = functions; - state.revision.change(); -} - -pub(super) fn revision(state: &State) -> &generate::Revision { - &state.revision -} - -/// Why an installed function could not be converted for constant evaluation. -pub(super) fn installed(state: &State) -> ConstantFunctions { - state.functions.borrow().clone() -} - -pub(super) fn conversion_error(state: &State, name: &str) -> Option { - let functions = state.functions.borrow(); +/// Why function `name` of `functions` could not be converted for constant +/// evaluation. +pub(super) fn conversion_error(functions: &ConstantFunctions, name: &str) -> Option { functions .errors .by_name @@ -140,21 +107,26 @@ pub(super) fn conversion_error(state: &State, name: &str) -> Option Arc>> { - let functions = state.functions.borrow().functions.clone(); - let mut cached = state.argument_names.borrow_mut(); - if !Arc::ptr_eq(&cached.0, &functions) { - let names = functions - .iter() - .map(|(name, function)| (name.clone(), function.argument_names.clone())) - .collect(); - *cached = (functions, Arc::new(names)); +/// The names of the formal arguments of each function of `functions`. +pub(super) fn argument_names(functions: &ConstantFunctions) -> HashMap> { + functions + .functions + .iter() + .map(|(name, function)| (name.clone(), function.argument_names.clone())) + .collect() +} + +impl ConstantFunctions { + /// Whether `other` is these functions, not only equal ones. + pub(super) fn same(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.functions, &other.functions) + && Arc::ptr_eq(&self.locals, &other.locals) + && Arc::ptr_eq(&self.errors, &other.errors) } - cached.1.clone() } -pub(super) fn is_constant_function(state: &State, name: &str) -> bool { - state.functions.borrow().functions.contains_key(name) +pub(super) fn is_constant_function(functions: &ConstantFunctions, name: &str) -> bool { + functions.functions.contains_key(name) } /// The module-scope functions of a module, for constant evaluation. When @@ -448,7 +420,7 @@ pub(super) fn symbolic_module_constant_functions( ) }); roots.extend_missing(&scope::imported(tree).constant_functions); - let _installed = install(&tree.state, roots); + let tree = &tree.with_functions(roots); collect_module_constant_functions( tree, const_env, @@ -786,11 +758,11 @@ pub(in crate::ast) fn visit_const_calls<'a>( /// Fill defaults in the declaration's bound scope; runtime IR keeps its holes. pub(super) fn resolved_arguments( - state: &State, + functions: &ConstantFunctions, callee: &Callee, args: &[Option], ) -> Option> { - let functions = state.functions.borrow().functions.clone(); + let functions = &functions.functions; let Some(function) = callee.subroutine().and_then(|name| functions.get(name)) else { return args.iter().cloned().collect(); }; @@ -809,12 +781,11 @@ pub(super) fn resolved_arguments( /// Check arity and defaults without evaluating any actual argument. pub(super) fn validate_argument_bindings( - state: &State, + functions: &ConstantFunctions, name: &str, present: &[bool], ) -> Converted<()> { { - let functions = state.functions.borrow(); let functions = &functions.functions; let Some(function) = functions.get(name) else { // The raw syntax validator reports functions that cannot be used @@ -838,7 +809,7 @@ pub(super) fn validate_argument_bindings( /// A named constant call can be folded only when its body and actuals evaluate. pub(super) fn eval_expression_literal( - state: &State, + functions: &ConstantFunctions, expr: &Expr, constants: &HashMap, ) -> Option { @@ -851,25 +822,44 @@ pub(super) fn eval_expression_literal( }; let env = Environment { constants, - functions: state, + functions, }; let constants: &dyn ConstantEnvironment = &env; - Frame::new(constants).eval(expr).map(Value::into_literal) + Frame::new(constants, &mut Budget::default()) + .eval(expr) + .map(Value::into_literal) } /// The value of a call of an installed constant function. -pub(crate) fn eval_call( +#[cfg(test)] +fn eval_call( name: &str, args: &[crate::ir::ConstExpr], constants: &dyn ConstantEnvironment, ) -> Option { - eval_ir_call(name, args, constants)?.number().copied() + eval_ir_call(name, args, constants, &mut Budget::default())? + .number() + .copied() +} + +/// The value of a call of a constant function inside an evaluation that +/// spends `budget`. +pub(crate) fn eval_call_budgeted( + name: &str, + args: &[crate::ir::ConstExpr], + constants: &dyn ConstantEnvironment, + budget: &mut Budget, +) -> Option { + eval_ir_call(name, args, constants, budget)? + .number() + .copied() } fn eval_ir_call( name: &str, args: &[crate::ir::ConstExpr], constants: &dyn ConstantEnvironment, + budget: &mut Budget, ) -> Option { let expr = Expr::Call { callee: Callee::Subroutine(name.into()), @@ -880,41 +870,40 @@ fn eval_ir_call( .collect(), arg_order: Vec::new(), }; - Frame::new(constants).eval(&expr) + Frame::new(constants, budget).eval(&expr) } /// Preserve the declared result type when freezing a caller's function value. pub(super) fn eval_call_literal( - state: &State, + functions: &ConstantFunctions, name: &str, args: &[crate::ir::ConstExpr], constants: &HashMap, ) -> Option { let env = Environment { constants, - functions: state, + functions, }; - eval_ir_call(name, args, &env).map(Value::into_literal) + eval_ir_call(name, args, &env, &mut Budget::default()).map(Value::into_literal) } -fn call_value(name: &str, args: &[Value], constants: &dyn ConstantEnvironment) -> Option { - let state = constants.function_state()?; - runtime::charge(state)?; - let functions = state.functions.borrow().functions.clone(); - let function = functions.get(name)?; - let depth = state.depth.get(); - if depth >= MAX_DEPTH { +/// The value of a call of function `name` of `constants`, whose frame sees +/// the constants of the caller's scope but not the caller's locals. +fn call_value( + name: &str, + args: &[Value], + constants: &dyn ConstantEnvironment, + budget: &mut Budget, +) -> Option { + budget.charge()?; + let function = constants.functions()?.functions.get(name)?; + if budget.depth >= MAX_DEPTH { return None; } - struct DepthGuard<'a>(&'a Cell, usize); - impl Drop for DepthGuard<'_> { - fn drop(&mut self) { - self.0.set(self.1); - } - } - state.depth.set(depth + 1); - let _depth = DepthGuard(&state.depth, depth); - call_in_frame(function, args, Frame::new(constants)) + budget.depth += 1; + let value = call_in_frame(function, args, Frame::new(constants, budget)); + budget.depth -= 1; + value } #[cfg(test)] @@ -924,9 +913,13 @@ fn call( constants: &dyn ConstantEnvironment, ) -> Option { let args = args.iter().copied().map(Value::integer).collect::>(); - call_in_frame(function, &args, Frame::new(constants))? - .number() - .copied() + call_in_frame( + function, + &args, + Frame::new(constants, &mut Budget::default()), + )? + .number() + .copied() } fn call_in_frame( @@ -962,7 +955,7 @@ fn call_in_frame( Flow::Next | Flow::Return(None) => {} Flow::Break | Flow::Continue => return None, } - frame.values.remove(return_name) + frame.scope.values.remove(return_name) } enum Flow { @@ -976,13 +969,31 @@ enum Flow { /// variable, and typed temporaries are owned here. Nested calls borrow this /// overlay, preserving the former copied environment's lookup precedence. struct Frame<'a> { + scope: Locals<'a>, + budget: &'a mut Budget, + return_width: Option, + temporaries: usize, + iterations: usize, +} + +/// What names in a frame denote: its own values over those of the +/// environment it was called in. +struct Locals<'a> { constants: &'a dyn ConstantEnvironment, values: HashMap, types: HashMap, two_state: HashSet, - return_width: Option, - temporaries: usize, - iterations: usize, +} + +impl Locals<'_> { + fn type_of(&self, name: &str) -> Option<(usize, bool)> { + self.types.get(name).copied().or_else(|| { + dimensions::parameter_type_from_lookup(name, &|marker| { + self.constants.get(marker).copied() + }) + .map(|ty| (ty.width, ty.signed)) + }) + } } /// `value` as a `width`-bit value of the given signedness. @@ -999,9 +1010,9 @@ fn fit(value: i128, width: usize, signed: bool) -> i128 { } } -impl ConstantEnvironment for Frame<'_> { - fn function_state(&self) -> Option<&State> { - self.constants.function_state() +impl ConstantEnvironment for Locals<'_> { + fn functions(&self) -> Option<&ConstantFunctions> { + self.constants.functions() } fn get(&self, name: &str) -> Option<&i128> { match self.values.get(name) { @@ -1018,12 +1029,15 @@ impl ConstantEnvironment for Frame<'_> { } impl<'a> Frame<'a> { - fn new(constants: &'a dyn ConstantEnvironment) -> Self { + fn new(constants: &'a dyn ConstantEnvironment, budget: &'a mut Budget) -> Self { Self { - constants, - values: HashMap::default(), - types: HashMap::default(), - two_state: HashSet::default(), + scope: Locals { + constants, + values: HashMap::default(), + types: HashMap::default(), + two_state: HashSet::default(), + }, + budget, return_width: None, temporaries: 0, iterations: 0, @@ -1031,23 +1045,22 @@ impl<'a> Frame<'a> { } fn type_of(&self, name: &str) -> Option<(usize, bool)> { - self.types.get(name).copied().or_else(|| { - dimensions::parameter_type_from_lookup(name, &|marker| { - self.constants.get(marker).copied() - }) - .map(|ty| (ty.width, ty.signed)) - }) + self.scope.type_of(name) } - fn eval_lowered(&self, expr: &crate::ir::ConstExpr) -> Option { - crate::typecheck::eval_const_expr_with_types_in_env(expr, self, &|name| self.type_of(name)) + /// The value of `expr`, whose calls spend this frame's budget. + fn eval_lowered(&mut self, expr: &crate::ir::ConstExpr) -> Option { + let scope = &self.scope; + crate::typecheck::eval_const_expr_with_types_in_env_budgeted( + expr, + scope, + &|name| scope.type_of(name), + self.budget, + ) } fn declare(&mut self, name: &str, r#type: &crate::ir::Type) -> Option<()> { - if self - .constants - .function_state() - .is_some_and(|state| state.runtime_two_state.get().is_some()) + if self.budget.two_state.is_some() && matches!( r#type.kind(), crate::ir::TypeKind::Real @@ -1058,23 +1071,21 @@ impl<'a> Frame<'a> { { return None; } - if !r#type.unpacked_ranges().is_empty() - && self - .constants - .function_state()? - .runtime_two_state - .get() - .is_none() - { - return None; + if !r#type.unpacked_ranges().is_empty() { + self.scope.constants.functions()?; + self.budget.two_state?; } // Resolved runtime types already include unpacked dimensions. // Elaboration types still need their dimensions evaluated here. let width = if let Some(width) = r#type.resolved_width() { width.max(1) } else { - let mut width = - crate::typecheck::resolve_packed_width_in_env(r#type.packed_ranges(), self)?.max(1); + let mut width = crate::typecheck::resolve_packed_width_in_env_budgeted( + r#type.packed_ranges(), + &self.scope, + self.budget, + )? + .max(1); for range in r#type.unpacked_ranges() { let (left, right) = range.resolved_bounds().or_else(|| { Some(( @@ -1091,19 +1102,17 @@ impl<'a> Frame<'a> { return None; } if r#type.kind() == crate::ir::TypeKind::Bit { - self.two_state.insert(name.to_string()); + self.scope.two_state.insert(name.to_string()); } - self.types + self.scope + .types .insert(name.to_string(), (width, r#type.is_signed())); Some(()) } fn initial_value(&self, name: &str) -> Option { - let runtime = self - .constants - .function_state() - .and_then(|state| state.runtime_two_state.get()); - if runtime == Some(true) || self.two_state.contains(name) { + let runtime = self.budget.two_state; + if runtime == Some(true) || self.scope.two_state.contains(name) { return Some(Value::integer(0)); } let (width, _) = self.type_of(name)?; @@ -1115,24 +1124,17 @@ impl<'a> Frame<'a> { Some((width, signed)) => value.resize(width, signed)?, None => value, }; - let value = if self.two_state.contains(name) - || self - .constants - .function_state() - .is_some_and(|state| state.runtime_two_state.get() == Some(true)) - { + let value = if self.scope.two_state.contains(name) || self.budget.two_state == Some(true) { value.into_two_state() } else { value }; - self.values.insert(name.to_string(), value); + self.scope.values.insert(name.to_string(), value); Some(()) } fn tick(&mut self) -> Option<()> { - if let Some(state) = self.constants.function_state() { - runtime::charge(state)?; - } + self.budget.charge()?; self.iterations += 1; (self.iterations <= MAX_ITERATIONS).then_some(()) } @@ -1140,7 +1142,7 @@ impl<'a> Frame<'a> { fn eval(&mut self, expr: &Expr) -> Option { let lowered: crate::ir::ConstExpr = self.lower(expr)?.into(); if let Some(literal) = - typecheck::eval_const_integral_literal_in_env(&lowered, self, &|name| { + typecheck::eval_const_integral_literal_in_env(&lowered, &self.scope, &|name| { self.type_of(name) }) { @@ -1162,7 +1164,7 @@ impl<'a> Frame<'a> { let lowered: crate::ir::ConstExpr = self.lower(expr)?.into(); if let Some(literal) = typecheck::eval_const_assignment_in_env( &lowered, - self, + &self.scope, &|name| self.type_of(name), width, ) { @@ -1178,7 +1180,7 @@ impl<'a> Frame<'a> { let lowered = self.lower(expr)?.into(); typecheck::eval_case_operand_in_env( &lowered, - self, + &self.scope, &|name| self.type_of(name), context.width, context.signed, @@ -1187,7 +1189,7 @@ impl<'a> Frame<'a> { } /// Type queries must not execute a case label or select a conditional arm. - fn expression_type(&self, expr: &Expr) -> Option { + fn expression_type(&mut self, expr: &Expr) -> Option { let ty = |(width, signed)| ExprType { width, signed }; let placeholder = |ty: ExprType| ConstExpr::Resize { expr: Box::new(ConstExpr::Literal("0".into())), @@ -1197,7 +1199,8 @@ impl<'a> Frame<'a> { let expression = match expr { Expr::Ident(name) => { return self.type_of(name).map(ty).or_else(|| { - self.constants + self.scope + .constants .literal(name) .map(|value| ty((value.width, value.signed))) }); @@ -1247,10 +1250,14 @@ impl<'a> Frame<'a> { callee: Callee::Subroutine(name), .. } => { - let functions = self.constants.function_state()?.functions.borrow(); + let functions = self.scope.constants.functions()?; let (_, result) = functions.functions.get(name)?.return_var.as_ref()?; let width = result.resolved_width().or_else(|| { - typecheck::resolve_packed_width_in_env(result.packed_ranges(), self) + typecheck::resolve_packed_width_in_env_budgeted( + result.packed_ranges(), + &self.scope, + self.budget, + ) })?; return Some(ty((width, result.is_signed()))); } @@ -1293,7 +1300,9 @@ impl<'a> Frame<'a> { let (width, signed) = value.r#type(); let name = format!("\0constant_function_temporary{}", self.temporaries); self.temporaries += 1; - self.types.insert(name.clone(), (width.max(1), signed)); + self.scope + .types + .insert(name.clone(), (width.max(1), signed)); self.set(&name, value)?; Some(ConstExpr::Ident(name)) } @@ -1324,35 +1333,33 @@ impl<'a> Frame<'a> { args, .. } => { - let functions = self - .constants - .function_state()? - .functions - .borrow() - .functions - .clone(); + let functions = self.scope.constants.functions()?.functions.clone(); let function = functions.get(name)?; let actuals = resolved_arguments( - self.constants.function_state()?, + self.scope.constants.functions()?, &Callee::Subroutine(name.clone()), args, )?; let mut values = Vec::with_capacity(actuals.len()); for (arg, (_, ty)) in actuals.iter().zip(&function.params) { let width = ty.resolved_width().or_else(|| { - typecheck::resolve_packed_width_in_env(ty.packed_ranges(), self) + typecheck::resolve_packed_width_in_env_budgeted( + ty.packed_ranges(), + &self.scope, + self.budget, + ) })?; values.push(self.assignment_value(arg, width)?); } if actuals.len() > function.params.len() { return None; } - let value = call_value(name, &values, self)?; + let value = call_value(name, &values, self.scope.constants, self.budget)?; self.temporary(value)? } Expr::Call { callee, args, .. } => ConstExpr::Function { callee: callee.clone(), - args: resolved_arguments(self.constants.function_state()?, callee, args)? + args: resolved_arguments(self.scope.constants.functions()?, callee, args)? .iter() .map(|arg| self.lower(arg)) .collect::>()?, @@ -1396,14 +1403,10 @@ impl<'a> Frame<'a> { // This interpreter uses four-state expression rules. Only reuse a // result when every intermediate is known; otherwise runtime lowering // supplies the state-mode semantics (including out-of-range selects). - if self - .constants - .function_state() - .is_some_and(|state| state.runtime_two_state.get() == Some(true)) - { + if self.budget.two_state == Some(true) { let literal = typecheck::eval_const_integral_literal_in_env( &lowered.clone().into(), - self, + &self.scope, &|name| self.type_of(name), )?; if literal.mask != BigUint::default() { @@ -1413,7 +1416,7 @@ impl<'a> Frame<'a> { Some(lowered) } - fn type_placeholder(&self, expr: &Expr) -> Option { + fn type_placeholder(&mut self, expr: &Expr) -> Option { let ty = self.expression_type(expr)?; if ty.width > constant_folding::MAX_CONSTANT_CONCAT_BITS { return None; @@ -1483,10 +1486,11 @@ impl<'a> Frame<'a> { }), }, }; - let comparison = - typecheck::eval_const_integral_literal_in_env(&comparison.into(), self, &|name| { - self.type_of(name) - })?; + let comparison = typecheck::eval_const_integral_literal_in_env( + &comparison.into(), + &self.scope, + &|name| self.type_of(name), + )?; result = match (result, typecheck::integral_literal_truth(&comparison)) { (Some(true), _) | (_, Some(true)) => Some(true), (Some(false), Some(false)) => Some(false), @@ -1517,7 +1521,7 @@ impl<'a> Frame<'a> { let lowered: crate::ir::ConstExpr = self.lower(expr)?.into(); return crate::typecheck::eval_const_integral_literal_in_env( &lowered, - self, + &self.scope, &|name| self.type_of(name), ); } @@ -1568,10 +1572,9 @@ impl<'a> Frame<'a> { LValue::Ident(name) => { if self.type_of(name).is_none() { let ty = self + .scope .constants - .function_state()? - .functions - .borrow() + .functions()? .locals .get(name) .cloned()?; @@ -1594,7 +1597,7 @@ impl<'a> Frame<'a> { } let msb = self.eval_lowered(&msb.clone().into())?; let lsb = self.eval_lowered(&lsb.clone().into())?; - let old = self.values.get(name)?.clone(); + let old = self.scope.values.get(name)?.clone(); let value = old.write(msb.max(lsb), msb.min(lsb), value)?; self.set(name, value)?; } @@ -1675,9 +1678,7 @@ impl<'a> Frame<'a> { } fn stmt(&mut self, stmt: &Stmt) -> Option { - if let Some(state) = self.constants.function_state() { - runtime::charge(state)?; - } + self.budget.charge()?; match stmt { Stmt::Assign { lhs, rhs, .. } => { let width = match lhs { @@ -1694,10 +1695,9 @@ impl<'a> Frame<'a> { } Stmt::Local { name, init } => { let r#type = self + .scope .constants - .function_state()? - .functions - .borrow() + .functions()? .locals .get(name) .cloned()?; @@ -1805,6 +1805,8 @@ impl<'a> Frame<'a> { } } +#[cfg(test)] +use std::cell::Cell; #[cfg(test)] thread_local! { static FUNCTION_CALLS: Cell = const { Cell::new(0) }; diff --git a/crates/celox-sv-analyzer/src/ast/const_functions/runtime.rs b/crates/celox-sv-analyzer/src/ast/const_functions/runtime.rs index 91944c75a21..785ec107d51 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions/runtime.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions/runtime.rs @@ -26,19 +26,12 @@ fn lvalue(value: crate::ir::LValue) -> LValue { /// This reuses the constant interpreter only after runtime lifetime and effect /// checks; functions with persistent storage or observable effects stay calls. pub struct RuntimeConstantFunctions<'a> { - state: State, + functions: ConstantFunctions, constants: &'a HashMap, - cache: RefCell>>, + cache: HashMap>, two_state: bool, } -pub(super) fn charge(state: &State) -> Option<()> { - if let Some(fuel) = state.runtime_fuel.get() { - state.runtime_fuel.set(Some(fuel.checked_sub(1)?)); - } - Some(()) -} - impl<'a> RuntimeConstantFunctions<'a> { pub fn new( module: &crate::ir::Module, @@ -164,8 +157,7 @@ impl<'a> RuntimeConstantFunctions<'a> { functions.remove(&name); } } - let state = State::default(); - *state.functions.borrow_mut() = ConstantFunctions { + let functions = ConstantFunctions { functions: Arc::new(functions), locals: Arc::new( module @@ -177,40 +169,33 @@ impl<'a> RuntimeConstantFunctions<'a> { errors: Arc::default(), }; Self { - state, + functions, constants, - cache: RefCell::default(), + cache: HashMap::default(), two_state: !four_state, } } /// A call with no actual or formal arguments, or `None` when it cannot be /// evaluated without runtime state, effects, or exceeding the shared budget. - pub fn value(&self, name: &str) -> Option { - if let Some(value) = self.cache.borrow().get(name) { + pub fn value(&mut self, name: &str) -> Option { + if let Some(value) = self.cache.get(name) { return value.clone(); } - if !self - .state - .functions - .borrow() - .functions - .get(name)? - .params - .is_empty() - { + if !self.functions.functions.get(name)?.params.is_empty() { return None; } - self.state.runtime_fuel.set(Some(MAX_ITERATIONS)); - self.state.runtime_two_state.set(Some(self.two_state)); let env = Environment { constants: self.constants, - functions: &self.state, + functions: &self.functions, }; - let value = call_value(name, &[], &env).map(Value::into_literal); - self.state.runtime_fuel.set(None); - self.state.runtime_two_state.set(None); - self.cache.borrow_mut().insert(name.into(), value.clone()); + let mut budget = Budget { + depth: 0, + fuel: Some(MAX_ITERATIONS), + two_state: Some(self.two_state), + }; + let value = call_value(name, &[], &env, &mut budget).map(Value::into_literal); + self.cache.insert(name.into(), value.clone()); value } } @@ -254,7 +239,7 @@ mod tests { ); let constants = HashMap::default(); for four_state in [false, true] { - let evaluator = RuntimeConstantFunctions::new(&module, &constants, four_state); + let mut evaluator = RuntimeConstantFunctions::new(&module, &constants, four_state); assert_eq!(evaluator.value("mixed").unwrap().value, BigUint::default()); } } @@ -271,7 +256,7 @@ mod tests { endmodule"#, ); let constants = HashMap::default(); - let evaluator = RuntimeConstantFunctions::new(&module, &constants, true); + let mut evaluator = RuntimeConstantFunctions::new(&module, &constants, true); let value = evaluator.value("unknown_match").unwrap(); assert_eq!(value.mask, BigUint::from(1u8)); assert_eq!(value.value, BigUint::from(1u8)); @@ -325,7 +310,7 @@ mod tests { ); let constants = HashMap::default(); for four_state in [false, true] { - let evaluator = RuntimeConstantFunctions::new(&module, &constants, four_state); + let mut evaluator = RuntimeConstantFunctions::new(&module, &constants, four_state); for name in ["arithmetic", "signed_case", "skip_label", "fill_case"] { assert_eq!( evaluator.value(name).unwrap().value, @@ -354,7 +339,7 @@ mod tests { endmodule"#, ); let constants = HashMap::default(); - let evaluator = RuntimeConstantFunctions::new(&module, &constants, true); + let mut evaluator = RuntimeConstantFunctions::new(&module, &constants, true); for (name, expected, mask) in [ ("definite_match", 1u8, 0u8), ("definite_mismatch", 0, 0), @@ -380,7 +365,7 @@ mod tests { endmodule"#, ); let constants = HashMap::default(); - let evaluator = RuntimeConstantFunctions::new(&module, &constants, true); + let mut evaluator = RuntimeConstantFunctions::new(&module, &constants, true); let result = evaluator.value("pattern").unwrap(); assert_eq!(result.width, 16); assert_eq!(result.value, BigUint::from(0x8421u32)); @@ -402,7 +387,7 @@ mod tests { ); assert!(module.subroutines()[0].persistent_locals.is_empty()); let constants = HashMap::default(); - let evaluator = RuntimeConstantFunctions::new(&module, &constants, true); + let mut evaluator = RuntimeConstantFunctions::new(&module, &constants, true); FUNCTION_CALLS.with(|calls| calls.set(0)); let value = evaluator.value("pattern").unwrap(); let mut expected = BigUint::default(); @@ -430,7 +415,7 @@ mod tests { endmodule"#, ); let constants = HashMap::default(); - let evaluator = RuntimeConstantFunctions::new(&module, &constants, true); + let mut evaluator = RuntimeConstantFunctions::new(&module, &constants, true); for name in [ "stateful", "writes_global", @@ -456,14 +441,14 @@ mod tests { endmodule"#, ); let constants = HashMap::default(); - let two_state = RuntimeConstantFunctions::new(&module, &constants, false); + let mut two_state = RuntimeConstantFunctions::new(&module, &constants, false); for name in ["explicit_unknown", "outside_select", "non_integral_local"] { assert!( two_state.value(name).is_none(), "{name} must retain runtime semantics" ); } - let four_state = RuntimeConstantFunctions::new(&module, &constants, true); + let mut four_state = RuntimeConstantFunctions::new(&module, &constants, true); for name in ["explicit_unknown", "outside_select"] { assert_eq!(four_state.value(name).unwrap().value, BigUint::default()); } @@ -484,15 +469,8 @@ mod tests { endmodule"#, ); let constants = HashMap::default(); - let evaluator = RuntimeConstantFunctions::new(&module, &constants, true); - assert!( - evaluator - .state - .functions - .borrow() - .functions - .contains_key("slices") - ); + let mut evaluator = RuntimeConstantFunctions::new(&module, &constants, true); + assert!(evaluator.functions.functions.contains_key("slices")); assert!(evaluator.value("slices").is_none()); } @@ -507,7 +485,7 @@ mod tests { ); let constants = HashMap::default(); for four_state in [false, true] { - let evaluator = RuntimeConstantFunctions::new(&module, &constants, four_state); + let mut evaluator = RuntimeConstantFunctions::new(&module, &constants, four_state); assert_eq!( evaluator.value("unknown_local").unwrap().value, BigUint::from(u8::from(!four_state)) @@ -535,7 +513,7 @@ mod tests { let mut actual = Vec::new(); let mut expected = Vec::new(); for four_state in [false, true] { - let evaluator = RuntimeConstantFunctions::new(&module, &constants, four_state); + let mut evaluator = RuntimeConstantFunctions::new(&module, &constants, four_state); for (name, value) in [("mixed_sign", 255u32), ("concat_width", 0xab00ffcdu32)] { let result = evaluator.value(name).unwrap(); actual.push((four_state, name, result.value, result.mask)); @@ -587,7 +565,7 @@ mod tests { ); let constants = HashMap::default(); for four_state in [false, true] { - let evaluator = RuntimeConstantFunctions::new(&module, &constants, four_state); + let mut evaluator = RuntimeConstantFunctions::new(&module, &constants, four_state); for (name, expected) in [ ("skipped_function", 255u32), ("skipped_function_false", 255), @@ -631,7 +609,7 @@ mod tests { endmodule"#, ); let constants = HashMap::default(); - let evaluator = RuntimeConstantFunctions::new(&module, &constants, true); + let mut evaluator = RuntimeConstantFunctions::new(&module, &constants, true); FUNCTION_CALLS.with(|count| count.set(0)); let result = evaluator.value("merged").unwrap(); assert_eq!(result.value, BigUint::from(0xa5u8)); diff --git a/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs b/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs index 557162da722..b40e2e116bd 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions/tests.rs @@ -1,5 +1,5 @@ use super::*; -use std::{hint::black_box, time::Instant}; +use std::{cell::Cell, hint::black_box, time::Instant}; fn ident(name: &str) -> Expr { Expr::Ident(name.into()) @@ -186,30 +186,34 @@ fn environment(count: usize) -> HashMap { // The former eager initialization, retained only for result and timing comparisons. fn copied_call( - state: &State, + functions: &ConstantFunctions, function: &ConstantFunction, args: &[i128], constants: &HashMap, ) -> Option { - let empty = HashMap::default(); + // Calls it makes see the caller's scope, not its frame. let context = Environment { - constants: &empty, - functions: state, + constants, + functions, }; + let mut budget = Budget::default(); call_in_frame( function, &args.iter().copied().map(Value::integer).collect::>(), Frame { - constants: &context, - values: constants - .iter() - .map(|(name, value)| (name.clone(), Value::integer(*value))) - .collect(), - types: parameter_types_from_const_env(constants) - .into_iter() - .map(|(name, ty)| (name, (ty.width, ty.signed))) - .collect(), - two_state: HashSet::default(), + scope: Locals { + constants: &context, + values: constants + .iter() + .map(|(name, value)| (name.clone(), Value::integer(*value))) + .collect(), + types: parameter_types_from_const_env(constants) + .into_iter() + .map(|(name, ty)| (name, (ty.width, ty.signed))) + .collect(), + two_state: HashSet::default(), + }, + budget: &mut budget, return_width: None, temporaries: 0, iterations: 0, @@ -222,8 +226,6 @@ fn copied_call( #[test] fn borrowed_calls_match_copied_frames_and_preserve_caller_values() { let functions = functions(); - let state = std::rc::Rc::new(AnalysisState::default()); - let _installed = install(&state, functions.clone()); for size in [16, 256, 4096] { let env = environment(size); let before = env.clone(); @@ -243,13 +245,13 @@ fn borrowed_calls_match_copied_frames_and_preserve_caller_values() { &args, &Environment { constants: &env, - functions: &state.const_functions, + functions: &functions, }, ); assert_eq!(borrowed, expected, "{name}"); assert_eq!( borrowed, - copied_call(&state.const_functions, function, &args, &env), + copied_call(&functions, function, &args, &env), "{name}" ); } @@ -272,8 +274,6 @@ impl ConstantEnvironment for CountedEnvironment<'_> { #[test] fn calls_query_only_referenced_values_and_types() { let functions = functions(); - let state = std::rc::Rc::new(AnalysisState::default()); - let _installed = install(&state, functions.clone()); let mut expected = None; for size in [16, 256, 4096] { let env = environment(size); @@ -294,7 +294,7 @@ fn calls_query_only_referenced_values_and_types() { &args, &Environment { constants: &counted, - functions: &state.const_functions + functions: &functions } ) .is_some() @@ -310,8 +310,6 @@ fn calls_query_only_referenced_values_and_types() { #[test] fn unresolved_values_and_recursion_limits_restore_the_call_context() { let functions = functions(); - let state = std::rc::Rc::new(AnalysisState::default()); - let _installed = install(&state, functions); let mut env = environment(0); env.remove("GLOBAL"); assert_eq!( @@ -320,7 +318,7 @@ fn unresolved_values_and_recursion_limits_restore_the_call_context() { &[], &Environment { constants: &env, - functions: &state.const_functions + functions: &functions } ), None @@ -334,20 +332,19 @@ fn unresolved_values_and_recursion_limits_restore_the_call_context() { &[arg("65")], &Environment { constants: &env, - functions: &state.const_functions + functions: &functions } ), None ); FUNCTION_CALLS.with(|count| assert_eq!(count.get(), MAX_DEPTH)); - assert_eq!(state.const_functions.depth.get(), 0); assert_eq!( eval_call( "recursive", &[arg("6")], &Environment { constants: &env, - functions: &state.const_functions + functions: &functions } ), Some(5) @@ -358,7 +355,7 @@ fn unresolved_values_and_recursion_limits_restore_the_call_context() { &[], &Environment { constants: &env, - functions: &state.const_functions + functions: &functions } ), Some(-1) @@ -369,8 +366,6 @@ fn unresolved_values_and_recursion_limits_restore_the_call_context() { #[ignore = "manual paired timing probe; no timing thresholds"] fn compare_borrowed_and_copied_function_environments() { let functions = functions(); - let state = std::rc::Rc::new(AnalysisState::default()); - let _installed = install(&state, functions.clone()); let function = &functions.functions["read"]; println!("parameters,calls,copied_ms,borrowed_ms"); for count in [32, 128, 512, 2048] { @@ -379,14 +374,14 @@ fn compare_borrowed_and_copied_function_environments() { let start = Instant::now(); for _ in 0..count { let value = if copied { - copied_call(&state.const_functions, function, &[], black_box(&env)) + copied_call(&functions, function, &[], black_box(&env)) } else { call( function, &[], &Environment { constants: black_box(&env), - functions: &state.const_functions, + functions: &functions, }, ) }; @@ -413,8 +408,7 @@ fn compare_borrowed_and_copied_function_environments() { #[test] fn literal_probes_do_not_execute_user_functions_and_recursion_is_not_repeated() { - let state = std::rc::Rc::new(AnalysisState::default()); - let _installed = install(&state, functions()); + let functions = functions(); let env = environment(0); let expr = crate::ir::ConstExpr::Function { callee: Callee::Subroutine("recursive".into()), @@ -429,7 +423,7 @@ fn literal_probes_do_not_execute_user_functions_and_recursion_is_not_repeated() &expr, &Environment { constants: &env, - functions: &state.const_functions + functions: &functions } ), Some(11) @@ -480,8 +474,6 @@ fn check_function_parameter_chains() { #[test] fn independent_evaluators_keep_their_function_bindings() { - let first = std::rc::Rc::new(AnalysisState::default()); - let second = std::rc::Rc::new(AnalysisState::default()); let bindings = |value: &str| ConstantFunctions { functions: Arc::new(HashMap::from_iter([( "read".to_string(), @@ -489,16 +481,16 @@ fn independent_evaluators_keep_their_function_bindings() { )])), ..ConstantFunctions::default() }; - let _first = install(&first, bindings("7")); - let _second = install(&second, bindings("11")); + let first = bindings("7"); + let second = bindings("11"); let constants = HashMap::default(); let first_env = Environment { constants: &constants, - functions: &first.const_functions, + functions: &first, }; let second_env = Environment { constants: &constants, - functions: &second.const_functions, + functions: &second, }; assert_eq!(eval_call("read", &[], &first_env), Some(7)); assert_eq!(eval_call("read", &[], &second_env), Some(11)); @@ -574,9 +566,13 @@ fn partial_returns_preserve_unwritten_unknown_bits() { }], ); function.return_var = Some(("partial".into(), fixed_ty(8, false))); - let value = call_in_frame(&function, &[], Frame::new(&constants)) - .unwrap() - .into_literal(); + let value = call_in_frame( + &function, + &[], + Frame::new(&constants, &mut Budget::default()), + ) + .unwrap() + .into_literal(); assert_eq!(value.value, BigUint::from(0xfdu8)); assert_eq!(value.mask, BigUint::from(0xfcu8)); } @@ -607,3 +603,33 @@ fn full_width_return_assignments_keep_all_128_bits() { Some(0xfedcba98765432100123456789abcdefu128 as i128) ); } + +#[test] +fn calls_in_select_indices_spend_the_budget_of_their_evaluation() { + // A call in a select index is evaluated by the typechecker, inside the + // evaluation of the function that selects: it is nested no deeper than + // MAX_DEPTH calls, rather than recursing until the stack overflows. + let source = |depth: usize| { + format!( + "module M(output int y); + function automatic int f(input int n); + logic [7:0] v; + v = 8'hff; + if (n == 0) return 0; + return v[f(n - 1)]; + endfunction + localparam int P = f({depth}); + assign y = P; + endmodule" + ) + }; + let value = |depth| { + let ir = crate::analyze_source(&source(depth), Path::new("select.sv")).unwrap(); + ir.modules()[0].parameters()[0].resolved_value() + }; + assert_eq!(value(3), Some(1)); + FUNCTION_CALLS.with(|count| count.set(0)); + assert_eq!(value(100_000), None); + // Each evaluation gave up after MAX_DEPTH nested calls. + FUNCTION_CALLS.with(|count| assert!(count.get() < 100_000, "{}", count.get())); +} diff --git a/crates/celox-sv-analyzer/src/ast/constant_binding.rs b/crates/celox-sv-analyzer/src/ast/constant_binding.rs index 84e3cce5d43..7918c5073ff 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_binding.rs @@ -202,7 +202,7 @@ fn bind_in_context( let expr = expression_binding::bind_value(id, native, tree, query_dimensions, None)?; let Some(value) = - selects::indexed_expression_value(&tree.state, expr, query_dimensions) + selects::indexed_expression_value(tree, expr, query_dimensions) else { return Ok(None); }; @@ -309,13 +309,9 @@ fn bind_in_context( .array_parameter_values .contains_key(&name_key) { - selects::indexed_expression_value( - &tree.state, - value, - query_dimensions, - ) + selects::indexed_expression_value(tree, value, query_dimensions) } else { - expr_to_index_const(&tree.state, value, query_dimensions) + expr_to_index_const(tree, value, query_dimensions) }; values.push( value.ok_or_else(|| unsupported("parameter selection shape"))?, @@ -335,7 +331,7 @@ fn bind_in_context( Err(error) => return Err(error), }; let Some(value) = - selects::indexed_expression_value(&tree.state, value, query_dimensions) + selects::indexed_expression_value(tree, value, query_dimensions) else { return Ok(None); }; @@ -350,7 +346,7 @@ fn bind_in_context( dimensions.clone() }; context.subroutine_param_names = - const_functions::argument_names(&tree.state.const_functions); + Arc::new(const_functions::argument_names(&tree.functions)); let value = match expression_binding::bind_value(id, native, tree, &context, None) { Ok(value) => value, @@ -377,13 +373,9 @@ fn bind_in_context( } ); let Some(value) = (if countbits { - constants::countbits_constant_call( - &tree.state, - value, - &dimensions.const_env, - ) + constants::countbits_constant_call(tree, value, &dimensions.const_env) } else { - constants::user_call_value(&tree.state, value, &dimensions.const_env) + constants::user_call_value(tree, value, &dimensions.const_env) }) else { return Ok(None); }; @@ -396,12 +388,9 @@ fn bind_in_context( }, Job::Cast(target) => { let value = values.pop().ok_or_else(disagreement)?; - let Some(value) = casts::cast_constant_target( - &tree.state, - value, - target, - &query_dimensions.const_env, - ) else { + let Some(value) = + casts::cast_constant_target(tree, value, target, &query_dimensions.const_env) + else { return Ok(None); }; values.push(value); @@ -464,7 +453,7 @@ fn bind_in_context( let mut indices = values.split_off(start); if let Some(indices) = indices .iter() - .map(|index| eval_ast_const_expr(&tree.state, index, &dimensions.const_env)) + .map(|index| eval_ast_const_expr(&tree.functions, index, &dimensions.const_env)) .collect::>>() && let Some(literal) = parameter_element_literal(&name, &indices, &dimensions.const_env) @@ -596,7 +585,7 @@ mod tests { .unwrap() .unwrap(); assert_eq!( - eval_ast_const_expr(&tree.state, &value, &HashMap::default()), + eval_ast_const_expr(&tree.functions, &value, &HashMap::default()), Some(expected) ); } diff --git a/crates/celox-sv-analyzer/src/ast/constant_folding.rs b/crates/celox-sv-analyzer/src/ast/constant_folding.rs index 7246b76e780..d2b073b3d3f 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_folding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_folding.rs @@ -8,10 +8,12 @@ mod tests; pub(super) const MAX_CONSTANT_CONCAT_BITS: usize = 65_536; pub(super) fn simplify_constant_mux_conditions( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: Expr, const_env: &HashMap, ) -> Expr { + let state = &*tree.state; + let functions = &tree.functions; match expr { Expr::Select { expr, @@ -19,7 +21,7 @@ pub(super) fn simplify_constant_mux_conditions( lsb, signed, } => Expr::Select { - expr: Box::new(simplify_constant_mux_conditions(state, *expr, const_env)), + expr: Box::new(simplify_constant_mux_conditions(tree, *expr, const_env)), msb, lsb, signed, @@ -27,14 +29,14 @@ pub(super) fn simplify_constant_mux_conditions( Expr::Concat(parts) => Expr::Concat( parts .into_iter() - .map(|part| simplify_constant_mux_conditions(state, part, const_env)) + .map(|part| simplify_constant_mux_conditions(tree, part, const_env)) .collect(), ), Expr::RepeatConcat { count, parts } => Expr::RepeatConcat { count, parts: parts .into_iter() - .map(|part| simplify_constant_mux_conditions(state, part, const_env)) + .map(|part| simplify_constant_mux_conditions(tree, part, const_env)) .collect(), }, Expr::Resize { @@ -42,7 +44,7 @@ pub(super) fn simplify_constant_mux_conditions( width, signed, } => { - let expr = simplify_constant_mux_conditions(state, *expr, const_env); + let expr = simplify_constant_mux_conditions(tree, *expr, const_env); if let Some(constant) = expr_to_const(state, expr.clone()) { let parameter_types = parameter_types_from_const_env(const_env) .into_iter() @@ -57,7 +59,7 @@ pub(super) fn simplify_constant_mux_conditions( ) { return Expr::Literal(typecheck::format_integral_literal_binary(&literal)); } - if let Some(value) = eval_ast_const_expr(state, &constant, const_env) { + if let Some(value) = eval_ast_const_expr(functions, &constant, const_env) { return Expr::Literal(format_typed_parameter_literal(value, width, signed)); } } @@ -69,21 +71,21 @@ pub(super) fn simplify_constant_mux_conditions( } Expr::Unary { op, expr } => Expr::Unary { op, - expr: Box::new(simplify_constant_mux_conditions(state, *expr, const_env)), + expr: Box::new(simplify_constant_mux_conditions(tree, *expr, const_env)), }, Expr::Binary { left, op, right } => Expr::Binary { - left: Box::new(simplify_constant_mux_conditions(state, *left, const_env)), + left: Box::new(simplify_constant_mux_conditions(tree, *left, const_env)), op, - right: Box::new(simplify_constant_mux_conditions(state, *right, const_env)), + right: Box::new(simplify_constant_mux_conditions(tree, *right, const_env)), }, Expr::Mux { condition, then_expr, else_expr, } => { - let condition = simplify_constant_mux_conditions(state, *condition, const_env); - let mut then_expr = simplify_constant_mux_conditions(state, *then_expr, const_env); - let mut else_expr = simplify_constant_mux_conditions(state, *else_expr, const_env); + let condition = simplify_constant_mux_conditions(tree, *condition, const_env); + let mut then_expr = simplify_constant_mux_conditions(tree, *then_expr, const_env); + let mut else_expr = simplify_constant_mux_conditions(tree, *else_expr, const_env); let parameter_types = parameter_types_from_const_env(const_env); let arm_type = |arm: &Expr| { if let Expr::Literal(literal) = arm @@ -141,7 +143,7 @@ pub(super) fn simplify_constant_mux_conditions( return value; } match expr_to_const(state, condition.clone()) - .and_then(|condition| eval_ast_const_expr(state, &condition, const_env)) + .and_then(|condition| eval_ast_const_expr(functions, &condition, const_env)) { Some(value) => { let (selected, unselected) = if value == 0 { @@ -189,7 +191,7 @@ pub(super) fn simplify_constant_mux_conditions( signed: result_type.signed, }; simplify_constant_mux_conditions( - state, + tree, Expr::Resize { expr: Box::new(selected), width: result_type.width, @@ -206,12 +208,12 @@ pub(super) fn simplify_constant_mux_conditions( } } Expr::Inside { expr, items } => Expr::Inside { - expr: Box::new(simplify_constant_mux_conditions(state, *expr, const_env)), + expr: Box::new(simplify_constant_mux_conditions(tree, *expr, const_env)), items: items .into_iter() .map(|item| { item.map(&mut |operand| { - simplify_constant_mux_conditions(state, operand, const_env) + simplify_constant_mux_conditions(tree, operand, const_env) }) }) .collect(), @@ -225,7 +227,7 @@ pub(super) fn simplify_constant_mux_conditions( callee, args: args .into_iter() - .map(|arg| arg.map(|arg| simplify_constant_mux_conditions(state, arg, const_env))) + .map(|arg| arg.map(|arg| simplify_constant_mux_conditions(tree, arg, const_env))) .collect(), }, Expr::Ident(_) | Expr::Literal(_) => expr, @@ -233,7 +235,7 @@ pub(super) fn simplify_constant_mux_conditions( } pub(super) fn fold_const_integral_expr_preserving_mask( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: Expr, const_env: &HashMap, ) -> Expr { @@ -246,17 +248,18 @@ pub(super) fn fold_const_integral_expr_preserving_mask( // conversion. Do not scan every visible binding to fold each such value. let parameter_types = |name: &str| parameter_type_from_const_env(const_env, name).map(|ty| (ty.width, ty.signed)); - eval_const_integral_expr_preserving_mask(state, &expr, const_env, ¶meter_types) + eval_const_integral_expr_preserving_mask(tree, &expr, const_env, ¶meter_types) .map(|literal| Expr::Literal(typecheck::format_integral_literal_binary(&literal))) .unwrap_or(expr) } fn eval_const_integral_expr_preserving_mask( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: &Expr, const_env: &HashMap, parameter_types: &impl Fn(&str) -> Option<(usize, bool)>, ) -> Option { + let functions = &tree.functions; match expr { Expr::Select { expr, @@ -264,14 +267,14 @@ fn eval_const_integral_expr_preserving_mask( lsb, signed, } => { - let msb = eval_ast_const_expr(state, msb, const_env)?; - let lsb = eval_ast_const_expr(state, lsb, const_env)?; + let msb = eval_ast_const_expr(functions, msb, const_env)?; + let lsb = eval_ast_const_expr(functions, lsb, const_env)?; let width = usize::try_from(msb.checked_sub(lsb)?.checked_add(1)?).ok()?; if width > MAX_CONSTANT_CONCAT_BITS { return None; } let operand = - eval_const_integral_expr_preserving_mask(state, expr, const_env, parameter_types)?; + eval_const_integral_expr_preserving_mask(tree, expr, const_env, parameter_types)?; let mut value = num_bigint::BigUint::default(); let mut mask = num_bigint::BigUint::default(); for offset in 0..width { @@ -302,7 +305,7 @@ fn eval_const_integral_expr_preserving_mask( signed, } => { let operand = - eval_const_integral_expr_preserving_mask(state, expr, const_env, parameter_types)?; + eval_const_integral_expr_preserving_mask(tree, expr, const_env, parameter_types)?; typecheck::parse_integral_literal(&resize_integral_literal_for_cast( operand, *width, *signed, )) @@ -311,23 +314,18 @@ fn eval_const_integral_expr_preserving_mask( parts .iter() .map(|part| { - eval_const_integral_expr_preserving_mask( - state, - part, - const_env, - parameter_types, - ) + eval_const_integral_expr_preserving_mask(tree, part, const_env, parameter_types) }) .collect::>>()?, ), Expr::RepeatConcat { count, parts } => { - let count = usize::try_from(eval_ast_const_expr(state, count, const_env)?).ok()?; + let count = usize::try_from(eval_ast_const_expr(functions, count, const_env)?).ok()?; let part = concat_integral_literals( parts .iter() .map(|part| { eval_const_integral_expr_preserving_mask( - state, + tree, part, const_env, parameter_types, @@ -344,7 +342,7 @@ fn eval_const_integral_expr_preserving_mask( } _ => { let constant: crate::ir::ConstExpr = constant_with_folded_selections_with_lookup( - state, + tree, expr, const_env, parameter_types, @@ -362,29 +360,31 @@ fn eval_const_integral_expr_preserving_mask( // Fold only self-determined operands. Keep arithmetic nodes intact so the // constant evaluator can propagate expression widths across compound trees. pub(super) fn constant_with_folded_selections( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: &Expr, const_env: &HashMap, parameter_types: &HashMap, ) -> Option { - constant_with_folded_selections_with_lookup(state, expr, const_env, &|name| { + constant_with_folded_selections_with_lookup(tree, expr, const_env, &|name| { parameter_types.get(name).copied() }) } fn constant_with_folded_selections_with_lookup( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: &Expr, const_env: &HashMap, parameter_types: &impl Fn(&str) -> Option<(usize, bool)>, ) -> Option { + let state = &*tree.state; + let functions = &tree.functions; let convert = |expr: &Expr| { - constant_with_folded_selections_with_lookup(state, expr, const_env, parameter_types) + constant_with_folded_selections_with_lookup(tree, expr, const_env, parameter_types) }; match expr { Expr::Select { .. } | Expr::Concat(_) | Expr::RepeatConcat { .. } | Expr::Resize { .. } => { let literal = - eval_const_integral_expr_preserving_mask(state, expr, const_env, parameter_types)?; + eval_const_integral_expr_preserving_mask(tree, expr, const_env, parameter_types)?; Some(ConstExpr::Literal( typecheck::format_integral_literal_binary(&literal), )) @@ -411,7 +411,7 @@ fn constant_with_folded_selections_with_lookup( // Materialize a constant function's self-determined return type // before the enclosing selection/arithmetic receives its context. if let Some(literal) = - const_functions::eval_expression_literal(&state.const_functions, expr, const_env) + const_functions::eval_expression_literal(functions, expr, const_env) { return Some(ConstExpr::Literal( typecheck::format_integral_literal_binary(&literal), @@ -511,14 +511,15 @@ mod constant_concat_limits_tests { #[test] fn bounds_repeated_constant_concatenation() { - let state = AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); for (count, accepted) in [(65_536, true), (65_537, false), (1_000_000_000, false)] { let expr = Expr::RepeatConcat { count: ConstExpr::Literal(count.to_string()), parts: vec![Expr::Literal("1'bx".to_string())], }; let result = eval_const_integral_expr_preserving_mask( - &state, + &tree, &expr, &HashMap::default(), &|_| None, @@ -534,7 +535,7 @@ mod constant_concat_limits_tests { parts: vec![Expr::Literal("2'bxz".to_string())], }; assert!( - eval_const_integral_expr_preserving_mask(&state, &expr, &HashMap::default(), &|_| None,) + eval_const_integral_expr_preserving_mask(&tree, &expr, &HashMap::default(), &|_| None,) .is_none() ); } diff --git a/crates/celox-sv-analyzer/src/ast/constant_folding/tests.rs b/crates/celox-sv-analyzer/src/ast/constant_folding/tests.rs index baa50fe4a7d..82a820fcc07 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_folding/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_folding/tests.rs @@ -4,7 +4,8 @@ use super::*; #[test] fn lazy_types_preserve_width_signedness_and_masks_across_expression_shapes() { - let state = &crate::ast::AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); let mut env = HashMap::from_iter([ ("A".into(), -2), ("B".into(), 1), @@ -153,11 +154,11 @@ fn lazy_types_preserve_width_signedness_and_masks_across_expression_shapes() { ]; for (expr, expected_lookups) in cases { let lookups = Cell::new(0); - let direct = eval_const_integral_expr_preserving_mask(state, &expr, &env, &|name| { + let direct = eval_const_integral_expr_preserving_mask(&tree, &expr, &env, &|name| { lookups.set(lookups.get() + 1); parameter_type_from_const_env(&env, name).map(|ty| (ty.width, ty.signed)) }); - let rebuilt = eval_const_integral_expr_preserving_mask(state, &expr, &env, &|name| { + let rebuilt = eval_const_integral_expr_preserving_mask(&tree, &expr, &env, &|name| { types.get(name).copied() }); assert_eq!(direct, rebuilt, "{expr:?}"); @@ -172,13 +173,13 @@ fn lazy_types_preserve_width_signedness_and_masks_across_expression_shapes() { expected }; assert_eq!( - fold_const_integral_expr_preserving_mask(state, expr.clone(), &env), + fold_const_integral_expr_preserving_mask(&tree, expr.clone(), &env), expected ); } // Fixed expected results also guard against losing typed signed shifts. let shifted = fold_const_integral_expr_preserving_mask( - state, + &tree, Expr::Binary { left: boxed_a(), op: BinaryOp::Shr, @@ -194,7 +195,7 @@ fn lazy_types_preserve_width_signedness_and_masks_across_expression_shapes() { assert!(shifted.signed); assert_eq!(shifted.value, num_bigint::BigUint::from(127u8)); let two_state = fold_const_integral_expr_preserving_mask( - state, + &tree, Expr::Unary { op: UnaryOp::ToTwoState, expr: Box::new(literal("8'b1xz001xz")), @@ -208,7 +209,7 @@ fn lazy_types_preserve_width_signedness_and_masks_across_expression_shapes() { typecheck::parse_integral_literal(&two_state), typecheck::parse_integral_literal("8'h84") ); - let wide = fold_const_integral_expr_preserving_mask(state, ident("W"), &env); + let wide = fold_const_integral_expr_preserving_mask(&tree, ident("W"), &env); let Expr::Literal(wide) = wide else { panic!("wide typed parameter must fold") }; @@ -223,7 +224,6 @@ fn lazy_types_preserve_width_signedness_and_masks_across_expression_shapes() { #[test] fn numeric_two_state_parameter_values_do_not_scan_visible_type_tables() { - let state = &crate::ast::AnalysisState::default(); for count in [16, 64, 256] { let mut code = String::from("module Top;\n"); for index in 0..count { @@ -240,9 +240,10 @@ fn numeric_two_state_parameter_values_do_not_scan_visible_type_tables() { .unwrap(); let source = Source::from_syntax(&tree).unwrap(); let parameters = source.modules()[0].parameters(); - let env = const_env_from_parameters(state, parameters); + let context = AnalysisContext::unspecialized(&tree); + let env = const_env_from_parameters(&context, parameters); dimensions::PARAMETER_TYPE_SCAN_ENTRIES.with(|counter| counter.set(0)); - let values = parameter_value_env(state, parameters, &env); + let values = parameter_value_env(&context, parameters, &env); assert_eq!( dimensions::PARAMETER_TYPE_SCAN_ENTRIES.with(|counter| counter.get()), 0 diff --git a/crates/celox-sv-analyzer/src/ast/constants.rs b/crates/celox-sv-analyzer/src/ast/constants.rs index f915a50fdf3..38403d0121c 100644 --- a/crates/celox-sv-analyzer/src/ast/constants.rs +++ b/crates/celox-sv-analyzer/src/ast/constants.rs @@ -3,14 +3,14 @@ use super::*; pub(super) fn bind_generate_parameter( - state: &AnalysisState, + tree: &AnalysisContext<'_>, parameter: Parameter, const_env: &mut HashMap, parameter_literals: &mut HashMap, ) { let mut parameter_types = parameter_types_from_const_env(const_env); bind_generate_parameter_with_types( - state, + tree, parameter, const_env, parameter_literals, @@ -19,7 +19,7 @@ pub(super) fn bind_generate_parameter( } pub(super) fn bind_generate_parameter_with_types( - state: &AnalysisState, + tree: &AnalysisContext<'_>, parameter: Parameter, const_env: &mut HashMap, parameter_literals: &mut HashMap, @@ -39,7 +39,7 @@ pub(super) fn bind_generate_parameter_with_types( ); let resolved_type = parameter.resolved_type(parameter_types); let (resolved, resolved_literal) = - parameter.resolved_value_and_literal(state, const_env, parameter_types, parameter_literals); + parameter.resolved_value_and_literal(tree, const_env, parameter_types, parameter_literals); let literal = if let Some(value) = resolved { const_env.insert(parameter.name().to_string(), value); Some(Expr::Literal(if let Some(ty) = resolved_type { @@ -49,7 +49,7 @@ pub(super) fn bind_generate_parameter_with_types( })) } else { resolved_literal.or_else(|| { - parameter_value_env(state, std::slice::from_ref(¶meter), const_env) + parameter_value_env(tree, std::slice::from_ref(¶meter), const_env) .remove(parameter.name()) .map(|value| substitute_expr_idents(value, parameter_literals)) }) @@ -64,7 +64,7 @@ pub(super) fn bind_generate_parameter_with_types( } pub(super) fn eval_ast_const_expr( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, expr: &ConstExpr, const_env: &HashMap, ) -> Option { @@ -79,18 +79,18 @@ pub(super) fn eval_ast_const_expr( &expr.into(), &const_functions::Environment { constants: const_env, - functions: &state.const_functions, + functions, }, ) } pub(super) fn substitute_process_constants( - state: &AnalysisState, + tree: &AnalysisContext<'_>, process: CombProcess, const_env: &HashMap, ) -> CombProcess { substitute_process_constants_with_parameter_literals( - state, + tree, process, const_env, &HashMap::default(), @@ -98,14 +98,14 @@ pub(super) fn substitute_process_constants( } pub(super) fn substitute_process_constants_with_parameter_literals( - state: &AnalysisState, + tree: &AnalysisContext<'_>, process: CombProcess, const_env: &HashMap, parameter_literals: &HashMap, ) -> CombProcess { let mut sensitivity_body = process.sensitivity_body; for stmt in &mut sensitivity_body { - procedural::substitute_stmt_constants(state, stmt, const_env, parameter_literals); + procedural::substitute_stmt_constants(tree, stmt, const_env, parameter_literals); } let condition = process .condition @@ -113,7 +113,7 @@ pub(super) fn substitute_process_constants_with_parameter_literals( if process.assignments.is_empty() { let mut body = process.body; for stmt in &mut body { - procedural::substitute_stmt_constants(state, stmt, const_env, parameter_literals); + procedural::substitute_stmt_constants(tree, stmt, const_env, parameter_literals); } return CombProcess { creation_order: process.creation_order, @@ -131,7 +131,7 @@ pub(super) fn substitute_process_constants_with_parameter_literals( .into_iter() .map(|assignment| { substitute_assignment_constants_with_parameter_literals( - state, + tree, assignment, const_env, parameter_literals, @@ -147,7 +147,7 @@ pub(super) fn substitute_process_constants_with_parameter_literals( } pub(super) fn substitute_assignment_constants_with_parameter_literals( - state: &AnalysisState, + tree: &AnalysisContext<'_>, assignment: Assignment, const_env: &HashMap, parameter_literals: &HashMap, @@ -155,7 +155,7 @@ pub(super) fn substitute_assignment_constants_with_parameter_literals( Assignment::new( substitute_lvalue_constants(assignment.lhs, const_env), substitute_expr_constants_with_parameter_literals( - state, + tree, assignment.rhs, const_env, parameter_literals, @@ -191,11 +191,12 @@ pub(super) fn substitute_lvalue_constants( } pub(super) fn substitute_expr_constants_with_parameter_literals( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: Expr, const_env: &HashMap, parameter_literals: &HashMap, ) -> Expr { + let state = &*tree.state; match expr { Expr::Ident(name) => parameter_literals .get(&name) @@ -233,7 +234,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( signed, } => Expr::Select { expr: Box::new(substitute_expr_constants_with_parameter_literals( - state, + tree, *expr, const_env, parameter_literals, @@ -247,7 +248,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( .into_iter() .map(|part| { substitute_expr_constants_with_parameter_literals( - state, + tree, part, const_env, parameter_literals, @@ -261,7 +262,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( .into_iter() .map(|part| { substitute_expr_constants_with_parameter_literals( - state, + tree, part, const_env, parameter_literals, @@ -275,7 +276,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( signed, } => Expr::Resize { expr: Box::new(substitute_expr_constants_with_parameter_literals( - state, + tree, *expr, const_env, parameter_literals, @@ -286,7 +287,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( Expr::Unary { op, expr } => Expr::Unary { op, expr: Box::new(substitute_expr_constants_with_parameter_literals( - state, + tree, *expr, const_env, parameter_literals, @@ -294,14 +295,14 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( }, Expr::Binary { left, op, right } => Expr::Binary { left: Box::new(substitute_expr_constants_with_parameter_literals( - state, + tree, *left, const_env, parameter_literals, )), op, right: Box::new(substitute_expr_constants_with_parameter_literals( - state, + tree, *right, const_env, parameter_literals, @@ -313,19 +314,19 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( else_expr, } => Expr::Mux { condition: Box::new(substitute_expr_constants_with_parameter_literals( - state, + tree, *condition, const_env, parameter_literals, )), then_expr: Box::new(substitute_expr_constants_with_parameter_literals( - state, + tree, *then_expr, const_env, parameter_literals, )), else_expr: Box::new(substitute_expr_constants_with_parameter_literals( - state, + tree, *else_expr, const_env, parameter_literals, @@ -333,7 +334,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( }, Expr::Inside { expr, items } => Expr::Inside { expr: Box::new(substitute_expr_constants_with_parameter_literals( - state, + tree, *expr, const_env, parameter_literals, @@ -343,7 +344,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( .map(|item| { item.map(&mut |operand| { substitute_expr_constants_with_parameter_literals( - state, + tree, operand, const_env, parameter_literals, @@ -362,7 +363,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( .map(|arg| { arg.map(|arg| { substitute_expr_constants_with_parameter_literals( - state, + tree, arg, const_env, parameter_literals, @@ -385,7 +386,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( } else if function == Some(SystemFunction::Countbits) { // Resolve constant calls before SLT lowering while retaining X/Z masks. fold_const_integral_expr_preserving_mask( - state, + tree, Expr::Call { callee, args, @@ -628,10 +629,12 @@ pub(super) fn expr_to_const(state: &AnalysisState, expr: Expr) -> Option, expr: Expr, dimensions: &PackedDimensions, ) -> Option { + let state = &*tree.state; + let functions = &tree.functions; match expr { Expr::Resize { expr, @@ -642,7 +645,7 @@ pub(super) fn expr_to_index_const( return Some(ConstExpr::Literal("0".into())); } Some(ConstExpr::Resize { - expr: Box::new(expr_to_index_const(state, *expr, dimensions)?), + expr: Box::new(expr_to_index_const(tree, *expr, dimensions)?), width, signed, }) @@ -651,12 +654,12 @@ pub(super) fn expr_to_index_const( Expr::Literal(value) => Some(ConstExpr::Literal(value)), Expr::Unary { op, expr } => Some(ConstExpr::Unary { op, - expr: Box::new(expr_to_index_const(state, *expr, dimensions)?), + expr: Box::new(expr_to_index_const(tree, *expr, dimensions)?), }), Expr::Binary { left, op, right } => Some(ConstExpr::Binary { - left: Box::new(expr_to_index_const(state, *left, dimensions)?), + left: Box::new(expr_to_index_const(tree, *left, dimensions)?), op, - right: Box::new(expr_to_index_const(state, *right, dimensions)?), + right: Box::new(expr_to_index_const(tree, *right, dimensions)?), }), Expr::Select { expr, @@ -665,7 +668,7 @@ pub(super) fn expr_to_index_const( signed, } if !matches!(&*expr, Expr::Concat(_) | Expr::RepeatConcat { .. }) => { Some(ConstExpr::SelectRange { - expr: Box::new(expr_to_index_const(state, *expr, dimensions)?), + expr: Box::new(expr_to_index_const(tree, *expr, dimensions)?), msb: Box::new(msb), lsb: Box::new(lsb), signed, @@ -676,9 +679,9 @@ pub(super) fn expr_to_index_const( then_expr, else_expr, } => Some(ConstExpr::Mux { - condition: Box::new(expr_to_index_const(state, *condition, dimensions)?), - then_expr: Box::new(expr_to_index_const(state, *then_expr, dimensions)?), - else_expr: Box::new(expr_to_index_const(state, *else_expr, dimensions)?), + condition: Box::new(expr_to_index_const(tree, *condition, dimensions)?), + then_expr: Box::new(expr_to_index_const(tree, *then_expr, dimensions)?), + else_expr: Box::new(expr_to_index_const(tree, *else_expr, dimensions)?), }), Expr::Call { callee, @@ -694,7 +697,7 @@ pub(super) fn expr_to_index_const( state, callee, args.into_iter() - .map(|arg| expr_to_index_const(state, arg?, dimensions)) + .map(|arg| expr_to_index_const(tree, arg?, dimensions)) .collect::>()?, )) } @@ -704,8 +707,8 @@ pub(super) fn expr_to_index_const( lsb, signed: false, } => { - let msb = eval_ast_const_expr(state, &msb, &dimensions.const_env)?; - let lsb = eval_ast_const_expr(state, &lsb, &dimensions.const_env)?; + let msb = eval_ast_const_expr(functions, &msb, &dimensions.const_env)?; + let lsb = eval_ast_const_expr(functions, &lsb, &dimensions.const_env)?; let width = usize::try_from(msb.abs_diff(lsb).checked_add(1)?).ok()?; if width > constant_folding::MAX_CONSTANT_CONCAT_BITS { return None; @@ -726,13 +729,13 @@ pub(super) fn expr_to_index_const( if inlining::calls_subroutine(&expr) { return None; } - let source = IndexBitSource::from_expr(state, expr, dimensions)?; + let source = IndexBitSource::from_expr(tree, expr, dimensions)?; positions .map(|bit| source.bit(bit)) .collect::>()? } expr => { - let expr = expr_to_index_const(state, expr, dimensions)?; + let expr = expr_to_index_const(tree, expr, dimensions)?; positions .map(|bit| ConstExpr::Select { expr: Box::new(expr.clone()), @@ -749,7 +752,7 @@ pub(super) fn expr_to_index_const( if inlining::calls_subroutine(&expr) { return None; } - let source = IndexBitSource::from_expr(state, expr, dimensions)?; + let source = IndexBitSource::from_expr(tree, expr, dimensions)?; let width = source.width(); if width > constant_folding::MAX_CONSTANT_CONCAT_BITS { return None; @@ -830,18 +833,23 @@ enum IndexBitSource { } impl IndexBitSource { - fn from_expr(state: &AnalysisState, expr: Expr, dimensions: &PackedDimensions) -> Option { - let width = expr_static_width(state, &expr, dimensions)?; + fn from_expr( + tree: &AnalysisContext<'_>, + expr: Expr, + dimensions: &PackedDimensions, + ) -> Option { + let functions = &tree.functions; + let width = expr_static_width(tree, &expr, dimensions)?; Some(match expr { Expr::Concat(parts) => Self::Concat { parts: parts .into_iter() - .map(|part| Self::from_expr(state, part, dimensions)) + .map(|part| Self::from_expr(tree, part, dimensions)) .collect::>()?, width, }, Expr::RepeatConcat { parts, .. } => Self::Repeat { - part: Box::new(Self::from_expr(state, Expr::Concat(parts), dimensions)?), + part: Box::new(Self::from_expr(tree, Expr::Concat(parts), dimensions)?), width, }, Expr::Resize { expr, .. } => { @@ -852,7 +860,7 @@ impl IndexBitSource { &dimensions.function_return_types, )?; Self::Resize { - part: Box::new(Self::from_expr(state, *expr, dimensions)?), + part: Box::new(Self::from_expr(tree, *expr, dimensions)?), width, extend_signed, } @@ -865,10 +873,10 @@ impl IndexBitSource { } => { match *expr { expr @ (Expr::Concat(_) | Expr::RepeatConcat { .. }) => { - let left = eval_ast_const_expr(state, &msb, &dimensions.const_env)?; - let right = eval_ast_const_expr(state, &lsb, &dimensions.const_env)?; + let left = eval_ast_const_expr(functions, &msb, &dimensions.const_env)?; + let right = eval_ast_const_expr(functions, &lsb, &dimensions.const_env)?; Self::Slice { - part: Box::new(Self::from_expr(state, expr, dimensions)?), + part: Box::new(Self::from_expr(tree, expr, dimensions)?), width, right, step: if left >= right { 1 } else { -1 }, @@ -878,7 +886,7 @@ impl IndexBitSource { // The selected value has [width-1:0] coordinates even // when its position in an unpacked array is dynamic. expr: expr_to_index_const( - state, + tree, Expr::Select { expr: Box::new(expr), msb, @@ -900,14 +908,15 @@ impl IndexBitSource { && !variable.packed[0].normalize_single { let range = &variable.packed[0]; - let left = eval_ast_const_expr(state, &range.left, &dimensions.const_env)?; - let right = eval_ast_const_expr(state, &range.right, &dimensions.const_env)?; + let left = eval_ast_const_expr(functions, &range.left, &dimensions.const_env)?; + let right = + eval_ast_const_expr(functions, &range.right, &dimensions.const_env)?; (right, if left >= right { 1 } else { -1 }) } else { (0, 1) }; Self::Scalar { - expr: expr_to_index_const(state, expr, dimensions)?, + expr: expr_to_index_const(tree, expr, dimensions)?, width, right, step, @@ -975,10 +984,12 @@ mod tests; /// Preserve constant-call resolution/default/result-type semantics independently /// of the syntax adapter that supplied the call and its actual values. pub(super) fn user_call_value( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expression: Expr, constants: &HashMap, ) -> Option { + let state = &*tree.state; + let functions = &tree.functions; if let Expr::Call { args, arg_order, .. } = &expression @@ -986,11 +997,7 @@ pub(super) fn user_call_value( { // Effectful runtime named calls keep their source order. Constant calls // are folded only when their bodies and actuals evaluate successfully. - let literal = const_functions::eval_expression_literal( - &state.const_functions, - &expression, - constants, - )?; + let literal = const_functions::eval_expression_literal(functions, &expression, constants)?; let Expr::Call { callee, args, .. } = &expression else { unreachable!() }; @@ -998,13 +1005,11 @@ pub(super) fn user_call_value( .into_iter() .map(|(name, ty)| (name, (ty.width, ty.signed))) .collect(); - let args = const_functions::resolved_arguments(&state.const_functions, callee, args)? + let args = const_functions::resolved_arguments(functions, callee, args)? .into_iter() .map(|arg| { expr_to_const(state, arg.clone()).or_else(|| { - constant_folding::constant_with_folded_selections( - state, &arg, constants, &types, - ) + constant_folding::constant_with_folded_selections(tree, &arg, constants, &types) }) }) .collect::>>()?; @@ -1037,9 +1042,7 @@ pub(super) fn user_call_value( .map(|arg| { let arg = arg?; expr_to_const(state, arg.clone()).or_else(|| { - constant_folding::constant_with_folded_selections( - state, &arg, constants, &types, - ) + constant_folding::constant_with_folded_selections(tree, &arg, constants, &types) }) }) .collect::>>()?; @@ -1051,10 +1054,11 @@ pub(super) fn user_call_value( // Counting each stream segment separately keeps parameter dependencies symbolic // and preserves the selected width, including when zero bits are counted. pub(super) fn countbits_constant_call( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expression: Expr, const_env: &HashMap, ) -> Option { + let state = &*tree.state; let Expr::Call { args, .. } = expression else { return None; }; @@ -1070,15 +1074,17 @@ pub(super) fn countbits_constant_call( control => expr_to_const(state, control), }) .collect::>>()?; - countbits_constant_operand(state, operand, &controls, const_env) + countbits_constant_operand(tree, operand, &controls, const_env) } fn countbits_constant_operand( - state: &AnalysisState, + tree: &AnalysisContext<'_>, operand: Expr, controls: &[ConstExpr], const_env: &HashMap, ) -> Option { + let state = &*tree.state; + let functions = &tree.functions; let call = |operand| { let mut args = Vec::with_capacity(controls.len() + 1); args.push(operand); @@ -1106,8 +1112,8 @@ fn countbits_constant_operand( }; match operand { Expr::Select { expr, msb, lsb, .. } if msb != lsb => { - let msb = usize::try_from(eval_ast_const_expr(state, &msb, const_env)?).ok()?; - let lsb = usize::try_from(eval_ast_const_expr(state, &lsb, const_env)?).ok()?; + let msb = usize::try_from(eval_ast_const_expr(functions, &msb, const_env)?).ok()?; + let lsb = usize::try_from(eval_ast_const_expr(functions, &lsb, const_env)?).ok()?; let width = msb.checked_sub(lsb)?.checked_add(1)?; if width > constant_folding::MAX_CONSTANT_CONCAT_BITS { return None; @@ -1124,15 +1130,15 @@ fn countbits_constant_operand( } Expr::Concat(parts) => sum(parts .into_iter() - .map(|part| countbits_constant_operand(state, part, controls, const_env)) + .map(|part| countbits_constant_operand(tree, part, controls, const_env)) .collect::>>()?), Expr::RepeatConcat { count, parts } => { - let count = eval_ast_const_expr(state, &count, const_env)?; + let count = eval_ast_const_expr(functions, &count, const_env)?; if count < 0 { return None; } let counted = - countbits_constant_operand(state, Expr::Concat(parts), controls, const_env)?; + countbits_constant_operand(tree, Expr::Concat(parts), controls, const_env)?; Some(ConstExpr::Binary { left: Box::new(counted), op: BinaryOp::Mul, diff --git a/crates/celox-sv-analyzer/src/ast/constants/tests.rs b/crates/celox-sv-analyzer/src/ast/constants/tests.rs index 9b838b227e9..6423dded4f6 100644 --- a/crates/celox-sv-analyzer/src/ast/constants/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/constants/tests.rs @@ -2,7 +2,8 @@ use super::*; use std::{fmt::Write, path::Path}; fn environment(count: usize) -> HashMap { - let state = &crate::ast::AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); let mut parameter = Parameter::new( "P".into(), Some(parameters::const_expr_from_i128(-2)), @@ -16,7 +17,7 @@ fn environment(count: usize) -> HashMap { ConstExpr::Literal("7".into()), ConstExpr::Literal("0".into()), )); - let mut env = const_env_from_parameters(state, &[parameter]); + let mut env = const_env_from_parameters(&tree, &[parameter]); env.insert("W".into(), 3); env.insert("Q".into(), 9); for i in 0..count { @@ -180,5 +181,8 @@ fn native_constant_calls_preserve_contextual_operand_shapes() { .width, 8 ); - assert_eq!(eval_ast_const_expr(&tree.state, &args[2], &env), Some(8)); + assert_eq!( + eval_ast_const_expr(&tree.functions, &args[2], &env), + Some(8) + ); } diff --git a/crates/celox-sv-analyzer/src/ast/containers.rs b/crates/celox-sv-analyzer/src/ast/containers.rs index 7f207c837ff..c8999a181a0 100644 --- a/crates/celox-sv-analyzer/src/ast/containers.rs +++ b/crates/celox-sv-analyzer/src/ast/containers.rs @@ -22,7 +22,7 @@ pub(super) fn with_dimensions( None => 0, Some(id) => { let bound = constant_binding::bind(id, tree, context)? - .and_then(|v| eval_ast_const_expr(&tree.state, &v, &context.const_env)) + .and_then(|v| eval_ast_const_expr(&tree.functions, &v, &context.const_env)) .and_then(|v| u32::try_from(v).ok()) .filter(|v| *v > 0 && *v < u32::MAX) .ok_or_else(|| { @@ -55,8 +55,9 @@ pub(super) fn with_dimensions( index_type = Some(ty.clone()); let string = ty.kind() == TypeKind::String; let object = ty.kind() == TypeKind::Object && ty.container.is_none(); - let shape = casts::expr_type_from_type(&tree.state, &ty, &context.const_env) - .ok_or_else(|| unsupported("associative index type"))?; + let shape = + casts::expr_type_from_type(&tree.functions, &ty, &context.const_env) + .ok_or_else(|| unsupported("associative index type"))?; // A process handle is an identity that the simulation // keeps until it ends, so it serves as an integral key // whose entry outlives the process (IEEE 1800-2023 7.8.5, @@ -106,10 +107,12 @@ pub(super) fn with_dimensions( if matches!(base.kind(), TypeKind::Real | TypeKind::Shortreal) { return Err(unsupported("real dynamic container elements")); } - let shape = casts::expr_type_from_type(&tree.state, &base, &context.const_env) + let shape = casts::expr_type_from_type(&tree.functions, &base, &context.const_env) .ok_or_else(|| unsupported("dynamic container element type"))?; let record = match base.unpacked_struct() { - Some(aggregate) => unpacked_structs::record(&tree.state, aggregate, &context.const_env)?, + Some(aggregate) => { + unpacked_structs::record(&tree.functions, aggregate, &context.const_env)? + } // An integral element wider than a container word is held in a // record of one field, like a structure element. None if shape.width > 64 @@ -119,7 +122,7 @@ pub(super) fn with_dimensions( TypeKind::Bit | TypeKind::Logic | TypeKind::Reg | TypeKind::Implicit ) => { - let mut field = classes::field(&tree.state, &base, &context.const_env, 0)?; + let mut field = classes::field(&tree.functions, &base, &context.const_env, 0)?; // A missing element reads as the default of its type. field.nullable = true; Some(crate::system_functions::Record { @@ -882,7 +885,7 @@ fn query( let dimension = match arguments.get(1).and_then(|a| a.value) { None => 1, Some(id) => constant_binding::bind(id, tree, dims)? - .and_then(|v| eval_ast_const_expr(&tree.state, &v, &dims.const_env)) + .and_then(|v| eval_ast_const_expr(&tree.functions, &v, &dims.const_env)) .ok_or_else(|| unsupported("nonconstant dynamic array query dimension"))?, }; if dimension != 1 { @@ -1421,7 +1424,7 @@ pub(super) fn element_member( if member.is_tagged() { return Err(unsupported("tagged union member of a container element")); } - let width = casts::expr_type_from_type(&tree.state, member.r#type(), &dims.const_env) + let width = casts::expr_type_from_type(&tree.functions, member.r#type(), &dims.const_env) .ok_or_else(|| unsupported("structure member width"))? .width; value = Expr::Select { diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index 9101e821062..6221d7723d0 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -82,7 +82,7 @@ pub(super) fn ports_from_scope( &dimensions, )?; let value = fold_const_integral_expr_preserving_mask( - &syntax_tree.state, + syntax_tree, expression, const_env, ); @@ -293,7 +293,7 @@ pub(super) fn signals_from_scope_with_declaration_ranges( item.env.remove(&local_parameter_marker(&name)); } } - let _constant_functions = item.enter(); + let syntax_tree = &item.enter(syntax_tree); let start = signals.len(); signals_from_body_item( item.id, diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index 78ed39a5a97..0dea117df2c 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -35,13 +35,13 @@ fn extend_interface_dimensions(tree: &AnalysisContext<'_>, dimensions: &mut Pack } pub(super) fn bound_bits_type( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expression: &Expr, dimensions: &PackedDimensions, ) -> Option { bound_query_type( expression, - expr_static_width(state, expression, dimensions)?, + expr_static_width(tree, expression, dimensions)?, dimensions, &dimensions.const_env, ) @@ -438,7 +438,7 @@ fn variable_type_is_signed(const_env: &HashMap, name: &str) -> boo } pub(super) fn extend_const_env_with_variable_types<'a>( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, const_env: &mut HashMap, variables: impl Iterator, ) { @@ -465,7 +465,7 @@ pub(super) fn extend_const_env_with_variable_types<'a>( { for (bound, value) in [("left", left), ("right", right)] { let key = variable_dimension_marker(name, index, bound); - if let Some(value) = eval_ast_const_expr(state, value, const_env) { + if let Some(value) = eval_ast_const_expr(functions, value, const_env) { const_env.insert(key, value); } else { const_env.remove(&key); @@ -473,16 +473,16 @@ pub(super) fn extend_const_env_with_variable_types<'a>( } } let dimension_width = |range: &PackedRange| { - let left = eval_ast_const_expr(state, range.left(), const_env)?; - let right = eval_ast_const_expr(state, range.right(), const_env)?; + let left = eval_ast_const_expr(functions, range.left(), const_env)?; + let right = eval_ast_const_expr(functions, range.right(), const_env)?; usize::try_from(left.abs_diff(right)).ok()?.checked_add(1) }; let unpacked_widths = r#type .unpacked_ranges() .iter() .map(|range| { - let left = eval_ast_const_expr(state, range.left(), const_env)?; - let right = eval_ast_const_expr(state, range.right(), const_env)?; + let left = eval_ast_const_expr(functions, range.left(), const_env)?; + let right = eval_ast_const_expr(functions, range.right(), const_env)?; usize::try_from(left.abs_diff(right)).ok()?.checked_add(1) }) .collect::>>(); diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index 8cecf432a9a..0a9be7eef3a 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -254,7 +254,9 @@ fn parameter( if local && let Some(value) = default .and_then(|id| constant_binding::bind(id, tree, context).ok().flatten()) - .and_then(|value| eval_ast_const_expr(&tree.state, &value, &context.const_env)) + .and_then(|value| { + eval_ast_const_expr(&tree.functions, &value, &context.const_env) + }) { context.const_env.insert(n.clone(), value); } @@ -390,18 +392,19 @@ fn formal_types( Ok(result) } fn return_metadata( - state: &AnalysisState, + tree: &AnalysisContext<'_>, ty: Option<&Type>, arguments: Arc<[FunctionArgumentMetadata]>, context: &PackedDimensions, ) -> FunctionReturnMetadata { + let functions = &tree.functions; let widths = ty.map(|ty| { ty.packed_ranges() .iter() .map(|range| { usize::try_from( - eval_ast_const_expr(state, range.left(), &context.const_env)?.abs_diff( - eval_ast_const_expr(state, range.right(), &context.const_env)?, + eval_ast_const_expr(functions, range.left(), &context.const_env)?.abs_diff( + eval_ast_const_expr(functions, range.right(), &context.const_env)?, ), ) .ok()? @@ -410,7 +413,7 @@ fn return_metadata( .collect::>>() }); let width = ty - .and_then(|ty| expr_type_from_type(state, ty, &context.const_env)) + .and_then(|ty| expr_type_from_type(&tree.functions, ty, &context.const_env)) .map(|ty| ty.width); FunctionReturnMetadata { arguments: Some(arguments), @@ -447,7 +450,7 @@ fn return_metadata( .and_then(|ty| { ty.pattern_target(&const_functions::Environment { constants: &*context.const_env, - functions: &state.const_functions, + functions, }) }), } @@ -912,7 +915,7 @@ fn publish_signature( Arc::make_mut(&mut context.subroutine_param_names).insert(n.clone(), names); } if let Some(ty) = result { - let metadata = return_metadata(&tree.state, ty.as_ref(), arguments, context); + let metadata = return_metadata(tree, ty.as_ref(), arguments, context); if context.function_return_types.get(&n) != Some(&metadata) { context.function_return_types.insert(n, metadata); } @@ -1194,7 +1197,7 @@ pub(in crate::ast) fn query_operand_dimensions_id( let Some(declared) = declared else { continue; }; - let _functions = item.enter(); + let tree = &item.enter(tree); let tree = &item.scoped(tree); let mut signals = Vec::new(); declarations::signals_from_body_item( @@ -1232,13 +1235,13 @@ mod tests { }).unwrap() } fn width( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, shape: &VariableDimensions, context: &PackedDimensions, ) -> Option { shape.packed.iter().try_fold(1i128, |all, dimension| { all.checked_mul(eval_ast_const_expr( - state, + functions, &dimension.width, &context.const_env, )?) @@ -1257,7 +1260,7 @@ mod tests { ); let context = query_operand_dimensions_id(argument(&tree), &tree, &input).unwrap(); assert_eq!( - width(&tree.state, context.get("N").unwrap(), &context), + width(&tree.functions, context.get("N").unwrap(), &context), Some(4) ); assert!(!context.const_env.contains_key("N")); @@ -1294,9 +1297,13 @@ mod tests { PackedDimensions::new(HashMap::default(), &HashMap::default(), &HashMap::default()); let context = query_operand_dimensions_id(argument(&tree), &tree, &input).unwrap(); let shape = context.get("a").unwrap(); - assert_eq!(width(&tree.state, shape, &context), Some(3)); + assert_eq!(width(&tree.functions, shape, &context), Some(3)); assert_eq!( - eval_ast_const_expr(&tree.state, &shape.unpacked[0].width, &context.const_env), + eval_ast_const_expr( + &tree.functions, + &shape.unpacked[0].width, + &context.const_env + ), Some(2) ); } @@ -1310,7 +1317,7 @@ mod tests { query_operand_dimensions_id(argument(&tree), &tree, &PackedDimensions::default()) .unwrap(); assert_eq!( - width(&tree.state, context.get("ordinary").unwrap(), &context), + width(&tree.functions, context.get("ordinary").unwrap(), &context), Some(32) ); assert!(context.get("dyn").unwrap().container.is_some()); diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/queries.rs b/crates/celox-sv-analyzer/src/ast/dimensions/queries.rs index 03a261e9584..a3914e75ca2 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/queries.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/queries.rs @@ -2,12 +2,14 @@ use super::*; pub(super) fn bound_query( - state: &AnalysisState, + tree: &AnalysisContext<'_>, query: ArrayQuery, bounds: &[(i128, i128)], dimension: Option, context: &PackedDimensions, ) -> Option { + let state = &*tree.state; + let functions = &tree.functions; let integer = |value| Expr::Literal(format_typed_parameter_literal(value, 32, true)); let env = &context.const_env; let dimensions = Some(context); @@ -28,7 +30,7 @@ pub(super) fn bound_query( }; let dimension = dimension.unwrap_or_else(|| integer(1)); if let Some(index) = expr_to_const(state, dimension.clone()) - .and_then(|expr| eval_ast_const_expr(state, &expr, env)) + .and_then(|expr| eval_ast_const_expr(functions, &expr, env)) { return Some( usize::try_from(index) @@ -44,7 +46,7 @@ pub(super) fn bound_query( // the sign bit. The dimension appears once, preserving function effects. // Widen the index so a large dimension cannot wrap into a valid slot. let index_width = dimensions - .and_then(|context| expr_static_width(state, &dimension, context)) + .and_then(|context| expr_static_width(tree, &dimension, context)) .unwrap_or(32) .max(32) .checked_add(6)?; diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs index 9c20efb6a38..4d753b80597 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -154,7 +154,7 @@ pub(in crate::ast) fn query_value( .try_fold(1usize, |value, width| { value.checked_mul( usize::try_from(eval_ast_const_expr( - &tree.state, + &tree.functions, width, &context.const_env, )?) @@ -191,7 +191,7 @@ pub(in crate::ast) fn query_value( let index = dimension .map(|value| expr_to_const(&tree.state, value)) .unwrap_or_else(|| Some(ConstExpr::Literal("1".into()))) - .and_then(|value| eval_ast_const_expr(&tree.state, &value, &context.const_env)); + .and_then(|value| eval_ast_const_expr(&tree.functions, &value, &context.const_env)); let width = if let (Some(shape), Some(index)) = (&shape, index) { let index = usize::try_from(index).ok().and_then(|i| i.checked_sub(1)); if index == Some(0) @@ -209,7 +209,7 @@ pub(in crate::ast) fn query_value( .nth(index) }) .and_then(|width| { - eval_ast_const_expr(&tree.state, width, &context.const_env) + eval_ast_const_expr(&tree.functions, width, &context.const_env) }) } .or_else(|| { @@ -233,7 +233,7 @@ pub(in crate::ast) fn query_value( .chain(shape.packed.iter().map(|d| &d.width)) .next() .and_then(|width| { - eval_ast_const_expr(&tree.state, width, &context.const_env) + eval_ast_const_expr(&tree.functions, width, &context.const_env) })?; return Some(vec![(width - 1, 0)]); } @@ -244,14 +244,14 @@ pub(in crate::ast) fn query_value( .chain(shape.packed.iter().map(|d| (&d.left, &d.right))) .map(|(l, r)| { Some(( - eval_ast_const_expr(&tree.state, l, &context.const_env)?, - eval_ast_const_expr(&tree.state, r, &context.const_env)?, + eval_ast_const_expr(&tree.functions, l, &context.const_env)?, + eval_ast_const_expr(&tree.functions, r, &context.const_env)?, )) }) .collect::>>() }); bounds.and_then(|bounds| { - super::queries::bound_query(&tree.state, query, &bounds, dimension, &context) + super::queries::bound_query(tree, query, &bounds, dimension, &context) }) } _ => unreachable!(), @@ -319,7 +319,7 @@ fn interface_array_size( } let dimension = match dimension { Some(id) => constant_binding::bind(id, tree, context)? - .and_then(|value| eval_ast_const_expr(&tree.state, &value, &context.const_env)) + .and_then(|value| eval_ast_const_expr(&tree.functions, &value, &context.const_env)) .ok_or_else(|| unsupported("nonconstant interface array query dimension"))?, None => 1, }; @@ -518,7 +518,7 @@ fn validate_index( ) -> Converted<()> { let native = tree.declarations(); let value = expression_binding::bind(root, tree, context)?; - if expr_static_width(&tree.state, &value, context).is_none() { + if expr_static_width(tree, &value, context).is_none() { return Err(unsupported("query index type")); } let mut jobs = vec![root]; @@ -736,7 +736,7 @@ pub(in crate::ast) fn shape( let shape = if matches!(name.spelling.as_str(), "pop_front" | "pop_back") { procedural::dimensions_from_type(&container.element) } else { - let ty = bound_bits_type(&tree.state, &value, context) + let ty = bound_bits_type(tree, &value, context) .ok_or_else(|| unsupported("container method result type"))?; scalar(ty.width, ty.signed, ty.width > 1) }; @@ -873,7 +873,7 @@ pub(in crate::ast) fn shape( values.push(procedural::dimensions_from_type(&ty)); } else { let value = expression_binding::bind(id, tree, context)?; - let Some(ty) = bound_bits_type(&tree.state, &value, context) else { + let Some(ty) = bound_bits_type(tree, &value, context) else { return Ok(None); }; values.push(scalar(ty.width, ty.signed, true)); @@ -884,7 +884,7 @@ pub(in crate::ast) fn shape( return Ok(None); } let value = expression_binding::bind(id, tree, context)?; - let Some(ty) = bound_bits_type(&tree.state, &value, context) else { + let Some(ty) = bound_bits_type(tree, &value, context) else { return Ok(None); }; let mut shape = scalar( @@ -938,11 +938,11 @@ pub(in crate::ast) fn shape( constant_binding::bind(left, tree, context)? }; let right = constant_binding::bind(right, tree, context)? - .and_then(|v| eval_ast_const_expr(&tree.state, &v, &context.const_env)); + .and_then(|v| eval_ast_const_expr(&tree.functions, &v, &context.const_env)); let width = if indexed { right } else { - left.and_then(|v| eval_ast_const_expr(&tree.state, &v, &context.const_env)) + left.and_then(|v| eval_ast_const_expr(&tree.functions, &v, &context.const_env)) .zip(right) .and_then(|(l, r)| i128::try_from(l.abs_diff(r)).ok()?.checked_add(1)) }; @@ -1064,7 +1064,9 @@ mod tests { .map(|(root, _)| { let value = query_value(root, &tree, &context).unwrap().unwrap(); expr_to_const(&tree.state, value) - .and_then(|value| eval_ast_const_expr(&tree.state, &value, &context.const_env)) + .and_then(|value| { + eval_ast_const_expr(&tree.functions, &value, &context.const_env) + }) .unwrap() }) .collect::>(); diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs index fd58ce7fa52..90a1ed90e9b 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs @@ -41,7 +41,7 @@ fn query_number( .ok() .flatten() .and_then(|value| expr_to_const(&tree.state, value)) - .and_then(|value| eval_ast_const_expr(&tree.state, &value, env)) + .and_then(|value| eval_ast_const_expr(&tree.functions, &value, env)) .and_then(|value| usize::try_from(value).ok()) } @@ -133,13 +133,12 @@ fn function_result_queries_preserve_expression_bodies() { let tree = AnalysisContext::unspecialized(&tree); let source = Source::from_syntax(&tree).unwrap(); let module = &source.modules()[0]; - let env = const_env_from_parameters(&tree.state, module.parameters()); + let env = const_env_from_parameters(&tree, module.parameters()); let aliases = type_aliases_from_scope_with_env(&tree, &env).unwrap(); let mut dimensions = packed_dimensions_from_ports_and_signals(module.ports(), module.signals(), &env, &aliases); dimensions.extend(parameter_packed_dimensions(module.parameters())); - dimensions.parameter_values = - parameter_value_env(&tree.state, module.parameters(), &env).into(); + dimensions.parameter_values = parameter_value_env(&tree, module.parameters(), &env).into(); let functions = functions_from_scope(&tree, &env, &dimensions).unwrap(); assert!(functions["f"].body.is_some(), "{:?}", functions["f"]); } @@ -172,13 +171,12 @@ fn complete_scope_queries_match_syntax_discovery_without_rewalking_declarations( let tree = AnalysisContext::unspecialized(&tree); let source = Source::from_syntax(&tree).unwrap(); let module = &source.modules()[0]; - let env = const_env_from_parameters(&tree.state, module.parameters()); + let env = const_env_from_parameters(&tree, module.parameters()); let aliases = type_aliases_from_scope_with_env(&tree, &env).unwrap(); let mut dimensions = packed_dimensions_from_ports_and_signals(module.ports(), module.signals(), &env, &aliases); dimensions.extend(parameter_packed_dimensions(module.parameters())); - dimensions.parameter_values = - parameter_value_env(&tree.state, module.parameters(), &env).into(); + dimensions.parameter_values = parameter_value_env(&tree, module.parameters(), &env).into(); let functions = functions_from_scope(&tree, &env, &dimensions).unwrap(); dimensions .function_return_types @@ -329,7 +327,7 @@ fn local_values_shadow_outer_typedefs_in_completed_generate_scopes() { let tree = AnalysisContext::unspecialized(&tree); let source = Source::from_syntax(&tree).unwrap(); let module = &source.modules()[0]; - let env = const_env_from_parameters(&tree.state, module.parameters()); + let env = const_env_from_parameters(&tree, module.parameters()); let aliases = type_aliases_from_scope_with_env(&tree, &env).unwrap(); let dimensions = packed_dimensions_from_ports_and_signals( module.ports(), @@ -583,7 +581,11 @@ fn recursive_generate_dimension_discovery_uses_explicit_specialization() { query_context_for_operand(operand, context, &PackedDimensions::default()).unwrap(); let data = dimensions.get("g.data").unwrap(); assert_eq!( - eval_ast_const_expr(&context.state, &data.packed[0].width, &dimensions.const_env), + eval_ast_const_expr( + &context.functions, + &data.packed[0].width, + &dimensions.const_env + ), Some(expected), ); } diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 5827b531cf0..1acd7446106 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -67,15 +67,15 @@ pub(super) fn expression( // shape, or a selection aligned to the left. if streams::is_stream(root, native) { let receiver = match shape { - Some(shape) => streams::receiver(shape, &tree.state, dimensions)?, + Some(shape) => streams::receiver(shape, &tree.functions, dimensions)?, None => streams::selection_receiver( lhs, - lvalue_expr_type(&tree.state, lhs, dimensions) + lvalue_expr_type(&tree.functions, lhs, dimensions) .map(|ty| ty.width) .ok_or_else(|| { unsupported("streaming concatenation into a selection of unknown width") })?, - &tree.state, + &tree.functions, dimensions, ), }; @@ -156,7 +156,7 @@ mod tests { expression(root, &native, &lhs, &tree, &PackedDimensions::default()).unwrap(); assert_eq!( expr_to_const(&tree.state, value).and_then(|value| eval_ast_const_expr( - &tree.state, + &tree.functions, &value, &HashMap::default() )), diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 38fed5ecbfa..2ae02fbd929 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -199,7 +199,7 @@ pub(in crate::ast) fn cast_target_native( .and_then(|name| dimensions.type_aliases.get(name)) { ( - casts::expr_type_from_type(&tree.state, ty, &dimensions.const_env) + casts::expr_type_from_type(&tree.functions, ty, &dimensions.const_env) .ok_or_else(|| unsupported("cast target type"))?, false, ty.kind() == TypeKind::Bit, @@ -217,7 +217,7 @@ pub(in crate::ast) fn cast_target_native( let ty = type_binding::binding::bind_in(id, native, tree, dimensions)? .ok_or_else(|| unsupported("cast target type"))?; ( - casts::expr_type_from_type(&tree.state, &ty, &dimensions.const_env) + casts::expr_type_from_type(&tree.functions, &ty, &dimensions.const_env) .ok_or_else(|| unsupported("cast target type"))?, false, ty.kind() == TypeKind::Bit, @@ -225,7 +225,7 @@ pub(in crate::ast) fn cast_target_native( } else { let value = super::bind_value(target, native, tree, dimensions, None)?; let value = expr_to_const(&tree.state, value) - .and_then(|value| eval_ast_const_expr(&tree.state, &value, &dimensions.const_env)) + .and_then(|value| eval_ast_const_expr(&tree.functions, &value, &dimensions.const_env)) .and_then(|value| usize::try_from(value).ok()) .filter(|width| *width > 0) .ok_or_else(|| unsupported("cast target type"))?; @@ -429,7 +429,7 @@ pub(in crate::ast) fn bind_value( { let actual = if let ExprKind::Cast { target, .. } = native.expression(id).kind { cast_shape(target, native, tree, dimensions)? - .and_then(|shape| shape.pattern_type(&tree.state, dimensions)) + .and_then(|shape| shape.pattern_type(&tree.functions, dimensions)) } else { bound_patterns::native_value_type(id, tree, dimensions)? }; @@ -715,7 +715,7 @@ pub(in crate::ast) fn bind_value( || !shape.unpacked.is_empty() }) { - let receiver = streams::receiver(&shape, &tree.state, dimensions)?; + let receiver = streams::receiver(&shape, &tree.functions, dimensions)?; values.push(streams::pack( *expression, Some(receiver), @@ -1290,12 +1290,7 @@ pub(in crate::ast) fn bind_value( let selected = selected_value(id, native, tree, dimensions)?; let handle = bind_value(handle, native, tree, dimensions, None)?; values.push(virtual_interfaces::selected_read( - &tree.state, - handle, - &ty, - &member, - selected, - dimensions, + tree, handle, &ty, &member, selected, dimensions, )?); continue; } @@ -1371,7 +1366,7 @@ pub(in crate::ast) fn bind_value( "a streaming concatenation operand shall first be cast to a bit-stream type".into(), )); }; - let receiver = streams::receiver(shape, &tree.state, dimensions)?; + let receiver = streams::receiver(shape, &tree.functions, dimensions)?; values.push(streams::pack(id, Some(receiver), native, tree, dimensions)?); continue; } @@ -1415,7 +1410,7 @@ pub(in crate::ast) fn bind_value( let mut operands = values.split_off(start); let value = match finish { Finish::Tagged(plan) => { - packed_structs::construct(&tree.state, plan, operands.pop(), dimensions)? + packed_structs::construct(tree, plan, operands.pop(), dimensions)? } Finish::Unary(op) => { let operand = operands.pop().ok_or_else(disagreement)?; @@ -1507,7 +1502,7 @@ pub(in crate::ast) fn bind_value( } Finish::Bits => { let operand = operands.pop().ok_or_else(disagreement)?; - let ty = dimensions::bound_bits_type(&tree.state, &operand, dimensions) + let ty = dimensions::bound_bits_type(tree, &operand, dimensions) .ok_or_else(|| unsupported("operand of `$bits`"))?; Expr::Literal(ty.width.to_string()) } @@ -1541,14 +1536,7 @@ pub(in crate::ast) fn bind_value( count, } => { let count = count.then(|| operands.pop()).flatten(); - enums::call( - &tree.state, - method, - &domain, - operands.pop(), - count, - dimensions, - )? + enums::call(tree, method, &domain, operands.pop(), count, dimensions)? } Finish::StringCall(op) => { strings::call(op, strings::operands(op, operands, dimensions)) @@ -1611,7 +1599,7 @@ pub(in crate::ast) fn bind_value( Finish::VirtualMember(access) => { let (ty, member) = *access; let handle = operands.pop().ok_or_else(disagreement)?; - virtual_interfaces::read(&tree.state, handle, &ty, &member, dimensions, Ok)? + virtual_interfaces::read(tree, handle, &ty, &member, dimensions, Ok)? } Finish::MethodCall(call) => { let MethodCall { @@ -1658,19 +1646,16 @@ pub(in crate::ast) fn bind_value( } Finish::Cast(target) => { let operand = remove_real_division_guards( - guard_zero_divisions( - &tree.state, - operands.pop().ok_or_else(disagreement)?, - ), + guard_zero_divisions(tree, operands.pop().ok_or_else(disagreement)?), dimensions, ); if dimensions.constant_indexed_base { let operand = - selects::indexed_expression_value(&tree.state, operand, dimensions) + selects::indexed_expression_value(tree, operand, dimensions) .ok_or_else(|| unsupported("constant cast operand"))?; const_expr_to_expr( casts::cast_constant_target( - &tree.state, + tree, operand, target, &dimensions.const_env, @@ -1678,12 +1663,7 @@ pub(in crate::ast) fn bind_value( .ok_or_else(|| unsupported("constant cast operand"))?, ) } else { - casts::runtime_cast_target_expr( - &tree.state, - target, - operand, - dimensions, - )? + casts::runtime_cast_target_expr(tree, target, operand, dimensions)? } } Finish::Repeat @@ -1704,7 +1684,7 @@ pub(in crate::ast) fn bind_value( Finish::Repeat => { let count = operands.remove(0); let count = expr_to_const(&tree.state, count.clone()) - .or_else(|| expr_to_index_const(&tree.state, count, dimensions)) + .or_else(|| expr_to_index_const(tree, count, dimensions)) .ok_or_else(|| unsupported("replication count"))?; Expr::RepeatConcat { count, @@ -1761,7 +1741,7 @@ pub(in crate::ast) fn bind_value( "writable $fread destination", )); } - } else if expr_static_width(&tree.state, value, dimensions) + } else if expr_static_width(tree, value, dimensions) .is_none() { return Err(unsupported("integral $fread argument")); @@ -1806,8 +1786,7 @@ pub(in crate::ast) fn bind_value( ) && position >= 2 && real_value(arg, dimensions); if (!real_output - && expr_static_width(&tree.state, arg, dimensions) - .is_none()) + && expr_static_width(tree, arg, dimensions).is_none()) || args .get(position) .copied() @@ -1856,10 +1835,7 @@ pub(in crate::ast) fn bind_value( operands.insert(1, Expr::Literal("1".into())); } expressions::numeric_system_function( - &tree.state, - function, - operands, - dimensions, + tree, function, operands, dimensions, )? } } else { @@ -1894,7 +1870,7 @@ pub(in crate::ast) fn bind_value( return Err(disagreement()); } Ok(remove_real_division_guards( - guard_zero_divisions(&tree.state, values.pop().unwrap()), + guard_zero_divisions(tree, values.pop().unwrap()), dimensions, )) } @@ -1916,9 +1892,9 @@ fn index_value( 0, true, ); - if let Some(folded) = selects::indexed_expression_value(&tree.state, value.clone(), dimensions) + if let Some(folded) = selects::indexed_expression_value(tree, value.clone(), dimensions) && (matches!(folded, ConstExpr::Literal(_)) - || eval_ast_const_expr(&tree.state, &folded, &dimensions.const_env).is_some()) + || eval_ast_const_expr(&tree.functions, &folded, &dimensions.const_env).is_some()) { if matches!(&folded, ConstExpr::Literal(text) if real_value(&Expr::Literal(text.clone()), dimensions)) { @@ -1927,9 +1903,9 @@ fn index_value( return Ok(folded); } (if dimensions.constant_indexed_base { - selects::indexed_expression_value(&tree.state, value, dimensions) + selects::indexed_expression_value(tree, value, dimensions) } else { - expr_to_index_const(&tree.state, value, dimensions) + expr_to_index_const(tree, value, dimensions) }) .ok_or_else(|| unsupported("index expression")) } @@ -1946,7 +1922,7 @@ fn read_index_value( native.expression(ungroup(id, native)).kind, ExprKind::Conditional { .. } ) - && eval_ast_const_expr(&tree.state, &value, &dimensions.const_env).is_none() + && eval_ast_const_expr(&tree.functions, &value, &dimensions.const_env).is_none() && !inlining::calls_subroutine(&bind_value(id, native, tree, dimensions, None)?) { return Err(unsupported(format!( @@ -2011,7 +1987,7 @@ pub(super) fn path( unreachable!() }; let value = index_value(index, native, tree, dimensions)?; - let value = eval_ast_const_expr(&tree.state, &value, &dimensions.const_env) + let value = eval_ast_const_expr(&tree.functions, &value, &dimensions.const_env) .ok_or_else(|| unsupported("hierarchical index"))?; let (mut prefix, base) = path(*expression, native, tree, dimensions)?; let last = prefix.last_mut().ok_or_else(disagreement)?; @@ -2174,10 +2150,14 @@ fn selected_value( // `[N-1:0]` range declares. let zero_based = match ty.packed_ranges() { [range] => { - eval_ast_const_expr(&tree.state, range.right(), &dimensions.const_env) + eval_ast_const_expr(&tree.functions, range.right(), &dimensions.const_env) == Some(0) - && eval_ast_const_expr(&tree.state, range.left(), &dimensions.const_env) - .is_some_and(|left| left >= 0) + && eval_ast_const_expr( + &tree.functions, + range.left(), + &dimensions.const_env, + ) + .is_some_and(|left| left >= 0) } _ => false, }; @@ -2214,7 +2194,7 @@ fn selected_value( }), _ => return Err(unsupported("concatenation select")), }; - return selects::aggregate_selection_value(&tree.state, expr, selection, dimensions); + return selects::aggregate_selection_value(tree, expr, selection, dimensions); } let (parts, qualified) = path(base, native, tree, dimensions)?; if dimensions.constant_indexed_base && parts.len() == 1 { @@ -2252,9 +2232,9 @@ fn selected_value( } } return if let Some(range) = range { - selects::indexed_parameter_range(&tree.state, name, indices, range, dimensions) + selects::indexed_parameter_range(tree, name, indices, range, dimensions) } else { - selects::indexed_parameter_indices(&tree.state, name, indices, dimensions) + selects::indexed_parameter_indices(tree, name, indices, dimensions) }; } for dimension in &suffix { @@ -2268,7 +2248,7 @@ fn selected_value( } } let value = expr_from_lvalue( - &tree.state, + tree, &selected_lvalue(root, native, tree, dimensions, false)?, dimensions, ); @@ -2280,7 +2260,7 @@ fn selected_value( let guards = member_context(root, native, tree, dimensions)? .map(|(guards, _)| guards) .unwrap_or_default(); - packed_structs::checked_value(guards, value, &tree.state, dimensions) + packed_structs::checked_value(guards, value, tree, dimensions) } pub(in crate::ast) fn selected_lvalue( @@ -2330,7 +2310,7 @@ pub(in crate::ast) fn selected_lvalue( ranged = !matches!(dimension, DimensionKind::Index(_)); match dimension { DimensionKind::Index(id) => indices.push(selects::self_determined_index( - &tree.state, + tree, index_value(*id, native, tree, context)?, context, )), @@ -2349,13 +2329,14 @@ pub(in crate::ast) fn selected_lvalue( let start = index_value(*base, native, tree, context)?; let width = index_value(*width, native, tree, context)?; let ((msb, lsb), dynamic) = if net { - let width = eval_ast_const_expr(&tree.state, &width, &context.const_env) - .ok_or_else(|| { - unsupported("indexed part-select width that is not constant") - })?; + let width = + eval_ast_const_expr(&tree.functions, &width, &context.const_env) + .ok_or_else(|| { + unsupported("indexed part-select width that is not constant") + })?; ( selects::indexed_select_bounds_values( - &tree.state, + tree, start, operator == "+:", width, @@ -2366,7 +2347,7 @@ pub(in crate::ast) fn selected_lvalue( ) } else { selects::indexed_range_values( - &tree.state, + tree, &name, start, width, @@ -2381,16 +2362,16 @@ pub(in crate::ast) fn selected_lvalue( } } if strict - && !selects::constant_packed_indices_in_range(&tree.state, &name, &indices, context) + && !selects::constant_packed_indices_in_range(&tree.functions, &name, &indices, context) { return Err(unsupported(format!( "constant select of `{name}` outside its declared range" ))); } if let Some((msb, lsb, dynamic)) = range { - selects::lvalue_from_range(&tree.state, name, indices, msb, lsb, dynamic, context) + selects::lvalue_from_range(tree, name, indices, msb, lsb, dynamic, context) } else { - selects::lvalue_from_indices(&tree.state, name, indices, context) + selects::lvalue_from_indices(tree, name, indices, context) } }; let lvalue = if parts.len() > 1 { @@ -2695,7 +2676,7 @@ fn check_tagged_copyout( }; if actual.tagged_identity().is_some() && formal - .and_then(|shape| shape.pattern_type(&tree.state, dims)) + .and_then(|shape| shape.pattern_type(&tree.functions, dims)) .as_ref() != Some(&actual) { @@ -2746,8 +2727,8 @@ fn zero_based_vector( ) -> bool { let zero_based = match r#type.packed_ranges() { [range] => { - eval_ast_const_expr(&tree.state, range.right(), &dimensions.const_env) == Some(0) - && eval_ast_const_expr(&tree.state, range.left(), &dimensions.const_env) + eval_ast_const_expr(&tree.functions, range.right(), &dimensions.const_env) == Some(0) + && eval_ast_const_expr(&tree.functions, range.left(), &dimensions.const_env) .is_some_and(|left| left >= 0) } _ => false, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs index 626108e11ef..813de9312be 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs @@ -339,13 +339,15 @@ fn element( /// The value of `method` of `domain` called on `receiver` with `count`. pub(super) fn call( - state: &AnalysisState, + tree: &AnalysisContext<'_>, method: Method, domain: &EnumDomain, receiver: Option, count: Option, dimensions: &PackedDimensions, ) -> Converted { + let state = &*tree.state; + let functions = &tree.functions; let members = &domain.members; let member = |index: usize| { Expr::Literal(format_typed_parameter_literal( @@ -399,7 +401,7 @@ pub(super) fn call( // extended by its own signedness; the type is 2-state, so unknown // bits become 0. let count = casts::runtime_cast_target_expr( - state, + tree, casts::RuntimeCastTarget::Integral { target: ExprType { width: 32, @@ -412,7 +414,7 @@ pub(super) fn call( dimensions, )?; let constant = expr_to_const(state, count.clone()) - .and_then(|count| eval_ast_const_expr(state, &count, &dimensions.const_env)) + .and_then(|count| eval_ast_const_expr(functions, &count, &dimensions.const_env)) .map(|count| (count as u32 as usize) % count_members); if let Some(shift) = constant { let shift = if method == Method::Next { 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 d701bb61172..0b4a5027ef1 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -1419,7 +1419,7 @@ pub(super) fn randomize_with( )); } let value = Expr::Ident(name); - let width = expr_static_width(&tree.state, &value, dimensions) + let width = expr_static_width(tree, &value, dimensions) .filter(|width| (1..=64).contains(width)) .ok_or_else(|| unsupported("inline input width"))?; let mut ty = classes::unsigned_type(width); diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs index 6f3ab3072c9..51f6273d0ed 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs @@ -158,8 +158,7 @@ pub(super) fn check_actual( "ref argument of `{name}` binding queues with different bounds" ))); } - if formal.is_some_and(|formal| !equivalent(&tree.state, formal, &shape, &dimensions.const_env)) - { + if formal.is_some_and(|formal| !equivalent(tree, formal, &shape, &dimensions.const_env)) { return Err(invalid( "the actual's type is not equivalent to the formal's (IEEE 1800-2023 6.22.2)", )); @@ -192,15 +191,16 @@ fn property_shape( /// only with the same structure type; a virtual interface only with one of /// the same interface and modport (25.9), not with its number. fn equivalent( - state: &AnalysisState, + tree: &AnalysisContext<'_>, a: &VariableDimensions, b: &VariableDimensions, env: &HashMap, ) -> bool { + let functions = &tree.functions; if a.virtual_interface != b.virtual_interface { return false; } - let count = |width: &ConstExpr| eval_ast_const_expr(state, width, env); + let count = |width: &ConstExpr| eval_ast_const_expr(functions, width, env); match (&a.container, &b.container) { (None, None) => {} (Some(a), Some(b)) => { @@ -211,7 +211,7 @@ fn equivalent( (ContainerKind::Associative { .. }, ContainerKind::Associative { .. }) => { match (&a.key, &b.key) { (Some(x), Some(y)) => equivalent( - state, + tree, &procedural::dimensions_from_type(x), &procedural::dimensions_from_type(y), env, @@ -224,7 +224,7 @@ fn equivalent( }; return same_kind && equivalent( - state, + tree, &procedural::dimensions_from_type(&a.element), &procedural::dimensions_from_type(&b.element), env, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/selected.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/selected.rs index d2ce6e2c29a..fff3c622339 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/selected.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/selected.rs @@ -164,11 +164,11 @@ mod range_tests { panic!() }; assert_eq!( - eval_ast_const_expr(&tree.state, &msb, &HashMap::default()), + eval_ast_const_expr(&tree.functions, &msb, &HashMap::default()), Some(high) ); assert_eq!( - eval_ast_const_expr(&tree.state, &lsb, &HashMap::default()), + eval_ast_const_expr(&tree.functions, &lsb, &HashMap::default()), Some(low) ); } diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/streams.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/streams.rs index a25122b1af2..317d99915df 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/streams.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/streams.rs @@ -42,7 +42,7 @@ fn constant( what: &str, ) -> Converted { constant_binding::bind(id, tree, dims)? - .and_then(|value| eval_ast_const_expr(&tree.state, &value, &dims.const_env)) + .and_then(|value| eval_ast_const_expr(&tree.functions, &value, &dims.const_env)) .ok_or_else(|| { unsupported(format!( "streaming concatenation {what} that is not constant" @@ -65,7 +65,7 @@ fn slice_size( .and_then(|name| dims.type_aliases.get(&name).cloned()), }; if let Some(ty) = ty { - return casts::expr_type_from_type(&tree.state, &ty, &dims.const_env) + return casts::expr_type_from_type(&tree.functions, &ty, &dims.const_env) .map(|ty| ty.width) .filter(|width| *width > 0) .ok_or_else(|| unsupported("streaming concatenation slice type of unknown width")); @@ -81,13 +81,13 @@ fn slice_size( /// their number. fn fixed_array( shape: &VariableDimensions, - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, dims: &PackedDimensions, ) -> Converted> { if shape.unpacked.is_empty() { return Ok(None); } - let array = array_compatibility::unpacked_array_type(state, shape, dims) + let array = array_compatibility::unpacked_array_type(functions, shape, dims) .ok_or_else(|| unsupported("streaming concatenation of an array of unknown size"))?; let count = array .dims @@ -154,7 +154,7 @@ fn stream_container(container: &ContainerType) -> Converted { /// The receiver of a variable of `shape` of bit-stream type. pub(in crate::ast) fn receiver( shape: &VariableDimensions, - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, dims: &PackedDimensions, ) -> Converted { if let Some(container) = &shape.container { @@ -176,14 +176,14 @@ pub(in crate::ast) fn receiver( "streaming concatenation into an unpacked structure", )); } - if let Some((element, count)) = fixed_array(shape, state, dims)? { + if let Some((element, count)) = fixed_array(shape, functions, dims)? { return Ok(Receiver::Fixed(StreamArg { width: element * count, bits: None, element: Some(element), })); } - patterns::shape_width(state, shape, dims) + patterns::shape_width(functions, shape, dims) .map(|width| Receiver::Fixed(StreamArg::packed(width))) .ok_or_else(|| unsupported("streaming concatenation into a variable of unknown width")) } @@ -194,7 +194,7 @@ pub(in crate::ast) fn receiver( pub(in crate::ast) fn selection_receiver( lhs: &LValue, width: usize, - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, dims: &PackedDimensions, ) -> Receiver { let element = match lhs { @@ -203,7 +203,7 @@ pub(in crate::ast) fn selection_receiver( .filter(|shape| !shape.unpacked.is_empty()) .and_then(|shape| { patterns::shape_width( - state, + functions, &VariableDimensions { unpacked: Vec::new(), ..shape.clone() @@ -384,7 +384,7 @@ fn operand( return Ok(vec![Item::Dynamic(StreamItem::String, vec![value])]); } let array = match &shape { - Some(shape) => fixed_array(shape, &tree.state, dims)?.map(|array| (array, shape)), + Some(shape) => fixed_array(shape, &tree.functions, dims)?.map(|array| (array, shape)), None => None, }; if let Expr::Concat(leaves) = &value @@ -414,7 +414,7 @@ fn operand( if range.is_some() { return Err(invalid("with applies to a one-dimensional unpacked array")); } - let width = expr_static_width(&tree.state, &value, dims) + let width = expr_static_width(tree, &value, dims) .filter(|width| *width > 0) .ok_or_else(|| unsupported("streaming concatenation operand of unknown width"))?; return Ok(vec![Item::Fixed(value, StreamArg::packed(width))]); @@ -434,7 +434,7 @@ fn operand( return Err(invalid("with applies to a one-dimensional unpacked array")); }; let bound = |expr| { - eval_ast_const_expr(&tree.state, expr, &dims.const_env) + eval_ast_const_expr(&tree.functions, expr, &dims.const_env) .ok_or_else(|| unsupported("streaming concatenation with an array of unknown bounds")) }; let bounds = (bound(&dimension.left)?, bound(&dimension.right)?); @@ -840,7 +840,7 @@ pub(in crate::ast) fn unpack( } let width = dims .get(leaf.name()) - .and_then(|shape| patterns::shape_width(&tree.state, shape, dims)) + .and_then(|shape| patterns::shape_width(&tree.functions, shape, dims)) .ok_or_else(|| unsupported("streaming concatenation unpack target"))?; takes.push(Take::Fixed(StreamArg::packed(width))); lvalues.push(leaf); @@ -852,7 +852,7 @@ pub(in crate::ast) fn unpack( "streaming concatenation into an unpacked structure member", )); } - let Receiver::Fixed(target) = receiver(&shape, &tree.state, dims)? else { + let Receiver::Fixed(target) = receiver(&shape, &tree.functions, dims)? else { unreachable!("a fixed-size variable receives fixed-size data"); }; takes.push(Take::Fixed(target)); diff --git a/crates/celox-sv-analyzer/src/ast/expressions.rs b/crates/celox-sv-analyzer/src/ast/expressions.rs index b69f6adfe7f..86932654c18 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -2,7 +2,9 @@ use super::*; -pub(super) fn guard_zero_divisions(state: &AnalysisState, expr: Expr) -> Expr { +pub(super) fn guard_zero_divisions(tree: &AnalysisContext<'_>, expr: Expr) -> Expr { + let state = &*tree.state; + let functions = &tree.functions; // Binding an enclosing expression can visit an already guarded operand. // Its children were guarded when it was constructed. Wrapping it again // loses the operation's type when the internal unknown arm is lowered. @@ -19,7 +21,7 @@ pub(super) fn guard_zero_divisions(state: &AnalysisState, expr: Expr) -> Expr { lsb, signed, } => Expr::Select { - expr: Box::new(guard_zero_divisions(state, *expr)), + expr: Box::new(guard_zero_divisions(tree, *expr)), msb, lsb, signed, @@ -27,14 +29,14 @@ pub(super) fn guard_zero_divisions(state: &AnalysisState, expr: Expr) -> Expr { Expr::Concat(parts) => Expr::Concat( parts .into_iter() - .map(|expr| guard_zero_divisions(state, expr)) + .map(|expr| guard_zero_divisions(tree, expr)) .collect(), ), Expr::RepeatConcat { count, parts } => Expr::RepeatConcat { count, parts: parts .into_iter() - .map(|expr| guard_zero_divisions(state, expr)) + .map(|expr| guard_zero_divisions(tree, expr)) .collect(), }, Expr::Resize { @@ -42,24 +44,24 @@ pub(super) fn guard_zero_divisions(state: &AnalysisState, expr: Expr) -> Expr { width, signed, } => Expr::Resize { - expr: Box::new(guard_zero_divisions(state, *expr)), + expr: Box::new(guard_zero_divisions(tree, *expr)), width, signed, }, Expr::Unary { op, expr } => Expr::Unary { op, - expr: Box::new(guard_zero_divisions(state, *expr)), + expr: Box::new(guard_zero_divisions(tree, *expr)), }, Expr::Binary { left, op, right } => { - let left = Box::new(guard_zero_divisions(state, *left)); - let right = Box::new(guard_zero_divisions(state, *right)); + let left = Box::new(guard_zero_divisions(tree, *left)); + let right = Box::new(guard_zero_divisions(tree, *right)); let operation = Expr::Binary { left, op, right: right.clone(), }; let divisor_is_nonzero = expr_to_const(state, (*right).clone()) - .and_then(|right| eval_ast_const_expr(state, &right, &HashMap::default())) + .and_then(|right| eval_ast_const_expr(functions, &right, &HashMap::default())) .is_some_and(|right| right != 0); if matches!(op, BinaryOp::Div | BinaryOp::Mod) && !divisor_is_nonzero { Expr::Mux { @@ -80,15 +82,15 @@ pub(super) fn guard_zero_divisions(state: &AnalysisState, expr: Expr) -> Expr { then_expr, else_expr, } => Expr::Mux { - condition: Box::new(guard_zero_divisions(state, *condition)), - then_expr: Box::new(guard_zero_divisions(state, *then_expr)), - else_expr: Box::new(guard_zero_divisions(state, *else_expr)), + condition: Box::new(guard_zero_divisions(tree, *condition)), + then_expr: Box::new(guard_zero_divisions(tree, *then_expr)), + else_expr: Box::new(guard_zero_divisions(tree, *else_expr)), }, Expr::Inside { expr, items } => Expr::Inside { - expr: Box::new(guard_zero_divisions(state, *expr)), + expr: Box::new(guard_zero_divisions(tree, *expr)), items: items .into_iter() - .map(|item| item.map(&mut |operand| guard_zero_divisions(state, operand))) + .map(|item| item.map(&mut |operand| guard_zero_divisions(tree, operand))) .collect(), }, Expr::Call { @@ -100,7 +102,7 @@ pub(super) fn guard_zero_divisions(state: &AnalysisState, expr: Expr) -> Expr { callee, args: args .into_iter() - .map(|arg| arg.map(|expr| guard_zero_divisions(state, expr))) + .map(|arg| arg.map(|expr| guard_zero_divisions(tree, expr))) .collect(), }, } @@ -122,17 +124,18 @@ pub(super) fn identifier_expression( /// Numeric system-function semantics for already-bound native arguments. pub(super) fn numeric_system_function( - state: &AnalysisState, + tree: &AnalysisContext<'_>, function: SystemFunction, mut arguments: Vec, dimensions: &PackedDimensions, ) -> Converted { + let state = &*tree.state; + let functions = &tree.functions; let operand_error = || unsupported(format!("operand of `{}`", function.name())); match function { SystemFunction::Signed | SystemFunction::Unsigned => { let argument = arguments.pop().ok_or_else(operand_error)?; - let width = - expr_static_width(state, &argument, dimensions).ok_or_else(operand_error)?; + let width = expr_static_width(tree, &argument, dimensions).ok_or_else(operand_error)?; Ok(Expr::Resize { expr: Box::new(argument), width, @@ -152,8 +155,7 @@ pub(super) fn numeric_system_function( arg_order: Vec::new(), }); } - let width = - expr_static_width(state, &argument, dimensions).ok_or_else(operand_error)?; + let width = expr_static_width(tree, &argument, dimensions).ok_or_else(operand_error)?; let signed = dimensions::expression_signedness(&argument, dimensions, &dimensions.const_env) .ok_or_else(operand_error)?; @@ -162,7 +164,8 @@ pub(super) fn numeric_system_function( if function == SystemFunction::Past && let Some(ticks) = arguments.get_mut(1) && let Some(constant) = expr_to_const(state, ticks.clone()) - && let Some(value) = eval_ast_const_expr(state, &constant, &dimensions.const_env) + && let Some(value) = + eval_ast_const_expr(functions, &constant, &dimensions.const_env) { *ticks = Expr::Literal(value.to_string()); } @@ -221,7 +224,7 @@ pub(super) fn numeric_system_function( && let [argument] = arguments.as_slice() && let Some(argument) = expr_to_const(state, argument.clone()) && let Some(value) = eval_ast_const_expr( - state, + functions, &ConstExpr::Function { callee: Callee::System(function), args: vec![argument], diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index 2f0f2765279..ae16e160777 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -17,7 +17,7 @@ pub(super) fn ff_processes_from_scope( let Some(procedure) = item.procedure(syntax_tree.declarations())? else { continue; }; - let _constant_functions = item.enter(); + let syntax_tree = &item.enter(syntax_tree); let start = processes.len(); let (dimensions, literals) = views.get(item); if let Some(process) = ff_process_from_procedure( @@ -87,12 +87,7 @@ fn ff_process_from_procedure( ); let mut body = builder.native_body(&[body], &procedure.authored_statements)?; for stmt in &mut body { - procedural::substitute_stmt_constants( - &syntax_tree.state, - stmt, - const_env, - parameter_literals, - ); + procedural::substitute_stmt_constants(syntax_tree, stmt, const_env, parameter_literals); } Ok((!events.is_empty()).then(|| { let mut process = FfProcess::new(events, body); diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index 14e26e94b48..b1f0839afde 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -60,7 +60,7 @@ pub(super) fn native_functions( for (item, id) in owners { let aliases = item.type_aliases(&dimensions.type_aliases); let tree = &item.scoped(tree); - let _constants = item.enter(); + let tree = &item.enter(tree); let mut signature_context = item.dimensions(dimensions); signature_context.const_env = item.env.clone(); signature_context.type_aliases = aliases.as_ref().clone().into(); @@ -203,7 +203,7 @@ fn native_signature( previous = ty.clone(); let expr_type = ty .as_ref() - .and_then(|ty| expr_type_from_type(&tree.state, ty, &context.const_env)); + .and_then(|ty| expr_type_from_type(&tree.functions, ty, &context.const_env)); params.push(FunctionParam { name: instances::normalize_identifier(&name.spelling), has_default: port.default.is_some(), @@ -224,11 +224,11 @@ fn native_signature( }; let result = ty .as_ref() - .and_then(|ty| expr_type_from_type(&tree.state, ty, &context.const_env)); + .and_then(|ty| expr_type_from_type(&tree.functions, ty, &context.const_env)); let first = match ty.as_ref().and_then(|ty| ty.packed_ranges().first()) { Some(range) => (|| { - let left = eval_ast_const_expr(&tree.state, &range.left, &context.const_env)?; - let right = eval_ast_const_expr(&tree.state, &range.right, &context.const_env)?; + let left = eval_ast_const_expr(&tree.functions, &range.left, &context.const_env)?; + let right = eval_ast_const_expr(&tree.functions, &range.right, &context.const_env)?; usize::try_from(left.abs_diff(right).checked_add(1)?).ok() })(), None => result.map(|ty| ty.width), @@ -274,7 +274,7 @@ fn native_signature( .and_then(|ty| { ty.pattern_target(&const_functions::Environment { constants: &*context.const_env, - functions: &tree.state.const_functions, + functions: &tree.functions, }) }), }) diff --git a/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs b/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs index 88aa54998a0..a11db6eb4f2 100644 --- a/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs +++ b/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs @@ -377,8 +377,9 @@ mod tests { } fn evaluate(expr: Expr, bindings: &HashMap) -> i128 { let expr = substitute_expr_idents(expr, bindings); + let syntax = crate::source_tree::SourceTree::empty(); let expr = expr_to_index_const( - &AnalysisState::default(), + &AnalysisContext::unspecialized(&syntax), expr, &PackedDimensions::default(), ) diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index f481e2bf5e0..869f075c312 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -60,7 +60,6 @@ fn scope_component(name: &str) -> String { #[derive(Clone)] pub(super) struct Item { - state: std::rc::Rc, /// The symbols the scope that elaborated the item imports. imported: Arc, pub id: celox_sv_syntax::BodyItemId, @@ -80,7 +79,6 @@ pub(super) struct Item { /// hold those declarations under their qualified names. #[derive(Clone, Copy)] struct BlockImports<'s> { - state: &'s std::rc::Rc, names: &'s HashMap, imports: &'s HashMap, /// The names the blocks declare or import. @@ -124,12 +122,14 @@ impl<'s> BlockImports<'s> { visible } - /// Make each imported name call the constant function of its - /// declaration, until the guard is dropped; a name that imports no - /// constant function calls none. Calls in the bodies of the functions it - /// hides keep their definition-site meaning. - fn install_constant_functions(self) -> Option { - let installed = const_functions::installed(&self.state.const_functions); + /// `installed` with each imported name calling the constant function of + /// its declaration, or `None` if no name rebinds one; a name that imports + /// no constant function calls none. Calls in the bodies of the functions + /// it hides keep their definition-site meaning. + fn visible_constant_functions( + self, + installed: &const_functions::ConstantFunctions, + ) -> Option { let rebound: Vec<_> = self .bindings() .filter(|(name, target)| installed.contains(name) || installed.contains(target)) @@ -148,7 +148,7 @@ impl<'s> BlockImports<'s> { for (name, target) in rebound { visible.alias(name, target); } - Some(const_functions::install(self.state, visible)) + Some(visible) } } @@ -185,7 +185,6 @@ impl Item { fn block_imports(&self) -> BlockImports<'_> { BlockImports { - state: &self.state, names: &self.names, imports: &self.imports, shadowed: &self.shadowed, @@ -209,10 +208,15 @@ impl Item { Cow::Owned(self.block_imports().type_aliases(&all).into_owned()) } - /// Make the constant functions this item sees the installed ones, until - /// the guard is dropped. - pub fn enter(&self) -> Option { - self.block_imports().install_constant_functions() + /// `tree` calling the constant functions this item sees. + pub fn enter<'a>(&self, tree: &AnalysisContext<'a>) -> AnalysisContext<'a> { + match self + .block_imports() + .visible_constant_functions(&tree.functions) + { + Some(functions) => tree.with_functions(functions), + None => tree.clone(), + } } pub fn scope_name(&self) -> &str { @@ -565,7 +569,6 @@ impl Scope { fn block_imports(&self) -> BlockImports<'_> { BlockImports { - state: &self.state, names: &self.names, imports: &self.imports, shadowed: &self.shadowed, @@ -574,7 +577,9 @@ impl Scope { } struct Elaborator<'a, 'b> { - tree: &'a AnalysisContext<'a>, + /// The context of the scope being elaborated, whose constant functions + /// change with the imports of each generate block. + tree: AnalysisContext<'a>, module_aliases: &'b HashMap, /// The type aliases of the scope being elaborated. aliases: Cow<'b, HashMap>, @@ -638,7 +643,7 @@ fn elaborate( literal_use: LiteralUse, ) -> Result, AnalyzerError> { let mut elaborator = Elaborator { - tree, + tree: tree.clone(), module_aliases: aliases, aliases: Cow::Borrowed(aliases), remaining: MAX_GENERATE_LOOP_EXPANSION, @@ -648,7 +653,7 @@ fn elaborate( let parameters = parameters_from_scope(tree, aliases, env, &tree.parameter_overrides)?; let references = parameter_literal_references(tree, literal_use)?; let mut literals = - parameters::parameter_value_env_for_references(&tree.state, ¶meters, env, &references); + parameters::parameter_value_env_for_references(tree, ¶meters, env, &references); if elaboration::needs_functions(tree)? { elaborator.functions = module_constant_functions(tree, env, aliases, &literals)?; } @@ -745,7 +750,7 @@ impl<'a> Elaborator<'a, '_> { let Some(expr) = constant_binding::expression( root, self.tree.declarations(), - self.tree, + &self.tree, &scope.env, &self.aliases, )? @@ -757,27 +762,28 @@ impl<'a> Elaborator<'a, '_> { ..PackedDimensions::default() }; let Some(mut expr) = expr_to_index_const( - &self.tree.state, + &self.tree, substitute_expr_idents(const_expr_to_expr(expr), &scope.literals), &dimensions, ) else { return Ok(None); }; Ok(self - .expand_constant_calls(&self.tree.state, &mut expr, scope) + .expand_constant_calls(&self.tree, &mut expr, scope) .map(|()| expr)) } fn expand_constant_calls( &self, - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: &mut ConstExpr, scope: &Scope, ) -> Option<()> { + let state = &*tree.state; match expr { ConstExpr::Function { callee, args, .. } => { for arg in args { - self.expand_constant_calls(state, arg, scope)?; + self.expand_constant_calls(tree, arg, scope)?; } // A block import binds the call to the qualified declaration, // which the installed constant functions evaluate. @@ -806,39 +812,39 @@ impl<'a> Elaborator<'a, '_> { 0, true, ); - let expanded = simplify_constant_mux_conditions(state, expanded, &scope.env); + let expanded = simplify_constant_mux_conditions(tree, expanded, &scope.env); // Fold only the call: surrounding case arithmetic still needs // the common comparison width, while function results are self-determined. *expr = expr_to_const( state, - fold_const_integral_expr_preserving_mask(state, expanded, &scope.env), + fold_const_integral_expr_preserving_mask(tree, expanded, &scope.env), )?; } } ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => { - self.expand_constant_calls(state, expr, scope)? + self.expand_constant_calls(tree, expr, scope)? } ConstExpr::SelectRange { expr, msb, lsb, .. } => { - self.expand_constant_calls(state, expr, scope)?; - self.expand_constant_calls(state, msb, scope)?; - self.expand_constant_calls(state, lsb, scope)?; + self.expand_constant_calls(tree, expr, scope)?; + self.expand_constant_calls(tree, msb, scope)?; + self.expand_constant_calls(tree, lsb, scope)?; } ConstExpr::Select { expr, bit } => { - self.expand_constant_calls(state, expr, scope)?; - self.expand_constant_calls(state, bit, scope)?; + self.expand_constant_calls(tree, expr, scope)?; + self.expand_constant_calls(tree, bit, scope)?; } ConstExpr::Binary { left, right, .. } => { - self.expand_constant_calls(state, left, scope)?; - self.expand_constant_calls(state, right, scope)?; + self.expand_constant_calls(tree, left, scope)?; + self.expand_constant_calls(tree, right, scope)?; } ConstExpr::Mux { condition, then_expr, else_expr, } => { - self.expand_constant_calls(state, condition, scope)?; - self.expand_constant_calls(state, then_expr, scope)?; - self.expand_constant_calls(state, else_expr, scope)?; + self.expand_constant_calls(tree, condition, scope)?; + self.expand_constant_calls(tree, then_expr, scope)?; + self.expand_constant_calls(tree, else_expr, scope)?; } ConstExpr::Ident(_) | ConstExpr::Literal(_) => {} } @@ -847,7 +853,7 @@ impl<'a> Elaborator<'a, '_> { fn value(&self, root: ExprId, scope: &Scope, detail: &str) -> Result { self.expression(root, scope)? - .and_then(|expr| eval_ast_const_expr(&self.tree.state, &expr, &scope.env)) + .and_then(|expr| eval_ast_const_expr(&self.tree.functions, &expr, &scope.env)) .ok_or_else(|| AnalyzerError::Unsupported(detail.to_string())) } @@ -869,7 +875,7 @@ impl<'a> Elaborator<'a, '_> { &expr, &const_functions::Environment { constants: &*scope.env, - functions: &self.tree.state.const_functions, + functions: &self.tree.functions, }, &|name| types.get(name).copied(), ) @@ -881,8 +887,7 @@ impl<'a> Elaborator<'a, '_> { fn push(&mut self, id: celox_sv_syntax::BodyItemId, scope: &Scope) { self.items.push(Item { - state: self.tree.state.clone(), - imported: scope::imported(self.tree), + imported: scope::imported(&self.tree), id, env: scope.env.clone(), literals: scope.literals.clone(), @@ -1060,7 +1065,7 @@ impl<'a> Elaborator<'a, '_> { let mut signals = Vec::new(); signals_from_body_item( id, - self.tree, + &self.tree, &self.aliases, &scope.env, Some(&name), @@ -1081,7 +1086,8 @@ impl<'a> Elaborator<'a, '_> { ) { if parameters::contains_unbounded_operand(bound, &scope.env) - && eval_ast_const_expr(&self.tree.state, bound, &scope.env).is_none() + && eval_ast_const_expr(&self.tree.functions, bound, &scope.env) + .is_none() { return Err(AnalyzerError::Unsupported( "numeric use of unbounded parameter in generate signal range" @@ -1091,7 +1097,7 @@ impl<'a> Elaborator<'a, '_> { } } extend_const_env_with_variable_types( - &self.tree.state, + &self.tree.functions, &mut scope.env, signals .iter() @@ -1108,7 +1114,7 @@ impl<'a> Elaborator<'a, '_> { // bind siblings. Either ends this run before rebuilding it. let base = scope.env.clone(); let mut environment = parameters::ParameterEnvironment::new( - self.tree, + &self.tree, &scope.parameters, &base, &pending @@ -1125,8 +1131,8 @@ impl<'a> Elaborator<'a, '_> { .expect("ready parameter is unbound"); let inherited_count = scope.parameters.len(); parameters::parameters_from_native_with_environment( - ¶meters::ownership::body(id, self.tree)?, - self.tree, + ¶meters::ownership::body(id, &self.tree)?, + &self.tree, &mut scope.parameters, true, &base, @@ -1145,7 +1151,7 @@ impl<'a> Elaborator<'a, '_> { )) })?; constants::bind_generate_parameter_with_types( - &self.tree.state, + &self.tree, parameter, &mut scope.env, &mut scope.literals, @@ -1175,8 +1181,8 @@ impl<'a> Elaborator<'a, '_> { // this scheduled parameter, without cloning the inherited prefix. let inherited_count = scope.parameters.len(); parameters::parameters_from_native( - ¶meters::ownership::body(id, self.tree)?, - self.tree, + ¶meters::ownership::body(id, &self.tree)?, + &self.tree, &mut scope.parameters, true, &scope.env, @@ -1191,12 +1197,7 @@ impl<'a> Elaborator<'a, '_> { AnalyzerError::Unsupported(format!("generate-local parameter `{name}`")) })?; scope.parameters.push(parameter.clone()); - bind_generate_parameter( - &self.tree.state, - parameter, - &mut scope.env, - &mut scope.literals, - ); + bind_generate_parameter(&self.tree, parameter, &mut scope.env, &mut scope.literals); } order.complete(index); } @@ -1262,14 +1263,14 @@ impl<'a> Elaborator<'a, '_> { } } let mut aliases = types::type_aliases_of_generate_scope( - self.tree, + &self.tree, children, &scope.env, &self.aliases, &scope.path, )?; let enums = parameters::enum_member_constants_from_items( - self.tree, + &self.tree, children, &scope.env, &aliases, @@ -1291,8 +1292,8 @@ impl<'a> Elaborator<'a, '_> { // another loop iteration shadows the names in their bounds. let ty = procedural::scoped_type(ty, &scope.env); if ty.packed_ranges().iter().any(|range| { - eval_ast_const_expr(&self.tree.state, range.left(), &scope.env).is_none() - || eval_ast_const_expr(&self.tree.state, range.right(), &scope.env) + eval_ast_const_expr(&self.tree.functions, range.left(), &scope.env).is_none() + || eval_ast_const_expr(&self.tree.functions, range.right(), &scope.env) .is_none() }) { return Err(unsupported(format!( @@ -1350,7 +1351,7 @@ impl<'a> Elaborator<'a, '_> { let mut signals = Vec::new(); signals_from_body_item( *id, - self.tree, + &self.tree, &self.aliases, &scope.env, None, @@ -1474,7 +1475,6 @@ fn module_constant_functions( _ => {} } roots.push(Item { - state: tree.state.clone(), imported: scope::imported(tree), id, env: env.clone().into(), @@ -1754,7 +1754,8 @@ mod tests { #[test] fn cached_generate_types_match_rebuilt_types_for_imports_and_four_state_values() { - let state = AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); let mut base = HashMap::from_iter([("pkg::IMPORTED".into(), -1)]); insert_parameter_type_markers( &mut base, @@ -1794,13 +1795,13 @@ mod tests { true, ); bind_generate_parameter( - &state, + &tree, parameter.clone(), &mut rebuilt_env, &mut rebuilt_literals, ); constants::bind_generate_parameter_with_types( - &state, + &tree, parameter, &mut cached_env, &mut cached_literals, @@ -2182,7 +2183,7 @@ mod tests { ) .unwrap(); let mut env = HashMap::default(); - extend_const_env_with_parameters(&tree.state, &mut env, ¶meters); + extend_const_env_with_parameters(&tree, &mut env, ¶meters); assert_eq!(env[¶meter_dimensions_marker("i")], 2); let active = items(&tree, &env, &HashMap::default()).unwrap(); let iterations: Vec<_> = active @@ -2223,7 +2224,11 @@ mod tests { panic!("{assignment:?}") }; assert_eq!( - eval_ast_const_expr(&AnalysisState::default(), lsb, &HashMap::default()), + eval_ast_const_expr( + &const_functions::ConstantFunctions::default(), + lsb, + &HashMap::default() + ), Some(index as i128), "{assignment:?}" ); @@ -2546,7 +2551,7 @@ mod tests { let env = HashMap::default(); let aliases = HashMap::default(); let parameters = parameters_from_scope(&tree, &aliases, &env, &HashMap::default()).unwrap(); - let full = parameter_value_env(&tree.state, ¶meters, &env); + let full = parameter_value_env(&tree, ¶meters, &env); let active = items(&tree, &env, &aliases).unwrap(); for item in active { assert_eq!(item.literals.get("B"), full.get("B")); diff --git a/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs b/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs index a3a3d9c1072..2a7ba37ab39 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs @@ -134,17 +134,19 @@ pub(super) fn needs_functions(tree: &AnalysisContext<'_>) -> Converted { } struct Context<'b> { outer: Cow<'b, HashMap>, - _functions: Option, + /// The constant functions outside the block, if its imports rebind some. + outer_functions: Option, } struct Contexts<'b>(Vec>); -impl Drop for Contexts<'_> { - fn drop(&mut self) { - while let Some(context) = self.0.pop() { - drop(context); +impl<'a, 'b> Elaborator<'a, 'b> { + /// Leave the generate block that `context` entered. + fn leave(&mut self, context: Context<'b>) { + self.aliases = context.outer; + if let Some(functions) = context.outer_functions { + self.tree.functions = functions; } } -} -impl<'a, 'b> Elaborator<'a, 'b> { + pub(super) fn elaborate_root( &mut self, scope: Scope, @@ -187,8 +189,7 @@ impl<'a, 'b> Elaborator<'a, 'b> { while let Some(job) = jobs.pop() { if let Err(error) = self.execute_job(job, &mut jobs, &mut contexts) { while let Some(context) = contexts.0.pop() { - self.aliases = context.outer; - drop(context._functions); + self.leave(context); } return Err(error); } @@ -207,8 +208,7 @@ impl<'a, 'b> Elaborator<'a, 'b> { match job { Job::ExitScope => { let context = contexts.0.pop().ok_or_else(mismatch)?; - self.aliases = context.outer; - drop(context._functions); + self.leave(context); Ok(()) } Job::Item { id, scope, ordinal } => self.item_job(id, scope, ordinal, jobs), @@ -385,19 +385,22 @@ impl<'a, 'b> Elaborator<'a, 'b> { } else { format!("{}.{name}", parent.path) }; - let imported = scope::imported(self.tree); + let imported = scope::imported(&self.tree); if let Some(bindings) = imported.generate_imports.get(&id) { for (name, target) in bindings { bind_import(&mut scope, name, target); } } let index_ref = index.as_ref().map(|(name, value)| (name.as_str(), *value)); - let functions = scope.block_imports().install_constant_functions(); + let outer_functions = scope + .block_imports() + .visible_constant_functions(&self.tree.functions) + .map(|functions| std::mem::replace(&mut self.tree.functions, functions)); let aliases = scope.type_aliases(self.module_aliases); let outer = std::mem::replace(&mut self.aliases, aliases); contexts.0.push(Context { outer, - _functions: functions, + outer_functions, }); let scope = Rc::new(self.prepare_block_contents(&children, scope, index_ref)?); jobs.push(Job::ExitScope); @@ -502,7 +505,7 @@ impl<'a, 'b> Elaborator<'a, 'b> { } => { let rhs = self.expression(*right, scope)?; rhs.and_then(|rhs| { - next_assignment(&self.tree.state, value, operator, rhs, &scope.env) + next_assignment(&self.tree.functions, value, operator, rhs, &scope.env) }) } }; @@ -592,14 +595,14 @@ fn step_name(step: &ForStep, native: &celox_sv_syntax::Declarations) -> Option, ) -> Option { if operator == "=" { - return eval_ast_const_expr(state, &rhs, env); + return eval_ast_const_expr(functions, &rhs, env); } let op = match operator { "+=" => BinaryOp::Add, @@ -612,7 +615,7 @@ fn next_assignment( _ => return None, }; eval_ast_const_expr( - state, + functions, &ConstExpr::Binary { left: Box::new(ConstExpr::Literal(format_typed_parameter_literal( value, 32, true, diff --git a/crates/celox-sv-analyzer/src/ast/generate/memo.rs b/crates/celox-sv-analyzer/src/ast/generate/memo.rs index e773f2e5347..bff30cc72a0 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/memo.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/memo.rs @@ -2,9 +2,10 @@ //! //! The collectors of a module each ask for the active items of the same //! scope. A window opened for the module keeps each elaboration, keyed by its -//! arguments, the imports and package of its context, and the revisions of -//! the analysis state that elaboration reads (constant functions, active -//! interface instances, time scopes), so a change of that state makes +//! arguments, the imports, package and constant functions of its context, +//! and the revisions of +//! the analysis state that elaboration reads (active interface instances, +//! time scopes), so a change of that state makes //! earlier results unreachable. //! A repeated elaboration allocates as many call sites as the first one did, //! so later calls keep their sites. @@ -49,10 +50,11 @@ struct Window { } struct Entry { - revisions: [u64; 3], + revisions: [u64; 2], /// The symbols the scope imported and the package it was in. imported: Arc, package: Option>, + functions: const_functions::ConstantFunctions, literal_use: LiteralUse, overrides: HashMap, env: HashMap, @@ -94,10 +96,9 @@ fn address(tree: &SyntaxTree) -> usize { tree as *const SyntaxTree as usize } -fn revisions(state: &AnalysisState) -> [u64; 3] { +fn revisions(state: &AnalysisState) -> [u64; 2] { [ state.revision.get(), - const_functions::revision(&state.const_functions).get(), timescales::revision(&state.timescales).get(), ] } @@ -132,6 +133,7 @@ pub(super) fn items( entry.revisions == current && Arc::ptr_eq(&entry.imported, &tree.imported) && entry.package == tree.package + && entry.functions.same(&tree.functions) && entry.literal_use == literal_use && entry.overrides == *tree.parameter_overrides && entry.env == *env @@ -161,6 +163,7 @@ pub(super) fn items( revisions: current, imported: tree.imported.clone(), package: tree.package.clone(), + functions: tree.functions.clone(), literal_use, overrides: tree.parameter_overrides.clone().into_owned(), env: env.clone(), diff --git a/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs b/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs index 76860b06920..592cca1c4a9 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/memo/sites.rs @@ -239,7 +239,6 @@ impl CallSites for UnpackedDimension { impl CallSites for Item { fn call_sites(&self, visit: &mut dyn FnMut(usize)) { let Item { - state: _, imported: _, id: _, env: _, diff --git a/crates/celox-sv-analyzer/src/ast/instances.rs b/crates/celox-sv-analyzer/src/ast/instances.rs index 87fe62ee0b0..6c133eccaff 100644 --- a/crates/celox-sv-analyzer/src/ast/instances.rs +++ b/crates/celox-sv-analyzer/src/ast/instances.rs @@ -27,7 +27,7 @@ pub(super) fn instances_from_scope( continue; } let native = syntax_tree.declarations().instantiation(native); - let _constant_functions = item.enter(); + let syntax_tree = &item.enter(syntax_tree); let start = instances.len(); let dimensions = views.dimensions(item); instances_from_native_declaration( @@ -45,7 +45,7 @@ pub(super) fn instances_from_scope( for connection in &mut instance.port_connections { connection.map_expressions(|expr| { let mut expr = substitute_expr_constants_with_parameter_literals( - &syntax_tree.state, + syntax_tree, expr, &item.env, &item.literals, @@ -88,7 +88,7 @@ fn instances_from_native_declaration( ¶meter_types_from_const_env(const_env), ); let value = expr_to_index_const( - &syntax_tree.state, + syntax_tree, substitute_expr_idents( const_expr_to_expr(value), &packed_dimensions.parameter_values, @@ -124,7 +124,7 @@ fn instances_from_native_declaration( for connection in &mut port_connections { connection.map_expressions(|expr| { substitute_expr_constants_with_parameter_literals( - &syntax_tree.state, + syntax_tree, expr, const_env, &HashMap::default(), @@ -154,8 +154,8 @@ fn instances_from_native_declaration( "multidimensional module instance array".to_string(), )); }; - let left = eval_ast_const_expr(&syntax_tree.state, range.left(), const_env); - let right = eval_ast_const_expr(&syntax_tree.state, range.right(), const_env); + let left = eval_ast_const_expr(&syntax_tree.functions, range.left(), const_env); + let right = eval_ast_const_expr(&syntax_tree.functions, range.right(), const_env); let bounds = left .zip(right) .filter(|(left, right)| left.abs_diff(*right) < 4096) @@ -358,9 +358,10 @@ fn array_argument_shape( Job::Conditional => { let right = values.pop()?; let left = values.pop()?; - let left_type = array_compatibility::unpacked_array_type(&tree.state, &left, dims)?; + let left_type = + array_compatibility::unpacked_array_type(&tree.functions, &left, dims)?; let right_type = - array_compatibility::unpacked_array_type(&tree.state, &right, dims)?; + array_compatibility::unpacked_array_type(&tree.functions, &right, dims)?; if left_type != right_type || left.packed != right.packed || left.members != right.members @@ -394,7 +395,7 @@ fn parameter_override( &packed_dimensions.type_aliases, )? .and_then(|ty| { - type_parameters::resolve(&syntax_tree.state, ty, &packed_dimensions.const_env) + type_parameters::resolve(&syntax_tree.functions, ty, &packed_dimensions.const_env) }) .ok_or_else(|| unsupported(format!("parameter type override `{name}`")))?; return Ok(ParameterOverride::type_override(name, ty)); @@ -426,7 +427,11 @@ fn parameter_override( { let condition = constant_binding::bind(condition, syntax_tree, packed_dimensions)? .and_then(|value| { - eval_ast_const_expr(&syntax_tree.state, &value, &packed_dimensions.const_env) + eval_ast_const_expr( + &syntax_tree.functions, + &value, + &packed_dimensions.const_env, + ) }) .ok_or_else(|| { unsupported("nonconstant or ambiguous condition in array parameter argument") @@ -463,7 +468,7 @@ fn parameter_override( &packed_dimensions.type_aliases, )? .and_then(|ty| { - type_parameters::resolve(&syntax_tree.state, ty, &packed_dimensions.const_env) + type_parameters::resolve(&syntax_tree.functions, ty, &packed_dimensions.const_env) }) .ok_or_else(|| unsupported("type parameter packed bounds"))?; return Ok(ParameterOverride::type_override(name, ty)); @@ -483,7 +488,7 @@ fn parameter_override( && let Some(ty) = packed_dimensions.type_aliases.get(&type_name) { let ty = type_parameters::resolve( - &syntax_tree.state, + &syntax_tree.functions, ty.clone(), &packed_dimensions.const_env, ) @@ -505,7 +510,7 @@ fn parameter_override( && let Some(r#type) = packed_dimensions.type_aliases.get(type_name) { let ty = type_parameters::resolve( - &syntax_tree.state, + &syntax_tree.functions, r#type.clone(), &packed_dimensions.const_env, ) diff --git a/crates/celox-sv-analyzer/src/ast/interface_ast.rs b/crates/celox-sv-analyzer/src/ast/interface_ast.rs index 80d23dde703..73f13eae3b6 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_ast.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_ast.rs @@ -132,9 +132,9 @@ pub(super) fn signature( // execution. A public declaration must retain those dependencies so its // consumers can specialize the interface with different header values. let tree = &tree.importing(Arc::new(imported.clone())); - let _functions = const_functions::install(&tree.state, module.constant_functions.clone()); + let tree = &tree.with_functions(module.constant_functions.clone()); let mut env = imported.const_env.clone(); - extend_const_env_with_parameters(&tree.state, &mut env, &module.parameters); + extend_const_env_with_parameters(tree, &mut env, &module.parameters); let aliases = type_aliases_from_scope_with_env(tree, &env)?; let declarations = declarations::signals_from_scope_with_declaration_ranges(tree, &env, &aliases, true)?; diff --git a/crates/celox-sv-analyzer/src/ast/interface_binding.rs b/crates/celox-sv-analyzer/src/ast/interface_binding.rs index a3d9c4de8b9..c8c6def8f20 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_binding.rs @@ -206,7 +206,7 @@ pub(super) fn analyze_module( )?; for (dimension, size) in array.shape.iter().enumerate() { if let Some(actual) = supplied.get(&format!("{}$$dimension{dimension}", port.name)) - && eval_ast_const_expr(&tree.state, actual, &array_symbols.const_env) + && eval_ast_const_expr(&tree.functions, actual, &array_symbols.const_env) != Some(*size as i128) { return Err(unsupported(format!( @@ -347,7 +347,7 @@ pub(super) fn analyze_module( let mut caller_ports = caller.ports.clone(); let mut caller_symbols = caller.symbols.as_ref().unwrap().clone(); let tree = &tree.importing(Arc::new(caller_symbols.clone())); - let _functions = const_functions::install(&tree.state, caller.constant_functions.clone()); + let tree = &tree.with_functions(caller.constant_functions.clone()); let mut port_assignments = Vec::new(); let mut pending = instantiations .iter() @@ -378,8 +378,7 @@ pub(super) fn analyze_module( let mut current = caller_symbols.clone(); current.extend(&imported); let tree = &tree.importing(Arc::new(current.clone())); - let _functions = - const_functions::install(&tree.state, current.constant_functions.clone()); + let tree = &tree.with_functions(current.constant_functions.clone()); for item in generate::items(tree, ¤t.const_env, ¤t.type_aliases)? { if let celox_sv_syntax::BodyItemKind::Instance(native) = tree.declarations().body_item(item.id).kind @@ -427,7 +426,7 @@ pub(super) fn analyze_module( .extend(item.env.iter().map(|(name, value)| (name.clone(), *value))); } let tree = &tree.importing(Arc::new(current.clone())); - let _functions = const_functions::install(&tree.state, current.constant_functions.clone()); + let tree = &tree.with_functions(current.constant_functions.clone()); // Exported scope symbols omit ordinary module ports. Keep the // selected caller header available for connection width discovery. let mut connection_ports = caller_ports.clone(); @@ -546,7 +545,8 @@ pub(super) fn analyze_module( imported.declarations_only, ) })?; - let port_state = module.constant_function_state(); + let port_syntax = SyntaxTree::empty(); + let port_tree = module.constant_context(&port_syntax); let port_symbols = module.symbols.as_ref().unwrap(); let port_dimensions = packed_dimensions_from_ports_and_signals( &module.ports, @@ -581,7 +581,7 @@ pub(super) fn analyze_module( pattern.resolve_types(&dimensions)?; pattern.map_expressions(&mut |expr| { let mut expr = substitute_expr_constants_with_parameter_literals( - &tree.state, + tree, expr, &dimensions.const_env, ¤t.parameter_values, @@ -594,7 +594,7 @@ pub(super) fn analyze_module( let shape = port_dimensions.get(&port.name).ok_or_else(|| { unsupported("interface assignment pattern port shape") })?; - pattern.lower(&port_state, shape, &port_dimensions)? + pattern.lower(&port_tree, shape, &port_dimensions)? } else if let Some(actual) = connection.actual_expr.clone() { actual } else { @@ -608,13 +608,13 @@ pub(super) fn analyze_module( } else { let port_shape = port_dimensions.get(&port.name).unwrap(); let port_width = lvalue_expr_type( - &port_state, + &port_tree.functions, &LValue::Ident(port.name.clone()), &port_dimensions, ) .ok_or_else(|| unsupported("interface array port width"))? .width; - let actual_width = expr_static_width(&tree.state, &actual, &dimensions) + let actual_width = expr_static_width(tree, &actual, &dimensions) .ok_or_else(|| unsupported("interface array connection width"))?; let actual_shape = if let Some(root) = connection_expression(authored, &port.name, Some(&interface))? @@ -627,14 +627,14 @@ pub(super) fn analyze_module( }; let unpacked_sizes = |shape: &VariableDimensions, - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, env: &HashMap| { shape .unpacked .iter() .map(|dimension| { usize::try_from(eval_ast_const_expr( - state, + functions, &dimension.width, env, )?) @@ -644,14 +644,19 @@ pub(super) fn analyze_module( }; let actual_shape = actual_shape .as_ref() - .map(|shape| unpacked_sizes(shape, &tree.state, &dimensions.const_env)) + .map(|shape| { + unpacked_sizes(shape, &tree.functions, &dimensions.const_env) + }) .unwrap_or_else(|| Some(Vec::new())) .ok_or_else(|| unsupported("interface array actual shape"))?; - let port_shape = - unpacked_sizes(port_shape, &port_state, &port_dimensions.const_env) - .ok_or_else(|| unsupported("interface array port shape"))?; + let port_shape = unpacked_sizes( + port_shape, + &port_tree.functions, + &port_dimensions.const_env, + ) + .ok_or_else(|| unsupported("interface array port shape"))?; let (origin, ascending) = - connection_slice_origin(&actual, &tree.state, &dimensions)?; + connection_slice_origin(&actual, &tree.functions, &dimensions)?; let shape = ConnectionShape { unpacked: actual_shape, width: actual_width, @@ -705,7 +710,7 @@ pub(super) fn analyze_module( let mut current = caller_symbols.clone(); current.extend(&imported); let tree = &tree.importing(Arc::new(current.clone())); - let _functions = const_functions::install(&tree.state, current.constant_functions.clone()); + let tree = &tree.with_functions(current.constant_functions.clone()); for item in generate::items(tree, ¤t.const_env, ¤t.type_aliases)? { let tree = &item.scoped(tree); let active_scope = scope::imported(tree); @@ -1050,7 +1055,7 @@ struct ConnectionShape { /// unpacked and multi-packed selections already use flat storage coordinates. fn connection_slice_origin( actual: &Expr, - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, dimensions: &PackedDimensions, ) -> Converted<(ConstExpr, bool)> { let (name, selected_origin) = match actual { @@ -1068,9 +1073,9 @@ fn connection_slice_origin( && let [dimension] = shape.packed.as_slice() && !dimension.normalize_single { - let left = eval_ast_const_expr(state, &dimension.left, &dimensions.const_env) + let left = eval_ast_const_expr(functions, &dimension.left, &dimensions.const_env) .ok_or_else(|| unsupported("interface connection packed bound"))?; - let right = eval_ast_const_expr(state, &dimension.right, &dimensions.const_env) + let right = eval_ast_const_expr(functions, &dimension.right, &dimensions.const_env) .ok_or_else(|| unsupported("interface connection packed bound"))?; return Ok(( selected_origin.unwrap_or_else(|| dimension.right.clone()), @@ -1316,14 +1321,14 @@ fn instance_elements( ) -> Converted { let context = PackedDimensions::new(HashMap::default(), env, aliases); let ranges = constant_binding::bind_unpacked_ranges(dimensions, tree, &context)?; - validate_unpacked_dimension_sizes(&tree.state, &ranges, env)?; + validate_unpacked_dimension_sizes(&tree.functions, &ranges, env)?; let mut shape = Vec::new(); let mut bounds = Vec::new(); let mut elements = vec![handle.to_string()]; for range in ranges { - let left = eval_ast_const_expr(&tree.state, &range.left, env) + let left = eval_ast_const_expr(&tree.functions, &range.left, env) .ok_or_else(|| unsupported("interface array bound"))?; - let right = eval_ast_const_expr(&tree.state, &range.right, env) + let right = eval_ast_const_expr(&tree.functions, &range.right, env) .ok_or_else(|| unsupported("interface array bound"))?; let count = usize::try_from(left.abs_diff(right)) .ok() @@ -1425,7 +1430,7 @@ fn connection_array( let context = PackedDimensions::new(HashMap::default(), env, &scope.type_aliases); let evaluate = |root| -> Converted { constant_binding::bind(root, tree, &context)? - .and_then(|value| eval_ast_const_expr(&tree.state, &value, env)) + .and_then(|value| eval_ast_const_expr(&tree.functions, &value, env)) .ok_or_else(|| unsupported("nonconstant interface array selection")) }; let selections = selections.into_iter().rev().collect::>(); @@ -1562,7 +1567,7 @@ pub(super) fn actual_handle_key( } Suffix::Index(root) => { let value = constant_binding::bind(root, tree, &context)? - .and_then(|value| eval_ast_const_expr(&tree.state, &value, env)) + .and_then(|value| eval_ast_const_expr(&tree.functions, &value, env)) .ok_or_else(|| unsupported("nonconstant interface index"))?; handle.push_str(&format!("[{value}]")); } diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index 9bfad974508..ef0d91c5afd 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -36,7 +36,7 @@ enum Entry { /// With `concurrent`, the bodies may run in overlapping activations, and /// every static local keeps its value. pub(super) fn keep_static_locals<'b, T>( - state: &AnalysisState, + tree: &AnalysisContext<'_>, statics: &HashMap, directions: &Directions, bodies: impl IntoIterator, bool)>, @@ -50,7 +50,7 @@ pub(super) fn keep_static_locals<'b, T>( } let mut bodies = bodies.into_iter().collect::>(); let initialized = match explicit { - Some(explicit) => initialized_at_time_zero(state, statics, explicit, &bodies), + Some(explicit) => initialized_at_time_zero(tree, statics, explicit, &bodies), None => HashSet::default(), }; for (body, _) in &mut bodies { @@ -59,7 +59,7 @@ pub(super) fn keep_static_locals<'b, T>( stmt.walk(&mut |stmt| concurrent |= matches!(stmt, Stmt::Fork { .. })); } keep_in( - state, + tree, body, statics, &initialized, @@ -85,7 +85,7 @@ pub(super) fn keep_static_locals<'b, T>( /// rather than on entry cannot repeat; in an `always` procedure it remains /// rejected, like one that reads an automatic variable. fn initialized_at_time_zero( - state: &AnalysisState, + tree: &AnalysisContext<'_>, statics: &HashMap, explicit: &HashSet, bodies: &[(&mut Vec, bool)], @@ -107,7 +107,7 @@ fn initialized_at_time_zero( } } let runtime = |init: &Expr| { - !expr_is_constant(state, init) && !automatic.iter().any(|name| expr_reads(init, name)) + !expr_is_constant(tree, init) && !automatic.iter().any(|name| expr_reads(init, name)) }; let mut pending = initializers .iter() @@ -117,7 +117,7 @@ fn initialized_at_time_zero( let mut initialized = HashSet::default(); while let Some(name) = pending.pop() { let (init, allowed) = initializers.get(name).copied().unwrap_or_default(); - if init.is_some_and(|init| !expr_is_constant(state, init) && !(allowed && runtime(init))) + if init.is_some_and(|init| !expr_is_constant(tree, init) && !(allowed && runtime(init))) || !initialized.insert(name.to_string()) { continue; @@ -136,7 +136,7 @@ fn initialized_at_time_zero( #[allow(clippy::too_many_arguments)] fn keep_in( - state: &AnalysisState, + tree: &AnalysisContext<'_>, stmts: &mut Vec, statics: &HashMap, initialized: &HashSet, @@ -155,7 +155,7 @@ fn keep_in( || concurrent || sampled_reads(&stmts[index + 1..], name) || entry( - state, + tree, name, init.as_ref(), &stmts[index + 1..], @@ -183,7 +183,7 @@ fn keep_in( .. } => { keep_in( - state, + tree, then_body, statics, initialized, @@ -193,7 +193,7 @@ fn keep_in( concurrent, )?; keep_in( - state, + tree, else_body, statics, initialized, @@ -206,7 +206,7 @@ fn keep_in( Stmt::Case { items, default, .. } => { for item in items { keep_in( - state, + tree, &mut item.body, statics, initialized, @@ -218,7 +218,7 @@ fn keep_in( } if let Some(default) = default { keep_in( - state, + tree, default, statics, initialized, @@ -233,7 +233,7 @@ fn keep_in( init, step, body, .. } => { keep_in( - state, + tree, init, statics, initialized, @@ -243,7 +243,7 @@ fn keep_in( concurrent, )?; keep_in( - state, + tree, step, statics, initialized, @@ -253,7 +253,7 @@ fn keep_in( concurrent, )?; keep_in( - state, + tree, body, statics, initialized, @@ -266,7 +266,7 @@ fn keep_in( Stmt::Fork { branches, .. } => { for branch in branches { keep_in( - state, + tree, branch, statics, initialized, @@ -286,7 +286,7 @@ fn keep_in( /// Reject a static local of `subroutine` that keeps its value between calls. pub(super) fn check_subroutine_statics( - state: &AnalysisState, + tree: &AnalysisContext<'_>, subroutine: &Subroutine, constants: &HashMap, locals: &[LocalVariable], @@ -305,7 +305,7 @@ pub(super) fn check_subroutine_statics( && result.is_ok() { result = entry( - state, + tree, name, init.as_ref(), &stmts[index + 1..], @@ -317,7 +317,7 @@ pub(super) fn check_subroutine_statics( Entry::Observed if init.is_none() && bit_result::proves_local( - state, + tree, name, &stmts[index + 1..], constants, @@ -372,7 +372,7 @@ pub(super) fn check_subroutine_statics( /// a static function the variable named after it is static too, so a call /// that does not assign it returns the result of an earlier call. pub(super) fn check_static_result( - state: &AnalysisState, + tree: &AnalysisContext<'_>, constants: &HashMap, locals: &[LocalVariable], subroutine: &Subroutine, @@ -391,7 +391,7 @@ pub(super) fn check_static_result( // `return value;` assigns the result as it leaves. match flow.block(&subroutine.body, false) { Ok(exits) if exits.next != Some(false) => Ok(()), - _ if bit_result::proves(state, subroutine, constants, locals) => Ok(()), + _ if bit_result::proves(tree, subroutine, constants, locals) => Ok(()), _ => Err(AnalyzerError::Unsupported(format!( "static function `{}` whose result keeps its value between calls (assign it on \ every path, or declare the function `automatic`)", @@ -434,7 +434,7 @@ fn source_name(name: &str) -> &str { /// Reject a static local of `body` whose initializer is not constant, as /// [`entry`] does for a local whose entry value it examines. pub(super) fn check_constant_initializers( - state: &AnalysisState, + tree: &AnalysisContext<'_>, body: &[Stmt], statics: &HashSet, ) -> Result<(), AnalyzerError> { @@ -448,7 +448,7 @@ pub(super) fn check_constant_initializers( && statics.contains(name) && result.is_ok() { - result = constant_initializer(state, name, init); + result = constant_initializer(tree, name, init); } }); } @@ -456,11 +456,11 @@ pub(super) fn check_constant_initializers( } fn constant_initializer( - state: &AnalysisState, + tree: &AnalysisContext<'_>, name: &str, init: &Expr, ) -> Result<(), AnalyzerError> { - if expr_is_constant(state, init) { + if expr_is_constant(tree, init) { return Ok(()); } Err(AnalyzerError::Unsupported(format!( @@ -473,7 +473,7 @@ fn constant_initializer( /// Whether the statements after the declaration of the static local `name` /// read the value it holds on entry. fn entry( - state: &AnalysisState, + tree: &AnalysisContext<'_>, name: &str, init: Option<&Expr>, after: &[Stmt], @@ -483,7 +483,7 @@ fn entry( // A static initializer runs once, before simulation starts; one that is // not constant could only run on every entry instead. if let Some(init) = init { - constant_initializer(state, name, init)?; + constant_initializer(tree, name, init)?; } let flow = Flow { name, @@ -1108,7 +1108,8 @@ fn const_expr_reads(expr: &ConstExpr, name: &str) -> bool { /// Whether `expr` has the same value wherever it is evaluated: it reads no /// variable and calls nothing that is not constant. -fn expr_is_constant(state: &AnalysisState, expr: &Expr) -> bool { +fn expr_is_constant(tree: &AnalysisContext<'_>, expr: &Expr) -> bool { + let state = &*tree.state; fn constant(expr: &ConstExpr) -> bool { match expr { ConstExpr::Ident(_) | ConstExpr::Function { .. } => false, @@ -1133,38 +1134,40 @@ fn expr_is_constant(state: &AnalysisState, expr: &Expr) -> bool { Expr::Call { args, .. } => { args.iter() .flatten() - .all(|expr| expr_is_constant(state, expr)) + .all(|expr| expr_is_constant(tree, expr)) && expr_to_const(state, expr.clone()) - .and_then(|call| eval_ast_const_expr(state, &call, &HashMap::default())) + .and_then(|call| { + eval_ast_const_expr(&tree.functions, &call, &HashMap::default()) + }) .is_some() } Expr::Literal(_) => true, Expr::Select { expr, msb, lsb, .. } => { - expr_is_constant(state, expr) && constant(msb) && constant(lsb) + expr_is_constant(tree, expr) && constant(msb) && constant(lsb) } - Expr::Concat(parts) => parts.iter().all(|expr| expr_is_constant(state, expr)), + Expr::Concat(parts) => parts.iter().all(|expr| expr_is_constant(tree, expr)), Expr::RepeatConcat { count, parts } => { - constant(count) && parts.iter().all(|expr| expr_is_constant(state, expr)) + constant(count) && parts.iter().all(|expr| expr_is_constant(tree, expr)) } - Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => expr_is_constant(state, expr), + Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => expr_is_constant(tree, expr), Expr::Binary { left, right, .. } => { - expr_is_constant(state, left) && expr_is_constant(state, right) + expr_is_constant(tree, left) && expr_is_constant(tree, right) } Expr::Mux { condition, then_expr, else_expr, } => { - expr_is_constant(state, condition) - && expr_is_constant(state, then_expr) - && expr_is_constant(state, else_expr) + expr_is_constant(tree, condition) + && expr_is_constant(tree, then_expr) + && expr_is_constant(tree, else_expr) } Expr::Inside { expr, items } => { - expr_is_constant(state, expr) + expr_is_constant(tree, expr) && items.iter().all(|item| match item { - InsideItem::Value(value) => expr_is_constant(state, value), + InsideItem::Value(value) => expr_is_constant(tree, value), InsideItem::Range { low, high } => { - expr_is_constant(state, low) && expr_is_constant(state, high) + expr_is_constant(tree, low) && expr_is_constant(tree, high) } }) } diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs b/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs index f30d26f43c9..ef6a3e7d59e 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs @@ -6,7 +6,7 @@ const MAX_BITS: usize = 65536; const MAX_STEPS: usize = 65536; pub(super) fn proves( - state: &AnalysisState, + tree: &AnalysisContext<'_>, subroutine: &Subroutine, constants: &HashMap, locals: &[LocalVariable], @@ -22,11 +22,11 @@ pub(super) fn proves( else { return false; }; - proves_variable(state, name, width, &subroutine.body, constants, locals) + proves_variable(tree, name, width, &subroutine.body, constants, locals) } pub(super) fn proves_local( - state: &AnalysisState, + tree: &AnalysisContext<'_>, name: &str, body: &[Stmt], constants: &HashMap, @@ -39,11 +39,11 @@ pub(super) fn proves_local( let Some(width) = local.r#type.resolved_width() else { return false; }; - proves_variable(state, name, width, body, constants, locals) + proves_variable(tree, name, width, body, constants, locals) } pub(super) fn proves_variable( - state: &AnalysisState, + tree: &AnalysisContext<'_>, name: &str, width: usize, body: &[Stmt], @@ -76,7 +76,7 @@ pub(super) fn proves_variable( } } let mut proof = Proof { - state, + tree, name, width, written: BigUint::default(), @@ -89,7 +89,7 @@ pub(super) fn proves_variable( } struct Proof<'a> { - state: &'a AnalysisState, + tree: &'a AnalysisContext<'a>, name: &'a str, width: usize, written: BigUint, @@ -109,8 +109,8 @@ impl Proof<'_> { return None; } let dims = PackedDimensions::new(HashMap::default(), &self.env, &HashMap::default()); - let value = expr_to_index_const(self.state, expression.clone(), &dims)?; - eval_ast_const_expr(self.state, &value, &self.env) + let value = expr_to_index_const(self.tree, expression.clone(), &dims)?; + eval_ast_const_expr(&self.tree.functions, &value, &self.env) } fn store(&mut self, name: &str, value: Option) -> Option<()> { @@ -163,8 +163,10 @@ impl Proof<'_> { if !pure_constant(msb) || !pure_constant(lsb) { return None; } - let left = eval_ast_const_expr(self.state, msb, &self.env)?; - let right = eval_ast_const_expr(self.state, lsb, &self.env)?; + let left = + eval_ast_const_expr(&self.tree.functions, msb, &self.env)?; + let right = + eval_ast_const_expr(&self.tree.functions, lsb, &self.env)?; let low = usize::try_from(left.min(right)).ok()?; let high = usize::try_from(left.max(right)).ok()?; if high >= self.width { diff --git a/crates/celox-sv-analyzer/src/ast/locators.rs b/crates/celox-sv-analyzer/src/ast/locators.rs index bfd6bc32543..d4cceb302c1 100644 --- a/crates/celox-sv-analyzer/src/ast/locators.rs +++ b/crates/celox-sv-analyzer/src/ast/locators.rs @@ -65,7 +65,7 @@ impl LocalSink { procedural::scoped_type(r#type, &dims.const_env), &const_functions::Environment { constants: &*dims.const_env, - functions: &tree.state.const_functions, + functions: &tree.functions, }, ), }); @@ -295,7 +295,7 @@ fn array( return Err(unsupported("array locator method on real elements")); } let bound = |expr: &ConstExpr| { - eval_ast_const_expr(&tree.state, expr, &dims.const_env) + eval_ast_const_expr(&tree.functions, expr, &dims.const_env) // The index local is an `int` (7.12.4). .and_then(|value| i32::try_from(value).ok()) .map(i64::from) @@ -326,7 +326,7 @@ fn array( ty.signed_element_depth = shape.signed_element_depth; ty }; - let width = casts::expr_type_from_type(&tree.state, &element, &dims.const_env) + let width = casts::expr_type_from_type(&tree.functions, &element, &dims.const_env) .map(|shape| shape.width) .filter(|width| (1..=64).contains(width)) .ok_or_else(|| unsupported("array locator method on elements wider than 64 bits"))?; @@ -470,7 +470,7 @@ pub(super) fn bind( if expression_binding::real_value(&value, &scope) { return Err(unsupported("array locator method on real values")); } - let r#type = dimensions::bound_bits_type(&tree.state, &value, &scope) + let r#type = dimensions::bound_bits_type(tree, &value, &scope) .filter(|r#type| (1..=64).contains(&r#type.width)) .ok_or_else(|| { unsupported("array locator with expression wider than 64 bits") @@ -538,7 +538,7 @@ pub(super) fn bind( }; let name = instances::normalize_identifier(&name.spelling); let lvalue = selects::lvalue_from_indices( - &tree.state, + tree, name, vec![ConstExpr::Ident(index.clone())], dims, @@ -548,7 +548,7 @@ pub(super) fn bind( left: *left, right: *right, }, - statements::expr_from_lvalue(&tree.state, &lvalue, dims), + statements::expr_from_lvalue(tree, &lvalue, dims), ) } }; @@ -640,8 +640,9 @@ pub(super) fn index( [] => {} [argument] if argument.name.is_none() => { let dimension = match argument.value { - Some(value) => constant_binding::bind(value, tree, dims)? - .and_then(|value| eval_ast_const_expr(&tree.state, &value, &dims.const_env)), + Some(value) => constant_binding::bind(value, tree, dims)?.and_then(|value| { + eval_ast_const_expr(&tree.functions, &value, &dims.const_env) + }), None => None, }; if dimension != Some(1) { diff --git a/crates/celox-sv-analyzer/src/ast/mailboxes.rs b/crates/celox-sv-analyzer/src/ast/mailboxes.rs index ce8b87dadab..c8b1948d2f9 100644 --- a/crates/celox-sv-analyzer/src/ast/mailboxes.rs +++ b/crates/celox-sv-analyzer/src/ast/mailboxes.rs @@ -26,7 +26,11 @@ struct Message { impl Message { /// The message type of `mailbox #(ty)`. - fn of(state: &AnalysisState, ty: &Type, env: &HashMap) -> Converted { + fn of( + functions: &const_functions::ConstantFunctions, + ty: &Type, + env: &HashMap, + ) -> Converted { if !ty.unpacked_ranges.is_empty() || ty.container.is_some() || ty.unpacked_struct().is_some() @@ -36,7 +40,7 @@ impl Message { "mailbox messages that are not integral values, strings or handles", )); } - let shape = casts::expr_type_from_type(state, ty, env) + let shape = casts::expr_type_from_type(functions, ty, env) .ok_or_else(|| unsupported("mailbox message type"))?; if shape.width == 0 || shape.width > 64 { return Err(unsupported("mailbox messages wider than 64 bits")); @@ -149,7 +153,7 @@ pub(super) fn named_type( let Some(message) = classes::specializations::type_argument(tree, argument, context)? else { return Ok(None); }; - let name = Message::of(&tree.state, &message, &context.const_env)?.class_name(&message); + let name = Message::of(&tree.functions, &message, &context.const_env)?.class_name(&message); Ok(Some(Box::new(classes::handle(&name)))) } diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index e76744d90db..e94ee1eaf33 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -518,6 +518,7 @@ fn analyze_package( parameter_overrides: Cow::Owned(HashMap::default()), imported: Arc::default(), package: None, + functions: const_functions::ConstantFunctions::default(), }; let tree = &context; let _timescales = diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs index f2f72a5e809..d86e72a8f1f 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/layout.rs @@ -13,7 +13,7 @@ pub(in crate::ast) enum AggregateKind { /// Freeze member bounds in the declaration environment before generated scopes /// can shadow their parameter names. Shared by both syntax owners. pub(in crate::ast) fn capture_member_type( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, mut ty: Type, env: &HashMap, ) -> Option { @@ -25,12 +25,12 @@ pub(in crate::ast) fn capture_member_type( } for range in &mut ty.packed_ranges { range.left = ConstExpr::Literal(format_typed_parameter_literal( - eval_ast_const_expr(state, &range.left, env)?, + eval_ast_const_expr(functions, &range.left, env)?, 128, true, )); range.right = ConstExpr::Literal(format_typed_parameter_literal( - eval_ast_const_expr(state, &range.right, env)?, + eval_ast_const_expr(functions, &range.right, env)?, 128, true, )); @@ -40,7 +40,7 @@ pub(in crate::ast) fn capture_member_type( /// Syntax-independent IEEE7.2.1/7.3.1 layout kernel. pub(in crate::ast) fn native_type( - state: &AnalysisState, + tree: &AnalysisContext<'_>, kind: AggregateKind, signed: bool, owner: Arc, @@ -48,6 +48,7 @@ pub(in crate::ast) fn native_type( ranges: Vec, env: &HashMap, ) -> Option { + let functions = &tree.functions; let mut names = HashSet::default(); let members = fields .into_iter() @@ -61,14 +62,14 @@ pub(in crate::ast) fn native_type( offset: 0, tag: None, is_void, - r#type: capture_member_type(state, ty, env)?, + r#type: capture_member_type(functions, ty, env)?, }) }) .collect::>>()?; - finish_type(state, kind, signed, members, ranges, env) + finish_type(&tree.functions, kind, signed, members, ranges, env) } fn finish_type( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, kind: AggregateKind, signed: bool, mut members: Vec, @@ -81,7 +82,7 @@ fn finish_type( let member_width = if member.is_void { 0 } else { - expr_type_from_type(state, &member.r#type, const_env)?.width + expr_type_from_type(functions, &member.r#type, const_env)?.width }; if !matches!(kind, AggregateKind::Struct) { // IEEE 1800-2023 7.3.1: hard packed members share all bits diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs index 302db1ca7e7..b8a501d88a3 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -96,21 +96,22 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) - } fn finish_lvalue( - state: &AnalysisState, + tree: &AnalysisContext<'_>, path: &[String], offset: usize, r#type: &Type, relative: LValue, dimensions: &PackedDimensions, ) -> Option { - let width = expr_type_from_type(state, r#type, &dimensions.const_env)?.width; + let functions = &tree.functions; + let width = expr_type_from_type(&tree.functions, r#type, &dimensions.const_env)?.width; let (msb, lsb, signed) = match relative { LValue::Ident(_) => (width.checked_sub(1)? as i128, 0, r#type.is_signed), LValue::Select { msb, lsb, signed, .. } => ( - eval_ast_const_expr(state, &msb, &dimensions.const_env)?, - eval_ast_const_expr(state, &lsb, &dimensions.const_env)?, + eval_ast_const_expr(functions, &msb, &dimensions.const_env)?, + eval_ast_const_expr(functions, &lsb, &dimensions.const_env)?, signed, ), }; @@ -137,7 +138,6 @@ pub(in crate::ast) fn whole_member( base: Option, dimensions: &PackedDimensions, ) -> Converted { - let state = &*tree.state; let bound_interface = bind_interface_path(tree, &mut path, dimensions); if !bound_interface && let Some(base) = base { path[0] = base; @@ -148,7 +148,7 @@ pub(in crate::ast) fn whole_member( let (offset, ty) = selected_member(&path, dimensions) .ok_or_else(|| unknown_member(&path, bound_interface, dimensions))?; finish_lvalue( - state, + tree, &path, offset, ty, @@ -172,7 +172,6 @@ pub(in crate::ast) fn select_member( dimensions: &PackedDimensions, select: impl FnOnce(String, &PackedDimensions, bool) -> Converted, ) -> Converted { - let state = &*tree.state; let bound_interface = bind_interface_path(tree, &mut path, dimensions); if !bound_interface && let Some(base) = base { path[0] = base; @@ -187,7 +186,7 @@ pub(in crate::ast) fn select_member( &member_dimensions(&path[0], ty, dimensions), true, )?; - finish_lvalue(state, &path, offset, ty, relative, dimensions).ok_or_else(|| { + finish_lvalue(tree, &path, offset, ty, relative, dimensions).ok_or_else(|| { unsupported(format!( "select of structure member `{}` outside the member", path.join(".") diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/tagged.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/tagged.rs index 6be65f9c5f1..f6dc84b895e 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/tagged.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/tagged.rs @@ -36,7 +36,7 @@ pub(in crate::ast) fn construction_member( } pub(in crate::ast) fn construct( - state: &AnalysisState, + tree: &AnalysisContext<'_>, plan: Construction, value: Option, dims: &PackedDimensions, @@ -49,7 +49,7 @@ pub(in crate::ast) fn construct( ))); } let width = match &plan.shape { - Some(shape) => patterns::shape_width(state, shape, dims) + Some(shape) => patterns::shape_width(&tree.functions, shape, dims) .ok_or_else(|| unsupported("tagged payload width"))?, None => 0, }; @@ -64,7 +64,7 @@ pub(in crate::ast) fn construct( let signed = dimensions::expression_signedness(&value, dims, &dims.const_env).unwrap_or(false); parts.push(patterns::assignment_value( - state, &value, signed, None, &shape, dims, false, + tree, &value, signed, None, &shape, dims, false, )?); } (None, None) => {} @@ -130,14 +130,14 @@ pub(in crate::ast) fn member_access( pub(in crate::ast) fn checked_value( guards: Vec, mut value: Expr, - state: &AnalysisState, + tree: &AnalysisContext<'_>, dims: &PackedDimensions, ) -> Converted { if guards.is_empty() { return Ok(value); } let width = - expr_static_width(state, &value, dims).ok_or_else(|| unsupported("tagged access width"))?; + expr_static_width(tree, &value, dims).ok_or_else(|| unsupported("tagged access width"))?; let signed = dimensions::expression_signedness(&value, dims, &dims.const_env).unwrap_or(false); for guard in guards.into_iter().rev() { value = Expr::Call { diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index 309f77f9ade..b1ceced0dbf 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -197,7 +197,6 @@ impl<'a> ParameterEnvironment<'a> { base: &'a HashMap, shadowed: &[String], ) -> Self { - let state = &*tree.state; let shadowed: HashSet<&str> = shadowed .iter() .map(String::as_str) @@ -226,7 +225,7 @@ impl<'a> ParameterEnvironment<'a> { .map(|(name, value)| (name.clone(), value.clone())) .collect(); for parameter in parameters { - bind_parameter(state, &mut bindings, &mut types, &mut literals, parameter); + bind_parameter(tree, &mut bindings, &mut types, &mut literals, parameter); for key in binding_keys(parameter.name(), &bindings, parameter.packed_ranges.len()) { if let Some(value) = bindings.get(&key) { values.insert(key, *value); @@ -254,9 +253,9 @@ impl<'a> ParameterEnvironment<'a> { } } - fn append(&mut self, state: &AnalysisState, parameter: &Parameter) { + fn append(&mut self, tree: &AnalysisContext<'_>, parameter: &Parameter) { let bound = bind_parameter( - state, + tree, &mut self.bindings, &mut self.types, &mut self.literals, @@ -442,7 +441,7 @@ pub(super) fn parameters_from_native_with_environment( proof_context .parameter_values .extend(parameter_value_env_filtered( - &syntax_tree.state, + syntax_tree, parameters, const_env, Some(&resolved_numeric), @@ -475,7 +474,7 @@ pub(super) fn parameters_from_native_with_environment( type_aliases, ); dimensions.parameter_values = parameter_value_env_with_imported( - &syntax_tree.state, + syntax_tree, parameters, const_env, &imported, @@ -537,7 +536,7 @@ pub(super) fn parameters_from_native_with_environment( &environment.literals, ); if !matches!( - fold_const_integral_expr_preserving_mask(&syntax_tree.state, lowered, const_env), + fold_const_integral_expr_preserving_mask(syntax_tree, lowered, const_env), Expr::Literal(_) ) { return Err(AnalyzerError::Unsupported(format!( @@ -583,7 +582,7 @@ pub(super) fn parameters_from_native_with_environment( .resolved_type(&environment.types) .map(|ty| ty.width), )?; - environment.append(&syntax_tree.state, ¶meter); + environment.append(syntax_tree, ¶meter); parameters.push(parameter); } Ok(()) @@ -612,7 +611,7 @@ fn parameter_declared_width( ) -> Converted> { let declared_alias = native.alias.clone(); if declared_alias.is_none() && native.data.packed_dimensions.is_empty() { - return Ok(native.scalar_width(&syntax_tree.state)); + return Ok(native.scalar_width(&syntax_tree.functions)); } // With the same immutable base and no inherited numeric value shadowed // by a nonnumeric literal, both former copies have exactly the contents @@ -652,7 +651,7 @@ fn parameter_declared_width( .flatten() }) }) - .and_then(|value| eval_ast_const_expr(&syntax_tree.state, &value, &range_env)); + .and_then(|value| eval_ast_const_expr(&syntax_tree.functions, &value, &range_env)); if let Some(value) = value { range_env.insert(name, value); } @@ -687,14 +686,14 @@ fn parameter_width_from_environments( return Ok(if prefix.alias.is_some() { Some(1) } else { - prefix.scalar_width(&syntax_tree.state) + prefix.scalar_width(&syntax_tree.functions) }); } let mut width = 1usize; for range in ranges { let (Some(left), Some(right)) = ( - eval_ast_const_expr(&syntax_tree.state, range.left(), env), - eval_ast_const_expr(&syntax_tree.state, range.right(), env), + eval_ast_const_expr(&syntax_tree.functions, range.left(), env), + eval_ast_const_expr(&syntax_tree.functions, range.right(), env), ) else { return Ok(None); }; @@ -741,33 +740,34 @@ fn normalize_unbased_unsized_parameter_value( } pub(super) fn const_env_from_parameters( - state: &AnalysisState, + tree: &AnalysisContext<'_>, parameters: &[Parameter], ) -> HashMap { let mut env = HashMap::default(); - extend_const_env_with_parameters(state, &mut env, parameters); + extend_const_env_with_parameters(tree, &mut env, parameters); env } pub(super) fn extend_const_env_with_parameters( - state: &AnalysisState, + tree: &AnalysisContext<'_>, env: &mut HashMap, parameters: &[Parameter], ) { let mut parameter_types = parameter_types_from_const_env(env); let mut literals = HashMap::default(); for parameter in parameters { - bind_parameter(state, env, &mut parameter_types, &mut literals, parameter); + bind_parameter(tree, env, &mut parameter_types, &mut literals, parameter); } } pub(super) fn bind_parameter( - state: &AnalysisState, + tree: &AnalysisContext<'_>, env: &mut HashMap, types: &mut HashMap, literals: &mut HashMap, parameter: &Parameter, ) -> bool { + let functions = &tree.functions; #[cfg(test)] PARAMETER_BINDINGS.with(|count| count.set(count.get() + 1)); for key in binding_keys(parameter.name(), env, parameter.packed_ranges.len()) { @@ -799,10 +799,10 @@ pub(super) fn bind_parameter( }; env.insert(parameter_rank_marker(parameter.name()), rank as i128); } - insert_parameter_dimension_markers(state, env, parameter); + insert_parameter_dimension_markers(functions, env, parameter); return true; } - let (value, literal) = parameter.resolved_value_and_literal(state, env, types, literals); + let (value, literal) = parameter.resolved_value_and_literal(tree, env, types, literals); if value.is_none() && literal.is_none() { return false; } @@ -823,7 +823,7 @@ pub(super) fn bind_parameter( // Shadow a numeric inherited binding with the four-state declaration. env.remove(parameter.name()); literals.insert(parameter.name().to_string(), literal); - insert_parameter_dimension_markers(state, env, parameter); + insert_parameter_dimension_markers(functions, env, parameter); return true; } let value = value.expect("a known value or a resolved literal was checked above"); @@ -832,13 +832,13 @@ pub(super) fn bind_parameter( if parameter.is_local { env.insert(local_parameter_marker(parameter.name()), value); } - insert_parameter_dimension_markers(state, env, parameter); + insert_parameter_dimension_markers(functions, env, parameter); true } /// Record packed bounds for parameter selects and array queries. fn insert_parameter_dimension_markers( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, env: &mut HashMap, parameter: &Parameter, ) { @@ -851,8 +851,8 @@ fn insert_parameter_dimension_markers( .iter() .map(|range| { Some(( - eval_ast_const_expr(state, range.left(), env)?, - eval_ast_const_expr(state, range.right(), env)?, + eval_ast_const_expr(functions, range.left(), env)?, + eval_ast_const_expr(functions, range.right(), env)?, )) }) .collect::>>() @@ -1042,7 +1042,7 @@ pub(super) fn enum_member_constants_from_items( parameter_overrides }, )?; - extend_const_env_with_parameters(&syntax_tree.state, &mut eval_env, ¶meters); + extend_const_env_with_parameters(syntax_tree, &mut eval_env, ¶meters); resolved_type_aliases = types::type_aliases_from_body_with_env( syntax_tree, declarations, @@ -1074,7 +1074,7 @@ pub(super) fn enum_member_constants_from_items( &PackedDimensions::new(HashMap::default(), &eval_env, &resolved_type_aliases), &member_base, )?; - let member_type = expr_type_from_type(&syntax_tree.state, &member_base, &eval_env) + let member_type = expr_type_from_type(&syntax_tree.functions, &member_base, &eval_env) .ok_or_else(|| unsupported("enum base type"))?; let mut next_enum_value = 0i128; for new in items { @@ -1114,8 +1114,8 @@ pub(super) fn enum_member_constants_from_items( .ok_or_else(|| { AnalyzerError::Unsupported(format!("enum member `{name}` value type")) })?; - let number = - eval_ast_const_expr(&syntax_tree.state, &value, &eval_env).ok_or_else(|| { + let number = eval_ast_const_expr(&syntax_tree.functions, &value, &eval_env) + .ok_or_else(|| { AnalyzerError::Unsupported(format!("unresolved enum member `{name}` value")) })?; if !enum_initializer_fits_base_type(number, value_type, member_type) { @@ -1153,17 +1153,17 @@ pub(super) fn enum_member_constants_from_items( } pub(super) fn parameter_value_env( - state: &AnalysisState, + tree: &AnalysisContext<'_>, parameters: &[Parameter], const_env: &HashMap, ) -> HashMap { - parameter_value_env_filtered(state, parameters, const_env, None) + parameter_value_env_filtered(tree, parameters, const_env, None) } /// Materialize only referenced values and their initializer dependencies. /// Preserve the full declaration-order type prefix, including unused parameters. pub(super) fn parameter_value_env_for_references( - state: &AnalysisState, + tree: &AnalysisContext<'_>, parameters: &[Parameter], const_env: &HashMap, references: &HashSet, @@ -1177,7 +1177,7 @@ pub(super) fn parameter_value_env_for_references( return HashMap::default(); } if needed.iter().all(|name| const_env.contains_key(name)) { - return parameter_value_env_filtered(state, parameters, const_env, Some(&needed)); + return parameter_value_env_filtered(tree, parameters, const_env, Some(&needed)); } // Include all declarations of a name so the projection preserves even // repeated-name prefixes used during preliminary collection. @@ -1233,11 +1233,11 @@ pub(super) fn parameter_value_env_for_references( } } } - parameter_value_env_filtered(state, parameters, const_env, Some(&needed)) + parameter_value_env_filtered(tree, parameters, const_env, Some(&needed)) } fn parameter_value_env_filtered( - state: &AnalysisState, + tree: &AnalysisContext<'_>, parameters: &[Parameter], const_env: &HashMap, needed: Option<&HashSet>, @@ -1306,9 +1306,9 @@ fn parameter_value_env_filtered( } } else if let Some(value) = parameter.value().cloned() { let value = substitute_typed_parameter_literals(value, const_env, ¶meter_types); - let value = replace_oob_const_selects_with_unknown(state, value, const_env); + let value = replace_oob_const_selects_with_unknown(tree, value, const_env); let value = substitute_expr_constants_with_parameter_literals( - state, + tree, const_expr_to_expr(value), const_env, &values, @@ -1349,17 +1349,18 @@ fn parameter_value_env_filtered( expr: Box::new(value), }; } - value = fold_const_integral_expr_preserving_mask(state, value, const_env); + value = fold_const_integral_expr_preserving_mask(tree, value, const_env); values.insert(parameter.name().to_string(), value); } values } fn replace_oob_const_selects_with_unknown( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: ConstExpr, const_env: &HashMap, ) -> ConstExpr { + let functions = &tree.functions; match expr { ConstExpr::SelectRange { expr, @@ -1368,23 +1369,23 @@ fn replace_oob_const_selects_with_unknown( signed, } => ConstExpr::SelectRange { expr: Box::new(replace_oob_const_selects_with_unknown( - state, *expr, const_env, + tree, *expr, const_env, )), msb: Box::new(replace_oob_const_selects_with_unknown( - state, *msb, const_env, + tree, *msb, const_env, )), lsb: Box::new(replace_oob_const_selects_with_unknown( - state, *lsb, const_env, + tree, *lsb, const_env, )), signed, }, ConstExpr::Select { expr, bit } => { - let expr = replace_oob_const_selects_with_unknown(state, *expr, const_env); - let bit = replace_oob_const_selects_with_unknown(state, *bit, const_env); + let expr = replace_oob_const_selects_with_unknown(tree, *expr, const_env); + let bit = replace_oob_const_selects_with_unknown(tree, *bit, const_env); if let ConstExpr::Literal(literal) = &expr && let Some(width) = typecheck::parse_integral_literal(literal).map(|literal| literal.width) - && match eval_ast_const_expr(state, &bit, const_env) { + && match eval_ast_const_expr(functions, &bit, const_env) { Some(bit_index) => { usize::try_from(bit_index).map_or(true, |bit_index| bit_index >= width) } @@ -1404,7 +1405,7 @@ fn replace_oob_const_selects_with_unknown( site, args: args .into_iter() - .map(|arg| replace_oob_const_selects_with_unknown(state, arg, const_env)) + .map(|arg| replace_oob_const_selects_with_unknown(tree, arg, const_env)) .collect(), }, ConstExpr::Resize { @@ -1413,7 +1414,7 @@ fn replace_oob_const_selects_with_unknown( signed, } => ConstExpr::Resize { expr: Box::new(replace_oob_const_selects_with_unknown( - state, *expr, const_env, + tree, *expr, const_env, )), width, signed, @@ -1421,16 +1422,16 @@ fn replace_oob_const_selects_with_unknown( ConstExpr::Unary { op, expr } => ConstExpr::Unary { op, expr: Box::new(replace_oob_const_selects_with_unknown( - state, *expr, const_env, + tree, *expr, const_env, )), }, ConstExpr::Binary { left, op, right } => ConstExpr::Binary { left: Box::new(replace_oob_const_selects_with_unknown( - state, *left, const_env, + tree, *left, const_env, )), op, right: Box::new(replace_oob_const_selects_with_unknown( - state, *right, const_env, + tree, *right, const_env, )), }, ConstExpr::Mux { @@ -1439,13 +1440,13 @@ fn replace_oob_const_selects_with_unknown( else_expr, } => ConstExpr::Mux { condition: Box::new(replace_oob_const_selects_with_unknown( - state, *condition, const_env, + tree, *condition, const_env, )), then_expr: Box::new(replace_oob_const_selects_with_unknown( - state, *then_expr, const_env, + tree, *then_expr, const_env, )), else_expr: Box::new(replace_oob_const_selects_with_unknown( - state, *else_expr, const_env, + tree, *else_expr, const_env, )), }, ConstExpr::Ident(name) => ConstExpr::Ident(name), diff --git a/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs b/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs index 08bf3f49f05..498cfd89521 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs @@ -72,10 +72,10 @@ impl Prefix<'_> { .or(self.primitive.as_ref()) .is_some_and(|ty| ty.kind == TypeKind::Bit) } - pub fn scalar_width(&self, state: &AnalysisState) -> Option { + pub fn scalar_width(&self, functions: &const_functions::ConstantFunctions) -> Option { self.primitive .as_ref() - .and_then(|ty| expr_type_from_type(state, ty, &HashMap::default())) + .and_then(|ty| expr_type_from_type(functions, ty, &HashMap::default())) .map(|ty| ty.width) } pub fn signed_element_depth(&self) -> Option { diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index e497e66f1a7..236bf97ac6a 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -5,7 +5,7 @@ use celox_sv_syntax::{DimensionKind, ExprId, ExprKind}; fn integer(root: ExprId, tree: &AnalysisContext<'_>, dims: &PackedDimensions) -> Converted { constant_binding::bind(root, tree, dims)? - .and_then(|value| eval_ast_const_expr(&tree.state, &value, &dims.const_env)) + .and_then(|value| eval_ast_const_expr(&tree.functions, &value, &dims.const_env)) .ok_or_else(|| unsupported("parameter shape expression that is not a known constant")) } @@ -17,7 +17,7 @@ fn bound( ) -> Converted<()> { let value = constant_binding::bind(root, tree, dims)? .ok_or_else(|| unsupported("parameter selection bound that is not constant"))?; - if eval_ast_const_expr(&tree.state, &value, &dims.const_env).is_none() + if eval_ast_const_expr(&tree.functions, &value, &dims.const_env).is_none() && !(unknown && selects::const_index_has_unknown_value(&value, dims)) { return Err(unsupported( @@ -65,7 +65,7 @@ fn dimension( } fn value_name( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, name: &str, query: bool, dims: &PackedDimensions, @@ -91,12 +91,10 @@ fn value_name( } // A zero-argument constant call may omit parentheses. A visible value // with the same spelling still shadows that callable, as in ordinary binding. - if dims.get(name).is_none() - && const_functions::is_constant_function(&state.const_functions, name) - { + if dims.get(name).is_none() && const_functions::is_constant_function(functions, name) { let (actuals, _) = expression_binding::arguments(name, &[], dims)?; return const_functions::validate_argument_bindings( - &state.const_functions, + functions, name, &actuals.iter().map(Option::is_some).collect::>(), ); @@ -129,7 +127,7 @@ pub(in crate::ast) fn validate( ExprKind::Name(name) => { let name = instances::normalize_identifier(&name.spelling); if names { - value_name(&tree.state, &name, query, dims, unavailable)?; + value_name(&tree.functions, &name, query, dims, unavailable)?; } } ExprKind::Group(inner) => jobs.push((*inner, query, receiving)), @@ -156,7 +154,7 @@ pub(in crate::ast) fn validate( && let Some(name) = expression_binding::native_name(tree, id, native) { if names { - value_name(&tree.state, &name, query, dims, unavailable)?; + value_name(&tree.functions, &name, query, dims, unavailable)?; } } else { push(&mut jobs, *expression); @@ -208,7 +206,7 @@ pub(in crate::ast) fn validate( } let (actuals, _) = expression_binding::arguments(&name, arguments, dims)?; const_functions::validate_argument_bindings( - &tree.state.const_functions, + &tree.functions, &name, &actuals.iter().map(Option::is_some).collect::>(), )?; @@ -319,7 +317,7 @@ pub(in crate::ast) fn validate( let valid = if let ExprKind::Type(ty) = native.expression(*slice).kind { type_binding::bind(ty, tree, dims)? .and_then(|ty| { - casts::expr_type_from_type(&tree.state, &ty, &dims.const_env) + casts::expr_type_from_type(&tree.functions, &ty, &dims.const_env) }) .is_some_and(|ty| ty.width > 0) } else { @@ -327,7 +325,7 @@ pub(in crate::ast) fn validate( .and_then(|(name, dimensions)| dimensions.is_empty().then_some(name)) .and_then(|name| dims.type_aliases.get(&name)) .and_then(|ty| { - casts::expr_type_from_type(&tree.state, ty, &dims.const_env) + casts::expr_type_from_type(&tree.functions, ty, &dims.const_env) }) .is_some_and(|ty| ty.width > 0) || integer(*slice, tree, dims).is_ok_and(|size| size > 0) @@ -462,9 +460,9 @@ fn pattern_items( } let (count, low, high, element) = if let Some((dim, rest)) = shape.unpacked.split_first() { let left = - eval_ast_const_expr(&tree.state, &dim.left, &dims.const_env).ok_or_else(wrong)?; + eval_ast_const_expr(&tree.functions, &dim.left, &dims.const_env).ok_or_else(wrong)?; let right = - eval_ast_const_expr(&tree.state, &dim.right, &dims.const_env).ok_or_else(wrong)?; + eval_ast_const_expr(&tree.functions, &dim.right, &dims.const_env).ok_or_else(wrong)?; let count = usize::try_from(left.abs_diff(right)) .ok() .and_then(|v| v.checked_add(1)) @@ -487,9 +485,9 @@ fn pattern_items( && !rest.is_empty() { let left = - eval_ast_const_expr(&tree.state, &dim.left, &dims.const_env).ok_or_else(wrong)?; + eval_ast_const_expr(&tree.functions, &dim.left, &dims.const_env).ok_or_else(wrong)?; let right = - eval_ast_const_expr(&tree.state, &dim.right, &dims.const_env).ok_or_else(wrong)?; + eval_ast_const_expr(&tree.functions, &dim.right, &dims.const_env).ok_or_else(wrong)?; let count = usize::try_from(left.abs_diff(right)) .ok() .and_then(|v| v.checked_add(1)) @@ -509,7 +507,7 @@ fn pattern_items( }, ) } else { - let count = patterns::shape_width(&tree.state, shape, dims).ok_or_else(wrong)?; + let count = patterns::shape_width(&tree.functions, shape, dims).ok_or_else(wrong)?; ( count, 0, @@ -747,7 +745,7 @@ pub(in crate::ast) fn literal_widths( true, ) && ty.width <= constant_folding::MAX_CONSTANT_CONCAT_BITS - && let Some(value) = eval_ast_const_expr(&tree.state, &proof, &dims.const_env) + && let Some(value) = eval_ast_const_expr(&tree.functions, &proof, &dims.const_env) { for id in visited { match &native.expression(id).kind { @@ -829,7 +827,7 @@ fn proof(root: ExprId, tree: &AnalysisContext<'_>, dims: &PackedDimensions) -> C dims.parameter_values .get(&name) .filter(|value| { - expr_static_width(&tree.state, value, dims).is_some_and(|width| { + expr_static_width(tree, value, dims).is_some_and(|width| { width <= constant_folding::MAX_CONSTANT_CONCAT_BITS }) }) @@ -863,7 +861,7 @@ fn proof(root: ExprId, tree: &AnalysisContext<'_>, dims: &PackedDimensions) -> C expression_binding::native_name(tree, base, native).is_some_and(|name| { dims.parameter_values .get(&name) - .and_then(|value| expr_static_width(&tree.state, value, dims)) + .and_then(|value| expr_static_width(tree, value, dims)) .is_some_and(|width| { width <= constant_folding::MAX_CONSTANT_CONCAT_BITS }) @@ -874,7 +872,7 @@ fn proof(root: ExprId, tree: &AnalysisContext<'_>, dims: &PackedDimensions) -> C expression_binding::bind(id, tree, &context) .ok() .and_then(|value| { - selects::indexed_expression_value(&tree.state, value, &context) + selects::indexed_expression_value(tree, value, &context) }) .map(const_expr_to_expr) .unwrap_or_else(unknown) @@ -1387,7 +1385,7 @@ mod tests { .unwrap() .unwrap(); assert_eq!( - eval_ast_const_expr(&tree.state, &value, &HashMap::default()), + eval_ast_const_expr(&tree.functions, &value, &HashMap::default()), Some(expected) ); } diff --git a/crates/celox-sv-analyzer/src/ast/parameters/tests.rs b/crates/celox-sv-analyzer/src/ast/parameters/tests.rs index ae822777444..9fa6207b781 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/tests.rs @@ -10,7 +10,6 @@ fn unresolved_local_parameter_masks_imported_bindings() { ) .unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let state = tree.state.as_ref(); let imported = scope::ScopeSymbols { const_env: [("W".into(), 18)].into_iter().collect(), parameter_values: [("W".into(), Expr::Literal("8'd18".into()))] @@ -32,17 +31,17 @@ fn unresolved_local_parameter_masks_imported_bindings() { "required W must not use an imported default" ); let values = - parameter_value_env_with_imported(state, ¶meters, &imported.const_env, &imported); + parameter_value_env_with_imported(&tree, ¶meters, &imported.const_env, &imported); assert!(!values.contains_key("W")); let mut numeric = imported.const_env.clone(); - extend_const_env_with_parameters(state, &mut numeric, ¶meters); + extend_const_env_with_parameters(&tree, &mut numeric, ¶meters); assert!(!numeric.contains_key("W")); let overrides = [("W".into(), ConstExpr::Literal("21".into()))] .into_iter() .collect(); let specialized = parameters_from_scope(&tree, &HashMap::default(), &imported.const_env, &overrides).unwrap(); - let values = const_env_from_parameters(state, &specialized); + let values = const_env_from_parameters(&tree, &specialized); assert_eq!(values["W"], 21); assert_eq!(values["N"], 5); } @@ -181,7 +180,6 @@ fn incremental_collection_binds_each_prefix_entry_once() { let tree = crate::source_tree::parse_scope_fixture(&code, Path::new("parameter_prefix.sv")).unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let state = tree.state.as_ref(); PARAMETER_BINDINGS.with(|count| count.set(0)); let parameters = parameters_from_scope( &tree, @@ -192,7 +190,7 @@ fn incremental_collection_binds_each_prefix_entry_once() { .unwrap(); assert_eq!(PARAMETER_BINDINGS.with(|count| count.get()), 128); assert_eq!(parameters.len(), 128); - assert_eq!(const_env_from_parameters(state, ¶meters)["P127"], 128); + assert_eq!(const_env_from_parameters(&tree, ¶meters)["P127"], 128); PARAMETER_BINDINGS.with(|count| count.set(0)); let enums = enum_member_constants_from_scope( &tree, @@ -325,7 +323,6 @@ fn collects_the_declarations_of_a_package() { endpackage\n"; let tree = crate::source_tree::parse_scope_fixture(code, Path::new("package.sv")).unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let state = tree.state.as_ref(); let parameters = parameters_from_scope( &tree, &HashMap::default(), @@ -333,7 +330,7 @@ fn collects_the_declarations_of_a_package() { &HashMap::default(), ) .unwrap(); - let env = const_env_from_parameters(state, ¶meters); + let env = const_env_from_parameters(&tree, ¶meters); assert_eq!((env["W"], env["N"]), (4, 8)); let aliases = type_aliases_from_scope_with_env(&tree, &env).unwrap(); assert_eq!(aliases["word_t"].packed_ranges().len(), 1); @@ -362,7 +359,6 @@ fn numeric_ranged_headers_do_not_copy_the_environment() { let tree = crate::source_tree::parse_scope_fixture(&code, Path::new("ranged_prefix.sv")).unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let state = tree.state.as_ref(); DECLARATION_ENV_COPIES.with(|copies| copies.set(0)); let parameters = parameters_from_scope( &tree, @@ -379,7 +375,7 @@ fn numeric_ranged_headers_do_not_copy_the_environment() { .all(|parameter| parameter.declared_width() == Some(32)) ); assert_eq!( - const_env_from_parameters(state, ¶meters)[&format!("P{}", count - 1)], + const_env_from_parameters(&tree, ¶meters)[&format!("P{}", count - 1)], count as i128 ); } @@ -456,14 +452,13 @@ fn four_state_prefix_keeps_the_separate_range_projection() { ) .unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let state = tree.state.as_ref(); let base = HashMap::from_iter([("P".into(), 99)]); DECLARATION_ENV_COPIES.with(|copies| copies.set(0)); let parameters = parameters_from_scope(&tree, &HashMap::default(), &base, &HashMap::default()).unwrap(); assert_eq!(DECLARATION_ENV_COPIES.with(|copies| copies.get()), 2); assert_eq!(parameters[1].declared_width(), Some(8)); - assert_eq!(const_env_from_parameters(state, ¶meters)["Q"], 255); + assert_eq!(const_env_from_parameters(&tree, ¶meters)["Q"], 255); } #[test] @@ -485,15 +480,14 @@ fn four_state_parameter_chains_do_not_copy_growing_environments() { ) .unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let state = tree.state.as_ref(); DECLARATION_ENV_COPIES.with(|copies| copies.set(0)); LITERAL_ENV_COPIES.with(|copies| copies.set(0)); let source = Source::from_syntax(&tree).unwrap(); let parameters = source.modules()[0].parameters(); let values = parameter_value_env( - state, + &tree, parameters, - &const_env_from_parameters(state, parameters), + &const_env_from_parameters(&tree, parameters), ); assert_eq!(values.len(), count); for parameter in parameters { @@ -585,7 +579,8 @@ fn copied_resolved_literal( types: &HashMap, literals: &HashMap, ) -> Option { - let state = &crate::ast::AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); let mut evaluation_constants = constants.clone(); evaluation_constants.remove(parameter.name()); let mut substituted = parameter.clone(); @@ -598,19 +593,20 @@ fn copied_resolved_literal( substituted.declared_signed = Some(ty.signed); } let value = parameter_value_env( - state, + &tree, std::slice::from_ref(&substituted), &evaluation_constants, ) .remove(parameter.name())?; let value = substitute_expr_idents(value, literals); - let value = fold_const_integral_expr_preserving_mask(state, value, &evaluation_constants); + let value = fold_const_integral_expr_preserving_mask(&tree, value, &evaluation_constants); matches!(value, Expr::Literal(_)).then_some(value) } #[test] fn borrowed_literal_environment_matches_self_masked_copy_with_types_and_unknowns() { - let state = &crate::ast::AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); let mut constants = HashMap::from_iter([("A".into(), -2), (unbounded_parameter_marker("U"), 1)]); insert_parameter_type_markers( @@ -669,7 +665,7 @@ fn borrowed_literal_environment_matches_self_masked_copy_with_types_and_unknowns false, ); LITERAL_ENV_COPIES.with(|copies| copies.set(0)); - let borrowed = parameter.resolved_literal(state, &env, &types, &literals); + let borrowed = parameter.resolved_literal(&tree, &env, &types, &literals); assert_eq!( LITERAL_ENV_COPIES.with(|copies| copies.get()), usize::from(stale_self.is_some()) @@ -727,17 +723,19 @@ fn separately_resolved_value_and_literal( types: &HashMap, literals: &HashMap, ) -> (Option, Option) { - let state = &crate::ast::AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); + let state = &*tree.state; // The former two-stage caller: numeric fallback discards its literal, // then a nonnumeric result requires literal resolution again. let value = parameter - .resolved_value(state, constants, types) + .resolved_value(&tree.functions, constants, types) .or_else(|| { - let literal = parameter.resolved_literal(state, constants, types, literals)?; - eval_ast_const_expr(state, &expr_to_const(state, literal)?, constants) + let literal = parameter.resolved_literal(&tree, constants, types, literals)?; + eval_ast_const_expr(&tree.functions, &expr_to_const(state, literal)?, constants) }); let literal = if value.is_none() { - parameter.resolved_literal(state, constants, types, literals) + parameter.resolved_literal(&tree, constants, types, literals) } else { None }; @@ -746,7 +744,8 @@ fn separately_resolved_value_and_literal( #[test] fn retained_parameter_literals_match_separate_resolution_across_types_and_dependencies() { - let state = &crate::ast::AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); let mut constants = HashMap::from_iter([("A".into(), -2), (unbounded_parameter_marker("U"), 1)]); insert_parameter_type_markers( @@ -807,7 +806,7 @@ fn retained_parameter_literals_match_separate_resolution_across_types_and_depend false, ); LITERAL_RESOLUTIONS.with(|calls| calls.set(0)); - let retained = parameter.resolved_value_and_literal(state, &env, &types, &literals); + let retained = parameter.resolved_value_and_literal(&tree, &env, &types, &literals); assert!(LITERAL_RESOLUTIONS.with(|calls| calls.get()) <= 1); assert!(!(retained.0.is_some() && retained.1.is_some())); assert_eq!( @@ -829,7 +828,7 @@ fn retained_parameter_literals_match_separate_resolution_across_types_and_depend ); LITERAL_RESOLUTIONS.with(|calls| calls.set(0)); assert_eq!( - numeric.resolved_value_and_literal(state, &constants, &types, &literals), + numeric.resolved_value_and_literal(&tree, &constants, &types, &literals), (Some(7), None) ); assert_eq!(LITERAL_RESOLUTIONS.with(|calls| calls.get()), 0); @@ -844,7 +843,7 @@ fn retained_parameter_literals_match_separate_resolution_across_types_and_depend ); LITERAL_RESOLUTIONS.with(|calls| calls.set(0)); assert_eq!( - two_state.resolved_value_and_literal(state, &constants, &types, &literals), + two_state.resolved_value_and_literal(&tree, &constants, &types, &literals), (Some(-125), None) ); assert_eq!(LITERAL_RESOLUTIONS.with(|calls| calls.get()), 1); @@ -890,7 +889,8 @@ fn module_parameter_bindings_and_ir_resolve_each_unknown_literal_once() { #[test] fn generate_bindings_keep_numeric_literals_and_unresolved_fallback_order() { - let state = &crate::ast::AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); for (initializer, two_state, expected_value) in [("X", false, 91), ("X", true, -125), ("missing", false, 91)] { @@ -908,7 +908,7 @@ fn generate_bindings_keep_numeric_literals_and_unresolved_fallback_order() { ); LITERAL_RESOLUTIONS.with(|calls| calls.set(0)); constants::bind_generate_parameter_with_types( - state, + &tree, parameter, &mut env, &mut literals, @@ -945,7 +945,8 @@ fn compare_retained_and_repeated_parameter_resolution() { use std::time::Instant; fn replay(parameters: &[Parameter], repeated: bool) { - let state = &crate::ast::AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); let mut env = HashMap::default(); let mut types = HashMap::default(); let mut literals = HashMap::default(); @@ -953,7 +954,7 @@ fn compare_retained_and_repeated_parameter_resolution() { let (value, literal) = if repeated { separately_resolved_value_and_literal(parameter, &env, &types, &literals) } else { - parameter.resolved_value_and_literal(state, &env, &types, &literals) + parameter.resolved_value_and_literal(&tree, &env, &types, &literals) }; assert!(value.is_none()); let ty = parameter.resolved_type(&types).unwrap(); @@ -1019,7 +1020,8 @@ fn compare_retained_and_repeated_parameter_resolution() { #[test] fn referenced_value_projection_matches_full_environment() { - let state = &crate::ast::AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); let p = |name: &str, value: ConstExpr, width: Option, two_state: bool| { Parameter::new( name.into(), @@ -1109,10 +1111,10 @@ fn referenced_value_projection_matches_full_environment() { HashMap::default(), HashMap::from_iter([("B".into(), -3), ("typed_known".into(), -1)]), ] { - let full = parameter_value_env(state, ¶meters, &env); + let full = parameter_value_env(&tree, ¶meters, &env); for parameter in ¶meters { let wanted = HashSet::from_iter([parameter.name().to_string()]); - let projected = parameter_value_env_for_references(state, ¶meters, &env, &wanted); + let projected = parameter_value_env_for_references(&tree, ¶meters, &env, &wanted); assert_eq!( projected.get(parameter.name()), full.get(parameter.name()), @@ -1126,7 +1128,7 @@ fn referenced_value_projection_matches_full_environment() { PARAMETER_VALUE_MATERIALIZATIONS.with(|count| count.set(0)); assert!( parameter_value_env_for_references( - state, + &tree, ¶meters, &env, &HashSet::from_iter(["not_a_parameter".into()]) @@ -1139,7 +1141,8 @@ fn referenced_value_projection_matches_full_environment() { #[test] fn numeric_projection_does_not_expand_initializer_dependencies() { - let state = &crate::ast::AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); let parameters = vec![ Parameter::new( "A".into(), @@ -1163,7 +1166,7 @@ fn numeric_projection_does_not_expand_initializer_dependencies() { let env = HashMap::from_iter([("B".into(), 3)]); PARAMETER_VALUE_MATERIALIZATIONS.with(|count| count.set(0)); let projected = parameter_value_env_for_references( - state, + &tree, ¶meters, &env, &HashSet::from_iter(["B".into()]), @@ -1172,7 +1175,7 @@ fn numeric_projection_does_not_expand_initializer_dependencies() { assert_eq!(projected.len(), 1); assert_eq!( projected["B"], - parameter_value_env(state, ¶meters, &env)["B"] + parameter_value_env(&tree, ¶meters, &env)["B"] ); } @@ -1183,7 +1186,8 @@ fn compare_full_and_referenced_parameter_values() { std::thread::Builder::new() .stack_size(16 * 1024 * 1024) .spawn(|| { - let state = &crate::ast::AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); use std::{hint::black_box, time::Instant}; println!("parameters,full_ms,referenced_ms,full_values,referenced_values"); for count in [32, 128, 512] { @@ -1210,14 +1214,14 @@ fn compare_full_and_referenced_parameter_values() { .collect(); let env = HashMap::default(); let references = HashSet::from_iter(["P0".into()]); - let expected = parameter_value_env(state, ¶meters[..1], &env)["P0"].clone(); + let expected = parameter_value_env(&tree, ¶meters[..1], &env)["P0"].clone(); let run = |full: bool| { let start = Instant::now(); let values = if full { - parameter_value_env(state, black_box(¶meters), &env) + parameter_value_env(&tree, black_box(¶meters), &env) } else { parameter_value_env_for_references( - state, + &tree, black_box(¶meters), &env, &references, @@ -1251,7 +1255,8 @@ fn compare_full_and_referenced_parameter_values() { #[test] fn unbounded_binding_keeps_declared_rank_without_a_numeric_value() { - let state = &crate::ast::AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); let mut env = HashMap::default(); let mut types = HashMap::default(); let mut literals = HashMap::default(); @@ -1266,7 +1271,7 @@ fn unbounded_binding_keeps_declared_rank_without_a_numeric_value() { false, ); assert!(bind_parameter( - state, + &tree, &mut env, &mut types, &mut literals, @@ -1283,7 +1288,8 @@ fn unbounded_binding_keeps_declared_rank_without_a_numeric_value() { #[test] fn unbounded_generate_binding_clears_inherited_numeric_values() { - let state = &crate::ast::AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); let parameter = Parameter::new( "P".into(), Some(ConstExpr::Literal("$".into())), @@ -1300,7 +1306,7 @@ fn unbounded_generate_binding_clears_inherited_numeric_values() { (unbounded_parameter_marker("P"), 0), ]); let mut literals = HashMap::default(); - bind_generate_parameter(state, parameter, &mut env, &mut literals); + bind_generate_parameter(&tree, parameter, &mut env, &mut literals); assert_eq!(env.get(&unbounded_parameter_marker("P")), Some(&1)); for key in [ "P".to_string(), @@ -1314,7 +1320,8 @@ fn unbounded_generate_binding_clears_inherited_numeric_values() { #[test] fn unbounded_projection_keeps_requested_aliases_and_omits_unused_dollars() { - let state = &crate::ast::AnalysisState::default(); + let syntax = crate::source_tree::SourceTree::empty(); + let tree = AnalysisContext::unspecialized(&syntax); let parameters = vec![ Parameter::new( "U".into(), @@ -1348,10 +1355,10 @@ fn unbounded_projection_keeps_requested_aliases_and_omits_unused_dollars() { HashMap::default(), HashMap::from_iter([(unbounded_parameter_marker("U"), 1), ("U".into(), 99)]), ] { - let full = parameter_value_env(state, ¶meters, &env); + let full = parameter_value_env(&tree, ¶meters, &env); for name in ["U", "ALIAS", "NUMBER"] { let projected = parameter_value_env_for_references( - state, + &tree, ¶meters, &env, &HashSet::from_iter([name.into()]), @@ -1406,7 +1413,7 @@ fn unbased_parameter_overrides_fill_declared_width_before_dependent_parameters() if reapplied { apply_parameter_overrides(&mut parameters, &overrides).unwrap(); } - let values = const_env_from_parameters(&tree.state, ¶meters); + let values = const_env_from_parameters(&tree, ¶meters); assert_eq!(values["FILL"], unsigned, "{literal}, reapplied={reapplied}"); assert_eq!(values["SIGNED_FILL"], signed); assert_eq!(values["COPY"], unsigned); @@ -1444,7 +1451,7 @@ fn inherited_alias_prefixes_bind_once_without_copying_declaration_environments() for (index, parameter) in parameters.iter().enumerate() { assert_eq!( parameter.resolved_value( - &tree.state, + &tree.functions, &base, ¶meter_types_from_const_env(&base) ), @@ -1478,7 +1485,7 @@ fn inherited_evaluation_masks_pending_local_names_and_their_type_markers() { false, true, ); - environment.append(&tree.state, &alias); + environment.append(&tree, &alias); assert!(!environment.values.contains_key("ALIAS")); assert!(!environment.types.contains_key("LOCAL")); assert_eq!(environment.bindings.get("EXTERNAL"), Some(&8)); diff --git a/crates/celox-sv-analyzer/src/ast/patterns.rs b/crates/celox-sv-analyzer/src/ast/patterns.rs index 8bfc9e4fee3..e0a7165ed92 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns.rs @@ -10,27 +10,33 @@ mod binding; pub(super) use binding::expression as native_expression; pub(super) use binding::{bind_native, constant_native, typed_shape}; -fn eval(state: &AnalysisState, expr: &ConstExpr, dims: &PackedDimensions) -> Option { - eval_ast_const_expr(state, expr, &dims.const_env) +fn eval( + functions: &const_functions::ConstantFunctions, + expr: &ConstExpr, + dims: &PackedDimensions, +) -> Option { + eval_ast_const_expr(functions, expr, &dims.const_env) } pub(super) fn shape_width( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, shape: &VariableDimensions, dims: &PackedDimensions, ) -> Option { let mut width = 1usize; for dimension in &shape.unpacked { - width = width.checked_mul(usize::try_from(eval(state, &dimension.width, dims)?).ok()?)?; + width = + width.checked_mul(usize::try_from(eval(functions, &dimension.width, dims)?).ok()?)?; } for dimension in &shape.packed { - width = width.checked_mul(usize::try_from(eval(state, &dimension.width, dims)?).ok()?)?; + width = + width.checked_mul(usize::try_from(eval(functions, &dimension.width, dims)?).ok()?)?; } Some(width) } fn constant_pattern_value( - state: &AnalysisState, + tree: &AnalysisContext<'_>, value: Expr, shape: &VariableDimensions, dims: &PackedDimensions, @@ -43,27 +49,29 @@ fn constant_pattern_value( .collect(); let value = substitute_expr_idents(value, &dims.array_parameter_values); let value = - substitute_expr_constants_with_parameter_literals(state, value, &dims.const_env, &values); + substitute_expr_constants_with_parameter_literals(tree, value, &dims.const_env, &values); let Expr::Literal(value) = - fold_const_integral_expr_preserving_mask(state, value, &dims.const_env) + fold_const_integral_expr_preserving_mask(tree, value, &dims.const_env) else { return Err(unsupported("nonconstant typed parameter pattern")); }; let value = typecheck::parse_integral_literal(&value) .ok_or_else(|| unsupported("typed parameter pattern value"))?; - pattern_value(state, &value, shape, 0, dims) + pattern_value(tree, &value, shape, 0, dims) } fn pattern_value( - state: &AnalysisState, + tree: &AnalysisContext<'_>, value: &typecheck::IntegralLiteral, shape: &VariableDimensions, offset: usize, dims: &PackedDimensions, ) -> Converted { + let functions = &tree.functions; let mut parts = Vec::new(); if let Some((dimension, rest)) = shape.unpacked.split_first() { - let (_, _, count) = dimension_bounds(state, &dimension.left, &dimension.right, dims)?; + let (_, _, count) = + dimension_bounds(&tree.functions, &dimension.left, &dimension.right, dims)?; let element = VariableDimensions { declared: type_names::Declared::default(), container: None, @@ -73,11 +81,11 @@ fn pattern_value( unpacked: rest.to_vec(), ..shape.clone() }; - let width = shape_width(state, &element, dims) + let width = shape_width(&tree.functions, &element, dims) .ok_or_else(|| unsupported("typed pattern element width"))?; for position in 0..count { parts.push(pattern_value( - state, + tree, value, &element, offset + position * width, @@ -85,7 +93,7 @@ fn pattern_value( )?); } } else { - let width = shape_width(state, shape, dims) + let width = shape_width(&tree.functions, shape, dims) .ok_or_else(|| unsupported("typed pattern value width"))?; let mask = (num_bigint::BigUint::from(1u8) << width) - num_bigint::BigUint::from(1u8); let mut literal = typecheck::IntegralLiteral { @@ -101,21 +109,21 @@ fn pattern_value( return Ok(bound_patterns::Value::Expression { expr: Expr::Literal(typecheck::format_integral_literal_binary(&literal)), signed: Some(shape.signed), - value_type: bound_patterns::ValueType::Known(shape.pattern_type(state, dims)), + value_type: bound_patterns::ValueType::Known(shape.pattern_type(functions, dims)), }); } Ok(bound_patterns::Value::list(parts)) } fn dimension_bounds( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, left: &ConstExpr, right: &ConstExpr, dims: &PackedDimensions, ) -> Converted<(i128, i128, usize)> { let bounds = || unsupported("assignment pattern target bounds"); - let left = eval(state, left, dims).ok_or_else(bounds)?; - let right = eval(state, right, dims).ok_or_else(bounds)?; + let left = eval(functions, left, dims).ok_or_else(bounds)?; + let right = eval(functions, right, dims).ok_or_else(bounds)?; let count = usize::try_from(left.abs_diff(right)) .ok() .and_then(|count| count.checked_add(1)) @@ -127,7 +135,7 @@ fn dimension_bounds( /// descends through subarrays and structures; state conversion happens at /// the leaf so mixed bit/logic aggregates preserve their member types. pub(super) fn assignment_value( - state: &AnalysisState, + tree: &AnalysisContext<'_>, value: &Expr, signed: bool, value_type: Option<&Type>, @@ -135,6 +143,7 @@ pub(super) fn assignment_value( dims: &PackedDimensions, default: bool, ) -> Converted { + let functions = &tree.functions; // A structure-valued default of the member's own type is one whole // value. Preserve its leaf expressions instead of resizing the handles // and state bits together as an integral vector (10.9.2). @@ -150,7 +159,8 @@ pub(super) fn assignment_value( return Ok(value.clone()); } let default = default - && !value_type.is_some_and(|ty| shape.pattern_type(state, dims).as_ref() == Some(ty)); + && !value_type + .is_some_and(|ty| shape.pattern_type(&tree.functions, dims).as_ref() == Some(ty)); if default { let array = if let Some((dim, rest)) = shape.unpacked.split_first() { Some(( @@ -183,12 +193,12 @@ pub(super) fn assignment_value( None }; if let Some((width, element)) = array { - let count = eval_ast_const_expr(state, width, &dims.const_env) + let count = eval_ast_const_expr(functions, width, &dims.const_env) .and_then(|n| usize::try_from(n).ok()) .ok_or_else(|| unsupported("pattern target array size"))?; return Ok(Expr::Concat(vec![ assignment_value( - state, value, signed, value_type, &element, dims, true + tree, value, signed, value_type, &element, dims, true )?; count ])); @@ -200,7 +210,7 @@ pub(super) fn assignment_value( .iter() .map(|member| { assignment_value( - state, + tree, value, signed, value_type, @@ -228,7 +238,7 @@ pub(super) fn assignment_value( .iter() .map(|member| { assignment_value( - state, + tree, value, signed, value_type, @@ -251,11 +261,11 @@ pub(super) fn assignment_value( let actual_shape = value_type.map(procedural::dimensions_from_type); let actual = actual_shape .as_ref() - .and_then(|actual| array_compatibility::unpacked_array_type(state, actual, dims)); - let target = array_compatibility::unpacked_array_type(state, shape, dims); + .and_then(|actual| array_compatibility::unpacked_array_type(&tree.functions, actual, dims)); + let target = array_compatibility::unpacked_array_type(&tree.functions, shape, dims); if let Some((actual, target)) = actual_shape .as_ref() - .and_then(|actual| array_compatibility::incompatible(state, actual, shape, dims)) + .and_then(|actual| array_compatibility::incompatible(tree, actual, shape, dims)) { return Err(AnalyzerError::IncompatibleUnpackedArray { context: "assignment pattern element".into(), @@ -276,7 +286,7 @@ pub(super) fn assignment_value( } _ => {} } - let width = shape_width(state, shape, dims) + let width = shape_width(&tree.functions, shape, dims) .ok_or_else(|| unsupported("assignment pattern element width"))?; let resized = Expr::Resize { expr: Box::new(value.clone()), diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index d37a98ed461..ec0d309230c 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -96,7 +96,7 @@ fn indexed_items( } } fn select<'a>( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, kind: NativeKind, bindings: Vec, shape: Shape<'a>, @@ -112,7 +112,7 @@ fn select<'a>( )); } if let Some((dim, rest)) = shape.unpacked.split_first() { - let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?; + let (left, right, count) = dimension_bounds(functions, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { declared: type_names::Declared::default(), container: None, @@ -145,7 +145,7 @@ fn select<'a>( if let Some((dim, rest)) = shape.packed.split_first() && !rest.is_empty() { - let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?; + let (left, right, count) = dimension_bounds(functions, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { declared: type_names::Declared::default(), container: None, @@ -259,7 +259,7 @@ fn select<'a>( false, )); } - let width = shape_width(state, &shape, dims) + let width = shape_width(functions, &shape, dims) .ok_or_else(|| unsupported("assignment pattern target width"))?; let bit = Shape::Owned(Rc::new(VariableDimensions { declared: type_names::Declared::default(), @@ -347,7 +347,7 @@ pub(in crate::ast) fn constant_native( let shape = typed_shape(root, tree, dims)?.ok_or_else(|| unsupported("assignment pattern type"))?; let value = bind_native(root, tree.declarations(), tree, dims, Some(&shape))?; - super::constant_pattern_value(&tree.state, value, &shape, dims) + super::constant_pattern_value(tree, value, &shape, dims) } pub(in crate::ast) fn expression( root: ExprId, @@ -386,7 +386,7 @@ pub(in crate::ast) fn bind_native( Job::Pattern(id, shape) => { let plan = bound_patterns::prepare_native(id, tree, dims, Some(&shape))?; let (items, reverse, keep) = - select(&tree.state, plan.kind, plan.bindings, shape, dims)?; + select(&tree.functions, plan.kind, plan.bindings, shape, dims)?; jobs.push(Job::Finish { count: items.len(), reverse, @@ -410,7 +410,8 @@ pub(in crate::ast) fn bind_native( && !pattern && native_rank(id, native, dims) < shape.unpacked.len() { - let (_, _, count) = dimension_bounds(&tree.state, &dim.left, &dim.right, dims)?; + let (_, _, count) = + dimension_bounds(&tree.functions, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { declared: type_names::Declared::default(), container: None, @@ -516,7 +517,7 @@ pub(in crate::ast) fn bind_native( || native_rank(id, native, dims) < shape.unpacked.len()); let value_type = bound_patterns::native_value_type(id, tree, &type_dims)?; values.push(assignment_value( - &tree.state, + tree, &value, signed, value_type.as_ref(), diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 92ba2db05cd..78ae412ac92 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -447,7 +447,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { scoped_type(r#type, &self.dims.const_env), &const_functions::Environment { constants: &*self.dims.const_env, - functions: &self.tree.state.const_functions, + functions: &self.tree.functions, }, ), }); @@ -808,7 +808,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } else { let value = expression_binding::value(right, self.tree.declarations(), self.tree, &self.dims)?; - assignment_op_expr(&self.tree.state, &written, op, value, &self.dims)? + assignment_op_expr(self.tree, &written, op, value, &self.dims)? }; // Preserve assignment sizing before checked accesses introduce a temporary // (IEEE 1800-2023 11.8.2), using the selected destination width. @@ -823,10 +823,10 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .as_ref() .is_some_and(|(guards, _)| !guards.is_empty()) { - rhs = coerce_procedural_assignment_rhs(&self.tree.state, rhs, &written, &self.dims); + rhs = coerce_procedural_assignment_rhs(self.tree, rhs, &written, &self.dims); } if let Some((guards, _)) = member_context { - rhs = packed_structs::checked_value(guards, rhs, &self.tree.state, &self.dims)?; + rhs = packed_structs::checked_value(guards, rhs, self.tree, &self.dims)?; } self.rename_expr(&mut rhs); Ok(Stmt::Assign { @@ -1099,7 +1099,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { if expression_binding::real_value(¤t, &self.dims) { return Err(unsupported("`$sformat` output that is not a string")); } - let ty = dimensions::bound_bits_type(&self.tree.state, ¤t, &self.dims) + let ty = dimensions::bound_bits_type(self.tree, ¤t, &self.dims) .ok_or_else(|| unsupported("`$sformat` output that is not a string"))?; let mut bits = Type::new(TypeKind::Logic); if ty.width > 1 { @@ -1305,7 +1305,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { let rhs = if op == "=" { value.clone() } else { - assignment_op_expr(&self.tree.state, &lhs, op, value.clone(), &self.dims)? + assignment_op_expr(self.tree, &lhs, op, value.clone(), &self.dims)? }; Ok(vec![Stmt::Assign { lhs, @@ -1947,7 +1947,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { let entry = self.take_binding(name, None, parameter.packed_ranges.len()); types.remove(name); if !parameters::bind_parameter( - &self.tree.state, + self.tree, &mut self.dims.const_env, &mut types, &mut self.dims.parameter_values, @@ -2403,7 +2403,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { None } else { expr_to_const(&self.tree.state, condition.clone()).and_then(|condition| { - eval_ast_const_expr(&self.tree.state, &condition, &self.dims.const_env) + eval_ast_const_expr(&self.tree.functions, &condition, &self.dims.const_env) }) }; if let Some(value) = constant { @@ -2443,7 +2443,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.tree, &self.dims, )?; - let mut condition = statements::simplify_condition(&self.tree.state, condition, &self.dims); + let mut condition = statements::simplify_condition(self.tree, condition, &self.dims); self.rename_expr(&mut condition); Ok(condition) } @@ -2569,9 +2569,9 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { let (left, right) = bounds .get(position) .ok_or_else(|| unsupported("foreach index beyond the array dimensions"))?; - let left = eval_ast_const_expr(&self.tree.state, left, &self.dims.const_env) + let left = eval_ast_const_expr(&self.tree.functions, left, &self.dims.const_env) .ok_or_else(|| unsupported("foreach bound"))?; - let right = eval_ast_const_expr(&self.tree.state, right, &self.dims.const_env) + let right = eval_ast_const_expr(&self.tree.functions, right, &self.dims.const_env) .ok_or_else(|| unsupported("foreach bound"))?; let name = self.declare(&variable, int_type()); loops.push(ForeachLoop::Static(name, left, right)); @@ -2788,7 +2788,7 @@ pub(super) fn subroutine_argument_names( let tree = &item.scoped(tree); for native_id in subroutine_owners::item(item.id, tree)? { let native = tree.declarations().subroutine(native_id); - let _constant_functions = item.enter(); + let tree = &item.enter(tree); let params = subroutine_param_declarations( native, tree, @@ -2810,7 +2810,7 @@ pub(super) fn subroutine_argument_names( shapes.insert(qualified, param_shapes); } for class in classes::item_classes(item.id, tree) { - let _constant_functions = item.enter(); + let tree = &item.enter(tree); let aliases = item.type_aliases(type_aliases); // A specialization's methods see its parameters (8.25). let (env, aliases) = classes::specializations::scope(tree, &class, &item.env, &aliases); @@ -3006,7 +3006,7 @@ pub(super) fn subroutines_with_symbolic_parameters( ) }; - let _constant_functions = item.enter(); + let tree = &item.enter(tree); let type_aliases = item.type_aliases(module_type_aliases); let name = instances::normalize_identifier( &tree.declarations().subroutine(native_id).name.spelling, @@ -3044,7 +3044,7 @@ pub(super) fn subroutines_with_symbolic_parameters( } for class in classes::item_classes(item.id, tree) { let (item_dimensions, literals) = views.get(item); - let _constant_functions = item.enter(); + let tree = &item.enter(tree); let type_aliases = item.type_aliases(module_type_aliases); match ( lower_class( @@ -3334,7 +3334,7 @@ pub(super) fn lower_subroutine( scoped_type(r#type, declaration_env), &const_functions::Environment { constants: &*item.env, - functions: &tree.state.const_functions, + functions: &tree.functions, }, ), default, @@ -3524,7 +3524,7 @@ pub(super) fn lower_subroutine( scoped_type(r#type, declaration_env), &const_functions::Environment { constants: &*item.env, - functions: &tree.state.const_functions, + functions: &tree.functions, }, ) }), @@ -3539,13 +3539,13 @@ pub(super) fn lower_subroutine( .chain(&mut subroutine.sensitivity_body) { qualify_stmt(item, stmt); - substitute_stmt_constants(&tree.state, stmt, declaration_env, literals); + substitute_stmt_constants(tree, stmt, declaration_env, literals); } for param in &mut subroutine.params { if let Some(default) = &mut param.default { item.expr(default); *default = substitute_expr_constants_with_parameter_literals( - &tree.state, + tree, default.clone(), &item.env, literals, @@ -3577,12 +3577,12 @@ pub(super) fn lower_subroutine( } } if suspends { - lifetimes::check_constant_initializers(&tree.state, &subroutine.body, &statics)?; + lifetimes::check_constant_initializers(tree, &subroutine.body, &statics)?; } if !builder.state.constant_evaluation { let retain_result = !builder.automatic && lifetimes::check_static_result( - &tree.state, + tree, &builder.dims.const_env, builder.state.locals, &subroutine, @@ -3595,7 +3595,7 @@ pub(super) fn lower_subroutine( .filter(|(name, _)| { suspends || lifetimes::check_subroutine_statics( - &tree.state, + tree, &subroutine, &builder.dims.const_env, builder.state.locals, @@ -3607,7 +3607,7 @@ pub(super) fn lower_subroutine( .map(|(name, ty)| (name.clone(), ty.clone())) .collect::>(); let (mut kept, mut initializers) = lifetimes::keep_static_locals( - &tree.state, + tree, &retained_types, builder.state.subroutine_directions, std::iter::once((&mut subroutine.body, false)), @@ -3631,7 +3631,7 @@ pub(super) fn lower_subroutine( } for initializer in &mut initializers { qualify_stmt(item, initializer); - substitute_stmt_constants(&tree.state, initializer, declaration_env, literals); + substitute_stmt_constants(tree, initializer, declaration_env, literals); } for name in &kept { let ty = static_types @@ -4062,16 +4062,14 @@ impl BodyBuilder<'_, '_, '_> { self.dims.property_select_base = Some(base); let target = expression_binding::value(left, native, self.tree, &self.dims); self.dims.property_select_base = None; - dimensions::bound_bits_type(&self.tree.state, &target.ok()?, &self.dims) - .map(|ty| ty.width) + dimensions::bound_bits_type(self.tree, &target.ok()?, &self.dims).map(|ty| ty.width) }); let rhs = lhs.and_then(|lhs| { let rhs = if op == "=" { expression_binding::expression(right, native, &lhs, self.tree, &self.dims) } else { - expression_binding::value(right, native, self.tree, &self.dims).and_then(|value| { - assignment_op_expr(&self.tree.state, &lhs, op, value, &self.dims) - }) + expression_binding::value(right, native, self.tree, &self.dims) + .and_then(|value| assignment_op_expr(self.tree, &lhs, op, value, &self.dims)) }; let mut lhs = lhs; self.rename_lvalue(&mut lhs); @@ -4164,7 +4162,7 @@ impl BodyBuilder<'_, '_, '_> { reads: &mut Vec<(ConstExpr, String)>, body: &mut Vec, ) -> Converted<()> { - if eval_ast_const_expr(&self.tree.state, expr, &self.dims.const_env).is_some() { + if eval_ast_const_expr(&self.tree.functions, expr, &self.dims.const_env).is_some() { return Ok(()); } match expr { @@ -4205,7 +4203,7 @@ impl BodyBuilder<'_, '_, '_> { Some((_, source)) => source.clone(), None => { let mut value = parameters::const_expr_to_expr(expr.clone()); - let ty = dimensions::bound_bits_type(&self.tree.state, &value, &self.dims) + let ty = dimensions::bound_bits_type(self.tree, &value, &self.dims) .ok_or_else(|| unsupported("index of a select of a class property"))?; let (source, unique) = self.hidden(vector_type(ty.width, ty.signed)); self.rename_expr(&mut value); @@ -4451,7 +4449,7 @@ fn lower_class( scoped_type(handle.clone(), declaration_env), &const_functions::Environment { constants: &*item.env, - functions: &tree.state.const_functions, + functions: &tree.functions, }, ); let mut builder = BodyBuilder::new( @@ -4496,7 +4494,7 @@ fn lower_class( }; for stmt in &mut subroutine.body { qualify_stmt(item, stmt); - substitute_stmt_constants(&tree.state, stmt, declaration_env, literals); + substitute_stmt_constants(tree, stmt, declaration_env, literals); } subroutines.push(subroutine); } @@ -4539,7 +4537,7 @@ fn lower_cast( ) -> Converted { let environment = const_functions::Environment { constants: &*item.env, - functions: &tree.state.const_functions, + functions: &tree.functions, }; let handle = classes::handle_type(tree, name).ok_or_else(|| unsupported(format!("class `{name}`")))?; @@ -4640,7 +4638,7 @@ pub(super) fn qualify_stmt(item: &generate::Item, stmt: &mut Stmt) { /// Replace parameters and genvars by their values. pub(super) fn substitute_stmt_constants( - state: &AnalysisState, + tree: &AnalysisContext<'_>, stmt: &mut Stmt, const_env: &HashMap, literals: &HashMap, @@ -4648,7 +4646,7 @@ pub(super) fn substitute_stmt_constants( stmt.visit_mut( &mut |expr| { *expr = substitute_expr_constants_with_parameter_literals( - state, + tree, expr.clone(), const_env, literals, @@ -4681,7 +4679,7 @@ pub(super) fn initial_processes_from_scope( if item.is_parameter_declaration(tree.declarations()) { continue; } - let _constant_functions = item.enter(); + let tree = &item.enter(tree); let mut assignments = Vec::new(); if let celox_sv_syntax::BodyItemKind::Data(id) = tree.declarations().body_item(item.id).kind { @@ -4796,7 +4794,7 @@ pub(super) fn initial_processes_from_scope( // The parameters of the class are its own constants. if scoped.is_some() { substitute_stmt_constants( - &tree.state, + tree, &mut stmt, &item_dimensions.const_env, literals, @@ -4806,9 +4804,9 @@ pub(super) fn initial_processes_from_scope( } let (_, literals) = views.get(item); for stmt in &mut body { - substitute_stmt_constants(&tree.state, stmt, &item.env, literals); + substitute_stmt_constants(tree, stmt, &item.env, literals); qualify_stmt(item, stmt); - substitute_stmt_constants(&tree.state, stmt, const_env, parameter_literals); + substitute_stmt_constants(tree, stmt, const_env, parameter_literals); } if !body.is_empty() { initializers.push(InitialProcess { @@ -4883,9 +4881,9 @@ pub(super) fn initial_processes_from_scope( body }; for stmt in body.iter_mut().chain(&mut validation_body) { - substitute_stmt_constants(&tree.state, stmt, &item.env, literals); + substitute_stmt_constants(tree, stmt, &item.env, literals); qualify_stmt(item, stmt); - substitute_stmt_constants(&tree.state, stmt, const_env, parameter_literals); + substitute_stmt_constants(tree, stmt, const_env, parameter_literals); } processes.push(InitialProcess { creation_order, @@ -5151,7 +5149,7 @@ fn dump_selection_name( let mut value = constant_binding::bind(*index, tree, dimensions)? .ok_or_else(|| unsupported("$dumpvars hierarchy index must be constant"))?; rename(&mut value); - let index = eval_ast_const_expr(&tree.state, &value, &dimensions.const_env) + let index = eval_ast_const_expr(&tree.functions, &value, &dimensions.const_env) .ok_or_else(|| { unsupported("$dumpvars hierarchy index must be a known constant integer") })?; diff --git a/crates/celox-sv-analyzer/src/ast/procedural/effects.rs b/crates/celox-sv-analyzer/src/ast/procedural/effects.rs index 28d612b065e..57c266d0e62 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/effects.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/effects.rs @@ -353,7 +353,7 @@ impl BodyBuilder<'_, '_, '_> { self.write_update(operand, id, stmts)?; return Ok(()); }; - let ty = dimensions::bound_bits_type(&self.tree.state, ¤t, &self.dims) + let ty = dimensions::bound_bits_type(self.tree, ¤t, &self.dims) .ok_or_else(|| unsupported("increment or decrement of this operand"))?; // The local is of the operand's type, so a prefix result is the value // the update stores. diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index 752407733c6..587fd5bb73d 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -48,7 +48,7 @@ fn lower_methods( ty, &const_functions::Environment { constants: env, - functions: &tree.state.const_functions, + functions: &tree.functions, }, ) }; diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs index f280f8e7993..9f58b30d9ba 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs @@ -178,7 +178,7 @@ impl BodyBuilder<'_, '_, '_> { }), }); } - virtual_interfaces::watched(&self.tree.state, handle, &ty, &member)? + virtual_interfaces::watched(self.tree, handle, &ty, &member)? } None => self.native_value(item.expression)?, }; diff --git a/crates/celox-sv-analyzer/src/ast/selects.rs b/crates/celox-sv-analyzer/src/ast/selects.rs index 7126968f141..29a11fcd9f6 100644 --- a/crates/celox-sv-analyzer/src/ast/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/selects.rs @@ -3,7 +3,7 @@ use super::*; pub(super) fn constant_packed_indices_in_range( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, name: &str, indices: &[ConstExpr], dimensions: &PackedDimensions, @@ -15,7 +15,7 @@ pub(super) fn constant_packed_indices_in_range( return false; } indices.iter().enumerate().all(|(position, index)| { - let Some(index) = eval_ast_const_expr(state, index, &dimensions.const_env) else { + let Some(index) = eval_ast_const_expr(functions, index, &dimensions.const_env) else { return false; }; let Some(dimension) = variable.packed.get(position) else { @@ -23,8 +23,8 @@ pub(super) fn constant_packed_indices_in_range( return index == 0; }; let (Some(left), Some(right)) = ( - eval_ast_const_expr(state, &dimension.left, &dimensions.const_env), - eval_ast_const_expr(state, &dimension.right, &dimensions.const_env), + eval_ast_const_expr(functions, &dimension.left, &dimensions.const_env), + eval_ast_const_expr(functions, &dimension.right, &dimensions.const_env), ) else { return false; }; @@ -35,7 +35,7 @@ pub(super) fn constant_packed_indices_in_range( /// Why a select of `name` with constant `indices` and, for a part-select, /// `bounds` has no representation. fn select_error( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, name: &str, indices: &[ConstExpr], bounds: Option<(&ConstExpr, &ConstExpr)>, @@ -61,7 +61,7 @@ fn select_error( .map(|range| (&range.left, &range.right)), ); for (position, (index, (left, right))) in indices.iter().zip(ranges.clone()).enumerate() { - if const_expr_is_out_of_range(state, index, left, right, const_env) { + if const_expr_is_out_of_range(functions, index, left, right, const_env) { return unsupported(format!( "index {} of `{name}` outside its declared range", position + 1 @@ -70,8 +70,8 @@ fn select_error( } if let Some((msb, lsb)) = bounds && let Some((left, right)) = ranges.clone().nth(indices.len()) - && (const_expr_is_out_of_range(state, msb, left, right, const_env) - || const_expr_is_out_of_range(state, lsb, left, right, const_env)) + && (const_expr_is_out_of_range(functions, msb, left, right, const_env) + || const_expr_is_out_of_range(functions, lsb, left, right, const_env)) { return unsupported(format!( "part-select of `{name}` outside its declared range" @@ -82,7 +82,7 @@ fn select_error( /// Syntax-independent index-only assignment target flattening. pub(super) fn lvalue_from_indices( - state: &AnalysisState, + tree: &AnalysisContext<'_>, name: String, indices: Vec, packed_dimensions: &PackedDimensions, @@ -92,7 +92,7 @@ pub(super) fn lvalue_from_indices( { if !packed_indices.is_empty() { if let Some((msb, lsb)) = - flatten_packed_select(state, &name, &packed_indices, packed_dimensions) + flatten_packed_select(tree, &name, &packed_indices, packed_dimensions) { let signed = selects_signed_element(&name, packed_indices.len(), packed_dimensions); return Ok(LValue::Select { @@ -162,7 +162,7 @@ pub(super) fn lvalue_from_indices( .is_some_and(|dimensions| !dimensions.unpacked.is_empty()) { return Err(select_error( - state, + &tree.functions, &name, &indices, None, @@ -190,10 +190,11 @@ pub(super) fn lvalue_from_indices( /// Keep the selected integral type even in an unselected conditional arm: /// both operands determine the conditional width and signedness (11.4.11). pub(super) fn invalid_unpacked_read( - state: &AnalysisState, + tree: &AnalysisContext<'_>, lhs: &LValue, dimensions: &PackedDimensions, ) -> Option { + let functions = &tree.functions; let LValue::Select { name, msb, @@ -209,9 +210,10 @@ pub(super) fn invalid_unpacked_read( { return None; } - let full_width = lvalue_expr_type(state, &LValue::Ident(name.clone()), dimensions)?.width; - let msb = eval_ast_const_expr(state, msb, &dimensions.const_env)?; - let lsb = eval_ast_const_expr(state, lsb, &dimensions.const_env)?; + let full_width = + lvalue_expr_type(&tree.functions, &LValue::Ident(name.clone()), dimensions)?.width; + let msb = eval_ast_const_expr(functions, msb, &dimensions.const_env)?; + let lsb = eval_ast_const_expr(functions, lsb, &dimensions.const_env)?; if msb < lsb || lsb < i128::try_from(full_width).ok()? { return None; } @@ -225,7 +227,7 @@ pub(super) fn invalid_unpacked_read( /// Shared syntax-independent assignment range flattening and array metadata. pub(super) fn lvalue_from_range( - state: &AnalysisState, + tree: &AnalysisContext<'_>, name: String, indices: Vec, mut msb: ConstExpr, @@ -245,10 +247,10 @@ pub(super) fn lvalue_from_range( }); } let (array_slice_width, array_slice_reversed) = - unpacked_select_range_metadata(state, &name, &indices, &msb, &lsb, packed_dimensions) + unpacked_select_range_metadata(tree, &name, &indices, &msb, &lsb, packed_dimensions) .map_or((None, false), |(width, reversed)| (Some(width), reversed)); (msb, lsb) = flatten_select_range( - state, + tree, &name, &indices, msb.clone(), @@ -257,7 +259,7 @@ pub(super) fn lvalue_from_range( ) .ok_or_else(|| { select_error( - state, + &tree.functions, &name, &indices, Some((&msb, &lsb)), @@ -294,7 +296,7 @@ struct DynamicIndexed { /// Bind the declared packed range of a runtime indexed part-select. fn dynamic_indexed_shape_values( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, name: &str, start: ConstExpr, width: usize, @@ -310,8 +312,8 @@ fn dynamic_indexed_shape_values( return None; } let dimension = &variable.packed[0]; - let left = eval_ast_const_expr(state, &dimension.left, &dimensions.const_env)?; - let right = eval_ast_const_expr(state, &dimension.right, &dimensions.const_env)?; + let left = eval_ast_const_expr(functions, &dimension.left, &dimensions.const_env)?; + let right = eval_ast_const_expr(functions, &dimension.right, &dimensions.const_env)?; Some(DynamicIndexed { start, width, @@ -348,7 +350,7 @@ fn dynamic_bounds_from_shape(shape: DynamicIndexed) -> (ConstExpr, ConstExpr) { /// Syntax-independent static or supported dynamic indexed range endpoints. pub(super) fn indexed_range_values( - state: &AnalysisState, + tree: &AnalysisContext<'_>, name: &str, base: ConstExpr, width: ConstExpr, @@ -356,13 +358,14 @@ pub(super) fn indexed_range_values( index_count: usize, dimensions: &PackedDimensions, ) -> Converted<((ConstExpr, ConstExpr), bool)> { - let width = eval_ast_const_expr(state, &width, &dimensions.const_env) + let functions = &tree.functions; + let width = eval_ast_const_expr(functions, &width, &dimensions.const_env) .ok_or_else(|| unsupported("indexed part-select width that is not constant"))?; - let start = self_determined_index(state, base.clone(), dimensions); - if eval_ast_const_expr(state, &start, &dimensions.const_env).is_none() + let start = self_determined_index(tree, base.clone(), dimensions); + if eval_ast_const_expr(functions, &start, &dimensions.const_env).is_none() && let Ok(width) = usize::try_from(width) && let Some(shape) = dynamic_indexed_shape_values( - state, + &tree.functions, name, start, width, @@ -374,7 +377,7 @@ pub(super) fn indexed_range_values( return Ok((dynamic_bounds_from_shape(shape), true)); } indexed_select_bounds_values( - state, + tree, base, plus, width, @@ -489,23 +492,24 @@ fn flatten_variable_select( } fn unpacked_select_range_metadata( - state: &AnalysisState, + tree: &AnalysisContext<'_>, name: &str, indices: &[ConstExpr], msb: &ConstExpr, lsb: &ConstExpr, packed_dimensions: &PackedDimensions, ) -> Option<(ConstExpr, bool)> { + let functions = &tree.functions; let dimensions = packed_dimensions.get(name)?; let dimension = dimensions.unpacked.get(indices.len())?; if const_expr_is_out_of_range( - state, + &tree.functions, msb, &dimension.left, &dimension.right, &packed_dimensions.const_env, ) || const_expr_is_out_of_range( - state, + &tree.functions, lsb, &dimension.left, &dimension.right, @@ -518,12 +522,12 @@ fn unpacked_select_range_metadata( return None; } let msb_offset = eval_ast_const_expr( - state, + functions, &unpacked_index_offset(dimension, msb.clone()), &packed_dimensions.const_env, )?; let lsb_offset = eval_ast_const_expr( - state, + functions, &unpacked_index_offset(dimension, lsb.clone()), &packed_dimensions.const_env, )?; @@ -560,7 +564,7 @@ fn remaining_unpacked_selection_width( } fn flatten_unpacked_select_range( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, name: &str, indices: &[ConstExpr], msb: ConstExpr, @@ -570,13 +574,13 @@ fn flatten_unpacked_select_range( ) -> Option<(ConstExpr, ConstExpr)> { let dimension = dimensions.unpacked.get(indices.len())?; if const_expr_is_out_of_range( - state, + functions, &msb, &dimension.left, &dimension.right, &packed_dimensions.const_env, ) || const_expr_is_out_of_range( - state, + functions, &lsb, &dimension.left, &dimension.right, @@ -643,13 +647,14 @@ fn flatten_unpacked_select_range( } fn flatten_select_range( - state: &AnalysisState, + tree: &AnalysisContext<'_>, name: &str, indices: &[ConstExpr], mut msb: ConstExpr, mut lsb: ConstExpr, packed_dimensions: &PackedDimensions, ) -> Option<(ConstExpr, ConstExpr)> { + let functions = &tree.functions; let Some(dimensions) = packed_dimensions.get(name) else { return indices.is_empty().then_some((msb, lsb)); }; @@ -662,7 +667,7 @@ fn flatten_select_range( } if indices.len() < dimensions.unpacked.len() { return flatten_unpacked_select_range( - state, + &tree.functions, name, indices, msb, @@ -674,13 +679,13 @@ fn flatten_select_range( let (array_offset, packed_indices) = flatten_variable_select(name, indices, packed_dimensions)?; let dimension = dimensions.packed.get(packed_indices.len())?; if const_expr_is_out_of_range( - state, + functions, &msb, &dimension.left, &dimension.right, &packed_dimensions.const_env, ) || const_expr_is_out_of_range( - state, + functions, &lsb, &dimension.left, &dimension.right, @@ -720,7 +725,7 @@ fn flatten_select_range( let prefix_offset = if packed_indices.is_empty() { ConstExpr::Literal("0".to_string()) } else { - let (_, offset) = flatten_packed_select(state, name, &packed_indices, packed_dimensions)?; + let (_, offset) = flatten_packed_select(tree, name, &packed_indices, packed_dimensions)?; offset }; let offset = add_expr(array_offset, prefix_offset); @@ -753,11 +758,12 @@ fn packed_index_in_range(index: &ConstExpr, dimension: &PackedDimension) -> Cons } fn flatten_packed_select( - state: &AnalysisState, + tree: &AnalysisContext<'_>, name: &str, indices: &[ConstExpr], packed_dimensions: &PackedDimensions, ) -> Option<(ConstExpr, ConstExpr)> { + let functions = &tree.functions; let variable_dimensions = packed_dimensions.get(name)?; let dimensions = &variable_dimensions.packed; if dimensions.is_empty() { @@ -765,7 +771,7 @@ fn flatten_packed_select( return None; } let zero = ConstExpr::Literal("0".to_string()); - if eval_ast_const_expr(state, &indices[0], &packed_dimensions.const_env) != Some(0) { + if eval_ast_const_expr(functions, &indices[0], &packed_dimensions.const_env) != Some(0) { return None; } return Some((zero.clone(), zero)); @@ -783,7 +789,7 @@ fn flatten_packed_select( for (idx, index) in indices.iter().enumerate() { let dimension = &dimensions[idx]; if const_expr_is_out_of_range( - state, + &tree.functions, index, &dimension.left, &dimension.right, @@ -818,7 +824,7 @@ fn flatten_packed_select( .iter() .zip(dimensions) .filter(|(index, _)| { - eval_ast_const_expr(state, index, &packed_dimensions.const_env).is_none() + eval_ast_const_expr(functions, index, &packed_dimensions.const_env).is_none() }) .map(|(index, dimension)| packed_index_in_range(index, dimension)) .reduce(|left, right| ConstExpr::Binary { @@ -921,16 +927,16 @@ pub(in crate::ast) fn const_index_has_unknown_value( } fn const_expr_is_out_of_range( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, index: &ConstExpr, left: &ConstExpr, right: &ConstExpr, const_env: &HashMap, ) -> bool { let (Some(index), Some(left), Some(right)) = ( - eval_ast_const_expr(state, index, const_env), - eval_ast_const_expr(state, left, const_env), - eval_ast_const_expr(state, right, const_env), + eval_ast_const_expr(functions, index, const_env), + eval_ast_const_expr(functions, left, const_env), + eval_ast_const_expr(functions, right, const_env), ) else { return false; }; @@ -977,13 +983,14 @@ fn is_one(expr: &ConstExpr) -> bool { /// Shared indexed endpoint arithmetic in declared coordinates. pub(super) fn indexed_select_bounds_values( - state: &AnalysisState, + tree: &AnalysisContext<'_>, base: ConstExpr, plus: bool, width: i128, selection: (Option<&str>, usize), dimensions: &PackedDimensions, ) -> Converted<(ConstExpr, ConstExpr)> { + let functions = &tree.functions; if width <= 0 { return Err(unsupported(format!("indexed part-select width {width}"))); } @@ -1000,14 +1007,14 @@ pub(super) fn indexed_select_bounds_values( (&dim.left, &dim.right) }; Some( - eval_ast_const_expr(state, left, &dimensions.const_env)? - < eval_ast_const_expr(state, right, &dimensions.const_env)?, + eval_ast_const_expr(functions, left, &dimensions.const_env)? + < eval_ast_const_expr(functions, right, &dimensions.const_env)?, ) }) .unwrap_or(false); // The base is self-determined; endpoint arithmetic must not inherit its // unsigned type or truncate a carry across the base expression's width. - let Some(base_value) = eval_ast_const_expr(state, &base, &dimensions.const_env) else { + let Some(base_value) = eval_ast_const_expr(functions, &base, &dimensions.const_env) else { // A procedural loop index is not constant while its body is bound. // Keep the endpoints in declared coordinates so normal range flattening // retains preceding unpacked and packed indices. Lowering can then unroll @@ -1022,12 +1029,12 @@ pub(super) fn indexed_select_bounds_values( .is_some_and(|ty| ty.width > 1) } }); - let ty = self_determined_type(state, &base, dimensions).filter(|ty| ty.0 <= 32); + let ty = self_determined_type(tree, &base, dimensions).filter(|ty| ty.0 <= 32); let Some(ty) = ty.filter(|_| selected_word) else { return Err(unsupported("indexed part-select start")); }; let base = ConstExpr::Resize { - expr: Box::new(self_determined_index(state, base, dimensions)), + expr: Box::new(self_determined_index(tree, base, dimensions)), width: 64, signed: ty.1, }; @@ -1070,19 +1077,20 @@ pub(super) fn indexed_select_bounds_values( /// Bound expressions keep both mux arms until typed folding establishes width. pub(super) fn indexed_expression_value( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expression: Expr, dimensions: &PackedDimensions, ) -> Option { - let expression = substitute_indexed_parameter_values(state, expression, dimensions); + let state = &*tree.state; + let expression = substitute_indexed_parameter_values(tree, expression, dimensions); expr_to_const( state, - fold_const_integral_expr_preserving_mask(state, expression, &dimensions.const_env), + fold_const_integral_expr_preserving_mask(tree, expression, &dimensions.const_env), ) } fn substitute_indexed_parameter_values( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expression: Expr, dimensions: &PackedDimensions, ) -> Expr { @@ -1099,7 +1107,7 @@ fn substitute_indexed_parameter_values( .map(|(name, value)| (name.clone(), value.clone())) .collect(); substitute_expr_constants_with_parameter_literals( - state, + tree, expression, &dimensions.const_env, &values, @@ -1122,21 +1130,16 @@ pub(super) fn selected_parameter_initializer( syntax_tree, &dimensions, )?; - fold_parameter_selection( - &syntax_tree.state, - expression, - &dimensions, - assignment_width, - ) + fold_parameter_selection(syntax_tree, expression, &dimensions, assignment_width) } fn fold_parameter_selection( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expression: Expr, dimensions: &PackedDimensions, assignment_width: Option, ) -> Converted { - let expression = substitute_indexed_parameter_values(state, expression, dimensions); + let expression = substitute_indexed_parameter_values(tree, expression, dimensions); if let Expr::Literal(text) = &expression && text.contains(['.', 'e', 'E']) && text.parse::().is_ok() @@ -1151,7 +1154,7 @@ fn fold_parameter_selection( .collect(); let not_constant = || unsupported("parameter initializer that is not constant"); let constant = constant_folding::constant_with_folded_selections( - state, + tree, &expression, &dimensions.const_env, &integral_types, @@ -1172,12 +1175,12 @@ fn fold_parameter_selection( } fn unknown_indexed_range_literal( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, width: i128, stride: &ConstExpr, dimensions: &PackedDimensions, ) -> Converted { - let width = eval_ast_const_expr(state, stride, &dimensions.const_env) + let width = eval_ast_const_expr(functions, stride, &dimensions.const_env) .and_then(|stride| width.checked_mul(stride)) .and_then(|width| usize::try_from(width).ok()) .filter(|width| *width > 0 && *width <= constant_folding::MAX_CONSTANT_CONCAT_BITS) @@ -1190,11 +1193,12 @@ fn unknown_indexed_range_literal( /// Explicit remaining typed-primary kernel. Native operator/control binding /// must call this only for its declared leaf classes, never as an error retry. pub(super) fn indexed_parameter_indices( - state: &AnalysisState, + tree: &AnalysisContext<'_>, name: String, indices: Vec, dimensions: &PackedDimensions, ) -> Converted { + let functions = &tree.functions; if !indices.is_empty() && let Some(variable) = dimensions.get(&name) && variable.unpacked.is_empty() @@ -1202,7 +1206,7 @@ pub(super) fn indexed_parameter_indices( { if indices.iter().zip(&variable.packed).any(|(index, range)| { const_expr_is_out_of_range( - state, + &tree.functions, index, &range.left, &range.right, @@ -1215,7 +1219,7 @@ pub(super) fn indexed_parameter_indices( .map(|range| range.width.clone()) .collect::>(), ); - let width = eval_ast_const_expr(state, &width, &dimensions.const_env) + let width = eval_ast_const_expr(functions, &width, &dimensions.const_env) .and_then(|width| usize::try_from(width).ok()) .ok_or_else(|| unsupported("constant parameter element width"))?; let signing = if selects_signed_element(&name, indices.len(), dimensions) { @@ -1232,18 +1236,18 @@ pub(super) fn indexed_parameter_indices( } let indices_were_empty = indices.is_empty(); let selected = lvalue_from_indices( - state, + tree, name.clone(), indices .into_iter() - .map(|index| self_determined_index(state, index, dimensions)) + .map(|index| self_determined_index(tree, index, dimensions)) .collect(), dimensions, )?; if matches!(selected, LValue::Ident(_)) && !indices_were_empty { return Err(unsupported(format!("constant select of `{name}`"))); } - Ok(expr_from_lvalue(state, &selected, dimensions)) + Ok(expr_from_lvalue(tree, &selected, dimensions)) } /// Already-bound range coordinates; syntax/source ownership remains outside @@ -1257,27 +1261,29 @@ pub(super) enum ParameterRange { }, } fn parameter_range_bounds( - state: &AnalysisState, + tree: &AnalysisContext<'_>, range: ParameterRange, selection: (Option<&str>, usize), dimensions: &PackedDimensions, ) -> Converted<(ConstExpr, ConstExpr)> { + let functions = &tree.functions; match range { ParameterRange::Bounds(left, right) => Ok((left, right)), ParameterRange::Indexed { base, width, plus } => { - let width = eval_ast_const_expr(state, &width, &dimensions.const_env) + let width = eval_ast_const_expr(functions, &width, &dimensions.const_env) .ok_or_else(|| unsupported("indexed part-select width that is not constant"))?; - indexed_select_bounds_values(state, base, plus, width, selection, dimensions) + indexed_select_bounds_values(tree, base, plus, width, selection, dimensions) } } } pub(super) fn indexed_parameter_range( - state: &AnalysisState, + tree: &AnalysisContext<'_>, name: String, indices: Vec, range: ParameterRange, dimensions: &PackedDimensions, ) -> Converted { + let functions = &tree.functions; let index_count = indices.len(); if let Some(variable) = dimensions.get(&name) && variable.unpacked.is_empty() @@ -1288,7 +1294,7 @@ pub(super) fn indexed_parameter_range( })?; // Clip to the selected element before its final range, without cloning // or altering original syntax to manufacture an element view. - let element = indexed_parameter_indices(state, name.clone(), indices, dimensions)?; + let element = indexed_parameter_indices(tree, name.clone(), indices, dimensions)?; let stride = product_expr( &variable.packed[index_count + 1..] .iter() @@ -1298,15 +1304,15 @@ pub(super) fn indexed_parameter_range( if let ParameterRange::Indexed { base, width, .. } = &range && const_index_has_unknown_value(base, dimensions) { - let width = eval_ast_const_expr(state, width, &dimensions.const_env) + let width = eval_ast_const_expr(functions, width, &dimensions.const_env) .ok_or_else(|| unsupported("indexed part-select width that is not constant"))?; if width <= 0 { return Err(unsupported(format!("indexed part-select width {width}"))); } - return unknown_indexed_range_literal(state, width, &stride, dimensions); + return unknown_indexed_range_literal(&tree.functions, width, &stride, dimensions); } let (msb, lsb) = - parameter_range_bounds(state, range, (Some(&name), index_count), dimensions)?; + parameter_range_bounds(tree, range, (Some(&name), index_count), dimensions)?; let mut msb = packed_index_offset(dimension, msb); let mut lsb = packed_index_offset(dimension, lsb); if !is_one(&stride) { @@ -1335,9 +1341,9 @@ pub(super) fn indexed_parameter_range( signed: false, }); } - let (msb, lsb) = parameter_range_bounds(state, range, (Some(&name), index_count), dimensions)?; - let selected = lvalue_from_range(state, name, indices, msb, lsb, false, dimensions)?; - Ok(expr_from_lvalue(state, &selected, dimensions)) + let (msb, lsb) = parameter_range_bounds(tree, range, (Some(&name), index_count), dimensions)?; + let selected = lvalue_from_range(tree, name, indices, msb, lsb, false, dimensions)?; + Ok(expr_from_lvalue(tree, &selected, dimensions)) } pub(super) enum AggregateSelection { @@ -1347,30 +1353,31 @@ pub(super) enum AggregateSelection { /// Select a self-determined concatenated value in descending bit coordinates. /// Syntax adapters supply values; unknown indexed bases retain four-state X. pub(super) fn aggregate_selection_value( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expression: Expr, selection: AggregateSelection, dimensions: &PackedDimensions, ) -> Converted { + let functions = &tree.functions; let (msb, lsb) = match selection { AggregateSelection::Index(bit) => (bit.clone(), bit), AggregateSelection::Range(range) => { if let ParameterRange::Indexed { base, width, .. } = &range && const_index_has_unknown_value(base, dimensions) { - let width = eval_ast_const_expr(state, width, &dimensions.const_env) + let width = eval_ast_const_expr(functions, width, &dimensions.const_env) .ok_or_else(|| unsupported("indexed part-select width that is not constant"))?; if width <= 0 { return Err(unsupported(format!("indexed part-select width {width}"))); } return unknown_indexed_range_literal( - state, + &tree.functions, width, &ConstExpr::Literal("1".into()), dimensions, ); } - parameter_range_bounds(state, range, (None, 0), dimensions)? + parameter_range_bounds(tree, range, (None, 0), dimensions)? } }; Ok(Expr::Select { @@ -1382,10 +1389,11 @@ pub(super) fn aggregate_selection_value( } fn self_determined_type( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: &ConstExpr, dimensions: &PackedDimensions, ) -> Option<(usize, bool)> { + let functions = &tree.functions; let const_env = &dimensions.const_env; match expr { ConstExpr::Literal(value) => { @@ -1404,7 +1412,7 @@ fn self_determined_type( let mut width = 1usize; for dimension in &variable.packed { let size = - usize::try_from(eval_ast_const_expr(state, &dimension.width, const_env)?) + usize::try_from(eval_ast_const_expr(functions, &dimension.width, const_env)?) .ok()?; width = width.checked_mul(size)?; } @@ -1425,7 +1433,7 @@ fn self_determined_type( ConstExpr::Function { .. } => None, ConstExpr::Unary { op, expr } => match op { UnaryOp::Plus | UnaryOp::Minus | UnaryOp::BitNot | UnaryOp::ToTwoState => { - self_determined_type(state, expr, dimensions) + self_determined_type(tree, expr, dimensions) } UnaryOp::LogicNot | UnaryOp::RedAnd | UnaryOp::RedOr | UnaryOp::RedXor => { Some((1, false)) @@ -1440,12 +1448,12 @@ fn self_determined_type( | BinaryOp::BitAnd | BinaryOp::BitOr | BinaryOp::BitXor => { - let (left_width, left_signed) = self_determined_type(state, left, dimensions)?; - let (right_width, right_signed) = self_determined_type(state, right, dimensions)?; + let (left_width, left_signed) = self_determined_type(tree, left, dimensions)?; + let (right_width, right_signed) = self_determined_type(tree, right, dimensions)?; Some((left_width.max(right_width), left_signed && right_signed)) } BinaryOp::Pow | BinaryOp::Shl | BinaryOp::Shr | BinaryOp::Sar => { - self_determined_type(state, left, dimensions) + self_determined_type(tree, left, dimensions) } _ => Some((1, false)), }, @@ -1454,8 +1462,8 @@ fn self_determined_type( else_expr, .. } => { - let (then_width, then_signed) = self_determined_type(state, then_expr, dimensions)?; - let (else_width, else_signed) = self_determined_type(state, else_expr, dimensions)?; + let (then_width, then_signed) = self_determined_type(tree, then_expr, dimensions)?; + let (else_width, else_signed) = self_determined_type(tree, else_expr, dimensions)?; Some((then_width.max(else_width), then_signed && else_signed)) } } @@ -1465,7 +1473,7 @@ fn self_determined_type( /// (IEEE 1800-2023 11.5.1): the flattening adds it to offsets at the width of /// unsized literals, where `j + 2'd1` would not wrap. pub(super) fn self_determined_index( - state: &AnalysisState, + tree: &AnalysisContext<'_>, index: ConstExpr, dimensions: &PackedDimensions, ) -> ConstExpr { @@ -1475,7 +1483,7 @@ pub(super) fn self_determined_index( ) { return index; } - let Some((width, signed)) = self_determined_type(state, &index, dimensions) else { + let Some((width, signed)) = self_determined_type(tree, &index, dimensions) else { return index; }; if width == 0 || width >= 32 { @@ -1493,7 +1501,7 @@ pub(super) fn self_determined_index( // A signed index is computed with its operands sign-extended to the // offsets' width, which leaves its low bits as they are except under a // logical right shift: shift in zeros from the operand's own width. - let index = zero_extend_logical_shifts(state, index, dimensions); + let index = zero_extend_logical_shifts(tree, index, dimensions); let masked = binary(index, BinaryOp::BitAnd, literal((1 << width) - 1)); // Sign-extend from the top bit: (x ^ s) - s. let sign = literal(1 << (width - 1)); @@ -1507,19 +1515,19 @@ pub(super) fn self_determined_index( /// `expr` with the left operand of each logical right shift reduced to its own /// width, so that a wider signed context does not shift its sign bits in. fn zero_extend_logical_shifts( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expr: ConstExpr, dimensions: &PackedDimensions, ) -> ConstExpr { - let go = |expr: Box| Box::new(zero_extend_logical_shifts(state, *expr, dimensions)); + let go = |expr: Box| Box::new(zero_extend_logical_shifts(tree, *expr, dimensions)); match expr { ConstExpr::Binary { left, op: BinaryOp::Shr, right, } => { - let left = zero_extend_logical_shifts(state, *left, dimensions); - let left = match self_determined_type(state, &left, dimensions) { + let left = zero_extend_logical_shifts(tree, *left, dimensions); + let left = match self_determined_type(tree, &left, dimensions) { Some((width, true)) if width < 32 => ConstExpr::Binary { left: Box::new(left), op: BinaryOp::BitAnd, diff --git a/crates/celox-sv-analyzer/src/ast/semantic_types/conversion.rs b/crates/celox-sv-analyzer/src/ast/semantic_types/conversion.rs index bfb1abc310a..fb8bfa1d1ed 100644 --- a/crates/celox-sv-analyzer/src/ast/semantic_types/conversion.rs +++ b/crates/celox-sv-analyzer/src/ast/semantic_types/conversion.rs @@ -2,7 +2,7 @@ //! [`VariableDimensions`] of variables. use super::*; use crate::ast::{ - AnalysisState, ConstExpr, ContainerKind, ContainerType, Type, TypeKind, VariableDimensions, + ConstExpr, ContainerKind, ContainerType, Type, TypeKind, VariableDimensions, const_functions, enums::EnumDomain, eval_ast_const_expr, packed_structs::PackedMember, type_names, unpacked_structs::UnpackedStruct, virtual_interfaces::VirtualInterface, }; @@ -11,7 +11,7 @@ use crate::ast::{ /// if a range is not constant or the type has no semantic type yet. pub(in crate::ast) fn of_type( table: &TyTable, - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, ty: &Type, env: &HashMap, ) -> Option { @@ -39,7 +39,7 @@ pub(in crate::ast) fn of_type( .unpacked_ranges .iter() .map(|range| (range.left(), range.right())); - parts.intern(table, state, env, unpacked) + parts.intern(table, functions, env, unpacked) } /// The semantic type of a variable of `shape`, whose dimensions name @@ -47,7 +47,7 @@ pub(in crate::ast) fn of_type( /// (which only `$typename` tells apart). pub(in crate::ast) fn of_shape( table: &TyTable, - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, shape: &VariableDimensions, env: &HashMap, ) -> Option { @@ -87,7 +87,7 @@ pub(in crate::ast) fn of_shape( .unpacked .iter() .map(|dimension| (&dimension.left, &dimension.right)); - parts.intern(table, state, env, unpacked) + parts.intern(table, functions, env, unpacked) } /// What a type is made of, from a [`Type`] or a [`VariableDimensions`]. @@ -116,17 +116,17 @@ impl Parts<'_> { fn intern<'b>( &self, table: &TyTable, - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, env: &HashMap, unpacked: impl DoubleEndedIterator, ) -> Option { let range = |left: &ConstExpr, right: &ConstExpr| { Some(Range { - left: eval_ast_const_expr(state, left, env)?, - right: eval_ast_const_expr(state, right, env)?, + left: eval_ast_const_expr(functions, left, env)?, + right: eval_ast_const_expr(functions, right, env)?, }) }; - let mut id = table.intern(self.element(table, state, env, &range)?); + let mut id = table.intern(self.element(table, functions, env, &range)?); for (left, right) in unpacked.rev() { id = table.intern(TyData::Array { kind: ArrayKind::Fixed(range(left, right)?), @@ -140,7 +140,7 @@ impl Parts<'_> { fn element( &self, table: &TyTable, - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, env: &HashMap, range: &dyn Fn(&ConstExpr, &ConstExpr) -> Option, ) -> Option { @@ -152,12 +152,12 @@ impl Parts<'_> { bound: capacity.checked_sub(1), }, ContainerKind::Associative { .. } => ArrayKind::Associative { - key: of_type(table, state, container.key.as_ref()?, env)?, + key: of_type(table, functions, container.key.as_ref()?, env)?, }, }; return Some(TyData::Array { kind, - element: of_type(table, state, &container.element, env)?, + element: of_type(table, functions, &container.element, env)?, }); } // Events and processes are handles of built-in classes. diff --git a/crates/celox-sv-analyzer/src/ast/semantic_types/tests.rs b/crates/celox-sv-analyzer/src/ast/semantic_types/tests.rs index f69278528b0..76ecac80c67 100644 --- a/crates/celox-sv-analyzer/src/ast/semantic_types/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/semantic_types/tests.rs @@ -18,7 +18,7 @@ fn typedefs(items: &str) -> (TyTable, HashMap) { let ids = aliases .iter() .map(|(name, ty)| { - let id = of_type(&table, &tree.state, ty, &env) + let id = of_type(&table, &tree.functions, ty, &env) .unwrap_or_else(|| panic!("`{name}` has no semantic type")); (name.clone(), id) }) @@ -153,7 +153,7 @@ fn aggregates_of_each_generate_scope_are_types_of_their_own() { let aliases = types::type_aliases_of_generate_scope(&tree, &items, &env, &HashMap::default(), path) .unwrap(); - ["p_t", "u_t"].map(|name| of_type(&table, &tree.state, &aliases[name], &env).unwrap()) + ["p_t", "u_t"].map(|name| of_type(&table, &tree.functions, &aliases[name], &env).unwrap()) }; let (first, second, again) = (scope("g[0]"), scope("g[1]"), scope("g[0]")); for index in 0..2 { diff --git a/crates/celox-sv-analyzer/src/ast/statements.rs b/crates/celox-sv-analyzer/src/ast/statements.rs index f256a9694e1..fba4edb72ce 100644 --- a/crates/celox-sv-analyzer/src/ast/statements.rs +++ b/crates/celox-sv-analyzer/src/ast/statements.rs @@ -3,12 +3,13 @@ use super::*; pub(super) fn coerce_procedural_assignment_rhs( - state: &AnalysisState, + tree: &AnalysisContext<'_>, rhs: Expr, lhs: &LValue, packed_dimensions: &PackedDimensions, ) -> Expr { - let Some(target_type) = lvalue_expr_type(state, lhs, packed_dimensions) else { + let functions = &tree.functions; + let Some(target_type) = lvalue_expr_type(functions, lhs, packed_dimensions) else { return rhs; }; let Some(source_signed) = expr_signedness_with_return_types( @@ -20,7 +21,7 @@ pub(super) fn coerce_procedural_assignment_rhs( return rhs; }; let assigned = if source_signed == target_type.signed - && expr_static_width(state, &rhs, packed_dimensions) == Some(target_type.width) + && expr_static_width(tree, &rhs, packed_dimensions) == Some(target_type.width) { rhs } else { @@ -58,7 +59,7 @@ pub(super) fn coerce_procedural_assignment_rhs( } pub(super) fn lvalue_expr_type( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, value: &LValue, packed_dimensions: &PackedDimensions, ) -> Option { @@ -72,7 +73,7 @@ pub(super) fn lvalue_expr_type( .chain(dimensions.unpacked.iter().map(|dimension| &dimension.width)) .try_fold(1usize, |width, dimension| { let dimension_width = - eval_ast_const_expr(state, dimension, &packed_dimensions.const_env)?; + eval_ast_const_expr(functions, dimension, &packed_dimensions.const_env)?; width.checked_mul(usize::try_from(dimension_width).ok()?) })?; Some(ExprType { @@ -83,8 +84,8 @@ pub(super) fn lvalue_expr_type( LValue::Select { msb, lsb, signed, .. } => { - let msb = eval_ast_const_expr(state, msb, &packed_dimensions.const_env)?; - let lsb = eval_ast_const_expr(state, lsb, &packed_dimensions.const_env)?; + let msb = eval_ast_const_expr(functions, msb, &packed_dimensions.const_env)?; + let lsb = eval_ast_const_expr(functions, lsb, &packed_dimensions.const_env)?; Some(ExprType { width: usize::try_from(msb.abs_diff(lsb)).ok()?.checked_add(1)?, signed: *signed, @@ -94,7 +95,7 @@ pub(super) fn lvalue_expr_type( } pub(super) fn simplify_condition( - state: &AnalysisState, + tree: &AnalysisContext<'_>, expression: Expr, packed_dimensions: &PackedDimensions, ) -> Expr { @@ -105,7 +106,7 @@ pub(super) fn simplify_condition( op: BinaryOp::LogicOr, right, } = &expression - && two_state_conditions_are_complements(state, left, right, packed_dimensions) + && two_state_conditions_are_complements(tree, left, right, packed_dimensions) { return Expr::Literal("1'b1".to_string()); } @@ -113,7 +114,7 @@ pub(super) fn simplify_condition( } pub(super) fn assignment_op_expr( - state: &AnalysisState, + tree: &AnalysisContext<'_>, lhs: &LValue, op: &str, rhs: Expr, @@ -135,7 +136,7 @@ pub(super) fn assignment_op_expr( "^" => BinaryOp::BitXor, _ => return Err(operator()), }; - let left = expr_from_lvalue(state, lhs, packed_dimensions); + let left = expr_from_lvalue(tree, lhs, packed_dimensions); if (expression_binding::real_value(&left, packed_dimensions) || expression_binding::real_value(&rhs, packed_dimensions)) && !matches!( @@ -147,7 +148,7 @@ pub(super) fn assignment_op_expr( } Ok(expression_binding::remove_real_division_guards( guard_zero_divisions( - state, + tree, Expr::Binary { left: Box::new(left), op, @@ -159,11 +160,12 @@ pub(super) fn assignment_op_expr( } pub(super) fn expr_from_lvalue( - state: &AnalysisState, + tree: &AnalysisContext<'_>, lhs: &LValue, packed_dimensions: &PackedDimensions, ) -> Expr { - if let Some(value) = selects::invalid_unpacked_read(state, lhs, packed_dimensions) { + let functions = &tree.functions; + if let Some(value) = selects::invalid_unpacked_read(tree, lhs, packed_dimensions) { return value; } let (base, array_slice_width, array_slice_reversed, signed) = match lhs { @@ -195,7 +197,7 @@ pub(super) fn expr_from_lvalue( .. } ) { - let Some(r#type) = lvalue_expr_type(state, lhs, packed_dimensions) else { + let Some(r#type) = lvalue_expr_type(&tree.functions, lhs, packed_dimensions) else { return base; }; Expr::Resize { @@ -216,7 +218,7 @@ pub(super) fn expr_from_lvalue( return base; }; let Some(element_width) = - eval_ast_const_expr(state, array_slice_width, &packed_dimensions.const_env) + eval_ast_const_expr(functions, array_slice_width, &packed_dimensions.const_env) .and_then(|width| usize::try_from(width).ok()) .filter(|width| *width != 0) else { @@ -225,9 +227,9 @@ pub(super) fn expr_from_lvalue( let Expr::Select { msb, lsb, .. } = &base else { return base; }; - let Some(total_width) = eval_ast_const_expr(state, msb, &packed_dimensions.const_env) + let Some(total_width) = eval_ast_const_expr(functions, msb, &packed_dimensions.const_env) .and_then(|msb| { - eval_ast_const_expr(state, lsb, &packed_dimensions.const_env) + eval_ast_const_expr(functions, lsb, &packed_dimensions.const_env) .and_then(|lsb| usize::try_from(msb.abs_diff(lsb)).ok()) }) .and_then(|width| width.checked_add(1)) diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/aggregates.rs b/crates/celox-sv-analyzer/src/ast/type_binding/aggregates.rs index fc8e286f19a..c668c4a34b7 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/aggregates.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/aggregates.rs @@ -97,7 +97,6 @@ mod tests { &HashMap::default(), &HashMap::default(), ); - let state = tree.state.clone(); drop(tree); drop(original); let ty = result.unwrap().unwrap(); @@ -109,9 +108,13 @@ mod tests { } assert_eq!(depth, 500); assert_eq!( - expr_type_from_type(&state, &ty, &HashMap::default()) - .unwrap() - .width, + expr_type_from_type( + &const_functions::ConstantFunctions::default(), + &ty, + &HashMap::default() + ) + .unwrap() + .width, 1 ); drop(ty); 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 af39f4560b8..db27ab3ce12 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -410,7 +410,7 @@ fn bind_in_mode( } let fields = names.into_iter().zip(values.split_off(start)).collect(); let Some(ty) = unpacked_structs::native_type( - &tree.state, + &tree.functions, owner, fields, &context.const_env, @@ -427,7 +427,7 @@ fn bind_in_mode( .map(|((name, ty), is_void)| (name, ty, is_void)) .collect(); let Some(mut ty) = packed_structs::native_type( - &tree.state, + tree, if tagged { packed_structs::AggregateKind::TaggedUnion } else if soft { @@ -589,7 +589,7 @@ pub(in crate::ast) fn expression_type( ) -> Converted> { if let ExprKind::Type(id) = tree.declarations().expression(root).kind { return Ok(bind(id, tree, context)? - .and_then(|ty| expr_type_from_type(&tree.state, &ty, &context.const_env))); + .and_then(|ty| expr_type_from_type(&tree.functions, &ty, &context.const_env))); } if let Some((name, ranges)) = argument_alias(root, tree.declarations()) && context.get(&name).is_none() @@ -602,7 +602,11 @@ pub(in crate::ast) fn expression_type( { let ty = types::enclose_aliased_packed_type(ty.clone(), packed_ranges(&ranges, tree, context)?); - return Ok(expr_type_from_type(&tree.state, &ty, &context.const_env)); + return Ok(expr_type_from_type( + &tree.functions, + &ty, + &context.const_env, + )); } let mut query = context.clone(); query.expression_signedness.extend( @@ -613,7 +617,7 @@ pub(in crate::ast) fn expression_type( query.type_query = true; query.functions = Arc::default(); let value = expression_binding::bind(root, tree, &query)?; - Ok(dimensions::bound_bits_type(&tree.state, &value, &query)) + Ok(dimensions::bound_bits_type(tree, &value, &query)) } /// IEEE 1800-2023 6.19 imposes declaration rules even when no enum member @@ -628,7 +632,7 @@ pub(in crate::ast) fn validate_enum_initializers( let DataTypeKind::Enum { base, items } = &native.data_type(id).kind else { return Ok(()); }; - let Some(shape) = casts::expr_type_from_type(&tree.state, ty, &context.const_env) else { + let Some(shape) = casts::expr_type_from_type(&tree.functions, ty, &context.const_env) else { return Ok(()); }; let mut env = context.const_env.clone(); @@ -680,7 +684,7 @@ pub(in crate::ast) fn validate_enum_initializers( expr_to_const( &tree.state, constants::substitute_expr_constants_with_parameter_literals( - &tree.state, + tree, const_expr_to_expr(expr), &env, &unknown_literals, @@ -731,7 +735,7 @@ pub(in crate::ast) fn validate_enum_initializers( } next = expr .as_ref() - .and_then(|expr| eval_ast_const_expr(&tree.state, expr, &env)) + .and_then(|expr| eval_ast_const_expr(&tree.functions, expr, &env)) .map(|value| { parameters::coerce_const_parameter_value(value, shape.width, shape.signed) }); @@ -761,7 +765,7 @@ fn enum_values( let DataTypeKind::Enum { items, .. } = &data.kind else { return None; }; - let shape = casts::expr_type_from_type(&tree.state, ty, &context.const_env)?; + let shape = casts::expr_type_from_type(&tree.functions, ty, &context.const_env)?; if shape.width > 64 { return None; } @@ -785,7 +789,7 @@ fn enum_values( ), expr => expr, }; - let value = eval_ast_const_expr(&tree.state, &expr, &env)?; + let value = eval_ast_const_expr(&tree.functions, &expr, &env)?; let value_type = infer_const_expr_type(&expr, ¶meter_types_from_const_env(&env))?; if !parameters::enum_initializer_fits_base_type(value, value_type, shape) { return None; diff --git a/crates/celox-sv-analyzer/src/ast/type_names.rs b/crates/celox-sv-analyzer/src/ast/type_names.rs index df32cde53ed..aaf1da7c195 100644 --- a/crates/celox-sv-analyzer/src/ast/type_names.rs +++ b/crates/celox-sv-analyzer/src/ast/type_names.rs @@ -372,7 +372,7 @@ pub(super) fn type_name( ) -> Converted { let range = |left: &ConstExpr, right: &ConstExpr| -> Converted { let bound = |bound: &ConstExpr| { - eval_ast_const_expr(&tree.state, bound, env) + eval_ast_const_expr(&tree.functions, bound, env) .ok_or_else(|| unsupported_operand("a type with a range that is not constant")) }; Ok(format!("[{}:{}]", bound(left)?, bound(right)?)) @@ -467,8 +467,8 @@ fn vector_name( }; r#type.kind == kind && matches!(r#type.packed_ranges.as_slice(), [only] - if eval_ast_const_expr(&tree.state, &only.left, env) == Some(width - 1) - && eval_ast_const_expr(&tree.state, &only.right, env) == Some(0)) + if eval_ast_const_expr(&tree.functions, &only.left, env) == Some(width - 1) + && eval_ast_const_expr(&tree.functions, &only.right, env) == Some(0)) }); let (mut name, signed) = match keyword { Some(keyword) => (keyword.to_owned(), keyword != "time"), diff --git a/crates/celox-sv-analyzer/src/ast/type_parameters.rs b/crates/celox-sv-analyzer/src/ast/type_parameters.rs index f589eea8a8c..49fd86a947c 100644 --- a/crates/celox-sv-analyzer/src/ast/type_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/type_parameters.rs @@ -67,16 +67,16 @@ pub(super) fn bind( /// Freeze every dimension in the caller's environment before crossing the /// instance boundary. A child's parameters must not reinterpret caller names. pub(super) fn resolve( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, mut ty: Type, env: &HashMap, ) -> Option { fn bound( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, expr: &ConstExpr, env: &HashMap, ) -> Option { - let value = eval_ast_const_expr(state, expr, env)?; + let value = eval_ast_const_expr(functions, expr, env)?; Some(if value >= 0 { ConstExpr::Literal(value.to_string()) } else { @@ -84,19 +84,19 @@ pub(super) fn resolve( }) } for range in &mut ty.packed_ranges { - range.left = bound(state, &range.left, env)?; - range.right = bound(state, &range.right, env)?; + range.left = bound(functions, &range.left, env)?; + range.right = bound(functions, &range.right, env)?; } for range in &mut ty.unpacked_ranges { - range.left = bound(state, &range.left, env)?; - range.right = bound(state, &range.right, env)?; + range.left = bound(functions, &range.left, env)?; + range.right = bound(functions, &range.right, env)?; if let Some(size) = &range.size { - range.size = Some(bound(state, size, env)?); + range.size = Some(bound(functions, size, env)?); } } let mut members = Vec::new(); for member in ty.members { - let resolved = resolve(state, member.r#type().clone(), env)?; + let resolved = resolve(functions, member.r#type().clone(), env)?; members.push(member.with_type(|_| resolved)); } ty.members = members; diff --git a/crates/celox-sv-analyzer/src/ast/types.rs b/crates/celox-sv-analyzer/src/ast/types.rs index a6882e4520b..743924cfe45 100644 --- a/crates/celox-sv-analyzer/src/ast/types.rs +++ b/crates/celox-sv-analyzer/src/ast/types.rs @@ -153,24 +153,30 @@ fn type_aliases_in_scope( // widen the index arithmetic of a run-time select to 128 bits. for ty in aliases.values_mut() { for range in &mut ty.packed_ranges { - if let Some(value) = eval_ast_const_expr(&syntax_tree.state, &range.left, const_env) { + if let Some(value) = eval_ast_const_expr(&syntax_tree.functions, &range.left, const_env) + { range.left = bound_literal(value); } - if let Some(value) = eval_ast_const_expr(&syntax_tree.state, &range.right, const_env) { + if let Some(value) = + eval_ast_const_expr(&syntax_tree.functions, &range.right, const_env) + { range.right = bound_literal(value); } } for range in &mut ty.unpacked_ranges { - if let Some(value) = eval_ast_const_expr(&syntax_tree.state, &range.left, const_env) { + if let Some(value) = eval_ast_const_expr(&syntax_tree.functions, &range.left, const_env) + { range.left = bound_literal(value); } - if let Some(value) = eval_ast_const_expr(&syntax_tree.state, &range.right, const_env) { + if let Some(value) = + eval_ast_const_expr(&syntax_tree.functions, &range.right, const_env) + { range.right = bound_literal(value); } if let Some(value) = range .size .as_ref() - .and_then(|size| eval_ast_const_expr(&syntax_tree.state, size, const_env)) + .and_then(|size| eval_ast_const_expr(&syntax_tree.functions, size, const_env)) { range.size = Some(bound_literal(value)); } @@ -276,14 +282,14 @@ pub(super) fn type_with_unpacked_ranges(mut r#type: Type, ranges: Vec, ) -> Result<(), AnalyzerError> { if ranges.iter().any(|range| { range .size() - .and_then(|size| eval_ast_const_expr(state, size, const_env)) + .and_then(|size| eval_ast_const_expr(functions, size, const_env)) .is_some_and(|size| size <= 0) }) { return Err(AnalyzerError::Unsupported( diff --git a/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs b/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs index 6ff910f21dd..865048b72a2 100644 --- a/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs +++ b/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs @@ -119,7 +119,7 @@ impl UnpackedStruct { /// The type of an unpacked structure with `fields`, or `None` when a member /// type has no supported unpacked-structure representation. pub(in crate::ast) fn native_type( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, owner: Arc, fields: Vec<(String, Type)>, env: &HashMap, @@ -140,11 +140,11 @@ pub(in crate::ast) fn native_type( } let ty = match ty.unpacked_struct() { Some(_) => ty, - None => packed_structs::capture_member_type(state, ty, env)?, + None => packed_structs::capture_member_type(functions, ty, env)?, }; let width = match ty.unpacked_struct() { Some(inner) => inner.width(), - None => casts::expr_type_from_type(state, &ty, env)?.width, + None => casts::expr_type_from_type(functions, &ty, env)?.width, }; Some(Member { name, @@ -478,7 +478,7 @@ pub(in crate::ast) fn leaf_parts(aggregate: &UnpackedStruct, value: &Expr) -> Op /// handle member and members that are all 2-state or all 4-state, so the /// container's default element is the structure's default. pub(in crate::ast) fn record( - state: &AnalysisState, + functions: &const_functions::ConstantFunctions, aggregate: &UnpackedStruct, env: &HashMap, ) -> Converted> { @@ -499,7 +499,7 @@ pub(in crate::ast) fn record( let mut size = 0; let mut fields = Vec::new(); for leaf in &leaves { - let mut field = classes::field(state, &leaf.r#type, env, size)?; + let mut field = classes::field(functions, &leaf.r#type, env, size)?; field.nullable = true; size = field.offset + field.storage(); fields.push(field); diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index caa509f6f37..55c4f7573f5 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -282,7 +282,7 @@ pub(super) fn reject_silently_ignored_constructs( for item in &active { item.procedure(syntax_tree.declarations())?; item.continuous_assignment(syntax_tree.declarations())?; - let _constant_functions = item.enter(); + let syntax_tree = &item.enter(syntax_tree); let syntax_tree = &item.scoped(syntax_tree); validate_scope(Some(item), syntax_tree, views.dimensions(item))?; } @@ -1103,10 +1103,8 @@ fn reject_constant_calls( detail: "not permitted in a constant-value expression".into(), }); } - } else if !const_functions::is_constant_function(&tree.state.const_functions, &name) { - if let Some(error) = - const_functions::conversion_error(&tree.state.const_functions, &name) - { + } else if !const_functions::is_constant_function(&tree.functions, &name) { + if let Some(error) = const_functions::conversion_error(&tree.functions, &name) { return Err(error); } let context = dimensions::query_context_for_operand(id, tree, dimensions)?; @@ -1147,9 +1145,9 @@ fn check_indexed_width( syntax_tree, &context, )?; - let width = selects::indexed_expression_value(&syntax_tree.state, value, &context) + let width = selects::indexed_expression_value(syntax_tree, value, &context) .ok_or_else(|| unsupported("constant index expression"))?; - match eval_ast_const_expr(&syntax_tree.state, &width, &dimensions.const_env) { + match eval_ast_const_expr(&syntax_tree.functions, &width, &dimensions.const_env) { Some(width) if width > 0 => Ok(()), Some(width) => Err(unsupported(format!("indexed part-select width {width}"))), None => Err(unsupported( diff --git a/crates/celox-sv-analyzer/src/ast/virtual_interfaces.rs b/crates/celox-sv-analyzer/src/ast/virtual_interfaces.rs index 9a3260e7846..70a5cc29cff 100644 --- a/crates/celox-sv-analyzer/src/ast/virtual_interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/virtual_interfaces.rs @@ -439,16 +439,17 @@ pub(super) fn native_selected_member( /// read from the instance that virtual interface `handle` of type `ty` /// denotes; an error for `null`. pub(super) fn selected_read( - state: &AnalysisState, + tree: &AnalysisContext<'_>, handle: Expr, ty: &VirtualInterface, member: &str, selected: Expr, dimensions: &PackedDimensions, ) -> Converted { + let state = &*tree.state; let (_, signals) = self::member(state, ty, member)?; check_pure(&handle)?; - let width = expr_static_width(state, &selected, dimensions) + let width = expr_static_width(tree, &selected, dimensions) .ok_or_else(|| unsupported(format!("width of a select of `{member}`")))?; let signed = dimensions::expression_signedness(&selected, dimensions, &dimensions.const_env) .unwrap_or(false); @@ -621,13 +622,15 @@ pub(super) fn null_access(handle: &Expr, width: usize, signed: bool) -> Expr { /// interface `handle` of type `ty` denotes, with `select` applied to the /// member of each instance. pub(super) fn read( - state: &AnalysisState, + tree: &AnalysisContext<'_>, handle: Expr, ty: &VirtualInterface, member: &str, dimensions: &PackedDimensions, select: impl Fn(Expr) -> Converted, ) -> Converted { + let state = &*tree.state; + let functions = &tree.functions; let (found, signals) = self::member(state, ty, member)?; check_pure(&handle)?; let mut arms = Vec::new(); @@ -636,12 +639,12 @@ pub(super) fn read( } let (width, signed) = match arms.first() { Some((_, value)) => ( - expr_static_width(state, value, dimensions), + expr_static_width(tree, value, dimensions), dimensions::expression_signedness(value, dimensions, &dimensions.const_env) .unwrap_or(false), ), None => { - let shape = casts::expr_type_from_type(state, &found.r#type, &HashMap::default()); + let shape = casts::expr_type_from_type(functions, &found.r#type, &HashMap::default()); (shape.map(|shape| shape.width), found.r#type.is_signed()) } }; @@ -1151,13 +1154,15 @@ pub(super) fn null_check(handle: &Expr) -> Expr { /// selection among the instances, which changes when `handle` does, and /// zero for `null`. pub(super) fn watched( - state: &AnalysisState, + tree: &AnalysisContext<'_>, handle: Expr, ty: &VirtualInterface, member: &str, ) -> Converted { + let state = &*tree.state; + let functions = &tree.functions; let (found, signals) = self::member(state, ty, member)?; - let width = casts::expr_type_from_type(state, &found.r#type, &HashMap::default()) + let width = casts::expr_type_from_type(functions, &found.r#type, &HashMap::default()) .map(|shape| shape.width) .ok_or_else(|| unsupported(format!("width of virtual interface member `{member}`")))?; let mut value = Expr::Literal(format!("{width}'d0")); diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index e1bae8e8c4e..05797163314 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -852,7 +852,7 @@ impl Type { pub(crate) fn has_symbolic_ranges( &self, - functions: &crate::ast::const_functions::State, + functions: &crate::ast::const_functions::ConstantFunctions, ) -> bool { let values = fxhash::FxHashMap::default(); let constants = crate::ast::const_functions::Environment { diff --git a/crates/celox-sv-analyzer/src/source_tree.rs b/crates/celox-sv-analyzer/src/source_tree.rs index 51351ee34e3..7e05fa17062 100644 --- a/crates/celox-sv-analyzer/src/source_tree.rs +++ b/crates/celox-sv-analyzer/src/source_tree.rs @@ -40,6 +40,11 @@ pub(crate) struct SourceTree { } impl SourceTree { + /// The tree of an empty source, for evaluation outside any scope. + pub(crate) fn empty() -> Self { + parse_source("", Path::new("")).expect("an empty source parses") + } + pub(crate) fn compilation_path(&self) -> &Path { &self.compilation_path } diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/function_symbolic.rs b/crates/celox-sv-analyzer/src/source_tree/tests/function_symbolic.rs index 96c8f640927..db0cb1c6626 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/function_symbolic.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/function_symbolic.rs @@ -9,8 +9,9 @@ fn inline(tree: &SourceTree, input: i128) -> i128 { args: vec![ConstExpr::Literal(input.to_string())], site: None, }; + let syntax = crate::source_tree::SourceTree::empty(); let expression = source.modules()[0].declaration_expr( - &crate::ast::AnalysisState::default(), + &crate::ast::AnalysisContext::unspecialized(&syntax), &expression, &HashMap::default(), ); diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 1ba86408ca5..a30b85e205a 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -5248,7 +5248,8 @@ fn named_constant_calls_retain_parameter_dependencies() { .unwrap(); let source = ast::Source::from_syntax(&syntax).unwrap(); let module = &source.modules()[0]; - let state = module.constant_function_state(); + let empty = crate::source_tree::SourceTree::empty(); + let evaluation = module.constant_context(&empty); let expression: ir::ConstExpr = module .parameters() .iter() @@ -5264,7 +5265,7 @@ fn named_constant_calls_retain_parameter_dependencies() { &expression, &ast::const_functions::Environment { constants: &values, - functions: &state.const_functions + functions: &evaluation.functions } ), Some(17) diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index 79df89fd202..943b270d181 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -10,6 +10,7 @@ use fxhash::FxHashMap as HashMap; use num_bigint::BigUint; +use crate::ast::const_functions::Budget; use crate::ir::{BinaryOp, Callee, ConstExpr, PackedRange, SystemFunction, UnaryOp}; #[derive(Debug, Clone, PartialEq, Eq)] @@ -87,14 +88,22 @@ pub fn resolve_packed_width_with_env( pub(crate) fn resolve_packed_width_in_env( ranges: &[PackedRange], constants: &dyn ConstantEnvironment, +) -> Option { + resolve_packed_width_in_env_budgeted(ranges, constants, &mut Budget::default()) +} + +pub(crate) fn resolve_packed_width_in_env_budgeted( + ranges: &[PackedRange], + constants: &dyn ConstantEnvironment, + budget: &mut Budget, ) -> Option { if ranges.is_empty() { return Some(1); } ranges.iter().try_fold(1usize, |acc, range| { - let left = eval_const_expr_in_env(range.left(), constants)?; - let right = eval_const_expr_in_env(range.right(), constants)?; + let left = eval_const_expr_in_env_budgeted(range.left(), constants, budget)?; + let right = eval_const_expr_in_env_budgeted(range.right(), constants, budget)?; let width = usize::try_from(left.abs_diff(right)).ok()?.checked_add(1)?; acc.checked_mul(width) }) @@ -103,7 +112,8 @@ pub(crate) fn resolve_packed_width_in_env( /// Value lookup shared by immutable module environments and function frames. /// Dynamic dispatch keeps recursive calls from nesting generic frame types. pub(crate) trait ConstantEnvironment { - fn function_state(&self) -> Option<&crate::ast::const_functions::State> { + /// The constant functions calls in the environment's expressions call. + fn functions(&self) -> Option<&crate::ast::const_functions::ConstantFunctions> { None } fn get(&self, name: &str) -> Option<&i128>; @@ -166,6 +176,14 @@ pub fn eval_const_expr(expr: &ConstExpr, constants: &HashMap) -> O pub(crate) fn eval_const_expr_in_env( expr: &ConstExpr, constants: &dyn ConstantEnvironment, +) -> Option { + eval_const_expr_in_env_budgeted(expr, constants, &mut Budget::default()) +} + +pub(crate) fn eval_const_expr_in_env_budgeted( + expr: &ConstExpr, + constants: &dyn ConstantEnvironment, + budget: &mut Budget, ) -> Option { // This evaluator serves integral-only bounds and selectors as well as // numeric parameters. A real result is converted only by a caller with @@ -174,7 +192,7 @@ pub(crate) fn eval_const_expr_in_env( return None; } if real::needs_real_evaluation(expr) { - return real::evaluate(expr, constants).map(real::round_to_i128); + return real::evaluate_budgeted(expr, constants, budget).map(real::round_to_i128); } match expr { ConstExpr::Literal(value) => literal_as_i128(value), @@ -188,14 +206,14 @@ pub(crate) fn eval_const_expr_in_env( if let Some(literal) = integral_literal_from_const_expr(expr) { return integral_literal_as_i128(&literal, *signed); } - let value = eval_const_expr_in_env(operand, constants)?; + let value = eval_const_expr_in_env_budgeted(operand, constants, budget)?; let selected = ConstExpr::SelectRange { expr: Box::new(ConstExpr::Literal(format!("128'sh{:x}", value as u128))), msb: Box::new(ConstExpr::Literal( - eval_const_expr_in_env(msb, constants)?.to_string(), + eval_const_expr_in_env_budgeted(msb, constants, budget)?.to_string(), )), lsb: Box::new(ConstExpr::Literal( - eval_const_expr_in_env(lsb, constants)?.to_string(), + eval_const_expr_in_env_budgeted(lsb, constants, budget)?.to_string(), )), signed: *signed, }; @@ -210,14 +228,14 @@ pub(crate) fn eval_const_expr_in_env( return integral_literal_as_i128(&literal, *signed); } let value = if real::has_real_type(operand) { - real::round_to_i128(real::evaluate(operand, constants)?) + real::round_to_i128(real::evaluate_budgeted(operand, constants, budget)?) } else { - eval_const_expr_in_env(operand, constants)? + eval_const_expr_in_env_budgeted(operand, constants, budget)? }; literal_as_i128(&format_typed_constant_literal(value, *width, *signed)) } ConstExpr::Select { expr, bit } => { - let bit = eval_const_expr_in_env(bit, constants)?; + let bit = eval_const_expr_in_env_budgeted(bit, constants, budget)?; let bit = usize::try_from(bit).ok()?; if let ConstExpr::Literal(value) = &**expr { let value = parse_integral_literal(value)?; @@ -226,61 +244,63 @@ pub(crate) fn eval_const_expr_in_env( } return Some(value.value.bit(bit as u64) as i128); } - let value = eval_const_expr_in_env(expr, constants)?; + let value = eval_const_expr_in_env_budgeted(expr, constants, budget)?; let bit = u32::try_from(bit).ok()?; value.checked_shr(bit).map(|value| value & 1) } ConstExpr::Function { callee, args, .. } => match callee { Callee::Subroutine(name) => { - crate::ast::const_functions::eval_call(name, args, constants) + crate::ast::const_functions::eval_call_budgeted(name, args, constants, budget) } - Callee::System(function) => eval_system_function(*function, args, constants), + Callee::System(function) => eval_system_function(*function, args, constants, budget), Callee::Checked { width, signed, .. } => { let [guard, payload] = args.as_slice() else { return None; }; // IEEE 1800-2023 7.3.2: a member can only be read with its active tag. // Keep the guard even when evaluating a constant function (13.4.3). - if eval_const_expr_in_env(guard, constants)? == 0 { + if eval_const_expr_in_env_budgeted(guard, constants, budget)? == 0 { return None; } - eval_const_expr_in_env( + eval_const_expr_in_env_budgeted( &ConstExpr::Resize { expr: Box::new(payload.clone()), width: *width, signed: *signed, }, constants, + budget, ) } Callee::Stream(stream) => { let values = args .iter() - .map(|arg| eval_const_expr_in_env(arg, constants)) + .map(|arg| eval_const_expr_in_env_budgeted(arg, constants, budget)) .collect::>>()?; stream.evaluate(&values) } Callee::Lookup { width, signed } => { let (selector, rest) = args.split_first()?; let (default, pairs) = rest.split_last()?; - let selector = eval_const_expr_in_env(selector, constants)?; + let selector = eval_const_expr_in_env_budgeted(selector, constants, budget)?; let (pairs, []) = pairs.as_chunks::<2>() else { return None; }; let mut value = default; for [key, candidate] in pairs { - if eval_const_expr_in_env(key, constants)? == selector { + if eval_const_expr_in_env_budgeted(key, constants, budget)? == selector { value = candidate; break; } } - eval_const_expr_in_env( + eval_const_expr_in_env_budgeted( &ConstExpr::Resize { expr: Box::new(value.clone()), width: *width, signed: *signed, }, constants, + budget, ) } Callee::String(_) | Callee::Object(_) => None, @@ -291,7 +311,7 @@ pub(crate) fn eval_const_expr_in_env( { return Some(value); } - let value = eval_const_expr_in_env(operand, constants)?; + let value = eval_const_expr_in_env_budgeted(operand, constants, budget)?; match op { UnaryOp::Plus => Some(value), UnaryOp::Minus => value.checked_neg(), @@ -312,14 +332,14 @@ pub(crate) fn eval_const_expr_in_env( // Numeric declaration bounds need the same short-circuiting as // four-state generate conditions (11.3.5, 6.20.7). if matches!(op, BinaryOp::LogicAnd | BinaryOp::LogicOr) - && let Some(Some(truth)) = eval_const_truth(left, constants) + && let Some(Some(truth)) = eval_const_truth(left, constants, budget) { if (*op == BinaryOp::LogicAnd && !truth) || (*op == BinaryOp::LogicOr && truth) { return Some(i128::from(truth)); } // Reuse the known left truth; reevaluating it recursively // would double the work at every level of a logical chain. - return eval_const_truth(right, constants)?.map(i128::from); + return eval_const_truth(right, constants, budget)?.map(i128::from); } if let Some(result) = eval_literal_binary(left, *op, right) { return Some(result); @@ -331,8 +351,8 @@ pub(crate) fn eval_const_expr_in_env( { return Some(result as i128); } - let left = eval_const_expr_in_env(left, constants)?; - let right = eval_const_expr_in_env(right, constants)?; + let left = eval_const_expr_in_env_budgeted(left, constants, budget)?; + let right = eval_const_expr_in_env_budgeted(right, constants, budget)?; match op { BinaryOp::Add => left.checked_add(right), BinaryOp::Sub => left.checked_sub(right), @@ -371,10 +391,10 @@ pub(crate) fn eval_const_expr_in_env( condition, then_expr, else_expr, - } => match eval_const_truth(condition, constants)? { - Some(true) => eval_const_expr_in_env(then_expr, constants), - Some(false) => eval_const_expr_in_env(else_expr, constants), - None => merge_unknown_const_mux_arms(then_expr, else_expr, constants), + } => match eval_const_truth(condition, constants, budget)? { + Some(true) => eval_const_expr_in_env_budgeted(then_expr, constants, budget), + Some(false) => eval_const_expr_in_env_budgeted(else_expr, constants, budget), + None => merge_unknown_const_mux_arms(then_expr, else_expr, constants, budget), }, } } @@ -498,9 +518,18 @@ pub(crate) fn eval_const_expr_with_types_in_env( expr: &ConstExpr, constants: &dyn ConstantEnvironment, types: &impl Fn(&str) -> Option<(usize, bool)>, +) -> Option { + eval_const_expr_with_types_in_env_budgeted(expr, constants, types, &mut Budget::default()) +} + +pub(crate) fn eval_const_expr_with_types_in_env_budgeted( + expr: &ConstExpr, + constants: &dyn ConstantEnvironment, + types: &impl Fn(&str) -> Option<(usize, bool)>, + budget: &mut Budget, ) -> Option { let expr = substitute_typed_constants_with_lookup(expr.clone(), constants, types); - eval_const_expr_in_env(&expr, constants) + eval_const_expr_in_env_budgeted(&expr, constants, budget) } /// An assignment supplies a size context before arithmetic is evaluated; @@ -1111,24 +1140,29 @@ pub(crate) fn integral_literal_truth(literal: &IntegralLiteral) -> Option } } -fn eval_const_truth(expr: &ConstExpr, constants: &dyn ConstantEnvironment) -> Option> { +fn eval_const_truth( + expr: &ConstExpr, + constants: &dyn ConstantEnvironment, + budget: &mut Budget, +) -> Option> { if real::has_real_type(expr) { - return real::evaluate(expr, constants).map(|value| Some(value != 0.0)); + return real::evaluate_budgeted(expr, constants, budget).map(|value| Some(value != 0.0)); } if let Some(literal) = integral_literal_from_const_expr(expr) { return Some(integral_literal_truth(&literal)); } - eval_const_expr_in_env(expr, constants).map(|value| Some(value != 0)) + eval_const_expr_in_env_budgeted(expr, constants, budget).map(|value| Some(value != 0)) } fn merge_unknown_const_mux_arms( then_expr: &ConstExpr, else_expr: &ConstExpr, constants: &dyn ConstantEnvironment, + budget: &mut Budget, ) -> Option { if let (Some(then_value), Some(else_value)) = ( - eval_const_expr_in_env(then_expr, constants), - eval_const_expr_in_env(else_expr, constants), + eval_const_expr_in_env_budgeted(then_expr, constants, budget), + eval_const_expr_in_env_budgeted(else_expr, constants, budget), ) && then_value == else_value { return Some(then_value); @@ -1247,7 +1281,8 @@ fn integral_literal_from_const_expr(expr: &ConstExpr) -> Option return Some(literal); } let (width, signed) = function.result_type()?; - let value = eval_system_function(*function, args, &HashMap::default())?; + let value = + eval_system_function(*function, args, &HashMap::default(), &mut Budget::default())?; let signing = if signed { "s" } else { "" }; parse_integral_literal(&format!("{width}'{signing}d{value}")) } @@ -1583,6 +1618,7 @@ fn eval_system_function( function: SystemFunction, args: &[ConstExpr], constants: &dyn ConstantEnvironment, + budget: &mut Budget, ) -> Option { if matches!( function, @@ -1591,7 +1627,7 @@ fn eval_system_function( let [arg] = args else { return None; }; - let value = real::evaluate(arg, constants)?; + let value = real::evaluate_budgeted(arg, constants, budget)?; return Some(match function { SystemFunction::Rtoi => celox_design::eval_float_unary( celox_design::FloatUnaryOp::ToSigned { @@ -1611,12 +1647,12 @@ fn eval_system_function( if controls.is_empty() { return None; } - let operand = const_countbits_literal(arg, constants)?; + let operand = const_countbits_literal(arg, constants, budget)?; // Control arguments are converted to logic: only their LSB matters. // A set of states prevents duplicate controls from counting twice. let mut states = [false; 4]; for control in controls { - let literal = const_countbits_literal(control, constants)?; + let literal = const_countbits_literal(control, constants, budget)?; let state = literal.value.bit(0) as usize + 2 * literal.mask.bit(0) as usize; states[state] = true; } @@ -1640,8 +1676,8 @@ fn eval_system_function( let [arg] = args else { return None; }; - let ones = || { - let value = const_expr_known_one_bits(arg, constants)?; + let mut ones = || { + let value = const_expr_known_one_bits(arg, constants, budget)?; Some(value.iter_u64_digits().map(u64::count_ones).sum::()) }; match function { @@ -1649,12 +1685,12 @@ fn eval_system_function( let literal = self_determined_integral_literal(arg)?; integral_literal_as_i128(&literal, function == SystemFunction::Signed) } - SystemFunction::Clog2 => clog2(eval_const_expr_in_env(arg, constants)?), + SystemFunction::Clog2 => clog2(eval_const_expr_in_env_budgeted(arg, constants, budget)?), SystemFunction::Isunknown => { if let Some(literal) = self_determined_integral_literal(arg) { Some((literal.mask != BigUint::default()) as i128) } else { - eval_const_expr_in_env(arg, constants).map(|_| 0) + eval_const_expr_in_env_budgeted(arg, constants, budget).map(|_| 0) } } SystemFunction::Countones => Some(ones()? as i32 as i128), @@ -1667,9 +1703,10 @@ fn eval_system_function( fn const_countbits_literal( expr: &ConstExpr, constants: &dyn ConstantEnvironment, + budget: &mut Budget, ) -> Option { self_determined_integral_literal(expr).or_else(|| { - let value = eval_const_expr_in_env(expr, constants)?; + let value = eval_const_expr_in_env_budgeted(expr, constants, budget)?; parse_integral_literal(&format_typed_constant_literal(value, 32, true)) }) } @@ -1677,13 +1714,14 @@ fn const_countbits_literal( fn const_expr_known_one_bits( expr: &ConstExpr, constants: &dyn ConstantEnvironment, + budget: &mut Budget, ) -> Option { if let Some(literal) = self_determined_integral_literal(expr) { // IEEE 1800-2023 20.9 counts only bits equal to 1; X/Z do not // contribute, and onehot/onehot0 always return a two-state bit. return Some(&literal.value ^ (&literal.value & &literal.mask)); } - let value = eval_const_expr_in_env(expr, constants)?; + let value = eval_const_expr_in_env_budgeted(expr, constants, budget)?; (value >= 0).then(|| BigUint::from(value as u128)) } diff --git a/crates/celox-sv-analyzer/src/typecheck/real.rs b/crates/celox-sv-analyzer/src/typecheck/real.rs index 0e7e8975c51..6e2be250a76 100644 --- a/crates/celox-sv-analyzer/src/typecheck/real.rs +++ b/crates/celox-sv-analyzer/src/typecheck/real.rs @@ -76,6 +76,14 @@ pub(crate) fn round_to_i128(value: f64) -> i128 { } pub(crate) fn evaluate(expr: &ConstExpr, constants: &dyn ConstantEnvironment) -> Option { + evaluate_budgeted(expr, constants, &mut Budget::default()) +} + +pub(crate) fn evaluate_budgeted( + expr: &ConstExpr, + constants: &dyn ConstantEnvironment, + budget: &mut Budget, +) -> Option { if !needs_real_evaluation(expr) { let integral = ConstExpr::Unary { op: UnaryOp::ToTwoState, @@ -93,7 +101,8 @@ pub(crate) fn evaluate(expr: &ConstExpr, constants: &dyn ConstantEnvironment) -> let value = magnitude.to_str_radix(10).parse::().ok()?; return Some(if negative { -value } else { value }); } - return eval_const_expr_in_env(&integral, constants).map(|value| value as f64); + return eval_const_expr_in_env_budgeted(&integral, constants, budget) + .map(|value| value as f64); } match expr { ConstExpr::Literal(text) => text.replace('_', "").parse::().ok(), @@ -105,7 +114,7 @@ pub(crate) fn evaluate(expr: &ConstExpr, constants: &dyn ConstantEnvironment) -> if function.is_real_math() { let args = args .iter() - .map(|arg| evaluate(arg, constants)) + .map(|arg| evaluate_budgeted(arg, constants, budget)) .collect::>>()?; return function.eval_real_math(&args); } @@ -121,24 +130,24 @@ pub(crate) fn evaluate(expr: &ConstExpr, constants: &dyn ConstantEnvironment) -> round: true, }, celox_design::FloatPrecision::F64, - evaluate(arg, constants)?.to_bits(), + evaluate_budgeted(arg, constants, budget)?.to_bits(), ) as u32 as i32 } else { - eval_const_expr_in_env(arg, constants)? as i32 + eval_const_expr_in_env_budgeted(arg, constants, budget)? as i32 }; Some(f64::from(value)) } - SystemFunction::Bitstoreal => Some(f64::from_bits(eval_const_expr_in_env( - arg, constants, - )? as u64)), + SystemFunction::Bitstoreal => Some(f64::from_bits( + eval_const_expr_in_env_budgeted(arg, constants, budget)? as u64, + )), SystemFunction::Bitstoshortreal => Some(f64::from(f32::from_bits( - eval_const_expr_in_env(arg, constants)? as u32, + eval_const_expr_in_env_budgeted(arg, constants, budget)? as u32, ))), _ => None, } } ConstExpr::Unary { op, expr } => { - let value = evaluate(expr, constants)?; + let value = evaluate_budgeted(expr, constants, budget)?; match op { UnaryOp::Plus | UnaryOp::ToTwoState => Some(value), UnaryOp::Minus => Some(-value), @@ -147,14 +156,14 @@ pub(crate) fn evaluate(expr: &ConstExpr, constants: &dyn ConstantEnvironment) -> } } ConstExpr::Binary { left, op, right } => { - let left = evaluate(left, constants)?; + let left = evaluate_budgeted(left, constants, budget)?; if *op == BinaryOp::LogicAnd && left == 0.0 { return Some(0.0); } if *op == BinaryOp::LogicOr && left != 0.0 { return Some(1.0); } - let right = evaluate(right, constants)?; + let right = evaluate_budgeted(right, constants, budget)?; Some(match op { BinaryOp::Add => left + right, BinaryOp::Sub => left - right, @@ -181,13 +190,14 @@ pub(crate) fn evaluate(expr: &ConstExpr, constants: &dyn ConstantEnvironment) -> condition, then_expr, else_expr, - } => evaluate( - if evaluate(condition, constants)? != 0.0 { + } => evaluate_budgeted( + if evaluate_budgeted(condition, constants, budget)? != 0.0 { then_expr } else { else_expr }, constants, + budget, ), _ => None, } From 37cf250d8918a0a2a8d53a17fd92f975ba7f2f47 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 31 Oct 2026 03:24:09 +0900 Subject: [PATCH 2/2] refactor(sv): carry interface instances and time scopes in the context The interface instances being analyzed, whether generate scopes elaborate only their items, the time scopes of the source being analyzed and the path of the interface instance were installed into the shared analysis state behind Cells and RefCells, swapped by guards and tracked by revisions that invalidated memoized elaborations. They are now values of the analysis context that entering an interface instance or a source derives, and the elaboration memo keys entries by them, so the revision counters are gone. Change-Id: I5b8ff269863165472c661c98e89dc8a9ee7c0c82 --- crates/celox-sv-analyzer/src/ast.rs | 55 ++++--- .../src/ast/array_reductions.rs | 2 +- .../src/ast/classes/foreign.rs | 7 +- .../src/ast/const_functions.rs | 24 +-- crates/celox-sv-analyzer/src/ast/generate.rs | 33 +--- .../src/ast/generate/memo.rs | 61 ++------ .../src/ast/interface_ast.rs | 57 +++---- .../src/ast/interface_binding.rs | 60 +++++--- crates/celox-sv-analyzer/src/ast/packages.rs | 11 +- .../celox-sv-analyzer/src/ast/timescales.rs | 143 ++++++------------ 10 files changed, 184 insertions(+), 269 deletions(-) diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 05bef7d6f91..c5173916c35 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -24,16 +24,10 @@ pub(super) struct AnalysisState { foreign_arguments: RefCell>, foreign_names: RefCell>, foreign_error: RefCell>, - interfaces: interface_ast::State, dimensions: dimensions::State, - root_subroutines: std::cell::Cell, inline_randomizations: RefCell>, next_call_site: std::rc::Rc>, - timescales: timescales::State, diagnostics: RefCell>, - /// Revision of the imported scope, the analyzed package, the active - /// interface instances and the root-subroutine mode. - revision: generate::Revision, generate_items: generate::Memo, /// Classes laid out so far, by name. classes: std::cell::RefCell>>, @@ -85,6 +79,16 @@ pub(crate) struct AnalysisContext<'a> { /// The constant functions that calls in constant expressions of the /// scope call (IEEE 1800-2023 13.4.3). pub(crate) functions: const_functions::ConstantFunctions, + /// Whether generate scopes elaborate only their items, and their + /// subroutines are collected later. + root_subroutines: bool, + /// The interface instances being analyzed, outermost first. + active_interfaces: Arc>, + /// The time scopes that time queries of the scope read (IEEE 1800-2023 + /// 3.14.2). + timescale: Arc, + /// The hierarchical path of the interface instance being analyzed. + interface_instance: Option>, } impl<'a> AnalysisContext<'a> { @@ -100,6 +104,10 @@ impl<'a> AnalysisContext<'a> { imported: Arc::default(), package: None, functions: const_functions::ConstantFunctions::default(), + root_subroutines: false, + active_interfaces: Arc::default(), + timescale: Arc::default(), + interface_instance: None, } } @@ -111,6 +119,10 @@ impl<'a> AnalysisContext<'a> { imported: Arc::default(), package: None, functions: const_functions::ConstantFunctions::default(), + root_subroutines: false, + active_interfaces: Arc::default(), + timescale: Arc::default(), + interface_instance: None, } } @@ -128,6 +140,10 @@ impl<'a> AnalysisContext<'a> { imported: Arc::default(), package: None, functions: const_functions::ConstantFunctions::default(), + root_subroutines: false, + active_interfaces: Arc::default(), + timescale: Arc::default(), + interface_instance: None, } } @@ -143,6 +159,10 @@ impl<'a> AnalysisContext<'a> { imported: self.imported.clone(), package: self.package.clone(), functions: self.functions.clone(), + root_subroutines: self.root_subroutines, + active_interfaces: self.active_interfaces.clone(), + timescale: self.timescale.clone(), + interface_instance: self.interface_instance.clone(), } } @@ -394,15 +414,15 @@ impl Source { .map(|(name, value)| (name.clone(), const_expr_from_i128(*value))) .collect(); let interfaces = Self::module_interfaces_from_syntax(syntax_tree)?; - let _timescales = timescales::install_for_tree( - &syntax_tree.state.timescales, - packages.timescales.clone(), - syntax_tree, - )?; + let timed = AnalysisContext { + timescale: timescales::for_tree(packages.timescales.clone(), syntax_tree)?, + ..syntax_tree.clone() + }; + let syntax_tree = &timed; let mut modules = Vec::new(); for handle in syntax_tree.root_scopes()? { let scoped = syntax_tree.scoped(handle)?; - let scoped_context = context.child(&scoped, ¶meter_overrides); + let scoped_context = timed.child(&scoped, ¶meter_overrides); let syntax_tree = &scoped_context; let unit = syntax_tree.root_unit()?; if !unit.kind.is_module_like() { @@ -504,11 +524,10 @@ impl Source { ) -> Result { let context = AnalysisContext::with_packages(syntax_tree, packages); let syntax_tree = &context; - let _timescales = timescales::install_for_tree( - &syntax_tree.state.timescales, - packages.timescales.clone(), - syntax_tree, - )?; + let timed = AnalysisContext { + timescale: timescales::for_tree(packages.timescales.clone(), syntax_tree)?, + ..syntax_tree.clone() + }; let interfaces = InterfaceLookup { local: &index.interfaces, extra: extra_interfaces, @@ -517,7 +536,7 @@ impl Source { let interface_plan = packages.interface_plan.modules.get(module_name); let original_name = interface_plan.map_or(module_name, |plan| plan.original.as_str()); for scope_tree in index.scopes(original_name) { - let scope_context = context.child(scope_tree, bindings.values); + let scope_context = timed.child(scope_tree, bindings.values); let syntax_tree = &scope_context; match syntax_tree.root_unit()?.port_style { celox_sv_syntax::PortStyle::Ansi => { diff --git a/crates/celox-sv-analyzer/src/ast/array_reductions.rs b/crates/celox-sv-analyzer/src/ast/array_reductions.rs index bad87287527..54535b193ea 100644 --- a/crates/celox-sv-analyzer/src/ast/array_reductions.rs +++ b/crates/celox-sv-analyzer/src/ast/array_reductions.rs @@ -32,7 +32,7 @@ pub(super) fn bind( "xor" => ContainerOp::ReduceXor, _ => return Ok(None), }; - if timescales::analysis_options(&tree.state.timescales).legacy_empty_reductions { + if timescales::analysis_options(tree).legacy_empty_reductions { op = match op { ContainerOp::ReduceProduct => ContainerOp::LegacyReduceProduct, ContainerOp::ReduceAnd => ContainerOp::LegacyReduceAnd, diff --git a/crates/celox-sv-analyzer/src/ast/classes/foreign.rs b/crates/celox-sv-analyzer/src/ast/classes/foreign.rs index 7b16bf02fc8..ab8ccb1a441 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/foreign.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/foreign.rs @@ -319,11 +319,14 @@ impl Registry { parameter_overrides: Cow::Owned(HashMap::default()), imported: Arc::default(), functions: const_functions::ConstantFunctions::default(), + root_subroutines: false, + active_interfaces: Arc::default(), // Inside the package, `p::x` names its own item `x`. package: Some(name.into()), + timescale: timescales::for_tree(owner.timescales.clone(), &owner.tree)?, + interface_instance: None, }; - let _timescales = - timescales::install_for_tree(&state.timescales, owner.timescales.clone(), &owner.tree)?; + let mut imports = owner.imports.clone(); if let Some(caller) = caller { // Preserve the owner's existing bindings when caller metadata also diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 08bafe6d978..a3e7607031f 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -400,7 +400,7 @@ pub(super) fn symbolic_module_constant_functions( if !has_functions { return ConstantFunctions::default(); } - let needs_bootstrap = !generate::root_subroutines_only(&tree.state) && has_controls; + let needs_bootstrap = !tree.root_subroutines && has_controls; if !needs_bootstrap { return collect_module_constant_functions( tree, @@ -410,15 +410,19 @@ pub(super) fn symbolic_module_constant_functions( symbolic_parameters, ); } - let mut roots = generate::with_root_subroutines(&tree.state, || { - collect_module_constant_functions( - tree, - const_env, - type_aliases, - parameter_literals, - symbolic_parameters, - ) - }); + // Seed the module's functions before conditions need to call them: + // generate scopes still select their items, but their subroutines are + // left for the full pass. + let mut roots = collect_module_constant_functions( + &AnalysisContext { + root_subroutines: true, + ..tree.clone() + }, + const_env, + type_aliases, + parameter_literals, + symbolic_parameters, + ); roots.extend_missing(&scope::imported(tree).constant_functions); let tree = &tree.with_functions(roots); collect_module_constant_functions( diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index 869f075c312..3fb23b0e406 100644 --- a/crates/celox-sv-analyzer/src/ast/generate.rs +++ b/crates/celox-sv-analyzer/src/ast/generate.rs @@ -7,7 +7,7 @@ use super::*; use celox_sv_syntax::ExprId; mod elaboration; mod memo; -pub(super) use memo::{CallSites, Revision, memoize}; +pub(super) use memo::{CallSites, memoize}; mod dependency_order; use dependency_order::DependencyOrder; @@ -17,35 +17,6 @@ pub(super) use scope_views::ScopeViews; // Temporary identifiers protect definition-site bindings while functions are // inlined into a generate scope. They are removed when that item's names are // qualified, and never reach the public analyzer IR. -pub(super) fn root_subroutines_only(state: &AnalysisState) -> bool { - state.root_subroutines.get() -} - -/// Seed module functions before conditions need to call them. The full pass -/// still selects generate scopes and reports every generate diagnostic. -pub(super) fn with_root_subroutines( - state: &std::rc::Rc, - f: impl FnOnce() -> T, -) -> T { - struct Restore { - state: std::rc::Rc, - previous: bool, - revision: u64, - } - impl Drop for Restore { - fn drop(&mut self) { - self.state.root_subroutines.set(self.previous); - self.state.revision.restore(self.revision); - } - } - let _restore = Restore { - state: state.clone(), - revision: state.revision.change(), - previous: state.root_subroutines.replace(true), - }; - f() -} - const OUTER_BINDING: &str = "\0generate_outer:"; // Whitespace terminates an escaped identifier (IEEE 1800-2023 5.6.1). @@ -610,7 +581,7 @@ pub(super) fn subroutine_items( tree, env, aliases, - if root_subroutines_only(&tree.state) { + if tree.root_subroutines { LiteralUse::RootSubroutines } else { LiteralUse::Subroutines diff --git a/crates/celox-sv-analyzer/src/ast/generate/memo.rs b/crates/celox-sv-analyzer/src/ast/generate/memo.rs index bff30cc72a0..20d8c016721 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/memo.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/memo.rs @@ -2,44 +2,18 @@ //! //! The collectors of a module each ask for the active items of the same //! scope. A window opened for the module keeps each elaboration, keyed by its -//! arguments, the imports, package and constant functions of its context, -//! and the revisions of -//! the analysis state that elaboration reads (active interface instances, -//! time scopes), so a change of that state makes -//! earlier results unreachable. +//! arguments and by the parts of its context that elaboration reads: the +//! imports, package, constant functions, active interface instances and time +//! scopes, so a change of any of them makes earlier results unreachable. //! A repeated elaboration allocates as many call sites as the first one did, //! so later calls keep their sites. use super::*; +#[cfg(test)] use std::cell::Cell; mod sites; pub(in crate::ast) use sites::CallSites; -/// Names a value of analysis state that elaboration reads. Each change gives -/// a new revision; a guard that restores the previous value restores its -/// revision too, so equal revisions mean equal state. -#[derive(Default)] -pub(in crate::ast) struct Revision { - current: Cell, - last: Cell, -} - -impl Revision { - /// Record a change, returning the revision to restore with the value. - pub(in crate::ast) fn change(&self) -> u64 { - self.last.set(self.last.get() + 1); - self.current.replace(self.last.get()) - } - - pub(in crate::ast) fn restore(&self, previous: u64) { - self.current.set(previous); - } - - pub(in crate::ast) fn get(&self) -> u64 { - self.current.get() - } -} - #[derive(Default)] pub(in crate::ast) struct State(RefCell>); @@ -50,11 +24,13 @@ struct Window { } struct Entry { - revisions: [u64; 2], /// The symbols the scope imported and the package it was in. imported: Arc, package: Option>, functions: const_functions::ConstantFunctions, + active_interfaces: Arc>, + timescale: Arc, + interface_instance: Option>, literal_use: LiteralUse, overrides: HashMap, env: HashMap, @@ -96,13 +72,6 @@ fn address(tree: &SyntaxTree) -> usize { tree as *const SyntaxTree as usize } -fn revisions(state: &AnalysisState) -> [u64; 2] { - [ - state.revision.get(), - timescales::revision(&state.timescales).get(), - ] -} - /// The items `elaborate` gives for these arguments, elaborated once per window. pub(super) fn items( tree: &AnalysisContext<'_>, @@ -128,12 +97,13 @@ pub(super) fn items( drop(window); return elaborate(); }; - let current = revisions(state); if let Some(entry) = window.entries.iter().find(|entry| { - entry.revisions == current - && Arc::ptr_eq(&entry.imported, &tree.imported) + Arc::ptr_eq(&entry.imported, &tree.imported) && entry.package == tree.package && entry.functions.same(&tree.functions) + && Arc::ptr_eq(&entry.active_interfaces, &tree.active_interfaces) + && Arc::ptr_eq(&entry.timescale, &tree.timescale) + && entry.interface_instance == tree.interface_instance && entry.literal_use == literal_use && entry.overrides == *tree.parameter_overrides && entry.env == *env @@ -145,12 +115,7 @@ pub(super) fn items( } } let first_site = state.next_call_site.get(); - let current = revisions(state); let items = elaborate()?; - // Elaboration that leaves the state changed is not repeatable. - if revisions(state) != current { - return Ok(items); - } let sites = first_site..state.next_call_site.get(); // Effectful calls the items retain must get new sites when they are // elaborated again. @@ -160,10 +125,12 @@ pub(super) fn items( let mut window = state.generate_items.0.borrow_mut(); if let Some(window) = window.as_mut().filter(|window| applies(window)) { window.entries.push(Entry { - revisions: current, imported: tree.imported.clone(), package: tree.package.clone(), functions: tree.functions.clone(), + active_interfaces: tree.active_interfaces.clone(), + timescale: tree.timescale.clone(), + interface_instance: tree.interface_instance.clone(), literal_use, overrides: tree.parameter_overrides.clone().into_owned(), env: env.clone(), diff --git a/crates/celox-sv-analyzer/src/ast/interface_ast.rs b/crates/celox-sv-analyzer/src/ast/interface_ast.rs index 73f13eae3b6..44819e5ac28 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_ast.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_ast.rs @@ -1,27 +1,12 @@ //! Native interface scope analysis and public type contracts. use super::*; -type ActiveInstance = ( +pub(super) type ActiveInstance = ( std::path::PathBuf, String, HashMap, Vec<(String, Type)>, ); -#[derive(Default)] -pub(super) struct State { - active_instances: RefCell>, -} -struct InstanceGuard { - state: std::rc::Rc, - revision: u64, -} -impl Drop for InstanceGuard { - fn drop(&mut self) { - self.state.interfaces.active_instances.borrow_mut().pop(); - self.state.revision.restore(self.revision); - } -} - /// Analyze the original interface body and retain its symbols for the scope /// that instantiates it. The structural view borrows every token's original /// source location, including the lexical time scope of processes/functions. @@ -44,24 +29,25 @@ pub(super) fn analyze( overrides.clone(), types.to_vec(), ); - { - let mut instances = tree.state.interfaces.active_instances.borrow_mut(); - if instances.len() >= 64 { - return Err(unsupported("interface instance nesting exceeds 64 levels")); - } - if instances.contains(&instance) { - return Err(unsupported(format!( - "recursive interface instantiation `{name}`" - ))); - } - instances.push(instance); + if tree.active_interfaces.len() >= 64 { + return Err(unsupported("interface instance nesting exceeds 64 levels")); + } + if tree.active_interfaces.contains(&instance) { + return Err(unsupported(format!( + "recursive interface instantiation `{name}`" + ))); } - let _instance = InstanceGuard { - state: tree.state.clone(), - revision: tree.state.revision.change(), + let mut active = (*tree.active_interfaces).clone(); + active.push(instance); + let tree = &AnalysisContext { + active_interfaces: Arc::new(active), + ..tree.clone() }; - let _timescales = - timescales::install_for_tree(&tree.state.timescales, packages.timescales.clone(), tree)?; + let timed = AnalysisContext { + timescale: timescales::for_tree(packages.timescales.clone(), tree)?, + ..tree.clone() + }; + let tree = &timed; let lookup = InterfaceLookup { local: interfaces, extra: &ModuleInterfaces::default(), @@ -114,8 +100,11 @@ pub(super) fn signature( let context = AnalysisContext::unspecialized(&projected_tree); let tree = &context; let imported = imports::imported_symbols(tree, packages, packages.unit(path))?; - let _timescales = - timescales::install_for_tree(&tree.state.timescales, packages.timescales.clone(), tree)?; + let timed = AnalysisContext { + timescale: timescales::for_tree(packages.timescales.clone(), tree)?, + ..tree.clone() + }; + let tree = &timed; let empty = ModuleInterfaces::default(); let interfaces = InterfaceLookup { local: &empty, diff --git a/crates/celox-sv-analyzer/src/ast/interface_binding.rs b/crates/celox-sv-analyzer/src/ast/interface_binding.rs index c8c6def8f20..bcc86cd9ff1 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_binding.rs @@ -241,18 +241,24 @@ pub(super) fn analyze_module( } else { format!("{}${ordinal}", port.name) }; - let mut interface = - timescales::with_interface_instance(&tree.state.timescales, handle, || { - interface_ast::analyze( - &tree.child(definition_tree, &values), - definition_path, - packages, - &values, - &types, - interfaces.extra, - imported.declarations_only, - ) - })?; + let mut interface = { + let tree = &AnalysisContext { + interface_instance: Some(timescales::interface_instance( + tree.interface_instance.as_deref(), + handle, + )), + ..tree.clone() + }; + interface_ast::analyze( + &tree.child(definition_tree, &values), + definition_path, + packages, + &values, + &types, + interfaces.extra, + imported.declarations_only, + ) + }?; // Header ports are members of the interface view, just like body signals. for port in &interface.ports { interface.symbols.as_mut().unwrap().signals.push(Signal { @@ -533,18 +539,24 @@ pub(super) fn analyze_module( &dimensions, Some(&interface), )?; - let mut module = - timescales::with_interface_instance(&tree.state.timescales, &handle, || { - interface_ast::analyze( - &tree.child(definition_tree, &values), - definition_path, - packages, - &values, - &types, - interfaces.extra, - imported.declarations_only, - ) - })?; + let mut module = { + let tree = &AnalysisContext { + interface_instance: Some(timescales::interface_instance( + tree.interface_instance.as_deref(), + &handle, + )), + ..tree.clone() + }; + interface_ast::analyze( + &tree.child(definition_tree, &values), + definition_path, + packages, + &values, + &types, + interfaces.extra, + imported.declarations_only, + ) + }?; let port_syntax = SyntaxTree::empty(); let port_tree = module.constant_context(&port_syntax); let port_symbols = module.symbols.as_ref().unwrap(); diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index e94ee1eaf33..97ce42acf11 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -519,10 +519,17 @@ fn analyze_package( imported: Arc::default(), package: None, functions: const_functions::ConstantFunctions::default(), + root_subroutines: false, + active_interfaces: Arc::default(), + timescale: Arc::default(), + interface_instance: None, }; let tree = &context; - let _timescales = - timescales::install_for_tree(&tree.state.timescales, packages.timescales.clone(), tree)?; + let timed = AnalysisContext { + timescale: timescales::for_tree(packages.timescales.clone(), tree)?, + ..tree.clone() + }; + let tree = &timed; let first = { // Inside the package, `p::x` names its own item `x`. analyze_package_scope(name, &tree.in_package(name), packages, None)? diff --git a/crates/celox-sv-analyzer/src/ast/timescales.rs b/crates/celox-sv-analyzer/src/ast/timescales.rs index bb0ffdb0d87..fe2513f9ccd 100644 --- a/crates/celox-sv-analyzer/src/ast/timescales.rs +++ b/crates/celox-sv-analyzer/src/ast/timescales.rs @@ -110,51 +110,18 @@ pub(super) struct Timescales { options: crate::AnalysisOptions, } -/// Time-query state owned by one analysis, shared explicitly by nested scopes. -#[derive(Default)] -pub(super) struct State { - design: RefCell, - interface_instance: RefCell>, - revision: generate::Revision, -} - -pub(super) fn revision(state: &State) -> &generate::Revision { - &state.revision +/// The options the design was analyzed with. +pub(super) fn analysis_options(tree: &AnalysisContext<'_>) -> crate::AnalysisOptions { + tree.timescale.design.options.clone() } -pub(super) fn analysis_options(state: &State) -> crate::AnalysisOptions { - state.design.borrow().design.options.clone() -} - -pub(super) fn with_interface_instance( - state: &State, - name: &str, - analyze: impl FnOnce() -> T, -) -> T { - struct Restore<'a> { - state: &'a State, - previous: Option, - revision: u64, - } - impl Drop for Restore<'_> { - fn drop(&mut self) { - *self.state.interface_instance.borrow_mut() = self.previous.take(); - self.state.revision.restore(self.revision); - } +/// The hierarchical path of interface instance `name` inside the instance +/// at `parent`, which time messages of its body are prefixed with. +pub(super) fn interface_instance(parent: Option<&str>, name: &str) -> Arc { + match parent { + Some(parent) => format!("{parent}.{name}").into(), + None => name.into(), } - let previous = { - let mut current = state.interface_instance.borrow_mut(); - let nested = current - .as_ref() - .map_or_else(|| name.to_string(), |parent| format!("{parent}.{name}")); - current.replace(nested) - }; - let _restore = Restore { - state, - previous, - revision: state.revision.change(), - }; - analyze() } #[cfg(test)] @@ -164,8 +131,9 @@ thread_local! { static SCOPE_CHECKS: std::cell::Cell = const { std::cell::Cell::new(0) }; } +/// The time scopes of the design, and those of the source being analyzed. #[derive(Default)] -struct QueryContext { +pub(super) struct QueryContext { design: Arc, prepared: Option, } @@ -175,24 +143,9 @@ struct PreparedTree { unit: Arc, } -pub(super) struct Installed<'a> { - previous: QueryContext, - revision: u64, - state: &'a State, - // A prepared tree's address is used only while this guard borrows it. - _tree: Option<&'a SyntaxTree>, -} -impl Drop for Installed<'_> { - fn drop(&mut self) { - *self.state.design.borrow_mut() = std::mem::take(&mut self.previous); - self.state.revision.restore(self.revision); - } -} -pub(super) fn install_for_tree<'a>( - state: &'a State, - design: Arc, - tree: &'a SyntaxTree, -) -> Converted> { +/// The time scopes of `design` with those of `tree`, which queries of the +/// tree's scopes read. +pub(super) fn for_tree(design: Arc, tree: &SyntaxTree) -> Converted> { let source = key(tree); // Missing sources and type-specialized trees contribute to the same design. // Collect and merge once, before any query or module-body analysis. @@ -208,24 +161,7 @@ pub(super) fn install_for_tree<'a>( address: tree as *const SyntaxTree as usize, unit, }); - Ok(install_context( - state, - QueryContext { design, prepared }, - Some(tree), - )) -} - -fn install_context<'a>( - state: &'a State, - context: QueryContext, - tree: Option<&'a SyntaxTree>, -) -> Installed<'a> { - Installed { - previous: state.design.replace(context), - revision: state.revision.change(), - state, - _tree: tree, - } + Ok(Arc::new(QueryContext { design, prepared })) } fn key(tree: &SyntaxTree) -> crate::source_tree::SourceText { @@ -961,9 +897,9 @@ pub(super) fn print_message( tree: &AnalysisContext<'_>, site: system_functions::CallSite, ) -> Converted { - let prefix = tree.state.timescales.interface_instance.borrow().clone(); + let prefix = tree.interface_instance.clone(); { - let context = tree.state.timescales.design.borrow(); + let context = &*tree.timescale; if let Some(prepared) = &context.prepared && prepared.address == tree.syntax_tree as *const SyntaxTree as usize { @@ -991,7 +927,7 @@ pub(super) fn print_message( pub(super) fn query(call: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>) -> Converted { { - let context = tree.state.timescales.design.borrow(); + let context = &*tree.timescale; if let Some(prepared) = &context.prepared && prepared.address == tree.syntax_tree as *const SyntaxTree as usize { @@ -1033,7 +969,7 @@ fn divisor( tree: &AnalysisContext<'_>, in_unit: fn(&Timescales, usize, &Unit) -> u64, ) -> Converted { - let context = tree.state.timescales.design.borrow(); + let context = &*tree.timescale; let at = tree.declarations().expression(node).tokens.start; if let Some(prepared) = &context.prepared && prepared.address == tree.syntax_tree as *const SyntaxTree as usize @@ -1068,7 +1004,7 @@ pub(super) fn delay_literal( .find_map(|(suffix, exponent)| text.strip_suffix(suffix).map(|n| (n, exponent))) else { return Ok(None); }; - let context = tree.state.timescales.design.borrow(); + let context = &*tree.timescale; let source = key(tree); let extended = (!context.design.units.contains_key(&source)) .then(|| context.design.including_tree(tree)) @@ -1110,17 +1046,12 @@ pub(super) fn delay_literal( mod tests { #[test] fn nested_interface_instances_keep_their_full_path() { - let state = State::default(); - with_interface_instance(&state, "outer", || { - with_interface_instance(&state, "child[2]", || { - assert_eq!( - state.interface_instance.borrow().as_deref(), - Some("outer.child[2]") - ); - }); - assert_eq!(state.interface_instance.borrow().as_deref(), Some("outer")); - }); - assert!(state.interface_instance.borrow().is_none()); + let outer = interface_instance(None, "outer"); + assert_eq!(&*outer, "outer"); + assert_eq!( + &*interface_instance(Some(&outer), "child[2]"), + "outer.child[2]" + ); } use super::*; @@ -1157,7 +1088,10 @@ mod tests { let design = Arc::new(Timescales::collect(&[(&tree, Path::new("many_queries.sv"))]).unwrap()); let tree = AnalysisContext::unspecialized(&tree); - let _guard = install_for_tree(&tree.state.timescales, design, &tree).unwrap(); + let tree = AnalysisContext { + timescale: for_tree(design, &tree).unwrap(), + ..tree.clone() + }; let before = SCOPE_CHECKS.with(|count| count.get()); let mut calls = 0; for call in native_calls(&tree) { @@ -1185,7 +1119,10 @@ mod tests { let design = Arc::new(Timescales::collect(&[(&tree, Path::new("nested_queries.sv"))]).unwrap()); let tree = AnalysisContext::unspecialized(&tree); - let _guard = install_for_tree(&tree.state.timescales, design, &tree).unwrap(); + let tree = AnalysisContext { + timescale: for_tree(design, &tree).unwrap(), + ..tree.clone() + }; let values: Vec<_> = native_calls(&tree) .into_iter() .map(|call| query(call, &tree).unwrap()) @@ -1659,12 +1596,18 @@ mod tests { let a = AnalysisContext::unspecialized(&a); let overrides = HashMap::default(); let b = a.child(&b, &overrides); - let _outer = install_for_tree(&a.state.timescales, design.clone(), &a).unwrap(); + let a = AnalysisContext { + timescale: for_tree(design.clone(), &a).unwrap(), + ..a.clone() + }; assert_eq!(query(call(&a), &a).unwrap(), -6); { - let _inner = install_for_tree(&b.state.timescales, design.clone(), &b).unwrap(); + let b = AnalysisContext { + timescale: for_tree(design.clone(), &b).unwrap(), + ..b.clone() + }; assert_eq!(query(call(&b), &b).unwrap(), -9); - assert!(install_for_tree(&b.state.timescales, design, &invalid).is_err()); + assert!(for_tree(design, &invalid).is_err()); assert_eq!(query(call(&b), &b).unwrap(), -9); } assert_eq!(query(call(&a), &a).unwrap(), -6);