diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 78b5804cc45..7bc79d843a8 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -945,12 +945,13 @@ fn package_warnings( /// instance each, numbered from `first`. fn lower_package_states( packages: &sv::Packages, + design: &sv::Design, first: usize, four_state: bool, ff_parts: bool, warnings: &mut Vec, ) -> Result, sv::AnalyzerError> { - let states = packages.specialized_state_modules(); + let states = packages.specialized_state_modules(design); let mut states = states.iter().collect::>(); states.sort_by(|left, right| left.name().cmp(right.name())); states @@ -2200,6 +2201,12 @@ fn prepare_external_hierarchy_collecting( analysis_options, )?; package_warnings(&analyzed, warnings); + // The specializations that the modules request of package class + // templates, shared by all of their analyses. + let mut design = analyzed + .values() + .next() + .map_or_else(sv::Design::default, |module| module.packages.design()); let dummy = sv::ParsedSource::parse( "module __celox_foreign(); endmodule", Path::new(""), @@ -2211,6 +2218,7 @@ fn prepare_external_hierarchy_collecting( &[], &sv::ModuleInterfaces::default(), &sv::Packages::default(), + &mut sv::Design::default(), )?; let lower_foreign = |signature: &ExternalModule| { let variables: HashMap<_, _> = signature @@ -2405,6 +2413,7 @@ fn prepare_external_hierarchy_collecting( .ok_or_else(|| unsupported_sv_instance(key.name.clone()))?; let lowered = specialize_module( base, + &mut design, &key, four_state, false, @@ -2444,6 +2453,7 @@ fn prepare_external_hierarchy_collecting( module_id, specialize_module( base, + &mut design, key, four_state, false, @@ -2517,6 +2527,7 @@ fn prepare_external_hierarchy_collecting( }; let package_states = lower_package_states( &any_module.packages, + &design, module_ids.len(), four_state, false, @@ -2875,6 +2886,12 @@ fn schedule_sources_collecting( let found_warnings = warnings.len(); let analyzed = analyze_sources(sources, &[top], analysis_options.clone())?; package_warnings(&analyzed, warnings); + // The specializations that the modules request of package class + // templates, shared by all of their analyses. + let mut design = analyzed + .values() + .next() + .map_or_else(sv::Design::default, |module| module.packages.design()); let top = top.to_string(); let root_key = LoweredSvModuleKey { name: top.clone(), @@ -2921,6 +2938,7 @@ fn schedule_sources_collecting( let module_id = module_ids[&key]; let module = match specialize_module( base, + &mut design, &key, four_state, false, @@ -2938,7 +2956,7 @@ fn schedule_sources_collecting( // hierarchical names. Err(error) if hierarchical_reference_path(&error).is_some() => { hierarchical_modules.push(module_id); - specialize_module_declarations(base, &key)? + specialize_module_declarations(base, &mut design, &key)? } Err(error) => return Err(error.into()), }; @@ -3018,7 +3036,13 @@ fn schedule_sources_collecting( .iter() .map(|reference| reference.signal.clone()) .collect(); - match analyze_specialization(&analyzed[&key.name], key, &signals, &mut Vec::new()) { + match analyze_specialization( + &analyzed[&key.name], + &mut design, + key, + &signals, + &mut Vec::new(), + ) { Ok(ir) => break ir, // A name with an instance index that is a constant // expression reaches the analysis with the index evaluated. @@ -3096,6 +3120,7 @@ fn schedule_sources_collecting( .collect(); Ok(specialize_module( base, + &mut design, key, four_state, parallel.enabled(), @@ -3185,6 +3210,7 @@ fn schedule_sources_collecting( let package_states = lower_package_states( &analyzed[&top].packages, + &design, module_ids.len(), four_state, parallel.enabled(), @@ -3434,6 +3460,7 @@ fn specialization_overrides( /// `hierarchical`. fn analyze_specialization( module: &AnalyzedSvModule, + design: &mut sv::Design, key: &LoweredSvModuleKey, hierarchical: &[sv::ast::HierarchicalSignal], warnings: &mut Vec, @@ -3446,6 +3473,7 @@ fn analyze_specialization( &pattern_overrides, &module.interfaces, &module.packages, + design, hierarchical, ); if let Err(error) = &analyzed { @@ -3459,6 +3487,7 @@ fn analyze_specialization( #[allow(clippy::too_many_arguments)] fn specialize_module( module: &AnalyzedSvModule, + design: &mut sv::Design, key: &LoweredSvModuleKey, four_state: bool, ff_parts: bool, @@ -3473,7 +3502,7 @@ fn specialize_module( ir } None => { - analyzed = analyze_specialization(module, key, hierarchical.signals, warnings)?; + analyzed = analyze_specialization(module, design, key, hierarchical.signals, warnings)?; &analyzed } }; @@ -3570,6 +3599,7 @@ fn propagate_force_signals(instances: &mut [LoweredSvInstance], force_signals: & /// The declarations and instances of specialization `key`. fn specialize_module_declarations( module: &AnalyzedSvModule, + design: &mut sv::Design, key: &LoweredSvModuleKey, ) -> Result { let (overrides, type_overrides, pattern_overrides) = specialization_overrides(key)?; @@ -3580,6 +3610,7 @@ fn specialize_module_declarations( &pattern_overrides, &module.interfaces, &module.packages, + design, )?; let specialized = ir .modules() diff --git a/crates/celox-sv-analyzer/src/analyze.rs b/crates/celox-sv-analyzer/src/analyze.rs index 2d24f7b20fd..2a9b8a6b309 100644 --- a/crates/celox-sv-analyzer/src/analyze.rs +++ b/crates/celox-sv-analyzer/src/analyze.rs @@ -18,6 +18,7 @@ fn analyze_source_impl(source: ast::Source) -> Result { for module in source.modules() { let syntax = crate::source_tree::SourceTree::empty(); let tree = &module.constant_context(&syntax); + let session = &mut ast::Session::default(); let id = module_table.insert(module)?; let mut constants = HashMap::default(); let mut parameter_types = HashMap::default(); @@ -44,6 +45,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( tree, + session, &constants, ¶meter_types, ¶meter_literals, @@ -80,7 +82,7 @@ fn analyze_source_impl(source: ast::Source) -> Result { .with_declaration( parameter.value().map(|value| { module - .declaration_expr(tree, value, ¶meter_signedness) + .declaration_expr(tree, session, value, ¶meter_signedness) .into() }), parameter @@ -89,10 +91,20 @@ fn analyze_source_impl(source: ast::Source) -> Result { .map(|range| { ir::PackedRange::new( module - .declaration_expr(tree, range.left(), ¶meter_signedness) + .declaration_expr( + tree, + session, + range.left(), + ¶meter_signedness, + ) .into(), module - .declaration_expr(tree, range.right(), ¶meter_signedness) + .declaration_expr( + tree, + session, + range.right(), + ¶meter_signedness, + ) .into(), ) }) diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index c5173916c35..39fd63d751b 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -9,7 +9,6 @@ use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; use std::{ borrow::Cow, - cell::RefCell, ops::{Deref, DerefMut}, path::Path, sync::Arc, @@ -17,52 +16,71 @@ use std::{ use crate::source_tree::SourceTree as SyntaxTree; -/// State owned by one analysis session, shared explicitly with nested scopes. +/// What one analysis owns and changes as it goes: the caches it keys by +/// their inputs and what it reports. Analysis passes it down as `&mut`. #[derive(Default)] -pub(super) struct AnalysisState { - foreign: std::rc::Rc, - foreign_arguments: RefCell>, - foreign_names: RefCell>, - foreign_error: RefCell>, +pub(crate) struct Session { + foreign: classes::foreign::Registry, + foreign_arguments: Vec<(String, classes::specializations::BoundArguments)>, + foreign_names: Vec<(String, classes::specializations::BoundArguments, String)>, + foreign_error: Option, dimensions: dimensions::State, - inline_randomizations: RefCell>, - next_call_site: std::rc::Rc>, - diagnostics: RefCell>, + inline_randomizations: Vec, + next_call_site: usize, + diagnostics: Vec, generate_items: generate::Memo, /// Classes laid out so far, by name. - classes: std::cell::RefCell>>, + classes: HashMap>, /// The constants and types of the scope that declares each class, which /// its parameter defaults and body see (IEEE 1800-2023 8.25). - class_declaration_scopes: - std::cell::RefCell, SharedMap)>>, + class_declaration_scopes: HashMap, SharedMap)>, /// The specializations that class references have named, by class /// declaration (see [`classes::specializations`]). - class_specialization_names: - std::cell::RefCell>>, + class_specialization_names: HashMap>, /// The classes declared in a generate block that elaboration repeats, /// which would be a class of their own in each repetition (27.4). - class_declarations_repeated: std::cell::RefCell>, + class_declarations_repeated: HashSet, /// Set once the class methods of the scope being analyzed have their /// signatures, after which a new specialization would have none. - class_specializations_frozen: std::cell::Cell, + class_specializations_frozen: bool, /// The class specializations being made, which their own declarations /// may name before they are complete. - class_specializations_building: std::cell::RefCell>, + class_specializations_building: Vec, /// How many class specializations are being made, one inside another. - class_specialization_depth: std::cell::Cell, + class_specialization_depth: usize, /// The specializations of classes made so far, in order. - class_specializations: std::cell::RefCell< - Vec<( - String, - std::rc::Rc, - )>, - >, + class_specializations: Vec<( + String, + std::rc::Rc, + )>, /// The virtual interfaces of the design, if it has any (IEEE 1800-2023 /// 25.9). virtual_interfaces: Option>, - /// The semantic types of the design, shared with the sessions of its - /// other scopes. - types: std::rc::Rc, + /// The semantic types of the design. + types: semantic_types::TyTable, +} + +impl Session { + /// A session for a scope analyzed with `packages`, which takes over the + /// package class specializations, types and call sites of the design + /// until [`Self::restore`] gives them back. + fn with_packages(packages: &packages::Packages, design: &mut packages::Design) -> Self { + Self { + next_call_site: design.call_sites, + foreign: std::mem::take(&mut design.foreign), + virtual_interfaces: packages.virtual_interfaces.clone(), + types: std::mem::take(&mut design.types), + ..Self::default() + } + } + + /// Gives `packages` back what [`Self::with_packages`] took, with what + /// this session added to it. + fn restore(self, design: &mut packages::Design) { + design.call_sites = self.next_call_site; + design.foreign = self.foreign; + design.types = self.types; + } } /// Syntax and specialization bindings for one scope within an analysis session. @@ -70,7 +88,6 @@ pub(super) struct AnalysisState { #[derive(Clone)] pub(crate) struct AnalysisContext<'a> { syntax_tree: &'a SyntaxTree, - state: std::rc::Rc, parameter_overrides: Cow<'a, HashMap>, /// The symbols the scope being analyzed imports (IEEE 1800-2023 26.3). imported: Arc, @@ -99,7 +116,6 @@ impl<'a> AnalysisContext<'a> { ) -> Self { Self { syntax_tree, - state: std::rc::Rc::default(), parameter_overrides: Cow::Borrowed(parameter_overrides), imported: Arc::default(), package: None, @@ -114,28 +130,6 @@ impl<'a> AnalysisContext<'a> { 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(), - root_subroutines: false, - active_interfaces: Arc::default(), - timescale: Arc::default(), - interface_instance: None, - } - } - - fn with_packages(syntax_tree: &'a SyntaxTree, packages: &packages::Packages) -> Self { - Self { - syntax_tree, - state: std::rc::Rc::new(AnalysisState { - next_call_site: packages.call_sites.clone(), - foreign: packages.foreign.clone(), - virtual_interfaces: packages.virtual_interfaces.clone(), - types: packages.types.clone(), - ..AnalysisState::default() - }), parameter_overrides: Cow::Owned(HashMap::default()), imported: Arc::default(), package: None, @@ -154,7 +148,6 @@ impl<'a> AnalysisContext<'a> { ) -> AnalysisContext<'b> { AnalysisContext { syntax_tree, - state: self.state.clone(), parameter_overrides: Cow::Borrowed(parameter_overrides), imported: self.imported.clone(), package: self.package.clone(), @@ -407,7 +400,8 @@ impl Source { parameter_overrides: &HashMap, ) -> Result { let packages = packages::Packages::analyze(&[(syntax_tree, Path::new(""))])?; - let context = AnalysisContext::with_packages(syntax_tree, &packages); + let session = &mut Session::with_packages(&packages, &mut packages.design()); + let context = AnalysisContext::unspecialized(syntax_tree); let syntax_tree = &context; let parameter_overrides = parameter_overrides .iter() @@ -438,6 +432,7 @@ impl Source { modules.push( Module::from_scope_with_parameter_overrides( syntax_tree, + session, module_name, ¶meter_overrides, &InterfaceLookup { @@ -446,9 +441,7 @@ impl Source { }, Arc::new(imported), ) - .map_err(|error| { - error.with_warnings(context.state.diagnostics.borrow().clone()) - })?, + .map_err(|error| error.with_warnings(session.diagnostics.clone()))?, ); } celox_sv_syntax::PortStyle::NonAnsi => { @@ -462,7 +455,7 @@ impl Source { Ok(Self { modules, - diagnostics: context.state.diagnostics.borrow().clone(), + diagnostics: session.diagnostics.clone(), }) } @@ -507,6 +500,7 @@ impl Source { }, extra_interfaces, &packages, + &mut packages.design(), ) } @@ -521,8 +515,35 @@ impl Source { bindings: ModuleParameterBindings<'_>, extra_interfaces: &ModuleInterfaces, packages: &packages::Packages, + design: &mut packages::Design, + ) -> Result { + let mut session = Session::with_packages(packages, design); + let source = Self::from_indexed_syntax_module_in( + syntax_tree, + path, + index, + module_name, + bindings, + extra_interfaces, + packages, + &mut session, + ); + session.restore(design); + source + } + + #[allow(clippy::too_many_arguments)] + fn from_indexed_syntax_module_in( + syntax_tree: &SyntaxTree, + path: &Path, + index: &module_index::ModuleIndex, + module_name: &str, + bindings: ModuleParameterBindings<'_>, + extra_interfaces: &ModuleInterfaces, + packages: &packages::Packages, + session: &mut Session, ) -> Result { - let context = AnalysisContext::with_packages(syntax_tree, packages); + let context = AnalysisContext::unspecialized(syntax_tree); let syntax_tree = &context; let timed = AnalysisContext { timescale: timescales::for_tree(packages.timescales.clone(), syntax_tree)?, @@ -583,6 +604,7 @@ impl Source { } if let Some(mut module) = interface_binding::analyze_module( syntax_tree, + session, path, packages, interface_binding::Bindings { @@ -594,9 +616,8 @@ impl Source { &interfaces, imported.clone(), ) - .map_err(|error| { - error.with_warnings(context.state.diagnostics.borrow().clone()) - })? { + .map_err(|error| error.with_warnings(session.diagnostics.clone()))? + { module.name = module_name.to_string(); modules.push(module); continue; @@ -604,14 +625,13 @@ impl Source { modules.push( Module::from_scope_with_parameter_overrides( syntax_tree, + session, module_name, bindings.values, &interfaces, Arc::new(imported), ) - .map_err(|error| { - error.with_warnings(context.state.diagnostics.borrow().clone()) - })?, + .map_err(|error| error.with_warnings(session.diagnostics.clone()))?, ); } celox_sv_syntax::PortStyle::NonAnsi if syntax_tree.root_name()? == module_name => { @@ -624,7 +644,7 @@ impl Source { } Ok(Self { modules, - diagnostics: context.state.diagnostics.borrow().clone(), + diagnostics: session.diagnostics.clone(), }) } @@ -713,6 +733,7 @@ impl Module { pub(crate) fn declaration_expr( &self, tree: &AnalysisContext<'_>, + session: &mut Session, expr: &ConstExpr, signedness: &HashMap, ) -> ConstExpr { @@ -723,7 +744,7 @@ impl Module { 0, true, ); - expr_to_index_const(tree, expanded, &PackedDimensions::default()) + expr_to_index_const(tree, session, expanded, &PackedDimensions::default()) .unwrap_or_else(|| expr.clone()) } @@ -742,6 +763,7 @@ impl Module { /// symbols of the packages it uses. fn from_scope_with_parameter_overrides( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, override_module_name: &str, parameter_overrides: &HashMap, interfaces: &InterfaceLookup<'_>, @@ -749,6 +771,7 @@ impl Module { ) -> Result { Self::from_scope_with_symbols( syntax_tree, + session, override_module_name, parameter_overrides, interfaces, @@ -759,6 +782,7 @@ impl Module { fn from_scope_with_symbols( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, override_module_name: &str, parameter_overrides: &HashMap, interfaces: &InterfaceLookup<'_>, @@ -767,6 +791,7 @@ impl Module { ) -> Result { Self::from_selected_scope( syntax_tree, + session, override_module_name, parameter_overrides, interfaces, @@ -779,6 +804,7 @@ impl Module { #[allow(clippy::too_many_arguments)] fn from_selected_scope( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, override_module_name: &str, parameter_overrides: &HashMap, interfaces: &InterfaceLookup<'_>, @@ -786,39 +812,36 @@ impl Module { export_symbols: bool, header_ports: Option<&port_owners::Selection<'_>>, ) -> Result { - let registry = syntax_tree.state.foreign.clone(); for _ in 0..1024 { - let revision = registry.revision(); + let revision = session.foreign.revision(); let mut symbols = (*imported).clone(); - registry.extend(syntax_tree, &mut symbols); + session.foreign.extend(syntax_tree, &mut symbols); let declarations_only = symbols.declarations_only; + let export_symbols = export_symbols || session.foreign.has_templates(); let result = Self::from_selected_scope_once( syntax_tree, + session, override_module_name, parameter_overrides, interfaces, Arc::new(symbols), - export_symbols || registry.has_templates(), + export_symbols, header_ports, ); if let Ok(module) = &result && !declarations_only && let Some(symbols) = &module.symbols { - registry.finish(syntax_tree, symbols)?; + classes::foreign::finish(syntax_tree, session, symbols)?; } - if registry.revision() == revision { + if session.foreign.revision() == revision { return result; } - syntax_tree.state.classes.borrow_mut().clear(); - syntax_tree.state.class_specializations.borrow_mut().clear(); - syntax_tree - .state - .class_specialization_names - .borrow_mut() - .clear(); - syntax_tree.state.foreign_error.borrow_mut().take(); - syntax_tree.state.foreign_names.borrow_mut().clear(); + session.classes.clear(); + session.class_specializations.clear(); + session.class_specialization_names.clear(); + session.foreign_error.take(); + session.foreign_names.clear(); } Err(unsupported( "foreign class specialization discovery did not converge", @@ -827,6 +850,7 @@ impl Module { fn from_selected_scope_once( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, override_module_name: &str, parameter_overrides: &HashMap, interfaces: &InterfaceLookup<'_>, @@ -836,7 +860,7 @@ impl Module { ) -> Result { // The scope makes its class specializations until its class methods // have signatures. - syntax_tree.state.class_specializations_frozen.set(false); + session.class_specializations_frozen = false; let unit = syntax_tree.scope_handle().unit(syntax_tree.declarations()); let is_package = unit.is_none_or(|unit| unit.kind == celox_sv_syntax::UnitKind::Package); let program = unit.is_some_and(|unit| unit.kind == celox_sv_syntax::UnitKind::Program); @@ -855,876 +879,977 @@ impl Module { let specialization = specialization.importing(imported.clone()); let syntax_tree = &specialization; // The collectors below each elaborate the same generate scopes. - let _elaborations = generate::memoize(syntax_tree); - let with_imported = |mut functions: const_functions::ConstantFunctions| { - functions.extend_missing(&imported.constant_functions); - functions - }; - 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 preliminary = - syntax_tree.with_functions(with_imported(const_functions::module_constant_functions( + let previous = generate::memoize(syntax_tree, session); + let module = (|session: &mut Session| -> Result { + let with_imported = |mut functions: const_functions::ConstantFunctions| { + functions.extend_missing(&imported.constant_functions); + functions + }; + let mut type_aliases = type_aliases_from_scope(syntax_tree, session)?; + // Constant functions see the module constants known so far; they are + // collected again once the parameters are known. + let preliminary = syntax_tree.with_functions(with_imported( + const_functions::module_constant_functions( + syntax_tree, + session, + &imported.const_env, + &type_aliases, + &imported.parameter_values, + ), + )); + let syntax_tree = &preliminary; + let mut parameters = parameters_from_scope( syntax_tree, - &imported.const_env, + session, &type_aliases, - &imported.parameter_values, - ))); - let syntax_tree = &preliminary; - let mut parameters = parameters_from_scope( - syntax_tree, - &type_aliases, - &imported.const_env, - applicable_parameter_overrides, - )?; - let mut parameter_names = HashSet::default(); - if let Some(parameter) = parameters - .iter() - .find(|parameter| !parameter_names.insert(parameter.name())) - { - return Err(AnalyzerError::DuplicateParameter { - module: name, - name: parameter.name().to_string(), - }); - } - if name == override_module_name { - apply_parameter_overrides(&mut parameters, parameter_overrides)?; - } - let mut const_env = imported.const_env.clone(); - 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, - &const_env, - &type_aliases, - applicable_parameter_overrides, - )?; - for (name, value) in &enum_constants.numbers { - const_env.entry(name.clone()).or_insert(*value); - const_env.insert(enum_marker(name), *value); - if let Some(r#type) = enum_constants.types.get(name) { - insert_parameter_type_markers(&mut const_env, name, *r#type); + &imported.const_env, + applicable_parameter_overrides, + )?; + let mut parameter_names = HashSet::default(); + if let Some(parameter) = parameters + .iter() + .find(|parameter| !parameter_names.insert(parameter.name())) + { + return Err(AnalyzerError::DuplicateParameter { + module: name, + name: parameter.name().to_string(), + }); } - } - enum_constants.extend_missing(&imported.enum_constants); - // Alias ranges may themselves contain casts sized by enum members. - // Rebuild them before assigning declared parameter widths. - type_aliases = type_aliases_from_scope_with_env(syntax_tree, &const_env)?; - // Constant casts are evaluated while parameter syntax is lowered. - // Repeat that lowering after enum constants become available so a - // cast operand such as `byte_t'(ENUM_MEMBER)` is not permanently - // discarded during the initial pass. Materialize only enum-member - // references so exported parameter expressions retain dependencies - // on other parameters for later specialization. - parameters = parameters_from_scope( - syntax_tree, - &type_aliases, - &const_env, - applicable_parameter_overrides, - )?; - for parameter in &mut parameters { - parameter.value = parameter.value.take().map(|value| { - substitute_typed_parameter_literals( - value, - &enum_constants.numbers, - &enum_constants.types, - ) - }); - } - if name == override_module_name { - apply_parameter_overrides(&mut parameters, parameter_overrides)?; - } - 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. - let symbolic_parameters = parameters - .iter() - .map(|parameter| parameter.name().to_string()) - .collect(); - // Class parameter defaults are bound where the class is declared. - classes::specializations::declare_scopes(syntax_tree, &const_env, &type_aliases); - let declaration_subroutines = - with_imported(const_functions::symbolic_module_constant_functions( + if name == override_module_name { + apply_parameter_overrides(&mut parameters, parameter_overrides)?; + } + let mut const_env = imported.const_env.clone(); + const_env.extend(const_env_from_parameters(syntax_tree, session, ¶meters)); + type_aliases = type_aliases_from_scope_with_env(syntax_tree, session, &const_env)?; + let mut enum_constants = enum_member_constants_from_scope( syntax_tree, + session, &const_env, &type_aliases, - &imported.parameter_values, - &symbolic_parameters, - )) - .declarations(); - let parameterized = - syntax_tree.with_functions(with_imported(const_functions::module_constant_functions( + applicable_parameter_overrides, + )?; + for (name, value) in &enum_constants.numbers { + const_env.entry(name.clone()).or_insert(*value); + const_env.insert(enum_marker(name), *value); + if let Some(r#type) = enum_constants.types.get(name) { + insert_parameter_type_markers(&mut const_env, name, *r#type); + } + } + enum_constants.extend_missing(&imported.enum_constants); + // Alias ranges may themselves contain casts sized by enum members. + // Rebuild them before assigning declared parameter widths. + type_aliases = type_aliases_from_scope_with_env(syntax_tree, session, &const_env)?; + // Constant casts are evaluated while parameter syntax is lowered. + // Repeat that lowering after enum constants become available so a + // cast operand such as `byte_t'(ENUM_MEMBER)` is not permanently + // discarded during the initial pass. Materialize only enum-member + // references so exported parameter expressions retain dependencies + // on other parameters for later specialization. + parameters = parameters_from_scope( + syntax_tree, + session, + &type_aliases, + &const_env, + applicable_parameter_overrides, + )?; + for parameter in &mut parameters { + parameter.value = parameter.value.take().map(|value| { + substitute_typed_parameter_literals( + value, + &enum_constants.numbers, + &enum_constants.types, + ) + }); + } + if name == override_module_name { + apply_parameter_overrides(&mut parameters, parameter_overrides)?; + } + extend_const_env_with_parameters(syntax_tree, session, &mut const_env, ¶meters); + type_aliases = type_aliases_from_scope_with_env(syntax_tree, session, &const_env)?; + // Contract dependency analysis must see module parameter references + // before the normal procedural lowering substitutes default literals. + let symbolic_parameters = parameters + .iter() + .map(|parameter| parameter.name().to_string()) + .collect(); + // Class parameter defaults are bound where the class is declared. + classes::specializations::declare_scopes( syntax_tree, + session, &const_env, &type_aliases, - ¶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)?; - for parameter in &array_parameters { - const_env.insert( - parameters::unbounded_parameter_marker(¶meter.signal.name), - 0, ); - } + let declaration_subroutines = + with_imported(const_functions::symbolic_module_constant_functions( + syntax_tree, + session, + &const_env, + &type_aliases, + &imported.parameter_values, + &symbolic_parameters, + )) + .declarations(); + let parameter_values = parameter_value_env_with_imported( + syntax_tree, + session, + ¶meters, + &const_env, + &imported, + ); + let parameterized = syntax_tree.with_functions(with_imported( + const_functions::module_constant_functions( + syntax_tree, + session, + &const_env, + &type_aliases, + ¶meter_values, + ), + )); + let syntax_tree = ¶meterized; + extend_const_env_with_parameters(syntax_tree, session, &mut const_env, ¶meters); - if !imported.declarations_only { - match reject_silently_ignored_constructs( + let mut array_parameters = array_parameters::array_parameters_from_scope( syntax_tree, + session, &const_env, &type_aliases, - ¶meter_packed_dimensions_with_imported(¶meters, &imported).into(), - ¶meter_value_env_with_imported(syntax_tree, ¶meters, &const_env, &imported), - ) { - Ok(()) => {} - // A parameter initializer may inspect a port or signal type - // through `$bits`/`$size`. Collect declarations only when that - // missing type metadata is the remaining validation failure, so - // unsupported constructs keep their original diagnostics. - Err(AnalyzerError::Unsupported(construct)) - if construct == "constant cast expression" => - { - let preliminary_ports = - ports_from_scope(syntax_tree, &const_env, &type_aliases, header_ports)?; - let preliminary_signals = - signals_from_scope(syntax_tree, &const_env, &type_aliases)?; - extend_const_env_with_variable_types( - &syntax_tree.functions, - &mut const_env, - preliminary_ports - .iter() - .map(|port| (port.name(), port.r#type())) - .chain( - preliminary_signals - .iter() - .map(|signal| (signal.name(), signal.r#type())), - ), - ); - parameters = parameters_from_scope( - syntax_tree, - &type_aliases, - &const_env, - applicable_parameter_overrides, - )?; - for parameter in &mut parameters { - parameter.value = parameter.value.take().map(|value| { - substitute_typed_parameter_literals( - value, - &enum_constants.numbers, - &enum_constants.types, - ) - }); - } - if name == override_module_name { - apply_parameter_overrides(&mut parameters, parameter_overrides)?; - } - 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, - &const_env, - &type_aliases, - )?; - reject_silently_ignored_constructs( - syntax_tree, - &const_env, - &type_aliases, - ¶meter_packed_dimensions_with_imported(¶meters, &imported).into(), - ¶meter_value_env_with_imported( + )?; + for parameter in &array_parameters { + const_env.insert( + parameters::unbounded_parameter_marker(¶meter.signal.name), + 0, + ); + } + + if !imported.declarations_only { + let parameter_values = parameter_value_env_with_imported( + syntax_tree, + session, + ¶meters, + &const_env, + &imported, + ); + match reject_silently_ignored_constructs( + syntax_tree, + session, + &const_env, + &type_aliases, + ¶meter_packed_dimensions_with_imported(¶meters, &imported).into(), + ¶meter_values, + ) { + Ok(()) => {} + // A parameter initializer may inspect a port or signal type + // through `$bits`/`$size`. Collect declarations only when that + // missing type metadata is the remaining validation failure, so + // unsupported constructs keep their original diagnostics. + Err(AnalyzerError::Unsupported(construct)) + if construct == "constant cast expression" => + { + let preliminary_ports = ports_from_scope( + syntax_tree, + session, + &const_env, + &type_aliases, + header_ports, + )?; + let preliminary_signals = + signals_from_scope(syntax_tree, session, &const_env, &type_aliases)?; + extend_const_env_with_variable_types( + &syntax_tree.functions, + &mut const_env, + preliminary_ports + .iter() + .map(|port| (port.name(), port.r#type())) + .chain( + preliminary_signals + .iter() + .map(|signal| (signal.name(), signal.r#type())), + ), + ); + parameters = parameters_from_scope( + syntax_tree, + session, + &type_aliases, + &const_env, + applicable_parameter_overrides, + )?; + for parameter in &mut parameters { + parameter.value = parameter.value.take().map(|value| { + substitute_typed_parameter_literals( + value, + &enum_constants.numbers, + &enum_constants.types, + ) + }); + } + if name == override_module_name { + apply_parameter_overrides(&mut parameters, parameter_overrides)?; + } + extend_const_env_with_parameters( + syntax_tree, + session, + &mut const_env, + ¶meters, + ); + type_aliases = + type_aliases_from_scope_with_env(syntax_tree, session, &const_env)?; + array_parameters = array_parameters::array_parameters_from_scope( syntax_tree, + session, + &const_env, + &type_aliases, + )?; + let parameter_values = parameter_value_env_with_imported( + syntax_tree, + session, ¶meters, &const_env, &imported, - ), - )?; + ); + reject_silently_ignored_constructs( + syntax_tree, + session, + &const_env, + &type_aliases, + ¶meter_packed_dimensions_with_imported(¶meters, &imported) + .into(), + ¶meter_values, + )?; + } + Err(error) => return Err(error), } - Err(error) => return Err(error), } - } - let mut ports = ports_from_scope(syntax_tree, &const_env, &type_aliases, header_ports)?; - ports.extend(imported.ports.iter().cloned()); - let mut port_names = HashSet::default(); - if let Some(port) = ports.iter().find(|port| !port_names.insert(port.name())) { - return Err(AnalyzerError::DuplicatePort { - module: name, - name: port.name().to_string(), - }); - } - if ports - .iter() - .any(|port| port.direction() == PortDirection::Ref) - { - return Err(AnalyzerError::Unsupported("ref port direction".to_string())); - } - // The static properties of each class specialization are variables - // of the module (IEEE 1800-2023 8.9, 8.25). - classes::specializations::collect( - syntax_tree, - &PackedDimensions::new(HashMap::default(), &const_env, &type_aliases), - ); - let mut signals = signals_from_scope(syntax_tree, &const_env, &type_aliases)?; - signals.extend( - array_parameters - .iter() - .map(|parameter| parameter.signal.clone()), - ); - // The array parameters of the packages the module uses are constant - // signals of the module, like its own. - signals.extend(imported.signals.iter().cloned()); - signals.extend(imported.state_signals.iter().cloned()); - for r#type in ports - .iter() - .map(Port::r#type) - .chain(signals.iter().map(Signal::r#type)) - { - validate_unpacked_dimension_sizes( - &syntax_tree.functions, - r#type.unpacked_ranges(), + let mut ports = ports_from_scope( + syntax_tree, + session, &const_env, + &type_aliases, + header_ports, )?; - } - let signal_names: HashSet<_> = signals.iter().map(Signal::name).collect(); - if let Some(parameter) = parameters.iter().find(|parameter| { - port_names.contains(parameter.name()) || signal_names.contains(parameter.name()) - }) { - return Err(AnalyzerError::Unsupported(format!( - "parameter name collides with port or signal `{}`", - parameter.name() - ))); - } - let mut packed_dimensions = - 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, ¶meters, &const_env, &imported) - .into(); - packed_dimensions - .parameter_values - .retain(|name, _| !const_env.contains_key(name)); - packed_dimensions.extend(parameter_packed_dimensions_with_imported( - ¶meters, - &imported, - )); - // Instance connections may call subroutines, of the module or of the - // packages it uses, with untyped assignment patterns. - let (mut subroutine_params, mut subroutine_shapes, mut subroutine_directions) = - procedural::subroutine_argument_names(syntax_tree, &const_env, &type_aliases)?; - for (name, params) in &imported.subroutine_params { - subroutine_params - .entry(name.clone()) - .or_insert_with(|| params.clone()); - } - for (name, shapes) in &imported.subroutine_shapes { - subroutine_shapes - .entry(name.clone()) - .or_insert_with(|| shapes.clone()); - } - // The subroutines of the packages the module uses, by their qualified - // names and by the names its imports give them. - for subroutine in &imported.subroutines { - subroutine_directions - .entry(subroutine.name.clone()) - .or_insert_with(|| { - subroutine - .params - .iter() - .map(|param| param.direction) - .collect() + ports.extend(imported.ports.iter().cloned()); + let mut port_names = HashSet::default(); + if let Some(port) = ports.iter().find(|port| !port_names.insert(port.name())) { + return Err(AnalyzerError::DuplicatePort { + module: name, + name: port.name().to_string(), }); - } - for (name, target) in &imported.aliases { - if let Some(directions) = subroutine_directions.get(target).cloned() { - subroutine_directions - .entry(name.clone()) - .or_insert(directions); } - } - let dpi_items = generate::items(syntax_tree, &const_env, &type_aliases)?; - let mut dpi_imports = dpi::imports(&dpi_items, syntax_tree, &type_aliases)?; - for import in &dpi_imports { - subroutine_params.insert( - import.name().to_string(), - import - .arguments() + if ports + .iter() + .any(|port| port.direction() == PortDirection::Ref) + { + return Err(AnalyzerError::Unsupported("ref port direction".to_string())); + } + // The static properties of each class specialization are variables + // of the module (IEEE 1800-2023 8.9, 8.25). + classes::specializations::collect( + syntax_tree, + session, + &PackedDimensions::new(HashMap::default(), &const_env, &type_aliases), + ); + let mut signals = signals_from_scope(syntax_tree, session, &const_env, &type_aliases)?; + signals.extend( + array_parameters .iter() - .map(|arg| arg.name().to_string()) - .collect(), + .map(|parameter| parameter.signal.clone()), ); - subroutine_directions.insert( - import.name().to_string(), - vec![crate::procedural::ParamDirection::Input; import.arguments().len()], + // The array parameters of the packages the module uses are constant + // signals of the module, like its own. + signals.extend(imported.signals.iter().cloned()); + signals.extend(imported.state_signals.iter().cloned()); + for r#type in ports + .iter() + .map(Port::r#type) + .chain(signals.iter().map(Signal::r#type)) + { + validate_unpacked_dimension_sizes( + &syntax_tree.functions, + r#type.unpacked_ranges(), + &const_env, + )?; + } + let signal_names: HashSet<_> = signals.iter().map(Signal::name).collect(); + if let Some(parameter) = parameters.iter().find(|parameter| { + port_names.contains(parameter.name()) || signal_names.contains(parameter.name()) + }) { + return Err(AnalyzerError::Unsupported(format!( + "parameter name collides with port or signal `{}`", + parameter.name() + ))); + } + let mut packed_dimensions = packed_dimensions_from_ports_and_signals( + &ports, + &signals, + &const_env, + &type_aliases, ); - } - packed_dimensions.subroutine_param_shapes = Arc::new(subroutine_shapes.clone()); - packed_dimensions.subroutine_directions = Arc::new(subroutine_directions.clone()); - packed_dimensions.subroutine_param_names = Arc::new(subroutine_params.clone()); - // Array parameters retain a constant value as well as their signal layout. - // Bind their values in declaration order before child parameter arguments. - for process in &imported.initial_processes { - for statement in &process.body { - if let Stmt::Assign { - lhs: LValue::Ident(name), - rhs, - .. - } = statement - { + // 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, + session, + ¶meters, + &const_env, + &imported, + ) + .into(); + packed_dimensions + .parameter_values + .retain(|name, _| !const_env.contains_key(name)); + packed_dimensions.extend(parameter_packed_dimensions_with_imported( + ¶meters, + &imported, + )); + // Instance connections may call subroutines, of the module or of the + // packages it uses, with untyped assignment patterns. + let (mut subroutine_params, mut subroutine_shapes, mut subroutine_directions) = + procedural::subroutine_argument_names( + syntax_tree, + session, + &const_env, + &type_aliases, + )?; + for (name, params) in &imported.subroutine_params { + subroutine_params + .entry(name.clone()) + .or_insert_with(|| params.clone()); + } + for (name, shapes) in &imported.subroutine_shapes { + subroutine_shapes + .entry(name.clone()) + .or_insert_with(|| shapes.clone()); + } + // The subroutines of the packages the module uses, by their qualified + // names and by the names its imports give them. + for subroutine in &imported.subroutines { + subroutine_directions + .entry(subroutine.name.clone()) + .or_insert_with(|| { + subroutine + .params + .iter() + .map(|param| param.direction) + .collect() + }); + } + for (name, target) in &imported.aliases { + if let Some(directions) = subroutine_directions.get(target).cloned() { + subroutine_directions + .entry(name.clone()) + .or_insert(directions); + } + } + let dpi_items = generate::items(syntax_tree, session, &const_env, &type_aliases)?; + let mut dpi_imports = dpi::imports(&dpi_items, syntax_tree, session, &type_aliases)?; + for import in &dpi_imports { + subroutine_params.insert( + import.name().to_string(), + import + .arguments() + .iter() + .map(|arg| arg.name().to_string()) + .collect(), + ); + subroutine_directions.insert( + import.name().to_string(), + vec![crate::procedural::ParamDirection::Input; import.arguments().len()], + ); + } + packed_dimensions.subroutine_param_shapes = Arc::new(subroutine_shapes.clone()); + packed_dimensions.subroutine_directions = Arc::new(subroutine_directions.clone()); + packed_dimensions.subroutine_param_names = Arc::new(subroutine_params.clone()); + // Array parameters retain a constant value as well as their signal layout. + // Bind their values in declaration order before child parameter arguments. + for process in &imported.initial_processes { + for statement in &process.body { + if let Stmt::Assign { + lhs: LValue::Ident(name), + rhs, + .. + } = statement + { + packed_dimensions + .array_parameter_values + .insert(name.clone(), rhs.clone()); + } + } + } + let mut array_initial_processes = Vec::new(); + let mut packed_pattern_values = HashMap::default(); + for parameter in &array_parameters { + let process = + parameter.initial_process(syntax_tree, session, &packed_dimensions)?; + if let Stmt::Assign { rhs, .. } = &process.body[0] { packed_dimensions .array_parameter_values - .insert(name.clone(), rhs.clone()); + .insert(parameter.signal.name.clone(), rhs.clone()); + let name = parameter.signal.name(); + let shape = packed_dimensions.get(name).expect("array parameter shape"); + if shape.unpacked.is_empty() + && !shape.real + && !shape.string + && shape.class.is_none() + { + // An integral value parameter is self-determined before + // conversion at a receiving declaration (6.20.2). The + // pattern's concatenation must retain its declared sign. + let signed = shape.signed; + let is_2state = shape.is_2state; + let width = expr_static_width( + syntax_tree, + &Expr::Ident(name.to_string()), + &packed_dimensions, + ) + .ok_or_else(|| unsupported("packed pattern parameter width"))?; + let mut value = Expr::Resize { + expr: Box::new(rhs.clone()), + width, + signed, + }; + if is_2state { + value = Expr::Unary { + op: UnaryOp::ToTwoState, + expr: Box::new(value), + }; + } + let value = fold_const_integral_expr_preserving_mask( + syntax_tree, + session, + value, + &packed_dimensions.const_env, + ); + packed_dimensions + .parameter_values + .insert(name.to_string(), value.clone()); + packed_pattern_values.insert(name.to_string(), value); + } } + array_initial_processes.push(process); } - } - let mut array_initial_processes = Vec::new(); - let mut packed_pattern_values = HashMap::default(); - for parameter in &array_parameters { - let process = parameter.initial_process(syntax_tree, &packed_dimensions)?; - if let Stmt::Assign { rhs, .. } = &process.body[0] { + let mut instances = instances_from_scope( + syntax_tree, + session, + &const_env, + &packed_dimensions, + interfaces, + )?; + let mut instance_names = HashSet::default(); + if let Some(instance) = instances + .iter() + .filter(|instance| { + instance + .condition() + .and_then(|condition| { + eval_ast_const_expr(&syntax_tree.functions, condition, &const_env) + }) + .is_none_or(|value| value != 0) + }) + .find(|instance| !instance_names.insert(instance.name())) + { + return Err(AnalyzerError::DuplicateInstance { + module: name, + name: instance.name().to_string(), + }); + } + // A generate block shares its name space with the module's other + // declarations (IEEE 1800-2023 27.6, 23.9). + // The members of a variable of unpacked structure type are named + // like declarations of a scope of the variable's name. + let aggregates: HashSet<&str> = signals + .iter() + .filter(|signal| signal.is_aggregate()) + .map(Signal::name) + .collect(); + let scope_heads: HashSet<&str> = signals + .iter() + .filter(|signal| signal.hierarchical.is_none()) + .map(Signal::name) + .chain(instances.iter().map(Instance::name)) + .filter_map(generate_scope_head) + .filter(|head| !aggregates.contains(head)) + .collect(); + if let Some(conflict) = ports + .iter() + .map(Port::name) + .chain(signals.iter().map(Signal::name)) + .chain(instances.iter().map(Instance::name)) + .find(|conflict| scope_heads.contains(conflict)) + { + return Err(AnalyzerError::DuplicateGenerateScope { + module: name, + name: conflict.to_string(), + }); + } + let mut parameter_values = parameter_value_env_with_imported( + syntax_tree, + session, + ¶meters, + &const_env, + &imported, + ); + parameter_values.extend(packed_pattern_values); + for (name, value) in &enum_constants.exprs { + parameter_values + .entry(name.clone()) + .or_insert_with(|| value.clone()); + } + let mut expression_signedness = ports + .iter() + .map(|port| (port.name().to_string(), port.r#type().is_signed())) + .chain( + signals + .iter() + .map(|signal| (signal.name().to_string(), signal.r#type().is_signed())), + ) + .collect::>(); + expression_signedness.extend( + parameter_types_from_const_env(&const_env) + .into_iter() + .map(|(name, r#type)| (name, r#type.signed)), + ); + let mut functions = + functions_from_scope(syntax_tree, session, &const_env, &packed_dimensions)?; + for (name, function) in &imported.functions { + functions + .entry(name.clone()) + .or_insert_with(|| function.clone()); + } + for (name, metadata) in &imported.function_return_types { packed_dimensions - .array_parameter_values - .insert(parameter.signal.name.clone(), rhs.clone()); - let name = parameter.signal.name(); - let shape = packed_dimensions.get(name).expect("array parameter shape"); - if shape.unpacked.is_empty() - && !shape.real - && !shape.string - && shape.class.is_none() - { - // An integral value parameter is self-determined before - // conversion at a receiving declaration (6.20.2). The - // pattern's concatenation must retain its declared sign. - let signed = shape.signed; - let is_2state = shape.is_2state; - let width = expr_static_width( - syntax_tree, - &Expr::Ident(name.to_string()), - &packed_dimensions, + .function_return_types + .entry(name.clone()) + .or_insert_with(|| metadata.clone()); + } + packed_dimensions + .function_return_types + .extend(functions.iter().map(|(name, function)| { + ( + name.clone(), + FunctionReturnMetadata { + arguments: Some(function_argument_metadata(&function.params)), + width: function.return_width, + first_packed_dimension_width: function + .return_first_packed_dimension_width, + dimensions: function.return_dimensions, + signed: function.return_signed, + is_2state: function.return_is_2state, + string: function.return_string, + pattern_type: function.return_type.clone(), + enum_domain: function.return_enum_domain.clone(), + class: function.return_class.clone(), + virtual_interface: function.return_virtual_interface.clone(), + }, ) - .ok_or_else(|| unsupported("packed pattern parameter width"))?; - let mut value = Expr::Resize { - expr: Box::new(rhs.clone()), - width, - signed, - }; - if is_2state { - value = Expr::Unary { - op: UnaryOp::ToTwoState, - expr: Box::new(value), - }; + })); + packed_dimensions + .function_return_types + .extend(dpi_imports.iter().filter_map(|import| { + let r#type = import.return_type()?; + Some(( + import.name().to_string(), + FunctionReturnMetadata { + arguments: Some(dpi_argument_metadata(import)), + width: Some(r#type.width()), + first_packed_dimension_width: (r#type.width() > 1) + .then_some(r#type.width()), + dimensions: Some(usize::from(r#type.width() > 1)), + signed: r#type.is_signed(), + is_2state: !r#type.is_4state(), + string: false, + pattern_type: None, + enum_domain: None, + class: None, + virtual_interface: None, + }, + )) + })); + // Class methods are subroutines `class::method` (IEEE 1800-2023 8.6). + dimensions::all_class_signatures(syntax_tree, session, &mut packed_dimensions); + packed_dimensions.functions = Arc::new(functions.clone()); + packed_dimensions.expression_signedness = expression_signedness.clone().into(); + for instance in &mut instances { + for connection in &mut instance.port_connections { + if let Some(pattern) = &mut connection.bound_pattern { + pattern.resolve_types(&packed_dimensions)?; } - let value = fold_const_integral_expr_preserving_mask( - syntax_tree, - value, - &packed_dimensions.const_env, - ); - packed_dimensions - .parameter_values - .insert(name.to_string(), value.clone()); - packed_pattern_values.insert(name.to_string(), value); + connection.map_expressions(|expr| { + let expr = + expand_expr_calls(expr, &functions, &expression_signedness, 0, true); + substitute_expr_constants_with_parameter_literals( + syntax_tree, + session, + expr, + &const_env, + &enum_constants.exprs, + ) + }); } } - array_initial_processes.push(process); - } - let mut instances = - instances_from_scope(syntax_tree, &const_env, &packed_dimensions, interfaces)?; - let mut instance_names = HashSet::default(); - if let Some(instance) = instances - .iter() - .filter(|instance| { - instance - .condition() - .and_then(|condition| { - eval_ast_const_expr(&syntax_tree.functions, condition, &const_env) + // Bodies now have the active module's declarations and function types. + // Declaration-time queries still use syntax discovery while metadata + // is incomplete; generated/procedural scopes overlay this complete base. + packed_dimensions.scope_types_complete = true; + let mut locals = Vec::new(); + let mut local_counter = 0usize; + let mut body_state = procedural::BodyState { + locals: &mut locals, + counter: &mut local_counter, + subroutine_params: &subroutine_params, + subroutine_directions: &subroutine_directions, + automatic: lifetimes::automatic_by_default(syntax_tree), + statics: Vec::new(), + explicit_statics: HashSet::default(), + static_initializers: Vec::new(), + constant_evaluation: false, + }; + let (mut subroutines, mut comb_processes, mut ff_processes, mut initial_processes) = + if imported.declarations_only { + (Vec::new(), Vec::new(), Vec::new(), Vec::new()) + } else { + let subroutines = procedural::subroutines_from_scope( + syntax_tree, + session, + &const_env, + &packed_dimensions, + ¶meter_values, + &mut body_state, + )?; + let mut comb_processes = comb_processes_from_scope( + syntax_tree, + session, + &const_env, + &packed_dimensions, + ¶meter_values, + &mut body_state, + )? + .into_iter() + .map(|process| { + substitute_process_constants_with_parameter_literals( + syntax_tree, + session, + process, + &const_env, + ¶meter_values, + ) }) - .is_none_or(|value| value != 0) - }) - .find(|instance| !instance_names.insert(instance.name())) - { - return Err(AnalyzerError::DuplicateInstance { - module: name, - name: instance.name().to_string(), - }); - } - // A generate block shares its name space with the module's other - // declarations (IEEE 1800-2023 27.6, 23.9). - // The members of a variable of unpacked structure type are named - // like declarations of a scope of the variable's name. - let aggregates: HashSet<&str> = signals - .iter() - .filter(|signal| signal.is_aggregate()) - .map(Signal::name) - .collect(); - let scope_heads: HashSet<&str> = signals - .iter() - .filter(|signal| signal.hierarchical.is_none()) - .map(Signal::name) - .chain(instances.iter().map(Instance::name)) - .filter_map(generate_scope_head) - .filter(|head| !aggregates.contains(head)) - .collect(); - if let Some(conflict) = ports - .iter() - .map(Port::name) - .chain(signals.iter().map(Signal::name)) - .chain(instances.iter().map(Instance::name)) - .find(|conflict| scope_heads.contains(conflict)) - { - return Err(AnalyzerError::DuplicateGenerateScope { - module: name, - name: conflict.to_string(), - }); - } - 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 - .entry(name.clone()) - .or_insert_with(|| value.clone()); - } - let mut expression_signedness = ports - .iter() - .map(|port| (port.name().to_string(), port.r#type().is_signed())) - .chain( - signals - .iter() - .map(|signal| (signal.name().to_string(), signal.r#type().is_signed())), - ) - .collect::>(); - expression_signedness.extend( - parameter_types_from_const_env(&const_env) - .into_iter() - .map(|(name, r#type)| (name, r#type.signed)), - ); - let mut functions = functions_from_scope(syntax_tree, &const_env, &packed_dimensions)?; - for (name, function) in &imported.functions { - functions - .entry(name.clone()) - .or_insert_with(|| function.clone()); - } - for (name, metadata) in &imported.function_return_types { - packed_dimensions - .function_return_types - .entry(name.clone()) - .or_insert_with(|| metadata.clone()); - } - packed_dimensions - .function_return_types - .extend(functions.iter().map(|(name, function)| { - ( - name.clone(), - FunctionReturnMetadata { - arguments: Some(function_argument_metadata(&function.params)), - width: function.return_width, - first_packed_dimension_width: function.return_first_packed_dimension_width, - dimensions: function.return_dimensions, - signed: function.return_signed, - is_2state: function.return_is_2state, - string: function.return_string, - pattern_type: function.return_type.clone(), - enum_domain: function.return_enum_domain.clone(), - class: function.return_class.clone(), - virtual_interface: function.return_virtual_interface.clone(), - }, - ) - })); - packed_dimensions - .function_return_types - .extend(dpi_imports.iter().filter_map(|import| { - let r#type = import.return_type()?; - Some(( - import.name().to_string(), - FunctionReturnMetadata { - arguments: Some(dpi_argument_metadata(import)), - width: Some(r#type.width()), - first_packed_dimension_width: (r#type.width() > 1) - .then_some(r#type.width()), - dimensions: Some(usize::from(r#type.width() > 1)), - signed: r#type.is_signed(), - is_2state: !r#type.is_4state(), - string: false, - pattern_type: None, - enum_domain: None, - class: None, - virtual_interface: None, - }, - )) - })); - // Class methods are subroutines `class::method` (IEEE 1800-2023 8.6). - dimensions::all_class_signatures(syntax_tree, &mut packed_dimensions); - packed_dimensions.functions = Arc::new(functions.clone()); - packed_dimensions.expression_signedness = expression_signedness.clone().into(); - for instance in &mut instances { - for connection in &mut instance.port_connections { - if let Some(pattern) = &mut connection.bound_pattern { - pattern.resolve_types(&packed_dimensions)?; - } - connection.map_expressions(|expr| { - let expr = expand_expr_calls(expr, &functions, &expression_signedness, 0, true); - substitute_expr_constants_with_parameter_literals( + .collect::>(); + let mut ff_processes = ff_processes_from_scope( syntax_tree, - expr, + session, &const_env, - &enum_constants.exprs, - ) - }); - } - } - // Bodies now have the active module's declarations and function types. - // Declaration-time queries still use syntax discovery while metadata - // is incomplete; generated/procedural scopes overlay this complete base. - packed_dimensions.scope_types_complete = true; - let mut locals = Vec::new(); - let mut local_counter = 0usize; - let mut body_state = procedural::BodyState { - locals: &mut locals, - counter: &mut local_counter, - subroutine_params: &subroutine_params, - subroutine_directions: &subroutine_directions, - automatic: lifetimes::automatic_by_default(syntax_tree), - statics: Vec::new(), - explicit_statics: HashSet::default(), - static_initializers: Vec::new(), - constant_evaluation: false, - }; - let (mut subroutines, mut comb_processes, mut ff_processes, mut initial_processes) = - if imported.declarations_only { - (Vec::new(), Vec::new(), Vec::new(), Vec::new()) - } else { - let subroutines = procedural::subroutines_from_scope( - syntax_tree, - &const_env, - &packed_dimensions, - ¶meter_values, - &mut body_state, - )?; - let mut comb_processes = comb_processes_from_scope( - syntax_tree, - &const_env, - &packed_dimensions, - ¶meter_values, - &mut body_state, - )? - .into_iter() - .map(|process| { - substitute_process_constants_with_parameter_literals( + ¶meter_values, + &packed_dimensions, + &mut body_state, + )?; + comb_processes.extend(imported.comb_processes.iter().cloned()); + ff_processes.extend(imported.ff_processes.iter().cloned()); + let mut initial_processes = array_initial_processes; + initial_processes.extend(imported.initial_processes.iter().cloned()); + initial_processes.extend(procedural::initial_processes_from_scope( syntax_tree, - process, + session, &const_env, + &packed_dimensions, ¶meter_values, - ) - }) - .collect::>(); - let mut ff_processes = ff_processes_from_scope( + &mut body_state, + )?); + (subroutines, comb_processes, ff_processes, initial_processes) + }; + let (inline_subroutines, inline_randomizations) = + procedural::randomization::inline_subroutines( syntax_tree, - &const_env, - ¶meter_values, - &packed_dimensions, + session, &mut body_state, - )?; - comb_processes.extend(imported.comb_processes.iter().cloned()); - ff_processes.extend(imported.ff_processes.iter().cloned()); - let mut initial_processes = array_initial_processes; - initial_processes.extend(imported.initial_processes.iter().cloned()); - initial_processes.extend(procedural::initial_processes_from_scope( - syntax_tree, - &const_env, &packed_dimensions, - ¶meter_values, - &mut body_state, - )?); - (subroutines, comb_processes, ff_processes, initial_processes) - }; - let (inline_subroutines, inline_randomizations) = - procedural::randomization::inline_subroutines( + )?; + subroutines.extend(inline_subroutines); + // Static locals of the processes that keep their value are variables + // 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, - &mut body_state, - &packed_dimensions, + session, + &statics, + &subroutine_directions, + comb_processes + .iter_mut() + .map(|process| (&mut process.body, false)) + .chain( + ff_processes + .iter_mut() + .map(|process| (&mut process.body, false)), + ) + .chain( + initial_processes + .iter_mut() + .map(|process| (&mut process.body, !process.repeats)), + ), + Some(&body_state.explicit_statics), + false, )?; - subroutines.extend(inline_subroutines); - // Static locals of the processes that keep their value are variables - // 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, - &statics, - &subroutine_directions, - comb_processes - .iter_mut() - .map(|process| (&mut process.body, false)) - .chain( - ff_processes - .iter_mut() - .map(|process| (&mut process.body, false)), - ) - .chain( - initial_processes - .iter_mut() - .map(|process| (&mut process.body, !process.repeats)), - ), - Some(&body_state.explicit_statics), - false, - )?; - for subroutine in &subroutines { - kept.extend(subroutine.persistent_locals.iter().cloned()); - } - // Statics of subroutines are initialized first: a run-time - // initializer of a process local may call the subroutine. - static_initializers.splice(0..0, body_state.static_initializers.drain(..)); - locals.retain(|local| !kept.contains(&local.name)); - for name in kept { - signals.push(Signal::new(name.clone(), statics[&name].clone())); - } - if !static_initializers.is_empty() { - // Declaration initializers run before the other initial blocks. - let first_block = initial_processes - .iter() - .position(|process| !process.is_initializer()) - .unwrap_or(initial_processes.len()); - // They may read module variables, so they also stay after those - // initializers when processes are reordered by creation. - let creation_order = initial_processes - .iter() - .filter(|process| process.is_initializer()) - .map(|process| process.creation_order) - .max() - .unwrap_or(0); - initial_processes.insert( - first_block, - InitialProcess { - creation_order, - site: None, - condition: None, - body: static_initializers, - kind: celox_design::ProcessKind::Initializer, - validation_body: Vec::new(), - synthetic: false, - repeats: false, - }, - ); - } - // A call of a name an import binds calls the package subroutine or - // DPI import. Calls of subroutines declared in a generate block were - // already bound to those. - let calls: HashMap = imported - .aliases - .iter() - .filter(|(_, target)| { - imported - .subroutines - .iter() - .any(|subroutine| subroutine.name == **target) - || imported - .dpi_imports - .iter() - .any(|import| import.name() == target.as_str()) - }) - .map(|(name, target)| (name.clone(), target.clone())) - .collect(); - if !calls.is_empty() { - let rename = scope::Renamer { names: &calls }; - let body = |body: Vec| body.into_iter().map(|stmt| rename.stmt(stmt)).collect(); - for process in &mut comb_processes { - process.body = body(std::mem::take(&mut process.body)); - process.sensitivity_body = body(std::mem::take(&mut process.sensitivity_body)); - for assignment in &mut process.assignments { - assignment.rhs = rename.expr(assignment.rhs.clone()); - } - } - for process in &mut ff_processes { - process.body = body(std::mem::take(&mut process.body)); + for subroutine in &subroutines { + kept.extend(subroutine.persistent_locals.iter().cloned()); } - for process in &mut initial_processes { - process.body = body(std::mem::take(&mut process.body)); - process.validation_body = body(std::mem::take(&mut process.validation_body)); + // Statics of subroutines are initialized first: a run-time + // initializer of a process local may call the subroutine. + static_initializers.splice(0..0, body_state.static_initializers.drain(..)); + locals.retain(|local| !kept.contains(&local.name)); + for name in kept { + signals.push(Signal::new(name.clone(), statics[&name].clone())); } - for subroutine in &mut subroutines { - *subroutine = rename.subroutine(subroutine.clone()); + if !static_initializers.is_empty() { + // Declaration initializers run before the other initial blocks. + let first_block = initial_processes + .iter() + .position(|process| !process.is_initializer()) + .unwrap_or(initial_processes.len()); + // They may read module variables, so they also stay after those + // initializers when processes are reordered by creation. + let creation_order = initial_processes + .iter() + .filter(|process| process.is_initializer()) + .map(|process| process.creation_order) + .max() + .unwrap_or(0); + initial_processes.insert( + first_block, + InitialProcess { + creation_order, + site: None, + condition: None, + body: static_initializers, + kind: celox_design::ProcessKind::Initializer, + validation_body: Vec::new(), + synthetic: false, + repeats: false, + }, + ); } - for instance in &mut instances { - for connection in &mut instance.port_connections { - connection.map_expressions(|expr| rename.expr(expr)); + // A call of a name an import binds calls the package subroutine or + // DPI import. Calls of subroutines declared in a generate block were + // already bound to those. + let calls: HashMap = imported + .aliases + .iter() + .filter(|(_, target)| { + imported + .subroutines + .iter() + .any(|subroutine| subroutine.name == **target) + || imported + .dpi_imports + .iter() + .any(|import| import.name() == target.as_str()) + }) + .map(|(name, target)| (name.clone(), target.clone())) + .collect(); + if !calls.is_empty() { + let rename = scope::Renamer { names: &calls }; + let body = + |body: Vec| body.into_iter().map(|stmt| rename.stmt(stmt)).collect(); + for process in &mut comb_processes { + process.body = body(std::mem::take(&mut process.body)); + process.sensitivity_body = body(std::mem::take(&mut process.sensitivity_body)); + for assignment in &mut process.assignments { + assignment.rhs = rename.expr(assignment.rhs.clone()); + } + } + for process in &mut ff_processes { + process.body = body(std::mem::take(&mut process.body)); + } + for process in &mut initial_processes { + process.body = body(std::mem::take(&mut process.body)); + process.validation_body = body(std::mem::take(&mut process.validation_body)); + } + for subroutine in &mut subroutines { + *subroutine = rename.subroutine(subroutine.clone()); + } + for instance in &mut instances { + for connection in &mut instance.port_connections { + connection.map_expressions(|expr| rename.expr(expr)); + } } } - } - let nets = signals - .iter() - .filter(|signal| signal.is_net()) - .map(Signal::name) - .chain(ports.iter().filter(|port| port.is_net).map(Port::name)) - .collect(); - procedural::references::validate( - subroutines.iter().chain(imported.subroutines.iter()), - &comb_processes, - &ff_processes, - &initial_processes, - &subroutine_directions, - &subroutine_params, - &nets, - )?; - procedural::timed_tasks::classify( - subroutines.iter().chain(imported.subroutines.iter()), - &mut comb_processes, - &mut ff_processes, - &mut initial_processes, - )?; - let assignments = comb_processes - .iter() - .flat_map(|process| process.assignments().iter().cloned()) - .collect(); - // A package keeps its symbols for the scopes that use it. - let symbols = (is_package || export_symbols).then(|| scope::ScopeSymbols { - package_scopes: imported.package_scopes.clone(), - classes: classes::scope_classes(syntax_tree, &const_env), - class_member_types: classes::specializations::export_member_types(syntax_tree), - inline_randomizations, - declarations_only: imported.declarations_only, - type_parameter_bindings: HashMap::default(), - pattern_parameter_bindings: HashMap::default(), - const_env: const_env.clone(), - parameter_values: parameter_values.clone(), - parameters: parameters.clone(), - // A class of the scope is a type of it (IEEE 1800-2023 8.3). - type_aliases: type_aliases - .iter() - .map(|(name, ty)| (name.clone(), ty.clone())) - .chain(classes::scope_class_types(syntax_tree)) - .collect(), - enum_constants: enum_constants.clone(), - functions: functions.clone(), - function_return_types: (*packed_dimensions.function_return_types).clone(), - constant_functions: syntax_tree.functions.clone(), - subroutine_params: subroutine_params.clone(), - subroutine_shapes: subroutine_shapes.clone(), - subroutines: subroutines.clone(), - locals: locals.clone(), - dpi_imports: dpi_imports.clone(), - // A package's signals are its array parameters and constant - // variables, initialized by its initial processes. - signals: signals.clone(), - ports: Vec::new(), - state_signals: Vec::new(), - initial_processes: initial_processes.clone(), - comb_processes: comb_processes.clone(), - ff_processes: ff_processes.clone(), - aliases: imported.aliases.clone(), - interface_members: imported.interface_members.clone(), - local_aliases: imported.local_aliases.clone(), - interface_types: imported.interface_types.clone(), - interface_modports: imported.interface_modports.clone(), - interface_arrays: imported.interface_arrays.clone(), - interface_scopes: imported.interface_scopes.clone(), - interface_declarations: imported.interface_declarations.clone(), - interface_instances: imported.interface_instances.clone(), - generate_imports: HashMap::default(), - }); - // The subroutines, locals and DPI imports of the packages the module - // uses are lowered with it. - for subroutine in &imported.subroutines { - if !subroutines + let nets = signals .iter() - .any(|known| known.name == subroutine.name) - { - subroutines.push(subroutine.clone()); - } - } - for local in &imported.locals { - if !locals.iter().any(|known| known.name == local.name) { - locals.push(local.clone()); - } - } - for import in &imported.dpi_imports { - if !dpi_imports + .filter(|signal| signal.is_net()) + .map(Signal::name) + .chain(ports.iter().filter(|port| port.is_net).map(Port::name)) + .collect(); + procedural::references::validate( + subroutines.iter().chain(imported.subroutines.iter()), + &comb_processes, + &ff_processes, + &initial_processes, + &subroutine_directions, + &subroutine_params, + &nets, + )?; + procedural::timed_tasks::classify( + subroutines.iter().chain(imported.subroutines.iter()), + &mut comb_processes, + &mut ff_processes, + &mut initial_processes, + )?; + let assignments = comb_processes .iter() - .any(|known| known.name() == import.name()) - { - dpi_imports.push(import.clone()); + .flat_map(|process| process.assignments().iter().cloned()) + .collect(); + // A package keeps its symbols for the scopes that use it. + let symbols = (is_package || export_symbols).then(|| scope::ScopeSymbols { + package_scopes: imported.package_scopes.clone(), + classes: classes::scope_classes(syntax_tree, session, &const_env), + class_member_types: classes::specializations::export_member_types( + syntax_tree, + session, + ), + inline_randomizations, + declarations_only: imported.declarations_only, + type_parameter_bindings: HashMap::default(), + pattern_parameter_bindings: HashMap::default(), + const_env: const_env.clone(), + parameter_values: parameter_values.clone(), + parameters: parameters.clone(), + // A class of the scope is a type of it (IEEE 1800-2023 8.3). + type_aliases: type_aliases + .iter() + .map(|(name, ty)| (name.clone(), ty.clone())) + .chain(classes::scope_class_types(syntax_tree)) + .collect(), + enum_constants: enum_constants.clone(), + functions: functions.clone(), + function_return_types: (*packed_dimensions.function_return_types).clone(), + constant_functions: syntax_tree.functions.clone(), + subroutine_params: subroutine_params.clone(), + subroutine_shapes: subroutine_shapes.clone(), + subroutines: subroutines.clone(), + locals: locals.clone(), + dpi_imports: dpi_imports.clone(), + // A package's signals are its array parameters and constant + // variables, initialized by its initial processes. + signals: signals.clone(), + ports: Vec::new(), + state_signals: Vec::new(), + initial_processes: initial_processes.clone(), + comb_processes: comb_processes.clone(), + ff_processes: ff_processes.clone(), + aliases: imported.aliases.clone(), + interface_members: imported.interface_members.clone(), + local_aliases: imported.local_aliases.clone(), + interface_types: imported.interface_types.clone(), + interface_modports: imported.interface_modports.clone(), + interface_arrays: imported.interface_arrays.clone(), + interface_scopes: imported.interface_scopes.clone(), + interface_declarations: imported.interface_declarations.clone(), + interface_instances: imported.interface_instances.clone(), + generate_imports: HashMap::default(), + }); + // The subroutines, locals and DPI imports of the packages the module + // uses are lowered with it. + for subroutine in &imported.subroutines { + if !subroutines + .iter() + .any(|known| known.name == subroutine.name) + { + subroutines.push(subroutine.clone()); + } } - } - let mut imported_parameters = imported.parameters.clone(); - imported_parameters - .retain(|parameter| !parameters.iter().any(|local| local.name == parameter.name)); - - // Expression construction tracks only whole-variable assignments. - // Leave calls of functions with selected/concatenated writes symbolic - // in declaration contracts rather than publishing a partial body. - // Expression inlining also sizes formal and return conversions at the - // default specialization; symbolic signature widths cannot be inlined. - for subroutine in &declaration_subroutines { - let mut selected_write = false; - for statement in &subroutine.body { - statement.walk(&mut |statement| { - selected_write |= matches!( - statement, - crate::procedural::StmtBase::Assign { - lhs: crate::ir::LValue::Select { .. }, - .. - } | crate::procedural::StmtBase::AssignConcat { .. } - ); - }); + for local in &imported.locals { + if !locals.iter().any(|known| known.name == local.name) { + locals.push(local.clone()); + } } - let symbolic_type = subroutine - .return_type - .as_ref() - .is_some_and(|ty| ty.has_symbolic_ranges(&syntax_tree.functions)) - || subroutine - .params + for import in &imported.dpi_imports { + if !dpi_imports .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) - { - function.body = None; + .any(|known| known.name() == import.name()) + { + dpi_imports.push(import.clone()); + } } - } - - // A native default value is not evidence of a representable symbolic - // body. Keep failed declaration lowerings visible to contract checking. - for function in functions.values_mut() { - if !declaration_subroutines - .iter() - .any(|subroutine| subroutine.name == function.name) - { - function.body = None; + let mut imported_parameters = imported.parameters.clone(); + imported_parameters + .retain(|parameter| !parameters.iter().any(|local| local.name == parameter.name)); + + // Expression construction tracks only whole-variable assignments. + // Leave calls of functions with selected/concatenated writes symbolic + // in declaration contracts rather than publishing a partial body. + // Expression inlining also sizes formal and return conversions at the + // default specialization; symbolic signature widths cannot be inlined. + for subroutine in &declaration_subroutines { + let mut selected_write = false; + for statement in &subroutine.body { + statement.walk(&mut |statement| { + selected_write |= matches!( + statement, + crate::procedural::StmtBase::Assign { + lhs: crate::ir::LValue::Select { .. }, + .. + } | crate::procedural::StmtBase::AssignConcat { .. } + ); + }); + } + let symbolic_type = subroutine + .return_type + .as_ref() + .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) + { + function.body = None; + } } - } - let mut interface_scope_names = imported - .interface_types - .keys() - .chain(imported.interface_arrays.keys()) - .cloned() - .collect::>(); - interface_scope_names.sort_unstable(); - interface_scope_names.dedup(); - let interface_handles = virtual_interfaces::handles(&syntax_tree.state, &imported, &ports); + // A native default value is not evidence of a representable symbolic + // body. Keep failed declaration lowerings visible to contract checking. + for function in functions.values_mut() { + if !declaration_subroutines + .iter() + .any(|subroutine| subroutine.name == function.name) + { + function.body = None; + } + } - Ok(Self { - name, - program, - interface_scope_names, - interface_handles, - parameters, - ports, - signals, - instances, - assignments, - comb_processes, - ff_processes, - initial_processes, - locals, - subroutines, - dpi_imports, - constant_functions: syntax_tree.functions.clone(), - symbolic_functions: functions, - declaration_subroutines, - imported_parameters, - symbols, - }) + let mut interface_scope_names = imported + .interface_types + .keys() + .chain(imported.interface_arrays.keys()) + .cloned() + .collect::>(); + interface_scope_names.sort_unstable(); + interface_scope_names.dedup(); + let interface_handles = virtual_interfaces::handles(session, &imported, &ports); + + Ok(Self { + name, + program, + interface_scope_names, + interface_handles, + parameters, + ports, + signals, + instances, + assignments, + comb_processes, + ff_processes, + initial_processes, + locals, + subroutines, + dpi_imports, + constant_functions: syntax_tree.functions.clone(), + symbolic_functions: functions, + declaration_subroutines, + imported_parameters, + symbols, + }) + })(session); + generate::restore(session, previous); + module } pub(crate) fn interface_scope_names(&self) -> &[String] { @@ -1897,26 +2022,26 @@ impl Parameter { pub(crate) fn resolved_value_and_literal( &self, tree: &AnalysisContext<'_>, + session: &mut Session, 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(tree, constants, parameter_types, literals), + self.resolved_literal(tree, session, constants, parameter_types, literals), ); } if let Some(value) = self.resolved_value(&tree.functions, constants, parameter_types) { return (Some(value), None); } - let literal = self.resolved_literal(tree, constants, parameter_types, literals); + let literal = self.resolved_literal(tree, session, constants, parameter_types, literals); let value = literal.as_ref().and_then(|literal| { eval_ast_const_expr( functions, - &expr_to_const(state, literal.clone())?, + &expr_to_const(session, literal.clone())?, constants, ) }); @@ -1930,6 +2055,7 @@ impl Parameter { pub(crate) fn resolved_literal( &self, tree: &AnalysisContext<'_>, + session: &mut Session, constants: &HashMap, parameter_types: &HashMap, literals: &HashMap, @@ -1966,12 +2092,14 @@ impl Parameter { } let value = parameter_value_env( tree, + session, 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(tree, value, &evaluation_constants); + let value = + fold_const_integral_expr_preserving_mask(tree, session, value, &evaluation_constants); matches!(value, Expr::Literal(_)).then_some(value) } @@ -2627,10 +2755,11 @@ pub enum ConstExpr { impl ConstExpr { /// Effectful calls get distinct sites; analyzer-created copies retain them. - fn call(state: &AnalysisState, callee: Callee, args: Vec) -> Self { - let site = callee - .is_effectful() - .then(|| state.next_call_site.replace(state.next_call_site.get() + 1)); + fn call(callee: Callee, args: Vec, session: &mut Session) -> Self { + let site = callee.is_effectful().then(|| { + session.next_call_site += 1; + session.next_call_site - 1 + }); ConstExpr::Function { callee, args, site } } } @@ -3166,11 +3295,12 @@ fn parameter_packed_dimensions_with_imported( /// enum members a scope imports. fn parameter_value_env_with_imported( tree: &AnalysisContext<'_>, + session: &mut Session, parameters: &[Parameter], const_env: &HashMap, imported: &scope::ScopeSymbols, ) -> HashMap { - let mut values = parameter_value_env(tree, parameters, const_env); + let mut values = parameter_value_env(tree, session, 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 0c176640c8a..8b5768c8024 100644 --- a/crates/celox-sv-analyzer/src/ast/array_compatibility.rs +++ b/crates/celox-sv-analyzer/src/ast/array_compatibility.rs @@ -102,15 +102,15 @@ fn incompatible_types( /// the first may not be assigned to the second (see [`incompatible_types`]). pub(super) fn incompatible( tree: &AnalysisContext<'_>, + session: &mut Session, actual: &VariableDimensions, target: &VariableDimensions, dims: &PackedDimensions, ) -> Option<(String, String)> { - 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)?) + let table = &mut session.types; + let actual = semantic_types::of_shape(table, &tree.functions, actual, &dims.const_env)?; + let target = semantic_types::of_shape(table, &tree.functions, target, &dims.const_env)?; + incompatible_types(table, actual, target) } /// The shape of a variable `name` after `indices` index selects, when that @@ -142,12 +142,13 @@ pub(super) fn selected_unpacked_shape( fn native_selection( mut id: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Option<(String, usize, Option)> { use celox_sv_syntax::{DimensionKind, ExprKind}; let native = tree.declarations(); - let constant = |id| { - constant_binding::bind(id, tree, dims) + let mut constant = |id| { + constant_binding::bind(id, tree, session, dims) .ok() .flatten() .and_then(|value| eval_ast_const_expr(&tree.functions, &value, &dims.const_env)) @@ -194,9 +195,10 @@ fn native_selection( pub(super) fn native_unpacked_shape( id: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Option { - let (path, indices, slice) = native_selection(id, tree, dims)?; + let (path, indices, slice) = native_selection(id, tree, session, dims)?; let mut shape = selected_unpacked_shape(&path, indices, dims)?; if let Some(count) = slice { let count = ConstExpr::Literal(count.to_string()); @@ -219,21 +221,22 @@ pub(super) fn native_unpacked_shape( fn native_unpacked_type( id: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Option { use semantic_types::{ArrayKind, Range, TyData}; - let (path, indices, slice) = native_selection(id, tree, dims)?; - let table = &tree.state.types; + let (path, indices, slice) = native_selection(id, tree, session, dims)?; + let table = &mut session.types; 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; }; - ty = element; + ty = *element; } if let Some(count) = slice { - let TyData::Array { element, .. } = table.data(ty) else { + let &TyData::Array { element, .. } = table.data(ty) else { return None; }; ty = table.intern(TyData::Array { @@ -273,15 +276,17 @@ fn dotted_path( /// conditional operator that selects the value is checked (11.4.11). pub(super) fn check_native_unpacked_assignment( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::ExprId, target: &VariableDimensions, context: impl Fn() -> String, dims: &PackedDimensions, ) -> Converted<()> { - check_assignment(tree, id, target, &context, dims) + check_assignment(tree, session, id, target, &context, dims) } fn check_assignment( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::ExprId, target: &VariableDimensions, context: &dyn Fn() -> String, @@ -296,14 +301,15 @@ fn check_assignment( .expression(expression_binding::ungroup(id, native)) .kind { - check_assignment(tree, *then_expression, target, context, dims)?; - return check_assignment(tree, *else_expression, target, context, dims); + check_assignment(tree, session, *then_expression, target, context, dims)?; + return check_assignment(tree, session, *else_expression, target, context, dims); } - let table = &tree.state.types; - let Some((actual, target)) = - 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)) + let target = + semantic_types::of_shape(&mut session.types, &tree.functions, target, &dims.const_env); + let actual = native_unpacked_type(id, tree, session, dims); + let Some((actual, target)) = target + .zip(actual) + .and_then(|(target, actual)| incompatible_types(&session.types, actual, target)) else { return Ok(()); }; diff --git a/crates/celox-sv-analyzer/src/ast/array_parameters.rs b/crates/celox-sv-analyzer/src/ast/array_parameters.rs index ded8ee86e9e..4613b4ecead 100644 --- a/crates/celox-sv-analyzer/src/ast/array_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/array_parameters.rs @@ -41,6 +41,7 @@ pub(super) fn is_array_parameter( fn declared_type( native: &celox_sv_syntax::Parameter, tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, type_aliases: &HashMap, ) -> Converted> { @@ -52,6 +53,7 @@ fn declared_type( type_binding::bind( data_type, tree, + session, &PackedDimensions::new(HashMap::default(), const_env, type_aliases), ) } @@ -61,6 +63,7 @@ fn declared_type( pub(super) fn uses_signal_representation( parameter: &celox_sv_syntax::Parameter, tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, aliases: &HashMap, ) -> Converted { @@ -71,7 +74,7 @@ pub(super) fn uses_signal_representation( if !parameter.local && tree.parameter_overrides.contains_key(&name) && matches!(¶meter.kind, celox_sv_syntax::ParameterKind::Value { dimensions, .. } if dimensions.is_empty()) - && declared_type(parameter, tree, const_env, aliases)? + && declared_type(parameter, tree, session, const_env, aliases)? .is_some_and(|ty| ty.unpacked_ranges.is_empty()) { return Ok(false); @@ -82,6 +85,7 @@ pub(super) fn uses_signal_representation( /// Array parameters declared directly in the selected native unit/scope. pub(super) fn array_parameters_from_scope( tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, type_aliases: &HashMap, ) -> Converted> { @@ -98,6 +102,7 @@ pub(super) fn array_parameters_from_scope( parameters.extend(array_parameters_from_declaration( &authored, tree, + session, const_env, type_aliases, &mut |_| {}, @@ -118,6 +123,7 @@ pub(super) fn array_parameters_from_scope( parameters.extend(array_parameters_from_declaration( &authored, tree, + session, const_env, type_aliases, &mut |_| {}, @@ -131,6 +137,7 @@ pub(super) fn array_parameters_from_scope( fn array_parameters_from_declaration( authored: &[&celox_sv_syntax::Parameter], tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, type_aliases: &HashMap, publish: &mut impl FnMut(&ArrayParameter), @@ -141,13 +148,16 @@ fn array_parameters_from_declaration( .pattern_parameter_bindings .get(&native.id) .cloned(); - if !uses_signal_representation(native, tree, const_env, type_aliases)? && bound.is_none() { + if !uses_signal_representation(native, tree, session, const_env, type_aliases)? + && bound.is_none() + { continue; } let name = instances::normalize_identifier(&native.name.spelling); - let element = declared_type(native, tree, const_env, type_aliases)?.ok_or_else(|| { - AnalyzerError::Unsupported(format!("type of array parameter `{name}`")) - })?; + let element = + declared_type(native, tree, session, const_env, type_aliases)?.ok_or_else(|| { + AnalyzerError::Unsupported(format!("type of array parameter `{name}`")) + })?; let celox_sv_syntax::ParameterKind::Value { dimensions, .. } = &native.kind else { return Err(AnalyzerError::Parse( "native array parameter kind disagrees".into(), @@ -156,7 +166,13 @@ fn array_parameters_from_declaration( let ranges = dimensions .iter() .map(|dimension| { - constant_binding::unpacked_dimension(dimension, tree, const_env, type_aliases) + constant_binding::unpacked_dimension( + dimension, + tree, + session, + const_env, + type_aliases, + ) }) .collect::>>()?; let pattern = parameters::ownership::default(native).filter(|id| { @@ -192,15 +208,17 @@ impl ArrayParameter { pub(super) fn initial_process( &self, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Result { 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, &shape, dims)? + bound.lower(tree, session, &shape, dims)? } else { match self.native_pattern { - Some(root) => match patterns::native_expression(root, &shape, tree, dims)? { + Some(root) => match patterns::native_expression(root, &shape, tree, session, dims)? + { Some(value) => value, None => return Err(unsupported("array parameter pattern target")), }, diff --git a/crates/celox-sv-analyzer/src/ast/array_reductions.rs b/crates/celox-sv-analyzer/src/ast/array_reductions.rs index 54535b193ea..d6a551f26dc 100644 --- a/crates/celox-sv-analyzer/src/ast/array_reductions.rs +++ b/crates/celox-sv-analyzer/src/ast/array_reductions.rs @@ -7,6 +7,7 @@ pub(super) fn bind( id: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { let callee = match &native.expression(id).kind { @@ -39,7 +40,7 @@ pub(super) fn bind( _ => op, }; } - if let Some(container) = containers::native_type(*base, native, tree, dims)? { + if let Some(container) = containers::native_type(*base, native, tree, session, dims)? { if let ExprKind::Call { arguments, .. } = &native.expression(id).kind && !arguments.is_empty() { @@ -59,7 +60,9 @@ pub(super) fn bind( containers::call( op, container.layout, - vec![expression_binding::value(*base, native, tree, dims)?], + vec![expression_binding::value( + *base, native, tree, session, dims, + )?], ), procedural::dimensions_from_type(&container.element), ))); diff --git a/crates/celox-sv-analyzer/src/ast/assignment_analysis.rs b/crates/celox-sv-analyzer/src/ast/assignment_analysis.rs index 92e2911e7b9..7e615b18c66 100644 --- a/crates/celox-sv-analyzer/src/ast/assignment_analysis.rs +++ b/crates/celox-sv-analyzer/src/ast/assignment_analysis.rs @@ -4,28 +4,29 @@ use super::*; pub(super) fn two_state_conditions_are_complements( tree: &AnalysisContext<'_>, + session: &mut Session, left: &Expr, right: &Expr, packed_dimensions: &PackedDimensions, ) -> bool { if let (Some((left, left_positive)), Some((right, right_positive))) = ( - normalized_two_state_boolean(tree, left, packed_dimensions), - normalized_two_state_boolean(tree, right, packed_dimensions), + normalized_two_state_boolean(tree, session, left, packed_dimensions), + normalized_two_state_boolean(tree, session, right, packed_dimensions), ) && left == right && left_positive != right_positive { return true; } - let is_complement = |candidate: &Expr, other: &Expr| { + let is_complement = |session: &mut Session, candidate: &Expr, other: &Expr| { matches!( candidate, Expr::Unary { op: UnaryOp::LogicNot, expr, - } if &**expr == other && expr_is_two_state(tree, other, packed_dimensions) + } if &**expr == other && expr_is_two_state(tree, session, other, packed_dimensions) ) }; - let are_inverse_equalities = |left: &Expr, right: &Expr| { + let are_inverse_equalities = |session: &mut Session, left: &Expr, right: &Expr| { let ( Expr::Binary { left: left_lhs, @@ -48,18 +49,21 @@ 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(tree, left_lhs, packed_dimensions) - && expr_is_two_state(tree, left_rhs, packed_dimensions) + expr_is_two_state(tree, session, left_lhs, packed_dimensions) + && expr_is_two_state(tree, session, left_rhs, packed_dimensions) } (BinaryOp::EqCase, BinaryOp::NeCase) | (BinaryOp::NeCase, BinaryOp::EqCase) => true, _ => false, } }; - is_complement(left, right) || is_complement(right, left) || are_inverse_equalities(left, right) + is_complement(session, left, right) + || is_complement(session, right, left) + || are_inverse_equalities(session, left, right) } fn normalized_two_state_boolean<'a>( tree: &AnalysisContext<'_>, + session: &mut Session, expr: &'a Expr, packed_dimensions: &PackedDimensions, ) -> Option<(&'a Expr, bool)> { @@ -70,15 +74,15 @@ fn normalized_two_state_boolean<'a>( .. } if expr_static_width(tree, operand, packed_dimensions) .is_some_and(|source| source <= *width) - && expr_is_two_state(tree, operand, packed_dimensions) => + && expr_is_two_state(tree, session, operand, packed_dimensions) => { - return normalized_two_state_boolean(tree, operand, packed_dimensions); + return normalized_two_state_boolean(tree, session, operand, packed_dimensions); } Expr::Unary { op: UnaryOp::ToTwoState, expr: operand, - } if expr_is_two_state(tree, operand, packed_dimensions) => { - return normalized_two_state_boolean(tree, operand, packed_dimensions); + } if expr_is_two_state(tree, session, operand, packed_dimensions) => { + return normalized_two_state_boolean(tree, session, operand, packed_dimensions); } _ => {} } @@ -86,9 +90,10 @@ fn normalized_two_state_boolean<'a>( && (*op == UnaryOp::LogicNot || (*op == UnaryOp::BitNot && expr_static_width(tree, expr, packed_dimensions) == Some(1) - && expr_is_two_state(tree, expr, packed_dimensions))) + && expr_is_two_state(tree, session, expr, packed_dimensions))) { - let (expr, positive) = normalized_two_state_boolean(tree, expr, packed_dimensions)?; + let (expr, positive) = + normalized_two_state_boolean(tree, session, expr, packed_dimensions)?; return Some((expr, !positive)); } if let Expr::Binary { left, op, right } = expr @@ -97,28 +102,30 @@ fn normalized_two_state_boolean<'a>( BinaryOp::Eq | BinaryOp::Ne | BinaryOp::EqCase | BinaryOp::NeCase ) { - let nonzero_side = if expr_is_constant_zero(tree, left, &packed_dimensions.const_env) { - &**right - } else if expr_is_constant_zero(tree, right, &packed_dimensions.const_env) { - &**left - } else { - return expr_is_two_state(tree, expr, packed_dimensions).then_some((expr, true)); - }; - if expr_is_two_state(tree, nonzero_side, packed_dimensions) { + let nonzero_side = + if expr_is_constant_zero(tree, session, left, &packed_dimensions.const_env) { + &**right + } else if expr_is_constant_zero(tree, session, right, &packed_dimensions.const_env) { + &**left + } else { + return expr_is_two_state(tree, session, expr, packed_dimensions) + .then_some((expr, true)); + }; + if expr_is_two_state(tree, session, nonzero_side, packed_dimensions) { return Some((nonzero_side, matches!(op, BinaryOp::Ne | BinaryOp::NeCase))); } } - expr_is_two_state(tree, expr, packed_dimensions).then_some((expr, true)) + expr_is_two_state(tree, session, expr, packed_dimensions).then_some((expr, true)) } fn expr_is_constant_zero( tree: &AnalysisContext<'_>, + session: &mut Session, expr: &Expr, const_env: &HashMap, ) -> bool { - let state = &*tree.state; let functions = &tree.functions; - expr_to_const(state, expr.clone()) + expr_to_const(session, 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 a383049349b..7543b231928 100644 --- a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs @@ -45,9 +45,10 @@ pub(super) enum Value { pub(super) fn from_param( root: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted { - match binding::value(root, tree, dims)? { + match binding::value(root, tree, session, dims)? { Value::Pattern(pattern) => Ok(pattern), Value::Expression { expr, .. } => Ok(BoundPattern { items: Items::Value(expr), @@ -58,25 +59,30 @@ pub(super) fn from_param( pub(super) fn from_array_parameter( root: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, shape: &VariableDimensions, ) -> Converted { 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)?, + expression_binding::bind(root, tree, session, dims)?, &dims.array_parameter_values, ); - let value = frozen(tree, value, dims)?; + let value = frozen(tree, session, value, dims)?; Ok(BoundPattern { items: Items::ArrayValue { value, ty }, }) } -fn frozen(tree: &AnalysisContext<'_>, expr: Expr, dims: &PackedDimensions) -> Converted { - let state = &*tree.state; +fn frozen( + tree: &AnalysisContext<'_>, + session: &mut Session, + expr: Expr, + dims: &PackedDimensions, +) -> Converted { let functions = &tree.functions; - let freeze = |expr| frozen(tree, expr, dims).map(Box::new); + let mut freeze = |expr| frozen(tree, session, expr, dims).map(Box::new); Ok(match expr { Expr::Literal(_) => expr, Expr::Unary { op, expr } => Expr::Unary { @@ -107,12 +113,13 @@ fn frozen(tree: &AnalysisContext<'_>, expr: Expr, dims: &PackedDimensions) -> Co .map(|arg| { let expr = frozen( tree, + session, arg.ok_or_else(|| { unsupported("default constant function argument in pattern") })?, dims, )?; - expr_to_const(state, expr) + expr_to_const(session, expr) .map(Into::into) .ok_or_else(|| unsupported("constant pattern function argument")) }) @@ -131,11 +138,13 @@ fn frozen(tree: &AnalysisContext<'_>, expr: Expr, dims: &PackedDimensions) -> Co .collect(); let value = substitute_expr_constants_with_parameter_literals( tree, + session, value, &dims.const_env, &values, ); - let folded = fold_const_integral_expr_preserving_mask(tree, value, &dims.const_env); + let folded = + fold_const_integral_expr_preserving_mask(tree, session, value, &dims.const_env); if !matches!(folded, Expr::Literal(_)) { return Err(unsupported("nonconstant parameter pattern element")); } @@ -153,12 +162,13 @@ impl Value { fn lower( &self, tree: &AnalysisContext<'_>, + session: &mut Session, shape: &VariableDimensions, dims: &PackedDimensions, default: bool, ) -> Converted { if let Self::Pattern(pattern) = self { - return pattern.lower(tree, shape, dims); + return pattern.lower(tree, session, shape, dims); } let (value, signed, value_type) = match self { Self::Expression { @@ -172,7 +182,9 @@ impl Value { ), Self::Pattern(_) => unreachable!(), }; - patterns::assignment_value(tree, value, signed, value_type, shape, dims, default) + patterns::assignment_value( + tree, session, value, signed, value_type, shape, dims, default, + ) } } @@ -180,6 +192,7 @@ impl BoundPattern { pub(super) fn lower( &self, tree: &AnalysisContext<'_>, + session: &mut Session, shape: &VariableDimensions, dims: &PackedDimensions, ) -> Converted { @@ -387,7 +400,7 @@ impl BoundPattern { let mut parts = selected .into_iter() .zip(shapes) - .map(|((v, default), shape)| v.lower(tree, &shape, dims, default)) + .map(|((v, default), shape)| v.lower(tree, session, &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 ce41af7fcda..9d7504c036f 100644 --- a/crates/celox-sv-analyzer/src/ast/bound_patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns/binding.rs @@ -16,6 +16,7 @@ pub(in crate::ast) struct Plan { pub(in crate::ast) fn prepare_native( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, shape: Option<&VariableDimensions>, ) -> Converted { @@ -23,8 +24,8 @@ pub(in crate::ast) fn prepare_native( let ExprKind::Pattern { items, .. } = &native.expression(root).kind else { return Err(mismatch()); }; - let integer = |id| { - constant_binding::bind(id, tree, dims)? + let mut integer = |id| { + constant_binding::bind(id, tree, session, dims)? .and_then(|value| eval_ast_const_expr(&tree.functions, &value, &dims.const_env)) .ok_or_else(|| unsupported("nonconstant assignment pattern key or count")) }; @@ -85,14 +86,16 @@ pub(in crate::ast) fn prepare_native( pub(super) fn value( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted { - value_mode(root, tree, dims, true) + value_mode(root, tree, session, dims, true) } pub(super) fn value_mode( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, constant: bool, ) -> Converted { @@ -112,25 +115,26 @@ pub(super) fn value_mode( } match &native.expression(id).kind { ExprKind::Pattern { target: None, .. } => { - let plan = prepare_native(id, tree, dims, None)?; + let plan = prepare_native(id, tree, session, dims, None)?; jobs.push(Job::Finish(plan.kind, plan.bindings.len())); jobs.extend(plan.bindings.into_iter().rev().map(Job::Enter)); } ExprKind::Pattern { .. } if constant => { - values.push(patterns::constant_native(id, tree, dims)?) + values.push(patterns::constant_native(id, tree, session, dims)?) } _ => { - let expr = expression_binding::bind(id, tree, dims)?; + let expr = expression_binding::bind(id, tree, session, dims)?; let (expr, signed, value_type) = if constant { // Capture the self-determined type before folding the // value into bits, just as for runtime port values. - let types = dimensions::query_context_for_operand(id, tree, dims)?; + let types = + dimensions::query_context_for_operand(id, tree, session, dims)?; let value_type = super::ports::ValueType::Known( - super::ports::native_value_type(id, tree, &types)?, + super::ports::native_value_type(id, tree, session, &types)?, ); let signed = dimensions::expression_signedness(&expr, &types, &types.const_env); - let expr = frozen(tree, expr, dims)?; + let expr = frozen(tree, session, expr, dims)?; let signed = Some(signed.unwrap_or_else(|| { dimensions::expression_signedness(&expr, &types, &types.const_env) .unwrap_or(false) @@ -143,7 +147,7 @@ pub(super) fn value_mode( ( expr, signed, - super::ports::native_value_type_plan(id, tree, dims)?, + super::ports::native_value_type_plan(id, tree, session, dims)?, ) }; values.push(Value::Expression { @@ -190,6 +194,7 @@ mod tests { } #[test] fn deeply_nested_native_override_pattern_jobs_use_the_default_stack() { + let session = &mut Session::default(); let tree = std::thread::Builder::new() .stack_size(128 * 1024 * 1024) .spawn(|| { @@ -215,7 +220,7 @@ mod tests { .unwrap(); let dims = PackedDimensions::new(HashMap::default(), &HashMap::default(), &HashMap::default()); - let result = super::super::from_param(root, tree, &dims); + let result = super::super::from_param(root, tree, session, &dims); drop(context); drop(original); let pattern = result.unwrap(); 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 b1c6f136eca..35e3904d4b3 100644 --- a/crates/celox-sv-analyzer/src/ast/bound_patterns/ports.rs +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns/ports.rs @@ -52,9 +52,10 @@ impl ValueType { pub(in crate::ast) fn from_port( root: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted { - match binding::value_mode(root, tree, dims, false)? { + match binding::value_mode(root, tree, session, dims, false)? { Value::Pattern(pattern) => Ok(pattern), _ => Err(unsupported("untyped port assignment pattern")), } @@ -129,23 +130,25 @@ impl BoundPattern { } pub(crate) fn bind_structure_port(&self, target: &Type) -> Converted> { + let session = &mut Session::default(); let aggregate = target .unpacked_struct() .ok_or_else(|| unsupported("unpacked structure port type"))?; let syntax = SyntaxTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); let shape = procedural::dimensions_from_type(target); - let value = self.lower(&tree, &shape, &PackedDimensions::default())?; + let value = self.lower(&tree, session, &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 session = &mut Session::default(); let syntax = SyntaxTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); let shape = procedural::dimensions_from_type(target); - self.lower(&tree, &shape, &PackedDimensions::default()) + self.lower(&tree, session, &shape, &PackedDimensions::default()) .map(Into::into) } } @@ -190,14 +193,16 @@ impl Type { pub(in crate::ast) fn native_value_type( root: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { - native_value_type_plan(root, tree, dims).map(|ty| ty.resolve(dims)) + native_value_type_plan(root, tree, session, dims).map(|ty| ty.resolve(dims)) } pub(super) fn native_value_type_plan( root: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted { use celox_sv_syntax::ExprKind; @@ -222,15 +227,15 @@ pub(super) fn native_value_type_plan( jobs.push(Job::Enter(else_expression)); jobs.push(Job::Enter(then_expression)); } - ExprKind::Call { .. } => { - values.push(ValueType::Call(expression_binding::bind(root, tree, dims)?)) - } + ExprKind::Call { .. } => values.push(ValueType::Call( + expression_binding::bind(root, tree, session, dims)?, + )), _ => { let shape = if matches!(native.expression(root).kind, ExprKind::Pattern { .. }) { patterns::typed_shape(root, tree, dims)? } else { - dimensions::operand_shape(root, tree, dims)? + dimensions::operand_shape(root, tree, session, dims)? }; values.push(ValueType::Known( shape diff --git a/crates/celox-sv-analyzer/src/ast/case.rs b/crates/celox-sv-analyzer/src/ast/case.rs index e767b5ed934..8dcfb203321 100644 --- a/crates/celox-sv-analyzer/src/ast/case.rs +++ b/crates/celox-sv-analyzer/src/ast/case.rs @@ -4,10 +4,10 @@ use super::*; pub(super) fn expr_is_two_state( tree: &AnalysisContext<'_>, + session: &mut Session, expr: &Expr, packed_dimensions: &PackedDimensions, ) -> bool { - let state = &*tree.state; let functions = &tree.functions; match expr { Expr::Ident(name) => { @@ -19,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(tree, expr, packed_dimensions) + expr_is_two_state(tree, session, expr, packed_dimensions) && select_bounds_are_statically_valid(tree, expr, msb, lsb, packed_dimensions) } - Expr::Resize { expr, .. } => expr_is_two_state(tree, expr, packed_dimensions), + Expr::Resize { expr, .. } => expr_is_two_state(tree, session, expr, packed_dimensions), Expr::Concat(parts) | Expr::RepeatConcat { parts, .. } => parts .iter() - .all(|part| expr_is_two_state(tree, part, packed_dimensions)), + .all(|part| expr_is_two_state(tree, session, part, packed_dimensions)), Expr::Unary { op, expr } => { - *op == UnaryOp::ToTwoState || expr_is_two_state(tree, expr, packed_dimensions) + *op == UnaryOp::ToTwoState || expr_is_two_state(tree, session, expr, packed_dimensions) } Expr::Binary { left, op, right } => { matches!(op, BinaryOp::EqCase | BinaryOp::NeCase) - || (expr_is_two_state(tree, left, packed_dimensions) - && expr_is_two_state(tree, right, packed_dimensions) + || (expr_is_two_state(tree, session, left, packed_dimensions) + && expr_is_two_state(tree, session, right, packed_dimensions) && (!matches!(op, BinaryOp::Div | BinaryOp::Mod) - || expr_to_const(state, (**right).clone()) + || expr_to_const(session, (**right).clone()) .and_then(|right| { eval_ast_const_expr(functions, &right, &packed_dimensions.const_env) }) .is_some_and(|right| right != 0))) } Expr::Inside { expr, items } => { - expr_is_two_state(tree, expr, packed_dimensions) + expr_is_two_state(tree, session, expr, packed_dimensions) && items.iter().all(|item| { item.exprs() .into_iter() - .all(|operand| expr_is_two_state(tree, operand, packed_dimensions)) + .all(|operand| expr_is_two_state(tree, session, operand, packed_dimensions)) }) } Expr::Mux { @@ -53,10 +53,10 @@ pub(super) fn expr_is_two_state( then_expr, else_expr, } => { - expr_is_two_state(tree, then_expr, packed_dimensions) + expr_is_two_state(tree, session, then_expr, packed_dimensions) && (then_expr == else_expr - || (expr_is_two_state(tree, condition, packed_dimensions) - && expr_is_two_state(tree, else_expr, packed_dimensions))) + || (expr_is_two_state(tree, session, condition, packed_dimensions) + && expr_is_two_state(tree, session, else_expr, packed_dimensions))) } Expr::Call { callee: Callee::System(function), @@ -73,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(tree, arg, packed_dimensions)) + .is_some_and(|arg| expr_is_two_state(tree, session, arg, packed_dimensions)) }), // Properties are 2-state. Expr::Call { @@ -92,7 +92,7 @@ pub(super) fn expr_is_two_state( key(index) || arg .as_ref() - .is_some_and(|arg| expr_is_two_state(tree, arg, packed_dimensions)) + .is_some_and(|arg| expr_is_two_state(tree, session, arg, packed_dimensions)) }) } Expr::Call { diff --git a/crates/celox-sv-analyzer/src/ast/casts.rs b/crates/celox-sv-analyzer/src/ast/casts.rs index 1f6f99bfe0a..85f1b241124 100644 --- a/crates/celox-sv-analyzer/src/ast/casts.rs +++ b/crates/celox-sv-analyzer/src/ast/casts.rs @@ -138,11 +138,11 @@ pub(super) fn runtime_cast_target_expr( /// of the syntax adapter that supplied its target and operand. pub(super) fn cast_constant_target( tree: &AnalysisContext<'_>, + session: &mut Session, operand: ConstExpr, target: RuntimeCastTarget, const_env: &HashMap, ) -> Option { - let state = &*tree.state; if let RuntimeCastTarget::Real { short } = target { let kind = if short { TypeKind::Shortreal @@ -150,7 +150,7 @@ pub(super) fn cast_constant_target( TypeKind::Real }; return expr_to_const( - state, + session, parameters::real_literal(&operand, kind, const_env, &HashMap::default())?, ); } diff --git a/crates/celox-sv-analyzer/src/ast/classes.rs b/crates/celox-sv-analyzer/src/ast/classes.rs index 35c81dc6221..21f6fb17bfb 100644 --- a/crates/celox-sv-analyzer/src/ast/classes.rs +++ b/crates/celox-sv-analyzer/src/ast/classes.rs @@ -309,6 +309,7 @@ impl Class { pub fn derives_from( &self, tree: &AnalysisContext<'_>, + session: &mut Session, ancestor: &str, env: &HashMap, aliases: &HashMap, @@ -322,7 +323,7 @@ impl Class { if !seen.insert(name.clone()) { continue; } - if let Ok(class) = self::class(tree, &name, env, aliases) { + if let Ok(class) = self::class(tree, session, &name, env, aliases) { pending.extend(class.base.iter().chain(&class.interfaces).cloned()); } } @@ -362,9 +363,10 @@ impl Class { /// exists. pub(super) fn declaration<'a>( tree: &'a AnalysisContext<'_>, + session: &mut Session, name: &str, ) -> Option<&'a celox_sv_syntax::ClassDeclaration> { - let name = specializations::generic(tree, name); + let name = specializations::generic(session, name); tree.declarations() .classes .iter() @@ -410,15 +412,21 @@ pub(super) fn scope_declarations<'a>( /// The classes the current scope declares, as they have been laid out, for /// the scopes that use it (see `scope::ScopeSymbols::classes`). -pub(super) fn scope_classes(tree: &AnalysisContext<'_>, env: &HashMap) -> Vec { - let laid_out = tree.state.classes.borrow(); - scope_declarations(tree) - .flat_map(|declaration| specializations_of(tree, declaration)) +pub(super) fn scope_classes( + tree: &AnalysisContext<'_>, + session: &mut Session, + env: &HashMap, +) -> Vec { + let names = scope_declarations(tree) + .flat_map(|declaration| specializations_of(tree, session, declaration)) + .collect::>(); + names + .into_iter() .filter_map(|name| { - let mut class = Class::clone(laid_out.get(&name)?); + let mut class = Class::clone(session.classes.get(&name)?); // The types are fixed in the scope that declares the class, // whose names another scope does not see. - let (env, _) = specializations::scope(tree, &name, env, &HashMap::default()); + let (env, _) = specializations::scope(session, &name, env, &HashMap::default()); let resolve = |ty: &mut Type| { if let Some(resolved) = type_parameters::resolve(&tree.functions, ty.clone(), &env) { @@ -455,8 +463,12 @@ pub(super) fn scope_class_types(tree: &AnalysisContext<'_>) -> Vec<(String, Type /// scope sees it: one the scope declares, or else one the compilation unit /// declares (IEEE 1800-2023 3.12.1). Classes of packages are seen through /// imports, as types. -pub(super) fn resolve(tree: &AnalysisContext<'_>, name: &str) -> Option { - if tree.state.foreign.contains(name) { +pub(super) fn resolve( + tree: &AnalysisContext<'_>, + session: &mut Session, + name: &str, +) -> Option { + if session.foreign.contains(name) { return Some(name.to_owned()); } let native = tree.declarations(); @@ -486,7 +498,7 @@ pub(super) fn resolve(tree: &AnalysisContext<'_>, name: &str) -> Option .and_then(Type::class) .unwrap_or(alias); if imported.classes.iter().any(|known| known.name == class) - || tree.state.foreign.contains(class) + || session.foreign.contains(class) { return Some(class.to_owned()); } @@ -511,8 +523,8 @@ pub(super) fn resolve(tree: &AnalysisContext<'_>, name: &str) -> Option } /// Whether class `name` is declared in the source of the current scope. -pub(super) fn is_declared(tree: &AnalysisContext<'_>, name: &str) -> bool { - declaration(tree, name).is_some() +pub(super) fn is_declared(tree: &AnalysisContext<'_>, session: &mut Session, name: &str) -> bool { + declaration(tree, session, name).is_some() } /// The innermost module, interface, program or package of `native` whose @@ -528,15 +540,19 @@ pub(super) fn enclosing_unit( } /// Whether `name` is an interface class (IEEE 1800-2023 8.26). -pub(super) fn is_interface(tree: &AnalysisContext<'_>, name: &str) -> bool { - declaration(tree, name).is_some_and(|declaration| declaration.interface) +pub(super) fn is_interface(tree: &AnalysisContext<'_>, session: &mut Session, name: &str) -> bool { + declaration(tree, session, name).is_some_and(|declaration| declaration.interface) } /// Whether `name` is a class declared with a parameter port list (IEEE /// 1800-2023 8.25). -pub(super) fn is_parameterized(tree: &AnalysisContext<'_>, name: &str) -> bool { - declaration(tree, name).is_some_and(|class| class.parameter_ports.is_some()) - || tree.state.foreign.contains(name) +pub(super) fn is_parameterized( + tree: &AnalysisContext<'_>, + session: &mut Session, + name: &str, +) -> bool { + declaration(tree, session, name).is_some_and(|class| class.parameter_ports.is_some()) + || session.foreign.contains(name) } /// The classes and interface classes that body item `item` declares: of a @@ -545,6 +561,7 @@ pub(super) fn is_parameterized(tree: &AnalysisContext<'_>, name: &str) -> bool { pub(super) fn item_classes( item: celox_sv_syntax::BodyItemId, tree: &AnalysisContext<'_>, + session: &mut Session, ) -> Vec { let native = tree.declarations(); let item = native.body_item(item); @@ -558,7 +575,7 @@ pub(super) fn item_classes( .filter(|class| { item.tokens.start <= class.tokens.start && class.tokens.end <= item.tokens.end }) - .flat_map(|class| specializations_of(tree, class)) + .flat_map(|class| specializations_of(tree, session, class)) .collect() } @@ -566,11 +583,12 @@ pub(super) fn item_classes( /// when it has no parameter port list. pub(super) fn specializations_of( tree: &AnalysisContext<'_>, + session: &mut Session, declaration: &celox_sv_syntax::ClassDeclaration, ) -> Vec { let name = declared_name(tree, declaration); if declaration.parameter_ports.is_some() { - specializations::of(tree, &name) + specializations::of(session, &name) } else { vec![name] } @@ -582,9 +600,10 @@ pub(super) fn specializations_of( /// whether it is static. pub(super) fn declared_methods( tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, ) -> Converted> { - let Some(declaration) = declaration(tree, name) else { + let Some(declaration) = declaration(tree, session, name) else { return Ok(Vec::new()); }; let native = tree.declarations(); @@ -615,13 +634,14 @@ pub(super) fn declared_methods( pub(super) fn item_statics( item: celox_sv_syntax::BodyItemId, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Vec { - item_classes(item, tree) + item_classes(item, tree, session) .into_iter() .filter_map(|name| { - let class = class(tree, &name, env, aliases).ok()?; + let class = class(tree, session, &name, env, aliases).ok()?; Some( class .statics @@ -639,9 +659,14 @@ pub(super) fn item_statics( /// constructor of its base (IEEE 1800-2023 8.17). pub(super) fn base_arguments<'a>( tree: &'a AnalysisContext<'_>, + session: &mut Session, name: &str, ) -> Option<&'a [celox_sv_syntax::Argument]> { - declaration(tree, name)?.base.as_ref()?.arguments.as_deref() + declaration(tree, session, name)? + .base + .as_ref()? + .arguments + .as_deref() } /// Whether class `name` is a built-in class whose objects the scheduler owns: @@ -655,8 +680,12 @@ pub(super) fn builtin(name: &str) -> bool { } /// The handle type of class `name`, if it is a class. -pub(super) fn handle_type(tree: &AnalysisContext<'_>, name: &str) -> Option { - (builtin(name) || declaration(tree, name).is_some() || imported(tree, name).is_some()) +pub(super) fn handle_type( + tree: &AnalysisContext<'_>, + session: &mut Session, + name: &str, +) -> Option { + (builtin(name) || declaration(tree, session, name).is_some() || imported(tree, name).is_some()) .then(|| handle(name)) } @@ -672,9 +701,9 @@ fn imported(tree: &AnalysisContext<'_>, name: &str) -> Option> { /// The classes whose objects the current scope may see: those it declares /// and those of the scopes it uses. -pub(super) fn visible_classes(tree: &AnalysisContext<'_>) -> Vec { +pub(super) fn visible_classes(tree: &AnalysisContext<'_>, session: &mut Session) -> Vec { let mut names = scope_declarations(tree) - .flat_map(|declaration| specializations_of(tree, declaration)) + .flat_map(|declaration| specializations_of(tree, session, declaration)) .collect::>(); for class in &scope::imported(tree).classes { if !names.contains(&class.name) { @@ -707,11 +736,12 @@ pub(super) fn handle(name: &str) -> Type { /// The class `name`, laid out with its bases. pub(super) fn class( tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, env: &HashMap, aliases: &HashMap, ) -> Converted> { - if let Some(class) = tree.state.classes.borrow().get(name) { + if let Some(class) = session.classes.get(name) { return Ok(class.clone()); } shared_class( @@ -719,6 +749,7 @@ pub(super) fn class( name, &SharedMap::from(env.clone()), &SharedMap::from(aliases.clone()), + session, ) } @@ -729,26 +760,24 @@ pub(super) fn shared_class( name: &str, env: &SharedMap, aliases: &SharedMap, + session: &mut Session, ) -> Converted> { - if let Some(class) = tree.state.classes.borrow().get(name) { + if let Some(class) = session.classes.get(name) { return Ok(class.clone()); } // A class of another scope is laid out in its own scope, where the // names it uses are declared. - let declaration = declaration(tree, name).filter(|declaration| { + let declaration = declaration(tree, session, name).filter(|declaration| { let native = tree.declarations(); enclosing_unit(native, declaration.tokens).map(|unit| unit.tokens) == tree.root_unit().ok().map(|unit| unit.tokens) }); let Some(declaration) = declaration else { let class = imported(tree, name).ok_or_else(|| unsupported(format!("class `{name}`")))?; - tree.state - .classes - .borrow_mut() - .insert(name.to_owned(), class.clone()); + session.classes.insert(name.to_owned(), class.clone()); return Ok(class); }; - let (scope_env, scope_aliases) = specializations::shared_scope(tree, name, env, aliases); + let (scope_env, scope_aliases) = specializations::shared_scope(session, name, env, aliases); // The types of the class are bound in one context of its scope. let context = PackedDimensions { const_env: scope_env.clone(), @@ -761,13 +790,14 @@ pub(super) fn shared_class( // it extends where its header is, as a class names its base below. let recorded = declaration .interface - .then(|| specializations::lookup(tree, name)) + .then(|| specializations::lookup(session, name)) .flatten() .map(|specialization| specialization.bases.clone()) .filter(|bases| { bases.len() == declaration.interfaces.len() && bases.iter().all(|base| { - self::declaration(tree, base).is_some_and(|declaration| declaration.interface) + self::declaration(tree, session, base) + .is_some_and(|declaration| declaration.interface) }) }); let interfaces = match recorded { @@ -775,26 +805,34 @@ pub(super) fn shared_class( None => declaration .interfaces .iter() - .map(|&interface| interface_name(tree, interface, env, aliases)) + .map(|&interface| interface_name(tree, session, interface, env, aliases)) .collect::>>()?, }; if declaration.interface { - return interface_class(tree, name, declaration, interfaces, env, &context); + return interface_class(tree, session, name, declaration, interfaces, env, &context); } let base = match &declaration.base { None => None, Some(base) => { // The specialization named its base where the class header is, // before the declarations it inherits could hide those names. - let recorded = specializations::lookup(tree, name) + let recorded = specializations::lookup(session, name) .and_then(|specialization| specialization.bases.first().cloned()); let ty = match recorded { Some(ty) => ty, - None => type_binding::binding::bind_in(base.data_type, native, tree, &context)? - .and_then(|ty| ty.class().map(str::to_owned)) - .ok_or_else(|| unsupported("base class type"))?, + None => { + type_binding::binding::bind_in(base.data_type, native, tree, session, &context)? + .and_then(|ty| ty.class().map(str::to_owned)) + .ok_or_else(|| unsupported("base class type"))? + } }; - Some(shared_class(tree, &ty, &scope_env, &scope_aliases)?) + Some(shared_class( + tree, + &ty, + &scope_env, + &scope_aliases, + session, + )?) } }; let mut properties = base @@ -820,11 +858,22 @@ pub(super) fn shared_class( { return Err(unsupported("static random class property")); } - let ty = - type_binding::binding::bind_in(property.declaration.data_type, native, tree, &context)? - .ok_or_else(|| unsupported("class property type"))?; + let ty = type_binding::binding::bind_in( + property.declaration.data_type, + native, + tree, + session, + &context, + )? + .ok_or_else(|| unsupported("class property type"))?; for variable in &property.declaration.variables { - let ty = containers::with_dimensions(ty.clone(), &variable.dimensions, tree, &context)?; + let ty = containers::with_dimensions( + ty.clone(), + &variable.dimensions, + tree, + session, + &context, + )?; if !ty.unpacked_ranges.is_empty() { return Err(unsupported("class property with unpacked dimensions")); } @@ -949,7 +998,7 @@ pub(super) fn shared_class( method.subroutine }; methods.retain(|known| known.name != method_name); - let (formals, result) = signature(tree, native_id, &context); + let (formals, result) = signature(tree, session, native_id, &context); methods.push(Method { name: method_name, owner: name.to_owned(), @@ -968,7 +1017,7 @@ pub(super) fn shared_class( let mut required = Vec::new(); for interface in &interfaces { required.extend( - class(tree, interface, env, aliases)? + class(tree, session, interface, env, aliases)? .methods .iter() .map(|method| (method.name.clone(), method.result.clone())), @@ -1025,7 +1074,7 @@ pub(super) fn shared_class( .and_then(|expressions| { expressions .iter() - .map(|&id| constraints::bind(id, tree, &properties, env)) + .map(|&id| constraints::bind(id, tree, session, &properties, env)) .collect() }); // Constraint indices survive overrides, including calls via base handles. @@ -1053,10 +1102,7 @@ pub(super) fn shared_class( declarations: Vec::new(), size: size.max(1), }); - tree.state - .classes - .borrow_mut() - .insert(name.to_owned(), class.clone()); + session.classes.insert(name.to_owned(), class.clone()); Ok(class) } @@ -1064,18 +1110,19 @@ pub(super) fn shared_class( /// interface class's `extends` list names (IEEE 1800-2023 8.26). fn interface_name( tree: &AnalysisContext<'_>, + session: &mut Session, interface: celox_sv_syntax::TypeId, env: &HashMap, aliases: &HashMap, ) -> Converted { let native = tree.declarations(); - let name = type_binding::procedural_type(interface, native, tree, env, aliases)? + let name = type_binding::procedural_type(interface, native, tree, session, env, aliases)? .and_then(|ty| ty.class().map(str::to_owned)) .ok_or_else(|| unsupported("implemented interface class type"))?; // An interface class of another scope is known by its layout. let interface = match imported(tree, &name) { Some(class) => class.is_interface, - None => declaration(tree, &name).is_some_and(|declaration| declaration.interface), + None => declaration(tree, session, &name).is_some_and(|declaration| declaration.interface), }; if !interface { return Err(unsupported(format!( @@ -1090,6 +1137,7 @@ fn interface_name( /// 8.26). A handle of it refers to an object of a class implementing it. fn interface_class( tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, declaration: &celox_sv_syntax::ClassDeclaration, interfaces: Vec, @@ -1107,7 +1155,7 @@ fn interface_class( let own = declarations.len(); let mut methods: Vec = Vec::new(); for interface in &interfaces { - let interface = class(tree, interface, env, aliases)?; + let interface = class(tree, session, interface, env, aliases)?; for method in &interface.methods { methods.retain(|known| known.name != method.name); methods.push(method.clone()); @@ -1138,11 +1186,11 @@ fn interface_class( // A method whose types cannot be resolved, such as one using a // type parameter or a typedef of the interface class, leaves the // interface class without a layout; it is lowered only when used. - type_binding::subroutine_formals(subroutine, tree, context)?; - return_type(tree, method.subroutine, context)?; + type_binding::subroutine_formals(subroutine, tree, session, context)?; + return_type(tree, session, method.subroutine, context)?; let method_name = instances::normalize_identifier(&subroutine.name.spelling); methods.retain(|known| known.name != method_name); - let (formals, result) = signature(tree, method.subroutine, context); + let (formals, result) = signature(tree, session, method.subroutine, context); methods.push(Method { name: method_name, owner: name.to_owned(), @@ -1171,10 +1219,7 @@ fn interface_class( declarations, size: 1, }); - tree.state - .classes - .borrow_mut() - .insert(name.to_owned(), class.clone()); + session.classes.insert(name.to_owned(), class.clone()); Ok(class) } @@ -1203,6 +1248,7 @@ fn own_declarations( /// The formal names and the return type of method `id`, see [`Method`]. fn signature( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::SubroutineId, context: &PackedDimensions, ) -> (Vec>, Option>) { @@ -1218,7 +1264,7 @@ fn signature( .map(|name| instances::normalize_identifier(&name.spelling)) }) .collect(); - let result = return_type(tree, id, context).ok().map(|ty| { + let result = return_type(tree, session, id, context).ok().map(|ty| { ty.and_then(|ty| type_parameters::resolve(&tree.functions, ty, &context.const_env)) }); (formals, result) @@ -1227,12 +1273,13 @@ fn signature( /// The return type of subroutine `id`, `None` for a task or `void`. fn return_type( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::SubroutineId, context: &PackedDimensions, ) -> Converted> { let native = tree.declarations(); match native.subroutine(id).return_type { - Some(ty) => type_binding::binding::bind_in(ty, native, tree, context), + Some(ty) => type_binding::binding::bind_in(ty, native, tree, session, context), None => Ok(None), } } @@ -1312,21 +1359,22 @@ fn class_id(name: &str) -> u32 { /// 1800-2023 8.16), laid out. fn object_classes( tree: &AnalysisContext<'_>, + session: &mut Session, ancestor: &str, env: &HashMap, aliases: &HashMap, ) -> Converted>> { let mut classes = Vec::new(); let mut ids = HashMap::default(); - for name in visible_classes(tree) { + for name in visible_classes(tree, session) { // A class that cannot be laid out has no objects. - let Ok(class) = class(tree, &name, env, aliases) else { + let Ok(class) = class(tree, session, &name, env, aliases) else { continue; }; if class.is_abstract || class.is_interface { continue; } - if !class.derives_from(tree, ancestor, env, aliases) { + if !class.derives_from(tree, session, ancestor, env, aliases) { continue; } if let Some(other) = ids.insert(class.id, name.clone()) { @@ -1344,13 +1392,14 @@ fn object_classes( /// or implementing `owner` and not abstract, whose objects run it. pub(super) fn dispatch_targets( tree: &AnalysisContext<'_>, + session: &mut Session, owner: &str, method: &str, env: &HashMap, aliases: &HashMap, ) -> Converted)>> { let mut targets: Vec<(String, Vec)> = Vec::new(); - for class in object_classes(tree, owner, env, aliases)? { + for class in object_classes(tree, session, owner, env, aliases)? { let Some(implementation) = class.method(method) else { continue; }; @@ -1367,11 +1416,12 @@ pub(super) fn dispatch_targets( /// to a variable of class `name` (IEEE 1800-2023 8.16). pub(super) fn cast_targets( tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, env: &HashMap, aliases: &HashMap, ) -> Converted> { - Ok(object_classes(tree, name, env, aliases)? + Ok(object_classes(tree, session, name, env, aliases)? .iter() .map(|class| class.id) .collect()) diff --git a/crates/celox-sv-analyzer/src/ast/classes/constraints.rs b/crates/celox-sv-analyzer/src/ast/classes/constraints.rs index d7fac4eaff5..d86791b998c 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/constraints.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/constraints.rs @@ -26,7 +26,7 @@ fn relation(op: &str, left: Typed, right: Typed) -> Typed { // Charge copies before allocating them: source nesting alone does not bound // the expanded tree of nested membership predicates. -fn bounded_clone(value: &Typed, budget: &std::cell::Cell) -> Result { +fn bounded_clone(value: &Typed, budget: &mut usize) -> Result { let mut pending = vec![value]; while let Some(value) = pending.pop() { charge(budget)?; @@ -39,12 +39,10 @@ fn bounded_clone(value: &Typed, budget: &std::cell::Cell) -> Result) -> Result<(), String> { - let remaining = budget - .get() +fn charge(budget: &mut usize) -> Result<(), String> { + *budget = budget .checked_sub(1) .ok_or("constraint expression expansion limit")?; - budget.set(remaining); Ok(()) } @@ -113,15 +111,17 @@ fn emit(value: Typed, context: Option<(u32, bool)>) -> ConstraintExpr { pub(in crate::ast) fn bind( id: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, properties: &[Property], env: &HashMap, ) -> Result { - bind_inputs(id, tree, properties, env, &HashMap::default()) + bind_inputs(id, tree, session, properties, env, &HashMap::default()) } pub(in crate::ast) fn bind_inputs( id: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, properties: &[Property], env: &HashMap, inputs: &HashMap, @@ -129,20 +129,32 @@ pub(in crate::ast) fn bind_inputs( fn expression( id: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, properties: &[Property], env: &HashMap, inputs: &HashMap, depth: usize, - budget: &std::cell::Cell, + budget: &mut usize, ) -> Result { if depth > 64 { return Err("constraint expression nesting limit".into()); } charge(budget)?; - let recurse = |id| expression(id, tree, properties, env, inputs, depth + 1, budget); + let recurse = |session: &mut Session, budget: &mut usize, id| { + expression( + id, + tree, + session, + properties, + env, + inputs, + depth + 1, + budget, + ) + }; let native = tree.declarations(); Ok(match &native.expression(id).kind { - ExprKind::Group(id) => return recurse(*id), + ExprKind::Group(id) => return recurse(session, budget, *id), ExprKind::Name(name) => { let name = instances::normalize_identifier(&name.spelling); if let Some((index, property)) = properties @@ -209,7 +221,7 @@ pub(in crate::ast) fn bind_inputs( expression, postfix: false, } if matches!(operator.as_str(), "+" | "-" | "~" | "!") => { - let value = recurse(*expression)?; + let value = recurse(session, budget, *expression)?; if operator == "+" { return Ok(value); } @@ -224,7 +236,7 @@ pub(in crate::ast) fn bind_inputs( operator, right, } if operator == "inside" => { - let value = recurse(*left)?; + let value = recurse(session, budget, *left)?; let ExprKind::Set(items) = &native.expression(*right).kind else { return Err("constraint inside set".into()); }; @@ -237,10 +249,11 @@ pub(in crate::ast) fn bind_inputs( for item in items { use celox_sv_syntax::DimensionKind; let (low, high) = match item.kind { - DimensionKind::Index(id) => (recurse(id)?, None), - DimensionKind::Range { left, right } => { - (recurse(left)?, Some(recurse(right)?)) - } + DimensionKind::Index(id) => (recurse(session, budget, id)?, None), + DimensionKind::Range { left, right } => ( + recurse(session, budget, left)?, + Some(recurse(session, budget, right)?), + ), _ => return Err("constraint inside range".into()), }; for operand in std::iter::once(&low).chain(high.iter()) { @@ -305,8 +318,8 @@ pub(in crate::ast) fn bind_inputs( | "||" ) => { - let a = recurse(*left)?; - let b = recurse(*right)?; + let a = recurse(session, budget, *left)?; + let b = recurse(session, budget, *right)?; let width = a.width.max(b.width); let signed = a.signed && b.signed; let logical = matches!(operator.as_str(), "&&" | "||"); @@ -321,16 +334,8 @@ pub(in crate::ast) fn bind_inputs( _ => return Err("unsupported scalar constraint expression".into()), }) } - expression( - id, - tree, - properties, - env, - inputs, - 0, - &std::cell::Cell::new(16_384), - ) - .map(|value| emit(value, None)) + expression(id, tree, session, properties, env, inputs, 0, &mut 16_384) + .map(|value| emit(value, None)) } impl Class { diff --git a/crates/celox-sv-analyzer/src/ast/classes/foreign.rs b/crates/celox-sv-analyzer/src/ast/classes/foreign.rs index ab8ccb1a441..1c60d8eb35d 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/foreign.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/foreign.rs @@ -2,13 +2,11 @@ use super::*; use crate::ast::scope::ScopeSymbols; use specializations::BoundArguments; -use std::cell::{Cell, RefCell}; #[derive(Debug)] struct Owner { tree: Rc, imports: ScopeSymbols, - calls: Rc>, timescales: Arc, } @@ -43,77 +41,65 @@ impl DeclarationScope { } } -#[derive(Debug, Default)] +#[derive(Clone, Debug, Default)] pub(in crate::ast) struct Registry { - owners: RefCell>>, - templates: RefCell>, - requests: RefCell>>, - prepared: RefCell>, - complete: RefCell>, - argument_symbols: RefCell, - active: RefCell>, - states: RefCell>, - revision: Cell, - generics: RefCell>, - specializations: RefCell>>, - declarations: RefCell>>, - /// The design's virtual interfaces, which a specialization's scope may - /// name as type arguments (IEEE 1800-2023 25.9). - virtual_interfaces: RefCell>>, + owners: HashMap>, + templates: HashMap, + requests: HashMap>, + prepared: HashMap, + complete: HashSet, + argument_symbols: ScopeSymbols, + active: HashSet, + states: HashMap, + revision: u64, + generics: HashMap, + specializations: HashMap>, + declarations: HashMap>, } impl Registry { - pub fn set_virtual_interfaces( - &self, - declarations: Option>, - ) { - *self.virtual_interfaces.borrow_mut() = declarations; - } pub fn revision(&self) -> u64 { - self.revision.get() + self.revision } pub fn has_templates(&self) -> bool { - !self.templates.borrow().is_empty() + !self.templates.is_empty() } pub fn generic(&self, name: &str) -> Option { - self.generics.borrow().get(name).cloned() + self.generics.get(name).cloned() } /// The specialization `name` that the scope of its class made. pub fn specialization(&self, name: &str) -> Option> { - self.specializations.borrow().get(name).cloned() + self.specializations.get(name).cloned() } pub fn parameter(&self, name: &str, parameter: &str) -> Option { self.declarations - .borrow() .get(name)? .literals .get(parameter) .cloned() } pub fn declarations(&self, name: &str) -> Option> { - self.declarations.borrow().get(name).cloned() + self.declarations.get(name).cloned() } pub fn member_type(&self, name: &str, member: &str) -> Option { self.prepared - .borrow() .values() .find_map(|symbols| symbols.class_member_types.get(name)?.get(member).cloned()) } pub fn names(&self) -> Vec { - self.templates.borrow().keys().cloned().collect() + self.templates.keys().cloned().collect() } pub fn contains(&self, name: &str) -> bool { - self.templates.borrow().contains_key(name) + self.templates.contains_key(name) } pub fn register( - &self, + &mut self, name: &str, tree: &SyntaxTree, imports: &ScopeSymbols, - calls: Rc>, timescales: Arc, ) { - if self.owners.borrow().contains_key(name) { + if self.owners.contains_key(name) { return; } let scope = tree.root_unit().ok().map(|unit| unit.tokens); @@ -122,7 +108,7 @@ impl Registry { && enclosing_unit(tree.declarations(), declaration.tokens).map(|unit| unit.tokens) == scope { - self.templates.borrow_mut().insert( + self.templates.insert( format!( "{}::{}", name, @@ -132,12 +118,11 @@ impl Registry { ); } } - self.owners.borrow_mut().insert( + self.owners.insert( name.into(), Rc::new(Owner { tree: Rc::new(tree.clone()), imports: imports.clone(), - calls, timescales, }), ); @@ -146,8 +131,8 @@ impl Registry { let local_classes = scope_declarations(tree) .map(|class| declared_name(tree, class)) .collect::>(); - for (owner, extra) in self.prepared.borrow().iter() { - if self.active.borrow().contains(owner) { + for (owner, extra) in self.prepared.iter() { + if self.active.contains(owner) { continue; } // An owner may import a caller's static field while binding T's @@ -186,366 +171,403 @@ impl Registry { symbols.declarations_only = declarations_only; } } - pub fn states(&self) -> HashMap { - self.states.borrow().clone() + pub fn states(&self) -> &HashMap { + &self.states } +} - pub fn request( - self: &Rc, +/// The name of the specialization of package class template `generic` with +/// `arguments`, which the scope of the package makes. +pub(in crate::ast) fn request( + tree: &AnalysisContext<'_>, + session: &mut Session, + generic: &str, + arguments: &[celox_sv_syntax::Argument], + context: &PackedDimensions, +) -> Converted> { + let registry = &session.foreign; + let Some(owner_name) = registry.templates.get(generic).cloned() else { + return Ok(None); + }; + let owner = registry.owners[&owner_name].clone(); + let native = owner.tree.declarations(); + // The source can declare classes of the same name in other scopes; + // the template is the one the owner package declares, as `register` + // found it. + let scope = owner.tree.root_unit().ok().map(|unit| unit.tokens); + let declaration = native + .classes + .iter() + .find(|class| { + enclosing_unit(native, class.tokens).map(|unit| unit.tokens) == scope + && format!( + "{}::{}", + owner_name, + instances::normalize_identifier(&class.name.spelling) + ) == generic + }) + .ok_or_else(|| unsupported(format!("class template `{generic}`")))?; + let Some(arguments) = specializations::bind_arguments( + tree, + session, + generic, + declaration, + native, + arguments, + context, + )? + else { + return Ok(None); + }; + // Module-local class names do not yet carry instance identity. They + // cannot safely key a design-wide package specialization (8.25). + fn module_class<'a>( tree: &AnalysisContext<'_>, - generic: &str, - arguments: &[celox_sv_syntax::Argument], - context: &PackedDimensions, - ) -> Converted> { - let Some(owner_name) = self.templates.borrow().get(generic).cloned() else { - return Ok(None); - }; - let owner = self.owners.borrow()[&owner_name].clone(); - let native = owner.tree.declarations(); - // The source can declare classes of the same name in other scopes; - // the template is the one the owner package declares, as `register` - // found it. - let scope = owner.tree.root_unit().ok().map(|unit| unit.tokens); - let declaration = native - .classes - .iter() - .find(|class| { - enclosing_unit(native, class.tokens).map(|unit| unit.tokens) == scope - && format!( - "{}::{}", - owner_name, - instances::normalize_identifier(&class.name.spelling) - ) == generic - }) - .ok_or_else(|| unsupported(format!("class template `{generic}`")))?; - let Some(arguments) = specializations::bind_arguments( - tree, - generic, - declaration, - native, - arguments, - context, - )? - else { - return Ok(None); - }; - // Module-local class names do not yet carry instance identity. They - // cannot safely key a design-wide package specialization (8.25). - fn module_class<'a>(tree: &AnalysisContext<'_>, ty: &'a Type) -> Option<&'a str> { - ty.class() - .filter(|class| { - !class.contains("::") - || super::declaration(tree, class).is_some_and(|declaration| { - enclosing_unit(tree.declarations(), declaration.tokens) - .is_some_and(|unit| unit.kind != celox_sv_syntax::UnitKind::Package) - }) - }) - .or_else(|| { - let container = ty.container.as_ref()?; - module_class(tree, &container.element).or_else(|| { - container - .key - .as_ref() - .and_then(|key| module_class(tree, key)) + session: &mut Session, + ty: &'a Type, + ) -> Option<&'a str> { + ty.class() + .filter(|class| { + !class.contains("::") + || super::declaration(tree, session, class).is_some_and(|declaration| { + enclosing_unit(tree.declarations(), declaration.tokens) + .is_some_and(|unit| unit.kind != celox_sv_syntax::UnitKind::Package) }) + }) + .or_else(|| { + let container = ty.container.as_ref()?; + module_class(tree, session, &container.element).or_else(|| { + container + .key + .as_ref() + .and_then(|key| module_class(tree, session, key)) }) - } - if let Some(class) = arguments - .types - .values() - .find_map(|ty| module_class(tree, ty)) + }) + } + if let Some(class) = arguments + .types + .values() + .find_map(|ty| module_class(tree, session, ty)) + { + return Err(unsupported(format!( + "module-local class `{class}` as a package class type argument" + ))); + } + let index = { + let registry = &mut session.foreign; + let requests = registry.requests.entry(owner_name.clone()).or_default(); + match requests + .iter() + .position(|r| r.generic == generic && r.arguments == arguments) { - return Err(unsupported(format!( - "module-local class `{class}` as a package class type argument" - ))); - } - let index = { - let mut requests = self.requests.borrow_mut(); - let requests = requests.entry(owner_name.clone()).or_default(); - match requests - .iter() - .position(|r| r.generic == generic && r.arguments == arguments) - { - Some(index) => index, - None => { - if requests.len() >= 1024 { - return Err(unsupported("more than 1024 foreign class specializations")); - } - requests.push(Request { - generic: generic.into(), - arguments, - name: None, - }); - self.complete.borrow_mut().remove(&owner_name); - requests.len() - 1 + Some(index) => index, + None => { + if requests.len() >= 1024 { + return Err(unsupported("more than 1024 foreign class specializations")); } + requests.push(Request { + generic: generic.into(), + arguments, + name: None, + }); + registry.complete.remove(&owner_name); + requests.len() - 1 } - }; - if self.requests.borrow()[&owner_name][index].name.is_none() { - self.build(&owner_name, None)?; } - Ok(self.requests.borrow()[&owner_name][index].name.clone()) + }; + if session.foreign.requests[&owner_name][index].name.is_none() { + build(session, &owner_name, None)?; } + Ok(session.foreign.requests[&owner_name][index].name.clone()) +} + +fn build(session: &mut Session, name: &str, caller: Option<&ScopeSymbols>) -> Converted<()> { + if session.foreign.active.len() >= 16 { + return Err(unsupported("foreign class scopes nested more than 16 deep")); + } + if !session.foreign.active.insert(name.into()) { + return Ok(()); + } + let result = build_inner(session, name, caller); + session.foreign.active.remove(name); + result +} - fn build(self: &Rc, name: &str, caller: Option<&ScopeSymbols>) -> Converted<()> { - if self.active.borrow().len() >= 16 { - return Err(unsupported("foreign class scopes nested more than 16 deep")); +/// Analyzes package `name` for the specializations requested of its class +/// templates, in a session of its own that takes over the registry, the +/// types and the call sites of `session` and gives them back. +fn build_inner(session: &mut Session, name: &str, caller: Option<&ScopeSymbols>) -> Converted<()> { + let owner = session.foreign.owners[name].clone(); + let requests = &session.foreign.requests[name]; + let mut scope = Session { + foreign_arguments: requests + .iter() + .map(|r| (r.generic.clone(), r.arguments.clone())) + .collect(), + foreign: std::mem::take(&mut session.foreign), + types: std::mem::take(&mut session.types), + virtual_interfaces: session.virtual_interfaces.clone(), + next_call_site: session.next_call_site, + ..Session::default() + }; + let result = specialize(&mut scope, &owner, name, caller); + session.foreign = scope.foreign; + session.types = scope.types; + session.next_call_site = scope.next_call_site; + let mut symbols = result?; + let registry = &mut session.foreign; + for request in registry.requests.get_mut(name).unwrap() { + if let Some((_, _, bound)) = scope.foreign_names.iter().find(|(generic, arguments, _)| { + generic == &request.generic && arguments == &request.arguments + }) { + request.name = Some(bound.clone()); } - if !self.active.borrow_mut().insert(name.into()) { - return Ok(()); + } + for (class, specialization) in &scope.class_specializations { + registry + .generics + .insert(class.clone(), specialization.generic.clone()); + registry + .specializations + .insert(class.clone(), specialization.clone()); + } + registry.declarations.extend(symbols.declarations.drain()); + registry.prepared.insert(name.into(), symbols.symbols); + if caller.is_some() { + registry.complete.insert(name.into()); + if let Some(module) = symbols.state_module { + registry.states.insert(name.into(), module); } - let result = self.build_inner(name, caller); - self.active.borrow_mut().remove(name); - result } - fn build_inner(self: &Rc, name: &str, caller: Option<&ScopeSymbols>) -> Converted<()> { - let owner = self.owners.borrow()[name].clone(); - let requests = self.requests.borrow()[name].clone(); - let state = Rc::new(AnalysisState { - foreign: self.clone(), - virtual_interfaces: self.virtual_interfaces.borrow().clone(), - next_call_site: owner.calls.clone(), - foreign_arguments: RefCell::new( - requests - .iter() - .map(|r| (r.generic.clone(), r.arguments.clone())) - .collect(), - ), + registry.revision += 1; + Ok(()) +} + +/// What analyzing a package for its specializations made. +struct Specialized { + symbols: ScopeSymbols, + declarations: HashMap>, + state_module: Option, +} + +fn specialize( + session: &mut Session, + owner: &Owner, + name: &str, + caller: Option<&ScopeSymbols>, +) -> Converted { + let context = AnalysisContext { + syntax_tree: &owner.tree, + 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 mut imports = owner.imports.clone(); + if let Some(caller) = caller { + // Preserve the owner's existing bindings when caller metadata also + // contains imported classes or routines from that package. + imports.extend(&ScopeSymbols { + classes: caller.classes.clone(), + class_member_types: caller.class_member_types.clone(), + state_signals: caller + .state_signals + .iter() + .filter(|signal| { + !signal.name().starts_with(&format!("{name}::")) + && signal + .package_variable + .as_ref() + .is_none_or(|(owner, _)| owner != name) + }) + .cloned() + .collect(), + // Only qualified routines, the methods of classes the actual + // type arguments name: a body of the package resolves an + // unqualified call in its own scope, not the caller's (26.3). + subroutine_params: qualified(&caller.subroutine_params), + subroutine_shapes: qualified(&caller.subroutine_shapes), + subroutines: caller + .subroutines + .iter() + .filter(|subroutine| subroutine.name.contains("::")) + .cloned() + .collect(), + function_return_types: qualified(&caller.function_return_types), ..Default::default() }); - let context = AnalysisContext { - syntax_tree: &owner.tree, - state: state.clone(), - 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 mut imports = owner.imports.clone(); - if let Some(caller) = caller { - // Preserve the owner's existing bindings when caller metadata also - // contains imported classes or routines from that package. - imports.extend(&ScopeSymbols { - classes: caller.classes.clone(), - class_member_types: caller.class_member_types.clone(), - state_signals: caller - .state_signals - .iter() - .filter(|signal| { - !signal.name().starts_with(&format!("{name}::")) - && signal - .package_variable - .as_ref() - .is_none_or(|(owner, _)| owner != name) - }) - .cloned() - .collect(), - // Only qualified routines, the methods of classes the actual - // type arguments name: a body of the package resolves an - // unqualified call in its own scope, not the caller's (26.3). - subroutine_params: qualified(&caller.subroutine_params), - subroutine_shapes: qualified(&caller.subroutine_shapes), - subroutines: caller - .subroutines - .iter() - .filter(|subroutine| subroutine.name.contains("::")) - .cloned() - .collect(), - function_return_types: qualified(&caller.function_return_types), - ..Default::default() - }); - } else { - imports.declarations_only = true; - } - // Like every scope, a specialization may reach the interface - // instances through virtual interfaces (IEEE 1800-2023 25.9). - if let Some(declarations) = crate::ast::virtual_interfaces::declarations(&state) { - for signal in crate::ast::virtual_interfaces::member_signals(declarations) { - if !imports - .state_signals - .iter() - .any(|known| known.name == signal.name) - { - imports.state_signals.push(signal); - } + } else { + imports.declarations_only = true; + } + // Like every scope, a specialization may reach the interface + // instances through virtual interfaces (IEEE 1800-2023 25.9). + if let Some(declarations) = crate::ast::virtual_interfaces::declarations(session) { + for signal in crate::ast::virtual_interfaces::member_signals(declarations) { + if !imports + .state_signals + .iter() + .any(|known| known.name == signal.name) + { + imports.state_signals.push(signal); } } - let self_qualified = imports::ScopeImports::from_scope(&context)? - .qualified + } + let self_qualified = imports::ScopeImports::from_scope(&context)? + .qualified + .iter() + .any(|(package, _)| package == name); + let mut package = packages::analyze_package_with_symbols( + name, + &context, + session, + imports.clone(), + HashMap::default(), + None, + )?; + if self_qualified { + let context = AnalysisContext { + package: None, + ..context.clone() + }; + // Class statics already have qualified names. Unlike ordinary + // package variables, their new declarations would collide with + // the first pass's imported storage. + let statics = package + .symbols + .classes .iter() - .any(|(package, _)| package == name); - let mut package = packages::analyze_package_with_symbols( + .flat_map(|class| class.statics.iter()) + .filter(|property| property.owner.starts_with(&format!("{name}::"))) + .map(|property| property.variable.clone()) + .collect(); + let own_items = package.symbols.clone().without(&statics); + package = packages::analyze_package_with_symbols( name, &context, - imports.clone(), + session, + imports, HashMap::default(), - None, + Some(&own_items), )?; - if self_qualified { - let context = AnalysisContext { - package: None, - ..context.clone() - }; - // Class statics already have qualified names. Unlike ordinary - // package variables, their new declarations would collide with - // the first pass's imported storage. - let statics = package - .symbols - .classes - .iter() - .flat_map(|class| class.statics.iter()) - .filter(|property| property.owner.starts_with(&format!("{name}::"))) - .map(|property| property.variable.clone()) - .collect(); - let own_items = package.symbols.clone().without(&statics); - package = packages::analyze_package_with_symbols( - name, - &context, - imports, - HashMap::default(), - Some(&own_items), - )?; - } - if let Some(error) = state.foreign_error.borrow_mut().take() { - return Err(error); + } + if let Some(error) = session.foreign_error.take() { + return Err(error); + } + let mut symbols = package.symbols; + symbols.aliases.clear(); + symbols.declarations_only = false; + let declarations = + specializations::export_declarations(&context, session, &symbols.class_member_types); + Ok(Specialized { + symbols, + declarations, + state_module: package.state_module.filter(|_| caller.is_some()), + }) +} + +/// Records what scope `tree` declared that specializations of package class +/// templates may name, and makes the specializations still to be made. +pub(in crate::ast) fn finish( + tree: &AnalysisContext<'_>, + session: &mut Session, + caller: &ScopeSymbols, +) -> Converted<()> { + let declarations = + specializations::export_declarations(tree, session, &caller.class_member_types); + session.foreign.declarations.extend(declarations); + let package_owner = match tree.root_unit() { + Ok(unit) if unit.kind == celox_sv_syntax::UnitKind::Package => { + Some(instances::normalize_identifier(&unit.name.spelling)) } - let mut symbols = package.symbols; - symbols.aliases.clear(); - symbols.declarations_only = false; - for request in self.requests.borrow_mut().get_mut(name).unwrap() { - if let Some((_, _, bound)) = - state - .foreign_names - .borrow() + Err(_) => Some(packages::UNIT.to_owned()), + _ => None, + }; + { + let known = &mut session.foreign.argument_symbols; + known + .class_member_types + .extend(caller.class_member_types.clone()); + let variables = caller + .classes + .iter() + .flat_map(|class| { + class + .statics .iter() - .find(|(generic, arguments, _)| { - generic == &request.generic && arguments == &request.arguments - }) - { - request.name = Some(bound.clone()); - } - } - for (class, specialization) in state.class_specializations.borrow().iter() { - self.generics - .borrow_mut() - .insert(class.clone(), specialization.generic.clone()); - self.specializations - .borrow_mut() - .insert(class.clone(), specialization.clone()); - } - let declarations = - specializations::export_declarations(&context, &symbols.class_member_types); - self.declarations.borrow_mut().extend(declarations); - self.prepared.borrow_mut().insert(name.into(), symbols); - if caller.is_some() { - self.complete.borrow_mut().insert(name.into()); - if let Some(module) = package.state_module { - self.states.borrow_mut().insert(name.into(), module); - } - } - self.revision.set(self.revision.get() + 1); - Ok(()) - } - pub fn finish( - self: &Rc, - tree: &AnalysisContext<'_>, - caller: &ScopeSymbols, - ) -> Converted<()> { - let declarations = specializations::export_declarations(tree, &caller.class_member_types); - self.declarations.borrow_mut().extend(declarations); - let package_owner = match tree.root_unit() { - Ok(unit) if unit.kind == celox_sv_syntax::UnitKind::Package => { - Some(instances::normalize_identifier(&unit.name.spelling)) - } - Err(_) => Some(packages::UNIT.to_owned()), - _ => None, - }; + .map(|property| property.variable.as_str()) + }) + .collect::>(); + for signal in caller + .signals + .iter() + .chain(&caller.state_signals) + .filter(|signal| variables.contains(signal.name())) { - let mut known = self.argument_symbols.borrow_mut(); - known - .class_member_types - .extend(caller.class_member_types.clone()); - let variables = caller - .classes + if !known + .state_signals .iter() - .flat_map(|class| { - class - .statics - .iter() - .map(|property| property.variable.as_str()) - }) - .collect::>(); - for signal in caller - .signals - .iter() - .chain(&caller.state_signals) - .filter(|signal| variables.contains(signal.name())) + .any(|old| old.name == signal.name) { - if !known - .state_signals - .iter() - .any(|old| old.name == signal.name) + let mut signal = signal.clone(); + if signal.package_variable.is_none() + && let Some(owner) = &package_owner { - let mut signal = signal.clone(); - if signal.package_variable.is_none() - && let Some(owner) = &package_owner - { - signal.package_variable = Some((owner.clone(), signal.name().into())); - } - known.state_signals.push(signal); + signal.package_variable = Some((owner.clone(), signal.name().into())); } + known.state_signals.push(signal); } + } - for class in &caller.classes { - if !known.classes.iter().any(|old| old.name == class.name) { - known.classes.push(class.clone()); - } + for class in &caller.classes { + if !known.classes.iter().any(|old| old.name == class.name) { + known.classes.push(class.clone()); } - known - .subroutine_params - .extend(caller.subroutine_params.clone()); - known - .subroutine_shapes - .extend(caller.subroutine_shapes.clone()); - for subroutine in &caller.subroutines { - if !known - .subroutines - .iter() - .any(|old| old.name == subroutine.name) - { - known.subroutines.push(subroutine.clone()); - } - } - known - .function_return_types - .extend(caller.function_return_types.clone()); } - let caller = self.argument_symbols.borrow().clone(); - let names = self - .requests - .borrow() - .keys() - .filter(|name| { - !self.complete.borrow().contains(*name) && !self.active.borrow().contains(*name) - }) - .cloned() - .collect::>(); - for name in names { - self.build(&name, Some(&caller))?; + known + .subroutine_params + .extend(caller.subroutine_params.clone()); + known + .subroutine_shapes + .extend(caller.subroutine_shapes.clone()); + for subroutine in &caller.subroutines { + if !known + .subroutines + .iter() + .any(|old| old.name == subroutine.name) + { + known.subroutines.push(subroutine.clone()); + } } - Ok(()) + known + .function_return_types + .extend(caller.function_return_types.clone()); + } + let registry = &session.foreign; + let caller = registry.argument_symbols.clone(); + let names = registry + .requests + .keys() + .filter(|name| !registry.complete.contains(*name) && !registry.active.contains(*name)) + .cloned() + .collect::>(); + for name in names { + build(session, &name, Some(&caller))?; } + Ok(()) } -pub(in crate::ast) fn is_foreign(tree: &AnalysisContext<'_>, generic: &str) -> bool { - let registry = &tree.state.foreign; - let Some(owner) = registry.templates.borrow().get(generic).cloned() else { +pub(in crate::ast) fn is_foreign( + tree: &AnalysisContext<'_>, + session: &Session, + generic: &str, +) -> bool { + let Some(owner) = session.foreign.templates.get(generic) else { return false; }; tree.root_unit() diff --git a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs index c15c56883fa..aedb0f3966f 100644 --- a/crates/celox-sv-analyzer/src/ast/classes/specializations.rs +++ b/crates/celox-sv-analyzer/src/ast/classes/specializations.rs @@ -8,6 +8,7 @@ //! `C` is the default specialization there too. A class without parameters //! is its own only specialization. +use crate::ast::Session; use std::rc::Rc; use super::*; @@ -58,13 +59,13 @@ fn inherited<'a>( /// The specialization `name` and the ones it inherits from, each after /// those it inherits from. -fn lineage(tree: &AnalysisContext<'_>, name: &str) -> Vec> { +fn lineage(session: &Session, name: &str) -> Vec> { let mut lineage: Vec> = Vec::new(); let mut seen = HashSet::default(); // A class that extends itself is rejected where it is laid out. let mut pending = vec![(name.to_owned(), false)]; while let Some((name, visited)) = pending.pop() { - let Some(specialization) = lookup(tree, &name) else { + let Some(specialization) = lookup(session, &name) else { continue; }; if visited { @@ -94,25 +95,6 @@ const MAX_SPECIALIZATIONS: usize = 1024; /// extends a specialization of itself would exceed. const MAX_NESTING: usize = 64; -/// A specialization in `class_specializations_building`, which it leaves -/// when dropped. -struct Building<'a>(&'a std::cell::RefCell>); - -impl Drop for Building<'_> { - fn drop(&mut self) { - self.0.borrow_mut().pop(); - } -} - -/// The specialization being made, which [`specialize`] leaves when dropped. -struct Nesting<'a>(&'a std::cell::Cell); - -impl Drop for Nesting<'_> { - fn drop(&mut self) { - self.0.set(self.0.get() - 1); - } -} - /// The key under which the scope of a class finds the specialization being /// declared: inside a parameterized class and its out-of-block methods, /// its name alone as the prefix of `::` refers to it, while as a type the @@ -122,20 +104,19 @@ pub(in crate::ast) fn scope_key(generic: &str) -> String { } /// The specialization `name`, if one has been made. -pub(in crate::ast) fn lookup(tree: &AnalysisContext<'_>, name: &str) -> Option> { - tree.state +pub(in crate::ast) fn lookup(session: &Session, name: &str) -> Option> { + session .class_specializations - .borrow() .iter() .find(|(known, _)| known == name) .map(|(_, specialization)| specialization.clone()) } /// The class declaration that class `name` specializes. -pub(in crate::ast) fn generic(tree: &AnalysisContext<'_>, name: &str) -> String { - lookup(tree, name).map_or_else( +pub(in crate::ast) fn generic(session: &Session, name: &str) -> String { + lookup(session, name).map_or_else( || { - tree.state + session .foreign .generic(name) .unwrap_or_else(|| name.to_owned()) @@ -146,10 +127,9 @@ pub(in crate::ast) fn generic(tree: &AnalysisContext<'_>, name: &str) -> String /// The specializations made of the class declared as `generic`, in the /// order they were made. -pub(in crate::ast) fn of(tree: &AnalysisContext<'_>, generic: &str) -> Vec { - tree.state +pub(in crate::ast) fn of(session: &mut Session, generic: &str) -> Vec { + session .class_specializations - .borrow() .iter() .filter(|(_, specialization)| specialization.generic == generic) .map(|(name, _)| name.clone()) @@ -159,26 +139,26 @@ pub(in crate::ast) fn of(tree: &AnalysisContext<'_>, generic: &str) -> Vec, + session: &mut Session, name: &str, env: &HashMap, aliases: &HashMap, ) -> (HashMap, HashMap) { - let (env, aliases) = shared_scope(tree, name, &env.clone().into(), &aliases.clone().into()); + let (env, aliases) = shared_scope(session, name, &env.clone().into(), &aliases.clone().into()); (env.into_iter().collect(), aliases.into_iter().collect()) } /// [`scope`] of shared tables, which are copied only when the class adds /// parameters or inherited types to them. pub(in crate::ast) fn shared_scope( - tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, env: &SharedMap, aliases: &SharedMap, ) -> (SharedMap, SharedMap) { let mut env = env.clone(); let mut aliases = aliases.clone(); - let edits = ScopeEdits::of(tree, name); + let edits = ScopeEdits::of(session, name); if !edits.env.is_empty() { for (key, value) in edits.env { match value { @@ -202,16 +182,16 @@ struct ScopeEdits { } impl ScopeEdits { - fn of(tree: &AnalysisContext<'_>, name: &str) -> Self { + fn of(session: &mut Session, name: &str) -> Self { let mut edits = Self { env: Vec::new(), aliases: Vec::new(), }; - let own = generic(tree, name); - for specialization in lineage(tree, name) { + let own = generic(session, name); + for specialization in lineage(session, name) { for base in &specialization.bases { - if lookup(tree, base).is_none() - && let Some(scope) = tree.state.foreign.declarations(base) + if lookup(session, base).is_none() + && let Some(scope) = session.foreign.declarations(base) { edits .env @@ -262,18 +242,18 @@ impl ClassScopes { /// `aliases`, the same as [`shared_scope`] gives. pub(in crate::ast) fn with( &mut self, - tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, env: &SharedMap, aliases: &SharedMap, - f: impl FnOnce(&SharedMap, &SharedMap) -> R, + f: impl FnOnce(&mut Session, &SharedMap, &SharedMap) -> R, ) -> R { // The copy follows the tables it was made from. if self.base.0.identity() != env.identity() || self.base.1.identity() != aliases.identity() { *self = Self::new(env, aliases); } - let edits = ScopeEdits::of(tree, name); + let edits = ScopeEdits::of(session, name); #[cfg(test)] if !edits.env.is_empty() && self.env.is_shared() || !edits.aliases.is_empty() && self.aliases.is_shared() @@ -294,7 +274,7 @@ impl ClassScopes { let old = self.aliases.insert(key.clone(), ty); aliases_undo.push((key, old)); } - let result = f(&self.env, &self.aliases); + let result = f(session, &self.env, &self.aliases); for (key, old) in env_undo.into_iter().rev() { match old { Some(old) => self.env.insert(key, old), @@ -316,20 +296,21 @@ impl ClassScopes { /// scope around their declarations. fn inherit( tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, own: &str, env: &mut HashMap, aliases: &mut HashMap, ) { - if lookup(tree, name).is_none() { - if let Some(scope) = tree.state.foreign.declarations(name) { + if lookup(session, name).is_none() { + if let Some(scope) = session.foreign.declarations(name) { scope.apply(env, aliases); } if let Some(members) = scope::imported(tree).class_member_types.get(name) { aliases.extend(members.clone()); } } - for specialization in lineage(tree, name) { + for specialization in lineage(session, name) { for (key, value) in &specialization.declared_env { match value { Some(value) => env.insert(key.clone(), *value), @@ -351,18 +332,18 @@ fn inherit( /// `dimensions` and `literals` with the parameters of class `name` added, /// for binding the bodies of its methods. pub(in crate::ast) fn body_scope( - tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, dimensions: &PackedDimensions, literals: &HashMap, ) -> (PackedDimensions, HashMap) { let mut dimensions = dimensions.clone(); let mut literals = literals.clone(); - let own = generic(tree, name); - for specialization in lineage(tree, name) { + let own = generic(session, name); + for specialization in lineage(session, name) { for base in &specialization.bases { - if lookup(tree, base).is_none() - && let Some(scope) = tree.state.foreign.declarations(base) + if lookup(session, base).is_none() + && let Some(scope) = session.foreign.declarations(base) { scope.apply(&mut dimensions.const_env, &mut dimensions.type_aliases); literals.extend(scope.literals.clone()); @@ -388,11 +369,11 @@ pub(in crate::ast) fn body_scope( /// The value of parameter `parameter` of class `name`, as a literal. pub(in crate::ast) fn parameter( - tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, parameter: &str, ) -> Option { - lineage(tree, name) + lineage(session, name) .iter() .rev() .find_map(|specialization| { @@ -400,15 +381,16 @@ pub(in crate::ast) fn parameter( specialization .bases .iter() - .filter(|base| lookup(tree, base).is_none()) - .find_map(|base| tree.state.foreign.parameter(base, parameter)) + .filter(|base| lookup(session, base).is_none()) + .find_map(|base| session.foreign.parameter(base, parameter)) }) }) - .or_else(|| tree.state.foreign.parameter(name, parameter)) + .or_else(|| session.foreign.parameter(name, parameter)) } pub(in crate::ast) fn export_declarations( tree: &AnalysisContext<'_>, + session: &mut Session, members: &HashMap>, ) -> HashMap> { // Only compilation-unit and package declarations have a design-wide name. @@ -421,17 +403,16 @@ pub(in crate::ast) fn export_declarations( let own = super::scope_declarations(tree) .map(|class| super::declared_name(tree, class)) .collect::>(); - tree.state + session .class_specializations - .borrow() .iter() .filter(|(_, specialization)| own.contains(&specialization.generic)) .map(|(name, _)| { let mut scope = super::foreign::DeclarationScope::default(); - for specialization in lineage(tree, name) { + for specialization in lineage(session, name) { for base in &specialization.bases { - if lookup(tree, base).is_none() - && let Some(parent) = tree.state.foreign.declarations(base) + if lookup(session, base).is_none() + && let Some(parent) = session.foreign.declarations(base) { scope.env.extend(parent.env.clone()); scope.literals.extend(parent.literals.clone()); @@ -450,14 +431,15 @@ pub(in crate::ast) fn export_declarations( /// or inherited. pub(in crate::ast) fn member_type( tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, member: &str, ) -> Option { if name == super::super::processes::CLASS { return (member == "state").then(super::super::processes::state_type); } - let generic = generic(tree, name); - lineage(tree, name) + let generic = generic(session, name); + lineage(session, name) .iter() .rev() .find_map(|specialization| { @@ -473,7 +455,7 @@ pub(in crate::ast) fn member_type( .get(member) .cloned() }) - .or_else(|| tree.state.foreign.member_type(name, member)) + .or_else(|| session.foreign.member_type(name, member)) } /// Only types declared by a class and its bases cross the scope boundary. @@ -481,15 +463,16 @@ pub(in crate::ast) fn member_type( /// reinterpret them (6.18, 8.13, 8.23, 8.25). pub(in crate::ast) fn export_member_types( tree: &AnalysisContext<'_>, + session: &mut Session, ) -> HashMap> { let imported = scope::imported(tree); let mut result = imported.class_member_types.clone(); for declaration in super::scope_declarations(tree) { - for name in super::specializations_of(tree, declaration) { + for name in super::specializations_of(tree, session, declaration) { let mut members = HashMap::default(); - for specialization in lineage(tree, &name) { + for specialization in lineage(session, &name) { for base in &specialization.bases { - if lookup(tree, base).is_none() + if lookup(session, base).is_none() && let Some(inherited) = imported.class_member_types.get(base) { members.extend(inherited.clone()); @@ -513,11 +496,12 @@ pub(in crate::ast) fn export_member_types( /// `context`, assign its parameters (IEEE 1800-2023 8.25), made if it is new. pub(in crate::ast) fn specialize( tree: &AnalysisContext<'_>, + session: &mut Session, generic: &str, arguments: &[Argument], context: &PackedDimensions, ) -> Converted { - match bind_specialization(tree, generic, arguments, context)? { + match bind_specialization(tree, session, generic, arguments, context)? { Binding::Ready(name) => Ok(name), Binding::Deferred(error) => Err(error), } @@ -529,12 +513,13 @@ pub(in crate::ast) fn specialize( /// subsequent typedef passes still require every parameter to be constant. pub(in crate::ast) fn specialize_if_ready( tree: &AnalysisContext<'_>, + session: &mut Session, generic: &str, arguments: &[Argument], context: &PackedDimensions, ) -> Converted> { Ok( - match bind_specialization(tree, generic, arguments, context)? { + match bind_specialization(tree, session, generic, arguments, context)? { Binding::Ready(name) => Some(name), Binding::Deferred(_) => None, }, @@ -553,25 +538,33 @@ fn unresolved_parameter(name: &str) -> AnalyzerError { fn bind_specialization( tree: &AnalysisContext<'_>, + session: &mut Session, generic: &str, arguments: &[Argument], context: &PackedDimensions, ) -> Converted { - let depth = &tree.state.class_specialization_depth; - if depth.get() >= MAX_NESTING { + if session.class_specialization_depth >= MAX_NESTING { return Err(unsupported(format!( "class specializations nested more than {MAX_NESTING} deep, as when class `{generic}` extends a specialization of itself" ))); } - depth.set(depth.get() + 1); - let _nesting = Nesting(depth); - if super::foreign::is_foreign(tree, generic) { + session.class_specialization_depth += 1; + let binding = bind_nested_specialization(tree, session, generic, arguments, context); + session.class_specialization_depth -= 1; + binding +} + +/// [`bind_specialization`] inside the specializations being made. +fn bind_nested_specialization( + tree: &AnalysisContext<'_>, + session: &mut Session, + generic: &str, + arguments: &[Argument], + context: &PackedDimensions, +) -> Converted { + if super::foreign::is_foreign(tree, session, generic) { return Ok( - match tree - .state - .foreign - .request(tree, generic, arguments, context)? - { + match super::foreign::request(tree, session, generic, arguments, context)? { Some(name) => Binding::Ready(name), None => Binding::Deferred(unsupported("class type parameter value")), }, @@ -579,18 +572,18 @@ fn bind_specialization( } // Parameter binding and body construction have large temporary values. // Keep those phases off the stack while resolving an inherited class. - let pending = match prepare(tree, generic, arguments, context)? { + let pending = match prepare(tree, session, generic, arguments, context)? { Preparation::Existing(name) => return Ok(Binding::Ready(name)), Preparation::Deferred(name) => return Ok(Binding::Deferred(name)), Preparation::Pending(pending) => pending, }; - tree.state + session .class_specializations_building - .borrow_mut() .push(pending.name.clone()); - let _building = Building(&tree.state.class_specializations_building); - let bases = bind_bases(tree, generic, &pending.env, &pending.aliases)?; - finish_specialization(tree, generic, pending, bases).map(Binding::Ready) + let name = bind_bases(tree, session, generic, &pending.env, &pending.aliases) + .and_then(|bases| finish_specialization(tree, session, generic, pending, bases)); + session.class_specializations_building.pop(); + name.map(Binding::Ready) } struct PendingSpecialization { @@ -654,6 +647,7 @@ impl Eq for BoundArguments {} pub(in crate::ast) fn bind_arguments( tree: &AnalysisContext<'_>, + session: &mut Session, generic: &str, declaration: &celox_sv_syntax::ClassDeclaration, native: &celox_sv_syntax::Declarations, @@ -707,7 +701,7 @@ pub(in crate::ast) fn bind_arguments( continue; }; match parameter.kind { - ParameterKind::Type { .. } => match type_argument(tree, value, context)? { + ParameterKind::Type { .. } => match type_argument(tree, session, value, context)? { Some(ty) => { types.insert(name, ty); } @@ -716,7 +710,7 @@ pub(in crate::ast) fn bind_arguments( } }, ParameterKind::Value { .. } => { - values.insert(name, value_argument(tree, value, context)?); + values.insert(name, value_argument(tree, session, value, context)?); } } } @@ -729,59 +723,57 @@ pub(in crate::ast) fn bind_arguments( #[inline(never)] fn prepare( tree: &AnalysisContext<'_>, + session: &mut Session, generic: &str, arguments: &[Argument], context: &PackedDimensions, ) -> Converted { let native = tree.declarations(); - let declaration = super::declaration(tree, generic) + let declaration = super::declaration(tree, session, generic) .ok_or_else(|| unsupported(format!("class `{generic}`")))?; - if tree - .state - .class_declarations_repeated - .borrow() - .contains(generic) - { + if session.class_declarations_repeated.contains(generic) { return Err(unsupported(format!( "class `{generic}` declared in a loop generate block" ))); } - let Some(arguments) = bind_arguments(tree, generic, declaration, native, arguments, context)? + let Some(arguments) = bind_arguments( + tree, + session, + generic, + declaration, + native, + arguments, + context, + )? else { return Ok(Preparation::Deferred(unsupported( "class type parameter value", ))); }; - prepare_bound(tree, generic, arguments, context) + prepare_bound(tree, session, generic, arguments, context) } fn prepare_bound( tree: &AnalysisContext<'_>, + session: &mut Session, generic: &str, arguments: BoundArguments, context: &PackedDimensions, ) -> Converted { - let declaration = super::declaration(tree, generic) + let declaration = super::declaration(tree, session, generic) .ok_or_else(|| unsupported(format!("class `{generic}`")))?; // The declarations of the class are bound in the scope that declares it, // the actuals in the scope that names the specialization. - let (base_env, base_aliases) = declaration_scope(tree, generic) + let (base_env, base_aliases) = declaration_scope(session, generic) .unwrap_or_else(|| (context.const_env.clone(), context.type_aliases.clone())); // The same arguments in the same tables name the same specialization: // a made one needs neither a copy of the tables nor its parameters bound // again. - let named = |name: &String| { - lookup(tree, name).is_some() - || tree - .state - .class_specializations_building - .borrow() - .contains(name) + let named = |session: &Session, name: &String| { + lookup(session, name).is_some() || session.class_specializations_building.contains(name) }; - if let Some(name) = tree - .state + if let Some(name) = session .class_specialization_names - .borrow() .get(generic) .and_then(|known| { known @@ -789,7 +781,7 @@ fn prepare_bound( .find(|known| known.of(&base_env, &base_aliases) && known.arguments == arguments) }) .map(|known| known.name.clone()) - .filter(named) + .filter(|name| named(session, name)) { return Ok(Preparation::Existing(name)); } @@ -810,7 +802,8 @@ fn prepare_bound( own_aliases: HashMap::default(), }; if let Some(id) = declaration.parameter_ports - && let Some(name) = parameters.bind(tree, declaration, id, true, &mut env, &mut aliases)? + && let Some(name) = + parameters.bind(tree, session, declaration, id, true, &mut env, &mut aliases)? { return Ok(Preparation::Deferred(unresolved_parameter(&name))); } @@ -830,7 +823,7 @@ fn prepare_bound( generic.to_owned() }; { - let mut names = tree.state.class_specialization_names.borrow_mut(); + let names = &mut session.class_specialization_names; let known = names.entry(generic.to_owned()).or_default(); known.retain(|known| !known.stale()); known.push(Named { @@ -842,15 +835,15 @@ fn prepare_bound( } // A declaration of the class may name the specialization being made, // as the type `C` of the default specialization does (8.25). - if named(&name) { + if named(session, &name) { return Ok(Preparation::Existing(name)); } - if tree.state.class_specializations_frozen.get() { + if session.class_specializations_frozen { return Err(unsupported(format!( "specialization `{name}` that only a procedure names, as with a value of a procedural localparam" ))); } - if tree.state.class_specializations.borrow().len() >= MAX_SPECIALIZATIONS { + if session.class_specializations.len() >= MAX_SPECIALIZATIONS { return Err(unsupported(format!( "more than {MAX_SPECIALIZATIONS} class specializations" ))); @@ -866,12 +859,13 @@ fn prepare_bound( #[inline(never)] fn bind_bases( tree: &AnalysisContext<'_>, + session: &mut Session, generic: &str, env: &HashMap, aliases: &HashMap, ) -> Converted> { let native = tree.declarations(); - let declaration = super::declaration(tree, generic) + let declaration = super::declaration(tree, session, generic) .ok_or_else(|| unsupported(format!("class `{generic}`")))?; // The bases are named in the scope of the parameters; a class does not // inherit the declarations of the interface classes it implements. @@ -882,7 +876,7 @@ fn bind_bases( }; let mut bases = Vec::new(); for id in inherited { - if let Some(base) = type_binding::procedural_type(id, native, tree, env, aliases)? + if let Some(base) = type_binding::procedural_type(id, native, tree, session, env, aliases)? .and_then(|ty| ty.class().map(str::to_owned)) { bases.push(base); @@ -894,6 +888,7 @@ fn bind_bases( #[inline(never)] fn finish_specialization( tree: &AnalysisContext<'_>, + session: &mut Session, generic: &str, pending: Box, bases: Vec, @@ -905,12 +900,12 @@ fn finish_specialization( mut aliases, } = *pending; let native = tree.declarations(); - let declaration = super::declaration(tree, generic) + let declaration = super::declaration(tree, session, generic) .ok_or_else(|| unsupported(format!("class `{generic}`")))?; // The body sees the parameters and types of the bases, hidden by the // class's own, and the scope of the specialization (8.25.1). for base in &bases { - inherit(tree, base, generic, &mut env, &mut aliases); + inherit(tree, session, base, generic, &mut env, &mut aliases); } for (key, value) in ¶meters.own_env { match value { @@ -941,9 +936,15 @@ fn finish_specialization( for (_, item) in body { match item { Ok(id) => { - if let Some(name) = - parameters.bind(tree, declaration, id, false, &mut env, &mut aliases)? - { + if let Some(name) = parameters.bind( + tree, + session, + declaration, + id, + false, + &mut env, + &mut aliases, + )? { return Err(unresolved_parameter(&name)); } } @@ -958,14 +959,20 @@ fn finish_specialization( // use of it reports the type unknown. let mut context = PackedDimensions::new(HashMap::default(), &env, &aliases); context.parameter_values = parameters.literals.clone().into(); - let ty = type_binding::binding::bind_in(target, native, tree, &context) + let ty = type_binding::binding::bind_in(target, native, tree, session, &context) .ok() .flatten() .and_then(|ty| { // Its unpacked dimensions may make it a dynamic // container (IEEE 1800-2023 7.5, 7.8, 7.10). - let ty = containers::with_dimensions(ty, &alias.dimensions, tree, &context) - .ok()?; + let ty = containers::with_dimensions( + ty, + &alias.dimensions, + tree, + session, + &context, + ) + .ok()?; type_parameters::resolve(&tree.functions, ty, &env) }); if let Some(mut ty) = ty { @@ -1021,7 +1028,7 @@ fn finish_specialization( } } } - tree.state.class_specializations.borrow_mut().push(( + session.class_specializations.push(( name.clone(), Rc::new(Specialization { generic: generic.to_owned(), @@ -1078,6 +1085,7 @@ impl Parameters { fn record_value( &mut self, tree: &AnalysisContext<'_>, + session: &mut Session, parameter: &celox_sv_syntax::Parameter, first: usize, env: &HashMap, @@ -1095,17 +1103,24 @@ impl Parameters { && self.lowered[first..] .iter() .all(|parameter| parameter.floating.is_none()) - && type_binding::procedural_type(*data_type, tree.declarations(), tree, env, aliases) - .ok() - .flatten() - .is_some_and(|ty| { - matches!( - ty.kind(), - TypeKind::Bit | TypeKind::Logic | TypeKind::Reg | TypeKind::Implicit - ) && ty.container.is_none() - && ty.class().is_none() - && ty.unpacked_ranges.is_empty() - }); + && type_binding::procedural_type( + *data_type, + tree.declarations(), + tree, + session, + env, + aliases, + ) + .ok() + .flatten() + .is_some_and(|ty| { + matches!( + ty.kind(), + TypeKind::Bit | TypeKind::Logic | TypeKind::Reg | TypeKind::Implicit + ) && ty.container.is_none() + && ty.class().is_none() + && ty.unpacked_ranges.is_empty() + }); let name = instances::normalize_identifier(¶meter.name.spelling); self.arguments.push(type_names::ClassArgument::Value( env.get(&name).copied().filter(|_| integral), @@ -1119,6 +1134,7 @@ impl Parameters { fn bind( &mut self, tree: &AnalysisContext<'_>, + session: &mut Session, declaration: &celox_sv_syntax::ClassDeclaration, id: celox_sv_syntax::ParameterDeclarationId, port: bool, @@ -1139,7 +1155,7 @@ impl Parameters { let id = default.ok_or_else(|| { unsupported(format!("type parameter `{name}` without a type")) })?; - type_binding::procedural_type(id, native, tree, env, aliases)? + type_binding::procedural_type(id, native, tree, session, env, aliases)? .ok_or_else(|| { unsupported(format!("type of type parameter `{name}`")) })? @@ -1171,6 +1187,7 @@ impl Parameters { parameters::parameters_from_native( &[parameter], tree, + session, &mut self.lowered, local, env, @@ -1187,6 +1204,7 @@ impl Parameters { )); constants::bind_generate_parameter( tree, + session, parameter, env, &mut self.literals, @@ -1205,7 +1223,7 @@ impl Parameters { }; if port { self.spelled.push(format!("{name}={spelling}")); - self.record_value(tree, parameter, first, env, aliases); + self.record_value(tree, session, parameter, first, env, aliases); } for key in keys { let value = env.get(&key).copied(); @@ -1224,12 +1242,13 @@ impl Parameters { /// declare, specializations among them. pub(in crate::ast) fn declare_scopes( tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) { let native = tree.declarations(); let scope = tree.root_unit().ok().map(|unit| unit.tokens); - let mut scopes = tree.state.class_declaration_scopes.borrow_mut(); + let scopes = &mut session.class_declaration_scopes; // The classes of the scope share its tables. let tables = ( SharedMap::from(env.clone()), @@ -1245,35 +1264,32 @@ pub(in crate::ast) fn declare_scopes( /// The constants and types of the scope that declares class `generic`, /// which [`collect`] records. fn declaration_scope( - tree: &AnalysisContext<'_>, + session: &mut Session, generic: &str, ) -> Option<(SharedMap, SharedMap)> { - tree.state - .class_declaration_scopes - .borrow() - .get(generic) - .cloned() + session.class_declaration_scopes.get(generic).cloned() } /// The type that argument `id` of a type parameter names, or `None` while a /// bound of it needs a constant that `context` does not know yet. pub(in crate::ast) fn type_argument( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::ExprId, context: &PackedDimensions, ) -> Converted> { let native = tree.declarations(); let ty = match &native.expression(id).kind { - ExprKind::Type(ty) => type_binding::bind(*ty, tree, context)?, + ExprKind::Type(ty) => type_binding::bind(*ty, tree, session, context)?, ExprKind::Name(name) => { let name = instances::normalize_identifier(&name.spelling); match context.type_aliases.get(&name) { Some(ty) => Some(ty.clone()), - None => match super::resolve(tree, &name) { + None => match super::resolve(tree, session, &name) { // A built-in class such as `process` has no declaration. Some(name) if super::builtin(&name) => Some(super::handle(&name)), Some(name) => { - let name = specialize(tree, &name, &[], context)?; + let name = specialize(tree, session, &name, &[], context)?; Some(super::handle(&name)) } None => None, @@ -1303,13 +1319,15 @@ pub(in crate::ast) fn type_argument( }, _ => Vec::new(), }; - match super::super::mailboxes::named_type(&path, tree, context)? { + match super::super::mailboxes::named_type(&path, tree, session, context)? { Some(ty) => Some(*ty), - None => expression_binding::named_class(tree, id, native, context)? + None => expression_binding::named_class(tree, session, id, native, context)? .map(|name| super::handle(&name)), } } - ExprKind::Member { separator, .. } if separator == "::" => scoped_type(tree, id, context)?, + ExprKind::Member { separator, .. } if separator == "::" => { + scoped_type(tree, session, id, context)? + } _ => None, }; finish(ty, context, tree) @@ -1319,6 +1337,7 @@ pub(in crate::ast) fn type_argument( /// or `C#(...)::T`, or of a package (IEEE 1800-2023 8.23, 26.3). pub(in crate::ast) fn scoped_type( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::ExprId, context: &PackedDimensions, ) -> Converted> { @@ -1338,7 +1357,7 @@ pub(in crate::ast) fn scoped_type( let class = match &native.expression(*expression).kind { ExprKind::Name(scope) => { let scope = instances::normalize_identifier(&scope.spelling); - if let Some(class) = super::resolve(tree, &scope) { + if let Some(class) = super::resolve(tree, session, &scope) { // Inside the class, its name refers to the // specialization being declared (8.25). match context @@ -1348,8 +1367,8 @@ pub(in crate::ast) fn scoped_type( .and_then(|ty| ty.class().map(str::to_owned)) { Some(specialization) => Some(specialization), - None if super::is_declared(tree, &class) => { - Some(specialize(tree, &class, &[], context)?) + None if super::is_declared(tree, session, &class) => { + Some(specialize(tree, session, &class, &[], context)?) } None => Some(class), } @@ -1366,11 +1385,11 @@ pub(in crate::ast) fn scoped_type( } // A class of a package, `p::C::T`, or a specialization. ExprKind::Member { .. } | ExprKind::Parameterized { .. } => { - expression_binding::named_class(tree, *expression, native, context)? + expression_binding::named_class(tree, session, *expression, native, context)? } _ => None, }; - Ok(class.and_then(|class: String| member_type(tree, &class, &member))) + Ok(class.and_then(|class: String| member_type(tree, session, &class, &member))) } /// The type argument `ty`, bound in `context`, fixed there and checked. @@ -1407,10 +1426,11 @@ fn finish( /// of the expression, which a parameter without a type takes (6.20.2). fn value_argument( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::ExprId, context: &PackedDimensions, ) -> Converted { - let expr = constant_binding::bind(id, tree, context)? + let expr = constant_binding::bind(id, tree, session, context)? .ok_or_else(|| unsupported("class parameter value that is not constant"))?; // An unbased unsized literal such as `'1` fills the width of the formal, // which it takes when the parameter is bound (5.7.1). @@ -1426,7 +1446,7 @@ fn value_argument( return match expr { ConstExpr::Literal(_) => Ok(expr), ConstExpr::Ident(name) - if let Some(literal) = literal_parameter(tree, &name, context) => + if let Some(literal) = literal_parameter(session, &name, context) => { Ok(ConstExpr::Literal(literal)) } @@ -1441,7 +1461,7 @@ fn value_argument( }, }; }; - let ty = type_binding::expression_type(id, tree, context)? + let ty = type_binding::expression_type(id, tree, session, context)? .ok_or_else(|| unsupported("class parameter value without a type"))?; Ok(ConstExpr::Literal(format_typed_parameter_literal( value, ty.width, ty.signed, @@ -1452,7 +1472,7 @@ fn value_argument( /// string wider than a constant holds: a parameter of the scope, or of a /// specialization whose declarations the scope is in. fn literal_parameter( - tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, context: &PackedDimensions, ) -> Option { @@ -1466,7 +1486,7 @@ fn literal_parameter( .type_aliases .iter() .filter(|(key, _)| key.ends_with("::")) - .filter_map(|(_, ty)| lookup(tree, ty.class()?)) + .filter_map(|(_, ty)| lookup(session, ty.class()?)) .find_map(|specialization| { if !specialization.hidden.iter().any(|hidden| hidden == name) { return None; @@ -1565,40 +1585,34 @@ pub(in crate::ast) fn spelling(ty: &Type) -> String { /// interface class, which is checked even when nothing names it. A name /// inside a class is bound in each specialization of the class, until no /// new specialization appears. -pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimensions) { - tree.state.class_specializations_frozen.set(false); - for (generic, arguments) in tree.state.foreign_arguments.borrow().clone() { - let pending = match prepare_bound(tree, &generic, arguments.clone(), context) { +pub(in crate::ast) fn collect( + tree: &AnalysisContext<'_>, + session: &mut Session, + context: &PackedDimensions, +) { + session.class_specializations_frozen = false; + for (generic, arguments) in session.foreign_arguments.clone() { + let pending = match prepare_bound(tree, session, &generic, arguments.clone(), context) { Ok(Preparation::Pending(pending)) => pending, Ok(Preparation::Existing(name)) => { - tree.state - .foreign_names - .borrow_mut() - .push((generic, arguments, name)); + session.foreign_names.push((generic, arguments, name)); continue; } Ok(Preparation::Deferred(error)) | Err(error) => { - *tree.state.foreign_error.borrow_mut() = Some(error); + session.foreign_error = Some(error); return; } }; - tree.state + session .class_specializations_building - .borrow_mut() .push(pending.name.clone()); - let _building = Building(&tree.state.class_specializations_building); - let result = (|| { - let bases = bind_bases(tree, &generic, &pending.env, &pending.aliases)?; - finish_specialization(tree, &generic, pending, bases) - })(); + let result = bind_bases(tree, session, &generic, &pending.env, &pending.aliases) + .and_then(|bases| finish_specialization(tree, session, &generic, pending, bases)); + session.class_specializations_building.pop(); match result { - Ok(name) => tree - .state - .foreign_names - .borrow_mut() - .push((generic, arguments, name)), + Ok(name) => session.foreign_names.push((generic, arguments, name)), Err(error) => { - *tree.state.foreign_error.borrow_mut() = Some(error); + session.foreign_error = Some(error); return; } } @@ -1629,11 +1643,11 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens ) }) .collect::>(); - for name in tree.state.foreign.names() { + for name in session.foreign.names() { names.entry(name.clone()).or_insert(name); } for (alias, name) in &scope::imported(tree).aliases { - if tree.state.foreign.contains(name) { + if session.foreign.contains(name) { names.entry(alias.clone()).or_insert(name.clone()); } } @@ -1706,7 +1720,7 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens instances::normalize_identifier(&package.name.spelling), instances::normalize_identifier(&member.name.spelling) ); - if tree.state.foreign.contains(&name) { + if session.foreign.contains(&name) { references.push(( enclosing(ty.tokens), name, @@ -1755,8 +1769,8 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens } // Outside classes, an assignment is bound in each generate scope that // contains it, which may give its genvars different values. - let items = - generate::items(tree, &context.const_env, &context.type_aliases).unwrap_or_default(); + let items = generate::items(tree, session, &context.const_env, &context.type_aliases) + .unwrap_or_default(); // The scope that declares each class: the innermost generate scope // around its declaration, or the module. for class in &classes { @@ -1776,15 +1790,9 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens }; let name = super::declared_name(tree, class); if item.is_some_and(|item| items.iter().filter(|other| other.id == item.id).count() > 1) { - tree.state - .class_declarations_repeated - .borrow_mut() - .insert(name.clone()); + session.class_declarations_repeated.insert(name.clone()); } - tree.state - .class_declaration_scopes - .borrow_mut() - .insert(name, scope); + session.class_declaration_scopes.insert(name, scope); } // Whether `tokens` is in a block of a generate construct. let generated = |tokens: celox_sv_syntax::TokenRange| { @@ -1830,7 +1838,7 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens let mut spelled = HashSet::<(String, String, String)>::default(); let mut contexts = HashMap::::default(); loop { - let before = tree.state.class_specializations.borrow().len(); + let before = session.class_specializations.len(); for (index, (scope, name, arguments, tokens)) in references.iter().enumerate() { let scopes = match scope { None => { @@ -1838,12 +1846,12 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens for context in module_scopes(*tokens) { // A specialization that cannot be made reports // why where it is used. - let _ = specialize(tree, name, arguments, &context); + let _ = specialize(tree, session, name, arguments, &context); } } continue; } - Some(scope) => of(tree, scope), + Some(scope) => of(session, scope), }; for scope in scopes { let shared = !crate::ast::dimensions::unshared_discovery(); @@ -1866,15 +1874,15 @@ pub(in crate::ast) fn collect(tree: &AnalysisContext<'_>, context: &PackedDimens let context = contexts.entry(scope.clone()).or_insert_with(|| { let mut context = context.clone(); let (env, aliases) = - shared_scope(tree, &scope, &context.const_env, &context.type_aliases); + shared_scope(session, &scope, &context.const_env, &context.type_aliases); context.const_env = env; context.type_aliases = aliases; context }); - let _ = specialize(tree, name, arguments, context); + let _ = specialize(tree, session, name, arguments, context); } } - let after = tree.state.class_specializations.borrow().len(); + let after = session.class_specializations.len(); if after == before || after >= MAX_SPECIALIZATIONS { break; } @@ -1901,6 +1909,7 @@ fn argument_spelling(native: &celox_sv_syntax::Declarations, arguments: &[Argume #[cfg(test)] mod tests { + use std::path::Path; #[test] diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs index 41de23a3705..f3fddf94c55 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_process.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs @@ -4,13 +4,19 @@ use super::*; pub(super) fn comb_processes_from_scope( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, packed_dimensions: &PackedDimensions, parameter_literals: &HashMap, state: &mut procedural::BodyState<'_>, ) -> Result, AnalyzerError> { let mut processes = Vec::new(); - let active = generate::items(syntax_tree, const_env, &packed_dimensions.type_aliases)?; + let active = generate::items( + syntax_tree, + session, + const_env, + &packed_dimensions.type_aliases, + )?; let mut views = generate::ScopeViews::with_literals(packed_dimensions, parameter_literals); for (creation_order, item) in active.iter().enumerate() { let syntax_tree = &item.scoped(syntax_tree); @@ -30,6 +36,7 @@ pub(super) fn comb_processes_from_scope( item, None, syntax_tree, + session, &item.env, dimensions, literals, @@ -56,6 +63,7 @@ fn comb_processes_from_item( item: &generate::Item, condition: Option, syntax_tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &SharedMap, packed_dimensions: &PackedDimensions, parameter_literals: &SharedMap, @@ -67,11 +75,13 @@ fn comb_processes_from_item( for mut process in continuous_assignments( syntax_tree.declarations().assign_statement(*id), syntax_tree, + session, packed_dimensions, )? { process.condition = condition.clone(); processes.push(substitute_process_constants_with_parameter_literals( syntax_tree, + session, process, const_env, parameter_literals, @@ -86,12 +96,14 @@ fn comb_processes_from_item( procedure, condition, syntax_tree, + session, &local_packed_dimensions, parameter_literals, state, )? { processes.push(substitute_process_constants( syntax_tree, + session, process, const_env, )); @@ -102,10 +114,12 @@ fn comb_processes_from_item( for assignment in net_declaration_assignments( syntax_tree.declarations().net_declaration(*id), syntax_tree, + session, packed_dimensions, )? { let assignment = substitute_assignment_constants_with_parameter_literals( syntax_tree, + session, assignment, const_env, parameter_literals, @@ -145,6 +159,7 @@ fn always_dimensions( fn net_declaration_assignments( native: &celox_sv_syntax::NetDeclaration, syntax_tree: &AnalysisContext<'_>, + session: &mut Session, packed_dimensions: &PackedDimensions, ) -> Result, AnalyzerError> { let mut assignments = Vec::new(); @@ -156,6 +171,7 @@ fn net_declaration_assignments( if let Some(target) = packed_dimensions.get(&name) { array_compatibility::check_native_unpacked_assignment( syntax_tree, + session, value, target, || "net declaration assignment".to_string(), @@ -168,6 +184,7 @@ fn net_declaration_assignments( syntax_tree.declarations(), &lhs, syntax_tree, + session, packed_dimensions, )?; assignments.push(Assignment::new(lhs, rhs)); @@ -179,6 +196,7 @@ fn net_declaration_assignments( fn continuous_assignments( native: &celox_sv_syntax::AssignSyntax, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted> { if native.assignments.is_empty() { @@ -223,12 +241,18 @@ fn continuous_assignments( id, native_tree, tree, + session, dimensions, )?); } } - let rhs = - expression_binding::value(assignment.right, native_tree, tree, dimensions)?; + let rhs = expression_binding::value( + assignment.right, + native_tree, + tree, + session, + dimensions, + )?; return Ok(CombProcess::procedural( CombProcessKind::ContinuousAssign, None, @@ -239,11 +263,15 @@ fn continuous_assignments( }], )); } - if let Some(shape) = - array_compatibility::native_unpacked_shape(assignment.left, tree, dimensions) - { + if let Some(shape) = array_compatibility::native_unpacked_shape( + assignment.left, + tree, + session, + dimensions, + ) { array_compatibility::check_native_unpacked_assignment( tree, + session, assignment.right, &shape, || "continuous assignment".into(), @@ -254,6 +282,7 @@ fn continuous_assignments( assignment.left, tree.declarations(), tree, + session, dimensions, )?; let rhs = expression_binding::expression( @@ -261,13 +290,20 @@ fn continuous_assignments( tree.declarations(), &lhs, tree, + session, dimensions, )?; // A variable of unpacked structure type: drive its leaves. if let LValue::Ident(name) = &lhs && let Some(parts) = unpacked_structs::targets(name, dimensions) { - unpacked_structs::check_assignment(name, assignment.right, tree, dimensions)?; + unpacked_structs::check_assignment( + name, + assignment.right, + tree, + session, + dimensions, + )?; return Ok(CombProcess::procedural( CombProcessKind::ContinuousAssign, None, @@ -302,6 +338,7 @@ fn comb_process_from_procedure( procedure: &celox_sv_syntax::Procedure, condition: Option, syntax_tree: &AnalysisContext<'_>, + session: &mut Session, packed_dimensions: &PackedDimensions, parameter_literals: &HashMap, state: &mut procedural::BodyState<'_>, @@ -317,6 +354,7 @@ fn comb_process_from_procedure( }; let mut builder = procedural::BodyBuilder::new( syntax_tree, + session, packed_dimensions, state, system_functions::Body::Always, @@ -325,6 +363,7 @@ fn comb_process_from_procedure( for stmt in &mut body { procedural::substitute_stmt_constants( syntax_tree, + builder.session, stmt, &HashMap::default(), parameter_literals, diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index a3e7607031f..2378a33b2c9 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -376,12 +376,14 @@ fn scope_flags(tree: &AnalysisContext<'_>) -> (bool, bool) { pub(super) fn module_constant_functions( tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, type_aliases: &HashMap, parameter_literals: &HashMap, ) -> ConstantFunctions { symbolic_module_constant_functions( tree, + session, const_env, type_aliases, parameter_literals, @@ -391,6 +393,7 @@ pub(super) fn module_constant_functions( pub(super) fn symbolic_module_constant_functions( tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, type_aliases: &HashMap, parameter_literals: &HashMap, @@ -404,6 +407,7 @@ pub(super) fn symbolic_module_constant_functions( if !needs_bootstrap { return collect_module_constant_functions( tree, + session, const_env, type_aliases, parameter_literals, @@ -418,6 +422,7 @@ pub(super) fn symbolic_module_constant_functions( root_subroutines: true, ..tree.clone() }, + session, const_env, type_aliases, parameter_literals, @@ -427,6 +432,7 @@ pub(super) fn symbolic_module_constant_functions( let tree = &tree.with_functions(roots); collect_module_constant_functions( tree, + session, const_env, type_aliases, parameter_literals, @@ -436,6 +442,7 @@ pub(super) fn symbolic_module_constant_functions( fn collect_module_constant_functions( tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, type_aliases: &HashMap, parameter_literals: &HashMap, @@ -456,14 +463,14 @@ fn collect_module_constant_functions( .filter(|(name, _)| !symbolic_parameters.contains(*name)) .map(|(name, value)| (name.clone(), *value)) .collect(); - symbolic_aliases = match type_aliases_from_scope_with_env(tree, &constants) { + symbolic_aliases = match type_aliases_from_scope_with_env(tree, session, &constants) { Ok(aliases) => aliases, Err(error) => return ConstantFunctions::unconverted(error), }; &symbolic_aliases }; let (subroutine_params, subroutine_shapes, subroutine_directions) = - match procedural::subroutine_argument_names(tree, const_env, type_aliases) { + match procedural::subroutine_argument_names(tree, session, const_env, type_aliases) { Ok(names) => names, Err(error) => return ConstantFunctions::unconverted(error), }; @@ -487,6 +494,7 @@ fn collect_module_constant_functions( let mut rejected = HashMap::default(); let subroutines = match procedural::subroutines_with_symbolic_parameters( tree, + session, const_env, &dimensions, parameter_literals, 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 785ec107d51..b61c1d81182 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions/runtime.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions/runtime.rs @@ -216,6 +216,7 @@ mod tests { &[], &crate::ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap() .modules()[0] diff --git a/crates/celox-sv-analyzer/src/ast/constant_binding.rs b/crates/celox-sv-analyzer/src/ast/constant_binding.rs index 7918c5073ff..cb5906ce1be 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_binding.rs @@ -8,6 +8,7 @@ pub(super) fn expression( root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Converted> { @@ -15,6 +16,7 @@ pub(super) fn expression( root, native, tree, + session, &PackedDimensions::new(HashMap::default(), env, aliases), ) } @@ -23,44 +25,49 @@ pub(super) fn value_expression( root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted> { let mut context = dimensions.clone(); context.const_env = HashMap::default().into(); context.type_aliases = SharedMap::default(); - bind_in_context(root, native, tree, &context, dimensions) + bind_in_context(root, native, tree, session, &context, dimensions) } pub(super) fn bind( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted> { - bind_in(root, tree.declarations(), tree, dimensions) + bind_in(root, tree.declarations(), tree, session, dimensions) } pub(super) fn indexed_expression( root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted { { let mut context = dimensions.clone(); context.constant_indexed_base = true; - expression_binding::bind_value(root, native, tree, &context, None) + expression_binding::bind_value(root, native, tree, session, &context, None) } } fn bind_in( root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted> { - bind_in_context(root, native, tree, dimensions, dimensions) + bind_in_context(root, native, tree, session, dimensions, dimensions) } fn bind_in_context( root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, query_dimensions: &PackedDimensions, ) -> Converted> { @@ -136,12 +143,17 @@ fn bind_in_context( && (typename_operand(*left, native).is_some() || typename_operand(*right, native).is_some()) { - let text = |id| -> Converted>> { + let mut text = |id| -> Converted>> { let id = expression_binding::ungroup(id, native); if let Some(argument) = typename_operand(id, native) { return Ok(Some( - type_names::query_string(argument, tree, query_dimensions)? - .into_bytes(), + type_names::query_string( + argument, + tree, + session, + query_dimensions, + )? + .into_bytes(), )); } Ok(match &native.expression(id).kind { @@ -186,6 +198,7 @@ fn bind_in_context( *expression, native, tree, + session, query_dimensions, ) { Ok(target) => target, @@ -199,10 +212,16 @@ fn bind_in_context( // Actual values retain the parent's specialization context. // The symbolic context deliberately omits its numeric env, // but a concat must be folded to a typed literal here. - let expr = - expression_binding::bind_value(id, native, tree, query_dimensions, None)?; + let expr = expression_binding::bind_value( + id, + native, + tree, + session, + query_dimensions, + None, + )?; let Some(value) = - selects::indexed_expression_value(tree, expr, query_dimensions) + selects::indexed_expression_value(tree, session, expr, query_dimensions) else { return Ok(None); }; @@ -304,14 +323,20 @@ fn bind_in_context( shape.packed.len() > 1 || !shape.unpacked.is_empty() }) { - let value = indexed_expression(id, native, tree, query_dimensions)?; + let value = + indexed_expression(id, native, tree, session, query_dimensions)?; let value = if query_dimensions .array_parameter_values .contains_key(&name_key) { - selects::indexed_expression_value(tree, value, query_dimensions) + selects::indexed_expression_value( + tree, + session, + value, + query_dimensions, + ) } else { - expr_to_index_const(tree, value, query_dimensions) + expr_to_index_const(tree, session, value, query_dimensions) }; values.push( value.ok_or_else(|| unsupported("parameter selection shape"))?, @@ -325,14 +350,18 @@ fn bind_in_context( )); jobs.extend(indices.into_iter().rev().map(Job::Enter)); } else { - let value = match indexed_expression(id, native, tree, query_dimensions) { - Ok(value) => value, - Err(AnalyzerError::Unsupported(_)) => return Ok(None), - Err(error) => return Err(error), - }; - let Some(value) = - selects::indexed_expression_value(tree, value, query_dimensions) - else { + let value = + match indexed_expression(id, native, tree, session, query_dimensions) { + Ok(value) => value, + Err(AnalyzerError::Unsupported(_)) => return Ok(None), + Err(error) => return Err(error), + }; + let Some(value) = selects::indexed_expression_value( + tree, + session, + value, + query_dimensions, + ) else { return Ok(None); }; values.push(value); @@ -347,12 +376,13 @@ fn bind_in_context( }; context.subroutine_param_names = Arc::new(const_functions::argument_names(&tree.functions)); - let value = - match expression_binding::bind_value(id, native, tree, &context, None) { - Ok(value) => value, - Err(AnalyzerError::Unsupported(_)) => return Ok(None), - Err(error) => return Err(error), - }; + let value = match expression_binding::bind_value( + id, native, tree, session, &context, None, + ) { + Ok(value) => value, + Err(AnalyzerError::Unsupported(_)) => return Ok(None), + Err(error) => return Err(error), + }; // A `$typename` string is the constant of its bytes, as a // string literal is (5.9). let value = match value { @@ -373,9 +403,14 @@ fn bind_in_context( } ); let Some(value) = (if countbits { - constants::countbits_constant_call(tree, value, &dimensions.const_env) + constants::countbits_constant_call( + tree, + session, + value, + &dimensions.const_env, + ) } else { - constants::user_call_value(tree, value, &dimensions.const_env) + constants::user_call_value(tree, session, value, &dimensions.const_env) }) else { return Ok(None); }; @@ -388,9 +423,13 @@ fn bind_in_context( }, Job::Cast(target) => { let value = values.pop().ok_or_else(disagreement)?; - let Some(value) = - casts::cast_constant_target(tree, value, target, &query_dimensions.const_env) - else { + let Some(value) = casts::cast_constant_target( + tree, + session, + value, + target, + &query_dimensions.const_env, + ) else { return Ok(None); }; values.push(value); @@ -446,7 +485,7 @@ fn bind_in_context( Job::System(function, count) => { let start = values.len().checked_sub(count).ok_or_else(disagreement)?; let args = values.split_off(start); - values.push(ConstExpr::call(&tree.state, Callee::System(function), args)); + values.push(ConstExpr::call(Callee::System(function), args, session)); } Job::Select(name, count) => { let start = values.len().checked_sub(count).ok_or_else(disagreement)?; @@ -478,57 +517,62 @@ fn bind_in_context( pub(super) fn packed_ranges( dimensions: &[Dimension], tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Converted> { let context = PackedDimensions::new(HashMap::default(), env, aliases); - type_binding::binding::packed_ranges(dimensions, tree, &context) + type_binding::binding::packed_ranges(dimensions, tree, session, &context) } pub(super) fn unpacked_ranges( dimensions: &[Dimension], tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Converted> { let context = PackedDimensions::new(HashMap::default(), env, aliases); dimensions .iter() - .map(|dimension| bind_unpacked_dimension(dimension, tree, &context)) + .map(|dimension| bind_unpacked_dimension(dimension, tree, session, &context)) .collect() } pub(super) fn unpacked_dimension( dimension: &Dimension, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Converted { let context = PackedDimensions::new(HashMap::default(), env, aliases); - bind_unpacked_dimension(dimension, tree, &context) + bind_unpacked_dimension(dimension, tree, session, &context) } /// Native array dimensions retain their authored bound handles. pub(super) fn bind_unpacked_ranges( dimensions: &[Dimension], tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted> { dimensions .iter() - .map(|dimension| bind_unpacked_dimension(dimension, tree, context)) + .map(|dimension| bind_unpacked_dimension(dimension, tree, session, context)) .collect() } pub(super) fn bind_unpacked_dimension( dimension: &Dimension, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted { let range = match dimension.kind { - DimensionKind::Range { left, right } => bind(left, tree, context)? - .zip(bind(right, tree, context)?) + DimensionKind::Range { left, right } => bind(left, tree, session, context)? + .zip(bind(right, tree, session, context)?) .map(|(left, right)| UnpackedRange::new(left, right)), - DimensionKind::Index(size) => bind(size, tree, context)?.map(UnpackedRange::sized), + DimensionKind::Index(size) => bind(size, tree, session, context)?.map(UnpackedRange::sized), DimensionKind::Unsized => return Err(unsupported("unsized unpacked array dimension")), DimensionKind::Queue(_) => return Err(unsupported("queue array dimension")), DimensionKind::Wildcard => return Err(unsupported("associative array dimension")), @@ -568,6 +612,7 @@ mod tests { use super::*; #[test] fn native_constant_literals_and_operators_supply_values() { + let session = &mut Session::default(); for (text, expected) in [("8", 8), ("7+8", 15), ("$bits(logic)", 1)] { let tree = crate::source_tree::parse_source( &format!("module M #(parameter P={text});endmodule"), @@ -581,7 +626,7 @@ mod tests { else { panic!() }; - let value = bind(id, &tree, &PackedDimensions::default()) + let value = bind(id, &tree, session, &PackedDimensions::default()) .unwrap() .unwrap(); assert_eq!( @@ -592,6 +637,7 @@ mod tests { } #[test] fn deeply_grouped_native_binding_uses_no_recursive_walk() { + let session = &mut Session::default(); let path = Path::new("deep-native-constant.sv"); let tree = crate::source_tree::parse_source("module M #(parameter P=7);endmodule", path).unwrap(); @@ -612,7 +658,7 @@ mod tests { panic!() }; assert_eq!( - bind_in(id, &native, &tree, &PackedDimensions::default()).unwrap(), + bind_in(id, &native, &tree, session, &PackedDimensions::default()).unwrap(), Some(ConstExpr::Literal("7".into())) ); } diff --git a/crates/celox-sv-analyzer/src/ast/constant_folding.rs b/crates/celox-sv-analyzer/src/ast/constant_folding.rs index d2b073b3d3f..fd5987c8319 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_folding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_folding.rs @@ -9,10 +9,10 @@ pub(super) const MAX_CONSTANT_CONCAT_BITS: usize = 65_536; pub(super) fn simplify_constant_mux_conditions( tree: &AnalysisContext<'_>, + session: &mut Session, expr: Expr, const_env: &HashMap, ) -> Expr { - let state = &*tree.state; let functions = &tree.functions; match expr { Expr::Select { @@ -21,7 +21,9 @@ pub(super) fn simplify_constant_mux_conditions( lsb, signed, } => Expr::Select { - expr: Box::new(simplify_constant_mux_conditions(tree, *expr, const_env)), + expr: Box::new(simplify_constant_mux_conditions( + tree, session, *expr, const_env, + )), msb, lsb, signed, @@ -29,14 +31,14 @@ pub(super) fn simplify_constant_mux_conditions( Expr::Concat(parts) => Expr::Concat( parts .into_iter() - .map(|part| simplify_constant_mux_conditions(tree, part, const_env)) + .map(|part| simplify_constant_mux_conditions(tree, session, part, const_env)) .collect(), ), Expr::RepeatConcat { count, parts } => Expr::RepeatConcat { count, parts: parts .into_iter() - .map(|part| simplify_constant_mux_conditions(tree, part, const_env)) + .map(|part| simplify_constant_mux_conditions(tree, session, part, const_env)) .collect(), }, Expr::Resize { @@ -44,8 +46,8 @@ pub(super) fn simplify_constant_mux_conditions( width, signed, } => { - let expr = simplify_constant_mux_conditions(tree, *expr, const_env); - if let Some(constant) = expr_to_const(state, expr.clone()) { + let expr = simplify_constant_mux_conditions(tree, session, *expr, const_env); + if let Some(constant) = expr_to_const(session, expr.clone()) { let parameter_types = parameter_types_from_const_env(const_env) .into_iter() .map(|(name, r#type)| (name, (r#type.width, r#type.signed))) @@ -71,23 +73,31 @@ pub(super) fn simplify_constant_mux_conditions( } Expr::Unary { op, expr } => Expr::Unary { op, - expr: Box::new(simplify_constant_mux_conditions(tree, *expr, const_env)), + expr: Box::new(simplify_constant_mux_conditions( + tree, session, *expr, const_env, + )), }, Expr::Binary { left, op, right } => Expr::Binary { - left: Box::new(simplify_constant_mux_conditions(tree, *left, const_env)), + left: Box::new(simplify_constant_mux_conditions( + tree, session, *left, const_env, + )), op, - right: Box::new(simplify_constant_mux_conditions(tree, *right, const_env)), + right: Box::new(simplify_constant_mux_conditions( + tree, session, *right, const_env, + )), }, Expr::Mux { condition, then_expr, else_expr, } => { - 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 condition = simplify_constant_mux_conditions(tree, session, *condition, const_env); + let mut then_expr = + simplify_constant_mux_conditions(tree, session, *then_expr, const_env); + let mut else_expr = + simplify_constant_mux_conditions(tree, session, *else_expr, const_env); let parameter_types = parameter_types_from_const_env(const_env); - let arm_type = |arm: &Expr| { + let arm_type = |session: &mut Session, arm: &Expr| { if let Expr::Literal(literal) = arm && resize_unbased_fill_literal_for_cast(literal, 1, false).is_some() { @@ -101,16 +111,15 @@ pub(super) fn simplify_constant_mux_conditions( signed: *signed, }) } else { - infer_const_expr_type(&expr_to_const(state, arm.clone())?, ¶meter_types) + infer_const_expr_type(&expr_to_const(session, arm.clone())?, ¶meter_types) } }; - let result_type = - arm_type(&then_expr) - .zip(arm_type(&else_expr)) - .map(|(then_type, else_type)| ExprType { - width: then_type.width.max(else_type.width), - signed: then_type.signed && else_type.signed, - }); + let result_type = arm_type(session, &then_expr) + .zip(arm_type(session, &else_expr)) + .map(|(then_type, else_type)| ExprType { + width: then_type.width.max(else_type.width), + signed: then_type.signed && else_type.signed, + }); // Repeated-condition mux folding is only valid for a condition // that cannot be X/Z. Procedural guards are explicitly coerced // to two state, but source-level ternaries need not be. @@ -138,11 +147,11 @@ pub(super) fn simplify_constant_mux_conditions( return then_expr; } if let Some(value) = - equivalent_constant_mux_value(state, &then_expr, &else_expr, const_env) + equivalent_constant_mux_value(session, &then_expr, &else_expr, const_env) { return value; } - match expr_to_const(state, condition.clone()) + match expr_to_const(session, condition.clone()) .and_then(|condition| eval_ast_const_expr(functions, &condition, const_env)) { Some(value) => { @@ -163,7 +172,7 @@ pub(super) fn simplify_constant_mux_conditions( return Expr::Literal(resized); } } - let Some(selected_type) = arm_type(&selected) else { + let Some(selected_type) = arm_type(session, &selected) else { return selected; }; // A signed ternary is extended in the context of its @@ -192,6 +201,7 @@ pub(super) fn simplify_constant_mux_conditions( }; simplify_constant_mux_conditions( tree, + session, Expr::Resize { expr: Box::new(selected), width: result_type.width, @@ -208,12 +218,14 @@ pub(super) fn simplify_constant_mux_conditions( } } Expr::Inside { expr, items } => Expr::Inside { - expr: Box::new(simplify_constant_mux_conditions(tree, *expr, const_env)), + expr: Box::new(simplify_constant_mux_conditions( + tree, session, *expr, const_env, + )), items: items .into_iter() .map(|item| { item.map(&mut |operand| { - simplify_constant_mux_conditions(tree, operand, const_env) + simplify_constant_mux_conditions(tree, session, operand, const_env) }) }) .collect(), @@ -227,7 +239,9 @@ pub(super) fn simplify_constant_mux_conditions( callee, args: args .into_iter() - .map(|arg| arg.map(|arg| simplify_constant_mux_conditions(tree, arg, const_env))) + .map(|arg| { + arg.map(|arg| simplify_constant_mux_conditions(tree, session, arg, const_env)) + }) .collect(), }, Expr::Ident(_) | Expr::Literal(_) => expr, @@ -236,6 +250,7 @@ pub(super) fn simplify_constant_mux_conditions( pub(super) fn fold_const_integral_expr_preserving_mask( tree: &AnalysisContext<'_>, + session: &mut Session, expr: Expr, const_env: &HashMap, ) -> Expr { @@ -248,13 +263,14 @@ 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(tree, &expr, const_env, ¶meter_types) + eval_const_integral_expr_preserving_mask(tree, session, &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( tree: &AnalysisContext<'_>, + session: &mut Session, expr: &Expr, const_env: &HashMap, parameter_types: &impl Fn(&str) -> Option<(usize, bool)>, @@ -273,8 +289,13 @@ fn eval_const_integral_expr_preserving_mask( if width > MAX_CONSTANT_CONCAT_BITS { return None; } - let operand = - eval_const_integral_expr_preserving_mask(tree, expr, const_env, parameter_types)?; + let operand = eval_const_integral_expr_preserving_mask( + tree, + session, + expr, + const_env, + parameter_types, + )?; let mut value = num_bigint::BigUint::default(); let mut mask = num_bigint::BigUint::default(); for offset in 0..width { @@ -304,8 +325,13 @@ fn eval_const_integral_expr_preserving_mask( width, signed, } => { - let operand = - eval_const_integral_expr_preserving_mask(tree, expr, const_env, parameter_types)?; + let operand = eval_const_integral_expr_preserving_mask( + tree, + session, + expr, + const_env, + parameter_types, + )?; typecheck::parse_integral_literal(&resize_integral_literal_for_cast( operand, *width, *signed, )) @@ -314,7 +340,13 @@ fn eval_const_integral_expr_preserving_mask( parts .iter() .map(|part| { - eval_const_integral_expr_preserving_mask(tree, part, const_env, parameter_types) + eval_const_integral_expr_preserving_mask( + tree, + session, + part, + const_env, + parameter_types, + ) }) .collect::>>()?, ), @@ -326,6 +358,7 @@ fn eval_const_integral_expr_preserving_mask( .map(|part| { eval_const_integral_expr_preserving_mask( tree, + session, part, const_env, parameter_types, @@ -343,6 +376,7 @@ fn eval_const_integral_expr_preserving_mask( _ => { let constant: crate::ir::ConstExpr = constant_with_folded_selections_with_lookup( tree, + session, expr, const_env, parameter_types, @@ -361,51 +395,57 @@ fn eval_const_integral_expr_preserving_mask( // constant evaluator can propagate expression widths across compound trees. pub(super) fn constant_with_folded_selections( tree: &AnalysisContext<'_>, + session: &mut Session, expr: &Expr, const_env: &HashMap, parameter_types: &HashMap, ) -> Option { - constant_with_folded_selections_with_lookup(tree, expr, const_env, &|name| { + constant_with_folded_selections_with_lookup(tree, session, expr, const_env, &|name| { parameter_types.get(name).copied() }) } fn constant_with_folded_selections_with_lookup( tree: &AnalysisContext<'_>, + session: &mut Session, 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(tree, expr, const_env, parameter_types) + let convert = |session: &mut Session, expr: &Expr| { + constant_with_folded_selections_with_lookup(tree, session, expr, const_env, parameter_types) }; match expr { Expr::Select { .. } | Expr::Concat(_) | Expr::RepeatConcat { .. } | Expr::Resize { .. } => { - let literal = - eval_const_integral_expr_preserving_mask(tree, expr, const_env, parameter_types)?; + let literal = eval_const_integral_expr_preserving_mask( + tree, + session, + expr, + const_env, + parameter_types, + )?; Some(ConstExpr::Literal( typecheck::format_integral_literal_binary(&literal), )) } Expr::Unary { op, expr } => Some(ConstExpr::Unary { op: *op, - expr: Box::new(convert(expr)?), + expr: Box::new(convert(session, expr)?), }), Expr::Binary { left, op, right } => Some(ConstExpr::Binary { - left: Box::new(convert(left)?), + left: Box::new(convert(session, left)?), op: *op, - right: Box::new(convert(right)?), + right: Box::new(convert(session, right)?), }), Expr::Mux { condition, then_expr, else_expr, } => Some(ConstExpr::Mux { - condition: Box::new(convert(condition)?), - then_expr: Box::new(convert(then_expr)?), - else_expr: Box::new(convert(else_expr)?), + condition: Box::new(convert(session, condition)?), + then_expr: Box::new(convert(session, then_expr)?), + else_expr: Box::new(convert(session, else_expr)?), }), Expr::Call { callee, args, .. } => { // Materialize a constant function's self-determined return type @@ -418,14 +458,14 @@ fn constant_with_folded_selections_with_lookup( )); } Some(ConstExpr::call( - state, callee.clone(), args.iter() - .map(|arg| convert(arg.as_ref()?)) + .map(|arg| convert(session, arg.as_ref()?)) .collect::>>()?, + session, )) } - _ => expr_to_const(state, expr.clone()), + _ => expr_to_const(session, expr.clone()), } } @@ -478,7 +518,7 @@ fn expr_is_intrinsically_two_state(expr: &Expr, const_env: &HashMap, @@ -511,6 +551,7 @@ mod constant_concat_limits_tests { #[test] fn bounds_repeated_constant_concatenation() { + let session = &mut Session::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)] { @@ -520,6 +561,7 @@ mod constant_concat_limits_tests { }; let result = eval_const_integral_expr_preserving_mask( &tree, + session, &expr, &HashMap::default(), &|_| None, @@ -535,8 +577,14 @@ mod constant_concat_limits_tests { parts: vec![Expr::Literal("2'bxz".to_string())], }; assert!( - eval_const_integral_expr_preserving_mask(&tree, &expr, &HashMap::default(), &|_| None,) - .is_none() + eval_const_integral_expr_preserving_mask( + &tree, + session, + &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 82a820fcc07..2c2e84836a0 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_folding/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_folding/tests.rs @@ -4,6 +4,7 @@ use super::*; #[test] fn lazy_types_preserve_width_signedness_and_masks_across_expression_shapes() { + let session = &mut Session::default(); let syntax = crate::source_tree::SourceTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); let mut env = HashMap::from_iter([ @@ -154,13 +155,15 @@ 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(&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(&tree, &expr, &env, &|name| { - types.get(name).copied() - }); + let direct = + eval_const_integral_expr_preserving_mask(&tree, session, &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(&tree, session, &expr, &env, &|name| { + types.get(name).copied() + }); assert_eq!(direct, rebuilt, "{expr:?}"); assert_eq!(lookups.get(), expected_lookups, "{expr:?}"); let expected = rebuilt @@ -173,13 +176,14 @@ fn lazy_types_preserve_width_signedness_and_masks_across_expression_shapes() { expected }; assert_eq!( - fold_const_integral_expr_preserving_mask(&tree, expr.clone(), &env), + fold_const_integral_expr_preserving_mask(&tree, session, expr.clone(), &env), expected ); } // Fixed expected results also guard against losing typed signed shifts. let shifted = fold_const_integral_expr_preserving_mask( &tree, + session, Expr::Binary { left: boxed_a(), op: BinaryOp::Shr, @@ -196,6 +200,7 @@ fn lazy_types_preserve_width_signedness_and_masks_across_expression_shapes() { assert_eq!(shifted.value, num_bigint::BigUint::from(127u8)); let two_state = fold_const_integral_expr_preserving_mask( &tree, + session, Expr::Unary { op: UnaryOp::ToTwoState, expr: Box::new(literal("8'b1xz001xz")), @@ -209,7 +214,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(&tree, ident("W"), &env); + let wide = fold_const_integral_expr_preserving_mask(&tree, session, ident("W"), &env); let Expr::Literal(wide) = wide else { panic!("wide typed parameter must fold") }; @@ -224,6 +229,7 @@ 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 session = &mut Session::default(); for count in [16, 64, 256] { let mut code = String::from("module Top;\n"); for index in 0..count { @@ -241,9 +247,9 @@ fn numeric_two_state_parameter_values_do_not_scan_visible_type_tables() { let source = Source::from_syntax(&tree).unwrap(); let parameters = source.modules()[0].parameters(); let context = AnalysisContext::unspecialized(&tree); - let env = const_env_from_parameters(&context, parameters); + let env = const_env_from_parameters(&context, session, parameters); dimensions::PARAMETER_TYPE_SCAN_ENTRIES.with(|counter| counter.set(0)); - let values = parameter_value_env(&context, parameters, &env); + let values = parameter_value_env(&context, session, 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 38403d0121c..ca397f2f1e0 100644 --- a/crates/celox-sv-analyzer/src/ast/constants.rs +++ b/crates/celox-sv-analyzer/src/ast/constants.rs @@ -4,6 +4,7 @@ use super::*; pub(super) fn bind_generate_parameter( tree: &AnalysisContext<'_>, + session: &mut Session, parameter: Parameter, const_env: &mut HashMap, parameter_literals: &mut HashMap, @@ -11,6 +12,7 @@ pub(super) fn bind_generate_parameter( let mut parameter_types = parameter_types_from_const_env(const_env); bind_generate_parameter_with_types( tree, + session, parameter, const_env, parameter_literals, @@ -20,6 +22,7 @@ pub(super) fn bind_generate_parameter( pub(super) fn bind_generate_parameter_with_types( tree: &AnalysisContext<'_>, + session: &mut Session, parameter: Parameter, const_env: &mut HashMap, parameter_literals: &mut HashMap, @@ -38,8 +41,13 @@ pub(super) fn bind_generate_parameter_with_types( i128::from(unbounded), ); let resolved_type = parameter.resolved_type(parameter_types); - let (resolved, resolved_literal) = - parameter.resolved_value_and_literal(tree, const_env, parameter_types, parameter_literals); + let (resolved, resolved_literal) = parameter.resolved_value_and_literal( + tree, + session, + 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 +57,7 @@ pub(super) fn bind_generate_parameter_with_types( })) } else { resolved_literal.or_else(|| { - parameter_value_env(tree, std::slice::from_ref(¶meter), const_env) + parameter_value_env(tree, session, std::slice::from_ref(¶meter), const_env) .remove(parameter.name()) .map(|value| substitute_expr_idents(value, parameter_literals)) }) @@ -86,11 +94,13 @@ pub(super) fn eval_ast_const_expr( pub(super) fn substitute_process_constants( tree: &AnalysisContext<'_>, + session: &mut Session, process: CombProcess, const_env: &HashMap, ) -> CombProcess { substitute_process_constants_with_parameter_literals( tree, + session, process, const_env, &HashMap::default(), @@ -99,13 +109,14 @@ pub(super) fn substitute_process_constants( pub(super) fn substitute_process_constants_with_parameter_literals( tree: &AnalysisContext<'_>, + session: &mut Session, 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(tree, stmt, const_env, parameter_literals); + procedural::substitute_stmt_constants(tree, session, stmt, const_env, parameter_literals); } let condition = process .condition @@ -113,7 +124,13 @@ 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(tree, stmt, const_env, parameter_literals); + procedural::substitute_stmt_constants( + tree, + session, + stmt, + const_env, + parameter_literals, + ); } return CombProcess { creation_order: process.creation_order, @@ -132,6 +149,7 @@ pub(super) fn substitute_process_constants_with_parameter_literals( .map(|assignment| { substitute_assignment_constants_with_parameter_literals( tree, + session, assignment, const_env, parameter_literals, @@ -148,6 +166,7 @@ pub(super) fn substitute_process_constants_with_parameter_literals( pub(super) fn substitute_assignment_constants_with_parameter_literals( tree: &AnalysisContext<'_>, + session: &mut Session, assignment: Assignment, const_env: &HashMap, parameter_literals: &HashMap, @@ -156,6 +175,7 @@ pub(super) fn substitute_assignment_constants_with_parameter_literals( substitute_lvalue_constants(assignment.lhs, const_env), substitute_expr_constants_with_parameter_literals( tree, + session, assignment.rhs, const_env, parameter_literals, @@ -192,11 +212,11 @@ pub(super) fn substitute_lvalue_constants( pub(super) fn substitute_expr_constants_with_parameter_literals( tree: &AnalysisContext<'_>, + session: &mut Session, expr: Expr, const_env: &HashMap, parameter_literals: &HashMap, ) -> Expr { - let state = &*tree.state; match expr { Expr::Ident(name) => parameter_literals .get(&name) @@ -235,6 +255,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( } => Expr::Select { expr: Box::new(substitute_expr_constants_with_parameter_literals( tree, + session, *expr, const_env, parameter_literals, @@ -249,6 +270,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( .map(|part| { substitute_expr_constants_with_parameter_literals( tree, + session, part, const_env, parameter_literals, @@ -263,6 +285,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( .map(|part| { substitute_expr_constants_with_parameter_literals( tree, + session, part, const_env, parameter_literals, @@ -277,6 +300,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( } => Expr::Resize { expr: Box::new(substitute_expr_constants_with_parameter_literals( tree, + session, *expr, const_env, parameter_literals, @@ -288,6 +312,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( op, expr: Box::new(substitute_expr_constants_with_parameter_literals( tree, + session, *expr, const_env, parameter_literals, @@ -296,6 +321,7 @@ 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( tree, + session, *left, const_env, parameter_literals, @@ -303,6 +329,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( op, right: Box::new(substitute_expr_constants_with_parameter_literals( tree, + session, *right, const_env, parameter_literals, @@ -315,18 +342,21 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( } => Expr::Mux { condition: Box::new(substitute_expr_constants_with_parameter_literals( tree, + session, *condition, const_env, parameter_literals, )), then_expr: Box::new(substitute_expr_constants_with_parameter_literals( tree, + session, *then_expr, const_env, parameter_literals, )), else_expr: Box::new(substitute_expr_constants_with_parameter_literals( tree, + session, *else_expr, const_env, parameter_literals, @@ -335,6 +365,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( tree, + session, *expr, const_env, parameter_literals, @@ -345,6 +376,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( item.map(&mut |operand| { substitute_expr_constants_with_parameter_literals( tree, + session, operand, const_env, parameter_literals, @@ -364,6 +396,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( arg.map(|arg| { substitute_expr_constants_with_parameter_literals( tree, + session, arg, const_env, parameter_literals, @@ -374,7 +407,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( let function = callee.system(); if let Some(function @ (SystemFunction::Signed | SystemFunction::Unsigned)) = function && let [Some(arg)] = args.as_slice() - && let Some(constant) = expr_to_const(state, arg.clone()) + && let Some(constant) = expr_to_const(session, arg.clone()) && let Some(ty) = infer_const_expr_type(&constant, ¶meter_types_from_const_env(const_env)) { @@ -387,6 +420,7 @@ pub(super) fn substitute_expr_constants_with_parameter_literals( // Resolve constant calls before SLT lowering while retaining X/Z masks. fold_const_integral_expr_preserving_mask( tree, + session, Expr::Call { callee, args, @@ -578,7 +612,7 @@ fn substitute_const_expr_constants_impl( } /// Convert an expression to its symbolic constant form when representable. -pub(super) fn expr_to_const(state: &AnalysisState, expr: Expr) -> Option { +pub(super) fn expr_to_const(state: &mut Session, expr: Expr) -> Option { match expr { Expr::Ident(name) => Some(ConstExpr::Ident(name)), Expr::Literal(value) => Some(ConstExpr::Literal(value)), @@ -613,11 +647,11 @@ pub(super) fn expr_to_const(state: &AnalysisState, expr: Expr) -> Option>()?, + state, )) } Expr::Select { .. } @@ -630,10 +664,10 @@ pub(super) fn expr_to_const(state: &AnalysisState, expr: Expr) -> Option, + session: &mut Session, expr: Expr, dimensions: &PackedDimensions, ) -> Option { - let state = &*tree.state; let functions = &tree.functions; match expr { Expr::Resize { @@ -645,7 +679,7 @@ pub(super) fn expr_to_index_const( return Some(ConstExpr::Literal("0".into())); } Some(ConstExpr::Resize { - expr: Box::new(expr_to_index_const(tree, *expr, dimensions)?), + expr: Box::new(expr_to_index_const(tree, session, *expr, dimensions)?), width, signed, }) @@ -654,12 +688,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(tree, *expr, dimensions)?), + expr: Box::new(expr_to_index_const(tree, session, *expr, dimensions)?), }), Expr::Binary { left, op, right } => Some(ConstExpr::Binary { - left: Box::new(expr_to_index_const(tree, *left, dimensions)?), + left: Box::new(expr_to_index_const(tree, session, *left, dimensions)?), op, - right: Box::new(expr_to_index_const(tree, *right, dimensions)?), + right: Box::new(expr_to_index_const(tree, session, *right, dimensions)?), }), Expr::Select { expr, @@ -668,7 +702,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(tree, *expr, dimensions)?), + expr: Box::new(expr_to_index_const(tree, session, *expr, dimensions)?), msb: Box::new(msb), lsb: Box::new(lsb), signed, @@ -679,9 +713,9 @@ pub(super) fn expr_to_index_const( then_expr, else_expr, } => Some(ConstExpr::Mux { - 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)?), + condition: Box::new(expr_to_index_const(tree, session, *condition, dimensions)?), + then_expr: Box::new(expr_to_index_const(tree, session, *then_expr, dimensions)?), + else_expr: Box::new(expr_to_index_const(tree, session, *else_expr, dimensions)?), }), Expr::Call { callee, @@ -694,11 +728,11 @@ pub(super) fn expr_to_index_const( return None; } Some(ConstExpr::call( - state, callee, args.into_iter() - .map(|arg| expr_to_index_const(tree, arg?, dimensions)) + .map(|arg| expr_to_index_const(tree, session, arg?, dimensions)) .collect::>()?, + session, )) } Expr::Select { @@ -729,13 +763,13 @@ pub(super) fn expr_to_index_const( if inlining::calls_subroutine(&expr) { return None; } - let source = IndexBitSource::from_expr(tree, expr, dimensions)?; + let source = IndexBitSource::from_expr(tree, session, expr, dimensions)?; positions .map(|bit| source.bit(bit)) .collect::>()? } expr => { - let expr = expr_to_index_const(tree, expr, dimensions)?; + let expr = expr_to_index_const(tree, session, expr, dimensions)?; positions .map(|bit| ConstExpr::Select { expr: Box::new(expr.clone()), @@ -752,7 +786,7 @@ pub(super) fn expr_to_index_const( if inlining::calls_subroutine(&expr) { return None; } - let source = IndexBitSource::from_expr(tree, expr, dimensions)?; + let source = IndexBitSource::from_expr(tree, session, expr, dimensions)?; let width = source.width(); if width > constant_folding::MAX_CONSTANT_CONCAT_BITS { return None; @@ -835,6 +869,7 @@ enum IndexBitSource { impl IndexBitSource { fn from_expr( tree: &AnalysisContext<'_>, + session: &mut Session, expr: Expr, dimensions: &PackedDimensions, ) -> Option { @@ -844,12 +879,17 @@ impl IndexBitSource { Expr::Concat(parts) => Self::Concat { parts: parts .into_iter() - .map(|part| Self::from_expr(tree, part, dimensions)) + .map(|part| Self::from_expr(tree, session, part, dimensions)) .collect::>()?, width, }, Expr::RepeatConcat { parts, .. } => Self::Repeat { - part: Box::new(Self::from_expr(tree, Expr::Concat(parts), dimensions)?), + part: Box::new(Self::from_expr( + tree, + session, + Expr::Concat(parts), + dimensions, + )?), width, }, Expr::Resize { expr, .. } => { @@ -860,7 +900,7 @@ impl IndexBitSource { &dimensions.function_return_types, )?; Self::Resize { - part: Box::new(Self::from_expr(tree, *expr, dimensions)?), + part: Box::new(Self::from_expr(tree, session, *expr, dimensions)?), width, extend_signed, } @@ -876,7 +916,7 @@ impl IndexBitSource { 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(tree, expr, dimensions)?), + part: Box::new(Self::from_expr(tree, session, expr, dimensions)?), width, right, step: if left >= right { 1 } else { -1 }, @@ -887,6 +927,7 @@ impl IndexBitSource { // when its position in an unpacked array is dynamic. expr: expr_to_index_const( tree, + session, Expr::Select { expr: Box::new(expr), msb, @@ -916,7 +957,7 @@ impl IndexBitSource { (0, 1) }; Self::Scalar { - expr: expr_to_index_const(tree, expr, dimensions)?, + expr: expr_to_index_const(tree, session, expr, dimensions)?, width, right, step, @@ -985,10 +1026,10 @@ mod tests; /// of the syntax adapter that supplied the call and its actual values. pub(super) fn user_call_value( tree: &AnalysisContext<'_>, + session: &mut Session, expression: Expr, constants: &HashMap, ) -> Option { - let state = &*tree.state; let functions = &tree.functions; if let Expr::Call { args, arg_order, .. @@ -1008,20 +1049,22 @@ pub(super) fn user_call_value( 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(tree, &arg, constants, &types) + expr_to_const(session, arg.clone()).or_else(|| { + constant_folding::constant_with_folded_selections( + tree, session, &arg, constants, &types, + ) }) }) .collect::>>()?; // Keep references to parameters for consumers that re-specialize the // declaration contract; retain the native function's result type too. return Some(ConstExpr::Resize { - expr: Box::new(ConstExpr::call(state, callee.clone(), args)), + expr: Box::new(ConstExpr::call(callee.clone(), args, session)), width: literal.width, signed: literal.signed, }); } - expr_to_const(state, expression.clone()).or_else(|| { + expr_to_const(session, expression.clone()).or_else(|| { let Expr::Call { callee, args, @@ -1041,12 +1084,14 @@ pub(super) fn user_call_value( .into_iter() .map(|arg| { let arg = arg?; - expr_to_const(state, arg.clone()).or_else(|| { - constant_folding::constant_with_folded_selections(tree, &arg, constants, &types) + expr_to_const(session, arg.clone()).or_else(|| { + constant_folding::constant_with_folded_selections( + tree, session, &arg, constants, &types, + ) }) }) .collect::>>()?; - Some(ConstExpr::call(state, callee, args)) + Some(ConstExpr::call(callee, args, session)) }) } @@ -1055,10 +1100,10 @@ pub(super) fn user_call_value( // and preserves the selected width, including when zero bits are counted. pub(super) fn countbits_constant_call( tree: &AnalysisContext<'_>, + session: &mut Session, expression: Expr, const_env: &HashMap, ) -> Option { - let state = &*tree.state; let Expr::Call { args, .. } = expression else { return None; }; @@ -1068,28 +1113,28 @@ pub(super) fn countbits_constant_call( .into_iter() .map(|control| match control { Expr::Select { expr, lsb, .. } => Some(ConstExpr::Select { - expr: Box::new(expr_to_const(state, *expr)?), + expr: Box::new(expr_to_const(session, *expr)?), bit: Box::new(lsb), }), - control => expr_to_const(state, control), + control => expr_to_const(session, control), }) .collect::>>()?; - countbits_constant_operand(tree, operand, &controls, const_env) + countbits_constant_operand(tree, session, operand, &controls, const_env) } fn countbits_constant_operand( tree: &AnalysisContext<'_>, + session: &mut Session, operand: Expr, controls: &[ConstExpr], const_env: &HashMap, ) -> Option { - let state = &*tree.state; let functions = &tree.functions; - let call = |operand| { + let call = |session: &mut Session, operand| { let mut args = Vec::with_capacity(controls.len() + 1); args.push(operand); args.extend_from_slice(controls); - ConstExpr::call(state, Callee::System(SystemFunction::Countbits), args) + ConstExpr::call(Callee::System(SystemFunction::Countbits), args, session) }; let sum = |mut terms: Vec| { // Keep large selected vectors from creating a deeply nested sum. @@ -1118,34 +1163,45 @@ fn countbits_constant_operand( if width > constant_folding::MAX_CONSTANT_CONCAT_BITS { return None; } - let operand = expr_to_const(state, *expr)?; + let operand = expr_to_const(session, *expr)?; sum((lsb..=msb) .map(|bit| { - call(ConstExpr::Select { - expr: Box::new(operand.clone()), - bit: Box::new(ConstExpr::Literal(bit.to_string())), - }) + call( + session, + ConstExpr::Select { + expr: Box::new(operand.clone()), + bit: Box::new(ConstExpr::Literal(bit.to_string())), + }, + ) }) .collect()) } Expr::Concat(parts) => sum(parts .into_iter() - .map(|part| countbits_constant_operand(tree, part, controls, const_env)) + .map(|part| countbits_constant_operand(tree, session, part, controls, const_env)) .collect::>>()?), Expr::RepeatConcat { count, parts } => { let count = eval_ast_const_expr(functions, &count, const_env)?; if count < 0 { return None; } - let counted = - countbits_constant_operand(tree, Expr::Concat(parts), controls, const_env)?; + let counted = countbits_constant_operand( + tree, + session, + Expr::Concat(parts), + controls, + const_env, + )?; Some(ConstExpr::Binary { left: Box::new(counted), op: BinaryOp::Mul, right: Box::new(ConstExpr::Literal(format!("32'sd{count}"))), }) } - operand => Some(call(expr_to_const(state, operand)?)), + operand => { + let operand = expr_to_const(session, operand)?; + Some(call(session, operand)) + } } } diff --git a/crates/celox-sv-analyzer/src/ast/constants/tests.rs b/crates/celox-sv-analyzer/src/ast/constants/tests.rs index 6423dded4f6..69d6f7d087e 100644 --- a/crates/celox-sv-analyzer/src/ast/constants/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/constants/tests.rs @@ -2,6 +2,7 @@ use super::*; use std::{fmt::Write, path::Path}; fn environment(count: usize) -> HashMap { + let session = &mut Session::default(); let syntax = crate::source_tree::SourceTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); let mut parameter = Parameter::new( @@ -17,7 +18,7 @@ fn environment(count: usize) -> HashMap { ConstExpr::Literal("7".into()), ConstExpr::Literal("0".into()), )); - let mut env = const_env_from_parameters(&tree, &[parameter]); + let mut env = const_env_from_parameters(&tree, session, &[parameter]); env.insert("W".into(), 3); env.insert("Q".into(), 9); for i in 0..count { @@ -126,6 +127,7 @@ fn concat_slice_indices_accept_dynamic_array_elements() { #[test] fn native_constant_calls_preserve_contextual_operand_shapes() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_source( "module M;parameter N=f(P[0+:W],byte_t'(P),$bits(P));endmodule", Path::new("native-call-context.sv"), @@ -161,7 +163,7 @@ fn native_constant_calls_preserve_contextual_operand_shapes() { _ => None, }) .unwrap(); - let value = constant_binding::bind(root, &tree, &context) + let value = constant_binding::bind(root, &tree, session, &context) .unwrap() .unwrap(); let ConstExpr::Function { callee, args, .. } = value else { diff --git a/crates/celox-sv-analyzer/src/ast/containers.rs b/crates/celox-sv-analyzer/src/ast/containers.rs index c8999a181a0..6f8542049a5 100644 --- a/crates/celox-sv-analyzer/src/ast/containers.rs +++ b/crates/celox-sv-analyzer/src/ast/containers.rs @@ -9,6 +9,7 @@ pub(super) fn with_dimensions( base: Type, dims: &[Dimension], tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted { let Some(first) = dims.first() else { @@ -21,7 +22,7 @@ pub(super) fn with_dimensions( let capacity = match bound { None => 0, Some(id) => { - let bound = constant_binding::bind(id, tree, context)? + let bound = constant_binding::bind(id, tree, session, context)? .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) @@ -35,15 +36,17 @@ pub(super) fn with_dimensions( } DimensionKind::Index(id) => { let key_type = match &tree.declarations().expression(id).kind { - ExprKind::Type(id) => type_binding::bind(*id, tree, context)?, + ExprKind::Type(id) => type_binding::bind(*id, tree, session, context)?, ExprKind::Name(name) => { let name = instances::normalize_identifier(&name.spelling); match context.type_aliases.get(&name) { Some(ty) => Some(ty.clone()), // A class: the index is an object handle (IEEE // 1800-2023 7.8.5). - None if context.get(&name).is_none() => classes::resolve(tree, &name) - .and_then(|class| classes::handle_type(tree, &class)), + None if context.get(&name).is_none() => { + classes::resolve(tree, session, &name) + .and_then(|class| classes::handle_type(tree, session, &class)) + } None => None, } } @@ -89,13 +92,13 @@ pub(super) fn with_dimensions( let Some(kind) = kind else { return Ok(types::type_with_unpacked_ranges( base, - constant_binding::bind_unpacked_ranges(dims, tree, context)?, + constant_binding::bind_unpacked_ranges(dims, tree, session, context)?, )); }; // `T a[x][y]`: each element of `a` is a container `T [y]` (IEEE // 1800-2023 7.4.5, 7.8), held by its handle like any container value. let base = if dims.len() > 1 { - with_dimensions(base, &dims[1..], tree, context)? + with_dimensions(base, &dims[1..], tree, session, context)? } else { base }; @@ -179,6 +182,7 @@ pub(super) fn native_type( id: ExprId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted>> { if let ExprKind::Name(name) = &native @@ -188,10 +192,12 @@ pub(super) fn native_type( { return Ok(shape.container.clone()); } - if let Some((property, _)) = expression_binding::object_property(tree, id, native, dims)? { + if let Some((property, _)) = + expression_binding::object_property(tree, session, id, native, dims)? + { return Ok(property.r#type.container); } - if let Some(name) = expression_binding::object_static_property(tree, id, native, dims)? + if let Some(name) = expression_binding::object_static_property(tree, session, id, native, dims)? && let Some(shape) = dims.get(&name) { return Ok(shape.container.clone()); @@ -210,7 +216,7 @@ pub(super) fn native_type( expression, name, .. } = &native.expression(callee).kind && matches!(name.spelling.as_str(), "pop_front" | "pop_back") - && let Some(outer) = native_type(*expression, native, tree, dims)? + && let Some(outer) = native_type(*expression, native, tree, session, dims)? && let Some(inner) = outer.element.container.clone() { return Ok(Some(inner)); @@ -226,11 +232,17 @@ pub(super) fn native_type( dimension.kind, DimensionKind::Index(_) | DimensionKind::Queue(None) ) - && let Some(outer) = native_type(*expression, native, tree, dims)? + && let Some(outer) = native_type(*expression, native, tree, session, dims)? { return Ok(outer.element.container.clone()); } - locators::result_type(expression_binding::ungroup(id, native), native, tree, dims) + locators::result_type( + expression_binding::ungroup(id, native), + native, + tree, + session, + dims, + ) } pub(super) fn call(op: ContainerOp, layout: ContainerLayout, args: Vec) -> Expr { @@ -268,6 +280,7 @@ pub(super) fn dynamic_array_new( pub(super) fn assignment( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, target: &ContainerType, ) -> Converted { @@ -280,11 +293,11 @@ pub(super) fn assignment( let DimensionKind::Index(size) = dimension.kind else { return Err(unsupported("dynamic array size")); }; - let size = expression_binding::value(size, native, tree, dims)?; + let size = expression_binding::value(size, native, tree, session, dims)?; let init = match initializer { Some(id) => { - check_compatible(id, native, tree, dims, target)?; - expression_binding::value(id, native, tree, dims)? + check_compatible(id, native, tree, session, dims, target)?; + expression_binding::value(id, native, tree, session, dims)? } None => Expr::Literal("0".into()), }; @@ -311,20 +324,20 @@ pub(super) fn assignment( let mut parts = Vec::with_capacity(items.len()); let mut values = Vec::with_capacity(items.len()); for id in items { - match native_type(id, native, tree, dims)? { + match native_type(id, native, tree, session, dims)? { Some(item) if concatenation && target.element.container.is_none() => { if matches!(item.layout.kind, ContainerKind::Associative { .. }) { return Err(unsupported( "associative array in an unpacked array concatenation", )); } - check_compatible(id, native, tree, dims, target)?; + check_compatible(id, native, tree, session, dims, target)?; parts.push(Some(item.layout)); - values.push(expression_binding::value(id, native, tree, dims)?); + values.push(expression_binding::value(id, native, tree, session, dims)?); } _ => { parts.push(None); - values.push(element_value(id, tree, dims, target)?); + values.push(element_value(id, tree, session, dims, target)?); } } } @@ -339,11 +352,13 @@ pub(super) fn assignment( } return Ok(call(ContainerOp::Literal, target.layout, values)); } - check_compatible(root, native, tree, dims, target)?; + check_compatible(root, native, tree, session, dims, target)?; Ok(call( ContainerOp::Convert, target.layout, - vec![expression_binding::value(root, native, tree, dims)?], + vec![expression_binding::value( + root, native, tree, session, dims, + )?], )) } /// An output or inout container formal is copied back to its actual, and an @@ -353,13 +368,15 @@ pub(super) fn assignment( pub(super) fn check_written_actual( id: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, formal: &ContainerType, inout: bool, ) -> Converted<()> { let native = tree.declarations(); - check_compatible(id, native, tree, dims, formal)?; - let actual = native_type(id, native, tree, dims)?.expect("checked by `check_compatible`"); + check_compatible(id, native, tree, session, dims, formal)?; + let actual = + native_type(id, native, tree, session, dims)?.expect("checked by `check_compatible`"); let bound = |kind| match kind { ContainerKind::Queue { capacity } => capacity, _ => 0, @@ -377,10 +394,11 @@ fn check_compatible( id: ExprId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, target: &ContainerType, ) -> Converted<()> { - let Some(source) = native_type(id, native, tree, dims)? else { + let Some(source) = native_type(id, native, tree, session, dims)? else { return Err(unsupported( "container assignment requires a compatible container", )); @@ -414,6 +432,7 @@ fn check_compatible( fn element_value( id: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, target: &ContainerType, ) -> Converted { @@ -421,24 +440,32 @@ fn element_value( // An element that is itself a container takes a container value, as an // assignment to a container variable does. if let Some(inner) = target.element.container.as_deref() { - return assignment(id, tree, dims, inner); + return assignment(id, tree, session, dims, inner); } - if native_type(id, native, tree, dims)?.is_some() { + if native_type(id, native, tree, session, dims)?.is_some() { return Err(unsupported("container used as an element")); } if let Some(class) = target.element.class.as_deref() { - if let Some(call) = expression_binding::object_constructor(tree, id, native, dims, class)? { + if let Some(call) = + expression_binding::object_constructor(tree, session, id, native, dims, class)? + { return Ok(call); } - expression_binding::check_handle_assignment(tree, id, native, dims, class, || { - "container element assignment".into() - })?; + expression_binding::check_handle_assignment( + tree, + session, + id, + native, + dims, + class, + || "container element assignment".into(), + )?; } if let Some(aggregate) = target.element.unpacked_struct() { - unpacked_structs::check_value(aggregate, id, native, tree, dims)?; + unpacked_structs::check_value(aggregate, id, native, tree, session, dims)?; } let shape = procedural::dimensions_from_type(&target.element); - let value = expression_binding::bind_value(id, native, tree, dims, Some(&shape))?; + let value = expression_binding::bind_value(id, native, tree, session, dims, Some(&shape))?; if let Some(record) = &target.record { return Ok(classes::object_call( ObjectOp::Box(record.clone()), @@ -472,6 +499,7 @@ fn index_value( id: ExprId, base: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, target: &ContainerType, ) -> Converted { @@ -483,14 +511,20 @@ fn index_value( ContainerKind::Associative { object: true, .. } ) }) { - expression_binding::check_handle_assignment(tree, id, native, dims, class, || { - "associative array index".into() - })?; + expression_binding::check_handle_assignment( + tree, + session, + id, + native, + dims, + class, + || "associative array index".into(), + )?; } if matches!( target.layout.kind, ContainerKind::Associative { string: true, .. } - ) && !expression_binding::native_string(tree, id, native, dims) + ) && !expression_binding::native_string(tree, session, id, native, dims) && !matches!(&native.expression(expression_binding::ungroup(id, native)).kind, ExprKind::Literal(text) if text.starts_with('"')) { return Err(unsupported( @@ -505,22 +539,25 @@ fn index_value( if name.spelling == "$" && matches!(target.layout.kind, ContainerKind::Queue { .. }) => { - last_index(target, expression_binding::value(base, native, tree, dims)?)? + last_index( + target, + expression_binding::value(base, native, tree, session, dims)?, + )? } ExprKind::Binary { left, operator, right, } if operator == "+" || operator == "-" => Expr::Binary { - left: Box::new(index_value(*left, base, tree, dims, target)?), + left: Box::new(index_value(*left, base, tree, session, dims, target)?), op: if operator == "+" { BinaryOp::Add } else { BinaryOp::Sub }, - right: Box::new(index_value(*right, base, tree, dims, target)?), + right: Box::new(index_value(*right, base, tree, session, dims, target)?), }, - _ => expression_binding::value(id, native, tree, dims)?, + _ => expression_binding::value(id, native, tree, session, dims)?, }; Ok( if matches!( @@ -538,10 +575,11 @@ pub(super) fn value( id: ExprId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, statement: bool, ) -> Converted> { - if let Some(query) = query(id, native, tree, dims)? { + if let Some(query) = query(id, native, tree, session, dims)? { return Ok(Some(query)); } match &native.expression(id).kind { @@ -549,14 +587,15 @@ pub(super) fn value( left, operator, right, - } if native_type(*left, native, tree, dims)?.is_some() - || native_type(*right, native, tree, dims)?.is_some() => + } if native_type(*left, native, tree, session, dims)?.is_some() + || native_type(*right, native, tree, session, dims)?.is_some() => { - let Some(target) = native_type(*left, native, tree, dims)? else { + let Some(target) = native_type(*left, native, tree, session, dims)? else { return Err(unsupported("container comparison requires two containers")); }; - check_compatible(*right, native, tree, dims, &target)?; - let source = native_type(*right, native, tree, dims)?.expect("checked compatibility"); + check_compatible(*right, native, tree, session, dims, &target)?; + let source = + native_type(*right, native, tree, session, dims)?.expect("checked compatibility"); if std::mem::discriminant(&source.layout.kind) != std::mem::discriminant(&target.layout.kind) { @@ -583,8 +622,8 @@ pub(super) fn value( op, target.layout, vec![ - expression_binding::value(*left, native, tree, dims)?, - expression_binding::value(*right, native, tree, dims)?, + expression_binding::value(*left, native, tree, session, dims)?, + expression_binding::value(*right, native, tree, session, dims)?, ], ); Ok(Some(if matches!(operator.as_str(), "!=" | "!==") { @@ -600,7 +639,7 @@ pub(super) fn value( expression, dimension, } => { - let Some(target) = native_type(*expression, native, tree, dims)? else { + let Some(target) = native_type(*expression, native, tree, session, dims)? else { return Ok(None); }; let index = match dimension.kind { @@ -618,12 +657,20 @@ pub(super) fn value( ContainerOp::Get, target.layout, vec![ - expression_binding::value(*expression, native, tree, dims)?, + expression_binding::value(*expression, native, tree, session, dims)?, match index { - Some(index) => index_value(index, *expression, tree, dims, &target)?, + Some(index) => { + index_value(index, *expression, tree, session, dims, &target)? + } None => last_index( &target, - expression_binding::value(*expression, native, tree, dims)?, + expression_binding::value( + *expression, + native, + tree, + session, + dims, + )?, )?, }, ], @@ -648,7 +695,7 @@ pub(super) fn value( else { return Ok(None); }; - let Some(target) = native_type(*base, native, tree, dims)? else { + let Some(target) = native_type(*base, native, tree, session, dims)? else { return Ok(None); }; if separator != "." { @@ -744,7 +791,9 @@ pub(super) fn value( { return Err(unsupported("type queries on nonintegral queue pop results")); } - let mut args = vec![expression_binding::value(*base, native, tree, dims)?]; + let mut args = vec![expression_binding::value( + *base, native, tree, session, dims, + )?]; for (index, arg) in arguments.iter().enumerate() { let id = arg.value.unwrap(); if matches!( @@ -773,13 +822,13 @@ pub(super) fn value( "incompatible associative traversal index variable", )); } - args.push(expression_binding::value(id, native, tree, dims)?); + args.push(expression_binding::value(id, native, tree, session, dims)?); } else if matches!(op, ContainerOp::PushFront | ContainerOp::PushBack) || op == ContainerOp::Insert && index == 1 { - args.push(element_value(id, tree, dims, &target)?); + args.push(element_value(id, tree, session, dims, &target)?); } else { - args.push(index_value(id, *base, tree, dims, &target)?); + args.push(index_value(id, *base, tree, session, dims, &target)?); } } let value = call(op, target.layout, args); @@ -799,6 +848,7 @@ fn query( id: ExprId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { let ExprKind::Call { @@ -828,7 +878,7 @@ fn query( let Some(base) = arguments.first().and_then(|a| a.value) else { return Ok(None); }; - let Some(target) = native_type(base, native, tree, dims)? else { + let Some(target) = native_type(base, native, tree, session, dims)? else { return Ok(None); }; if arguments @@ -884,7 +934,7 @@ fn query( } let dimension = match arguments.get(1).and_then(|a| a.value) { None => 1, - Some(id) => constant_binding::bind(id, tree, dims)? + Some(id) => constant_binding::bind(id, tree, session, dims)? .and_then(|v| eval_ast_const_expr(&tree.functions, &v, &dims.const_env)) .ok_or_else(|| unsupported("nonconstant dynamic array query dimension"))?, }; @@ -896,11 +946,13 @@ fn query( if matches!(target.layout.kind, ContainerKind::Associative { .. }) && name.spelling != "$size" { return Err(unsupported("associative bound query")); } - let size = || -> Converted { + let mut size = || -> Converted { Ok(call( ContainerOp::Size, target.layout, - vec![expression_binding::value(base, native, tree, dims)?], + vec![expression_binding::value( + base, native, tree, session, dims, + )?], )) }; Ok(Some(match name.spelling.as_str() { @@ -921,6 +973,7 @@ pub(super) fn set( op: &str, nonblocking: bool, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { let native = tree.declarations(); @@ -931,21 +984,29 @@ pub(super) fn set( else { return Ok(None); }; - let Some(target) = native_type(*expression, native, tree, dims)? else { + let Some(target) = native_type(*expression, native, tree, session, dims)? else { return Ok(None); }; if nonblocking { return Err(unsupported("nonblocking dynamic element assignment")); } - let container = expression_binding::value(*expression, native, tree, dims)?; + let container = expression_binding::value(*expression, native, tree, session, dims)?; let index = match dimension.kind { - DimensionKind::Index(index) => index_value(index, *expression, tree, dims, &target)?, + DimensionKind::Index(index) => { + index_value(index, *expression, tree, session, dims, &target)? + } DimensionKind::Queue(None) if matches!(target.layout.kind, ContainerKind::Queue { .. }) => { Expr::Binary { left: Box::new(call( ContainerOp::Size, target.layout, - vec![expression_binding::value(*expression, native, tree, dims)?], + vec![expression_binding::value( + *expression, + native, + tree, + session, + dims, + )?], )), op: BinaryOp::Sub, right: Box::new(Expr::Literal("1".into())), @@ -954,9 +1015,9 @@ pub(super) fn set( _ => return Err(unsupported("dynamic element slice assignment")), }; let value = if op == "=" { - element_value(right, tree, dims, &target)? + element_value(right, tree, session, dims, &target)? } else { - compound_value(op, right, &container, &index, tree, dims, &target)? + compound_value(op, right, &container, &index, tree, session, dims, &target)? }; Ok(Some(Stmt::Eval(call( ContainerOp::Set, @@ -975,6 +1036,7 @@ fn compound_value( container: &Expr, index: &Expr, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, target: &ContainerType, ) -> Converted { @@ -1023,6 +1085,7 @@ fn compound_value( right, tree.declarations(), tree, + session, dims, )?), }) @@ -1251,6 +1314,7 @@ fn struct_element( id: ExprId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted, Expr)>> { let id = expression_binding::ungroup(id, native); @@ -1273,13 +1337,13 @@ fn struct_element( } _ => return Ok(None), }; - let Some(target) = native_type(base, native, tree, dims)? else { + let Some(target) = native_type(base, native, tree, session, dims)? else { return Ok(None); }; if target.element.unpacked_struct().is_none() { return Ok(None); } - let Some(value) = value(id, native, tree, dims, false)? else { + let Some(value) = value(id, native, tree, session, dims, false)? else { return Ok(None); }; let raw = match value { @@ -1302,6 +1366,7 @@ pub(super) fn native_struct_element( id: ExprId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted>> { let id = expression_binding::ungroup(id, native); @@ -1321,7 +1386,7 @@ pub(super) fn native_struct_element( } if matches!(name.spelling.as_str(), "pop_front" | "pop_back") => *expression, _ => return Ok(None), }; - Ok(native_type(base, native, tree, dims)? + Ok(native_type(base, native, tree, session, dims)? .and_then(|target| target.element.unpacked_struct().cloned())) } @@ -1331,6 +1396,7 @@ pub(super) fn element_member( id: ExprId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { let mut names = Vec::new(); @@ -1349,12 +1415,12 @@ pub(super) fn element_member( } names.push(instances::normalize_identifier(&name.spelling)); current = expression_binding::ungroup(*expression, native); - if native_struct_element(current, native, tree, dims)?.is_some() { + if native_struct_element(current, native, tree, session, dims)?.is_some() { break current; } }; names.reverse(); - let Some((target, raw)) = struct_element(element, native, tree, dims)? else { + let Some((target, raw)) = struct_element(element, native, tree, session, dims)? else { return Ok(None); }; let aggregate = target diff --git a/crates/celox-sv-analyzer/src/ast/declarations.rs b/crates/celox-sv-analyzer/src/ast/declarations.rs index 6221d7723d0..56bc4a11bb5 100644 --- a/crates/celox-sv-analyzer/src/ast/declarations.rs +++ b/crates/celox-sv-analyzer/src/ast/declarations.rs @@ -4,6 +4,7 @@ use super::*; pub(super) fn ports_from_scope( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, type_aliases: &HashMap, selected: Option<&port_owners::Selection<'_>>, @@ -30,11 +31,12 @@ pub(super) fn ports_from_scope( celox_sv_syntax::DataTypeKind::Implicit ) }); - let base = match type_binding::port_type(native, syntax_tree, const_env, type_aliases)? { - Some(ty) => ty, - None if native.data_type.is_none() => inherited_type.clone(), - None => return Err(unsupported("unsupported port data type")), - }; + let base = + match type_binding::port_type(native, syntax_tree, session, const_env, type_aliases)? { + Some(ty) => ty, + None if native.data_type.is_none() => inherited_type.clone(), + None => return Err(unsupported("unsupported port data type")), + }; inherited_direction = direction; inherited_type = base.clone(); let ty = type_with_unpacked_ranges( @@ -42,6 +44,7 @@ pub(super) fn ports_from_scope( constant_binding::unpacked_ranges( &native.dimensions, syntax_tree, + session, const_env, type_aliases, )?, @@ -79,20 +82,23 @@ pub(super) fn ports_from_scope( syntax_tree.declarations(), &LValue::Ident(name), syntax_tree, + session, &dimensions, )?; let value = fold_const_integral_expr_preserving_mask( syntax_tree, + session, expression, const_env, ); - return expr_to_const(&syntax_tree.state, value) + return expr_to_const(session, value) .ok_or_else(|| unsupported("nonconstant unpacked input port default")); } constant_binding::expression( value, syntax_tree.declarations(), syntax_tree, + session, const_env, type_aliases, )? @@ -188,6 +194,7 @@ pub(super) fn module_interface_from_scope( pub(super) fn parameters_from_scope( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, type_aliases: &HashMap, base_const_env: &HashMap, parameter_overrides: &HashMap, @@ -195,6 +202,7 @@ pub(super) fn parameters_from_scope( let mut parameters = Vec::new(); let mut environment = parameters::ParameterEnvironment::new( syntax_tree, + session, ¶meters, base_const_env, ¶meters::ownership::scope_names(syntax_tree)?, @@ -229,6 +237,7 @@ pub(super) fn parameters_from_scope( parameters::parameters_from_native_with_environment( values, syntax_tree, + session, &mut parameters, values[0].local, base_const_env, @@ -258,6 +267,7 @@ pub(super) fn parameters_from_scope( parameters::parameters_from_native_with_environment( &values, syntax_tree, + session, &mut parameters, local, base_const_env, @@ -272,20 +282,22 @@ pub(super) fn parameters_from_scope( pub(super) fn signals_from_scope( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, type_aliases: &HashMap, ) -> Result, AnalyzerError> { - signals_from_scope_with_declaration_ranges(syntax_tree, const_env, type_aliases, false) + signals_from_scope_with_declaration_ranges(syntax_tree, session, const_env, type_aliases, false) } pub(super) fn signals_from_scope_with_declaration_ranges( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, type_aliases: &HashMap, preserve_parameters: bool, ) -> Result, AnalyzerError> { let mut signals = Vec::new(); - for mut item in generate::items(syntax_tree, const_env, type_aliases)? { + for mut item in generate::items(syntax_tree, session, const_env, type_aliases)? { let syntax_tree = &item.scoped(syntax_tree); if preserve_parameters { let names = item.env.keys().cloned().collect::>(); @@ -298,6 +310,7 @@ pub(super) fn signals_from_scope_with_declaration_ranges( signals_from_body_item( item.id, syntax_tree, + session, &item.type_aliases(type_aliases), &item.env, None, @@ -323,6 +336,7 @@ pub(super) fn signals_from_scope_with_declaration_ranges( pub(super) fn signals_from_body_item( id: celox_sv_syntax::BodyItemId, tree: &AnalysisContext<'_>, + session: &mut Session, aliases: &HashMap, env: &HashMap, selected_name: Option<&str>, @@ -359,9 +373,9 @@ pub(super) fn signals_from_body_item( celox_sv_syntax::DataTypeKind::Named(_) ) { - type_binding::alias_signals(value, tree, env, aliases, selected_name)? + type_binding::alias_signals(value, tree, session, env, aliases, selected_name)? } else { - type_binding::local_signals(value, tree, env, aliases, selected_name)? + type_binding::local_signals(value, tree, session, env, aliases, selected_name)? } } DataDeclaration::Unconverted(_) => { @@ -373,6 +387,7 @@ pub(super) fn signals_from_body_item( BodyItemKind::Net(id) => type_binding::net_signals( tree.declarations().net_declaration(id), tree, + session, env, aliases, selected_name, @@ -393,6 +408,7 @@ pub(super) fn signals_from_body_item( constant_binding::bind_unpacked_ranges( &variable.dimensions, tree, + session, &context, )?, ); @@ -401,7 +417,7 @@ pub(super) fn signals_from_body_item( } values } - BodyItemKind::Unconverted { .. } => classes::item_statics(id, tree, env, aliases) + BodyItemKind::Unconverted { .. } => classes::item_statics(id, tree, session, env, aliases) .into_iter() .filter(|property| selected_name.is_none_or(|selected| selected == property.variable)) .map(|property| Signal::new(property.variable, property.r#type)) diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs index 7cc71fda770..cf7078ecfa2 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/discovery.rs @@ -16,15 +16,15 @@ struct Key { } #[derive(Default)] pub(in crate::ast) struct State { - partial: RefCell>, + partial: HashMap, /// The class method signatures that discovery last published in each /// scope, by arena and scope. class_signatures: - RefCell>>, + HashMap<(usize, crate::source_tree::ScopeHandle), std::rc::Rc>, /// The declarations a query discovered in each scope, before the parts /// that depend on its operand, while the query's input and the set of /// specializations stay the same. - settled: RefCell>, + settled: HashMap, } /// A settled discovery of [`State::settled`]. `input` is held so that the @@ -66,17 +66,8 @@ struct ClassSignatures { names: Vec<(String, Vec)>, returns: Vec<(String, FunctionReturnMetadata)>, } -struct Guard<'a>(&'a State, Key); -impl Drop for Guard<'_> { - fn drop(&mut self) { - self.0.partial.borrow_mut().remove(&self.1); - } -} -fn publish(state: &State, key: &Key, context: &PackedDimensions) { - state - .partial - .borrow_mut() - .insert(key.clone(), context.clone()); +fn publish(state: &mut State, key: &Key, context: &PackedDimensions) { + state.partial.insert(key.clone(), context.clone()); } fn contains(outer: TokenRange, inner: TokenRange) -> bool { outer.start <= inner.start && inner.end <= outer.end @@ -184,9 +175,10 @@ fn type_with_dimensions( ty: Type, dimensions: &[celox_sv_syntax::Dimension], tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted { - containers::with_dimensions(ty, dimensions, tree, context) + containers::with_dimensions(ty, dimensions, tree, session, context) } fn shape(context: &mut PackedDimensions, name: String, ty: &Type, local: bool) { let value = procedural::dimensions_from_type(ty); @@ -201,38 +193,40 @@ fn shape(context: &mut PackedDimensions, name: String, ty: &Type, local: bool) { // only our own old snapshot during that edit, so ScopedMap need not copy its // growing overlay on every declaration, then publish before the next query. fn publish_shape( - tree: &AnalysisContext<'_>, + session: &mut Session, key: &Key, context: &mut PackedDimensions, name: String, ty: &Type, local: bool, ) { - tree.state.dimensions.partial.borrow_mut().remove(key); + session.dimensions.partial.remove(key); shape(context, name, ty, local); - publish(&tree.state.dimensions, key, context); + publish(&mut session.dimensions, key, context); } fn variables( declaration: &celox_sv_syntax::VariableDeclaration, tree: &AnalysisContext<'_>, + session: &mut Session, context: &mut PackedDimensions, key: &Key, local: bool, ) -> Converted<()> { - let Some(base) = type_binding::bind(declaration.data_type, tree, context)? else { + let Some(base) = type_binding::bind(declaration.data_type, tree, session, context)? else { return Ok(()); }; for variable in declaration.variables.iter().filter(|variable| { type_binding::ordinary_variable(variable, declaration.data_type, tree.declarations()) }) { - let ty = type_with_dimensions(base.clone(), &variable.dimensions, tree, context)?; - publish_shape(tree, key, context, name(&variable.name), &ty, local); + let ty = type_with_dimensions(base.clone(), &variable.dimensions, tree, session, context)?; + publish_shape(session, key, context, name(&variable.name), &ty, local); } Ok(()) } fn parameter( parameter: &celox_sv_syntax::Parameter, tree: &AnalysisContext<'_>, + session: &mut Session, context: &mut PackedDimensions, key: &Key, local: bool, @@ -241,7 +235,7 @@ fn parameter( match ¶meter.kind { ParameterKind::Type { default: Some(id) } => { if !context.type_aliases.contains_key(&n) - && let Some(ty) = type_binding::bind(*id, tree, context)? + && let Some(ty) = type_binding::bind(*id, tree, session, context)? { context.type_aliases.insert(n, ty); } @@ -253,7 +247,11 @@ fn parameter( } => { if local && let Some(value) = default - .and_then(|id| constant_binding::bind(id, tree, context).ok().flatten()) + .and_then(|id| { + constant_binding::bind(id, tree, session, context) + .ok() + .flatten() + }) .and_then(|value| { eval_ast_const_expr(&tree.functions, &value, &context.const_env) }) @@ -268,16 +266,18 @@ fn parameter( && !context .const_env .contains_key(¶meter_dimensions_marker(&n)); - if !scalar_binding && let Some(base) = type_binding::bind(*data_type, tree, context)? { - let ty = type_with_dimensions(base, dimensions, tree, context)?; + if !scalar_binding + && let Some(base) = type_binding::bind(*data_type, tree, session, context)? + { + let ty = type_with_dimensions(base, dimensions, tree, session, context)?; if !dimensions.is_empty() || !ty.packed_ranges().is_empty() { - publish_shape(tree, key, context, n, &ty, local); + publish_shape(session, key, context, n, &ty, local); } } } _ => {} } - publish(&tree.state.dimensions, key, context); + publish(&mut session.dimensions, key, context); Ok(()) } /// Discover declaration `id`, which `top` says is an item of the unit @@ -285,6 +285,7 @@ fn parameter( fn declaration( id: BodyItemId, tree: &AnalysisContext<'_>, + session: &mut Session, context: &mut PackedDimensions, key: &Key, top: bool, @@ -295,30 +296,35 @@ fn declaration( if let celox_sv_syntax::DataDeclaration::Variables(data) | celox_sv_syntax::DataDeclaration::Constructed(data) = native.data_declaration(*id) { - variables(data, tree, context, key, false)?; + variables(data, tree, session, context, key, false)?; } } BodyItemKind::Net(id) => { let data = native.net_declaration(*id); - if let Some(base) = type_binding::bind(data.data_type, tree, context)? { + if let Some(base) = type_binding::bind(data.data_type, tree, session, context)? { for variable in &data.variables { - let ty = - type_with_dimensions(base.clone(), &variable.dimensions, tree, context)?; - publish_shape(tree, key, context, name(&variable.name), &ty, false); + let ty = type_with_dimensions( + base.clone(), + &variable.dimensions, + tree, + session, + context, + )?; + publish_shape(session, key, context, name(&variable.name), &ty, false); } } } BodyItemKind::Parameter(id) => { for item in &native.parameter_declaration(*id).parameters { - parameter(item, tree, context, key, false)?; + parameter(item, tree, session, context, key, false)?; } } BodyItemKind::TypeAlias(id) => { let alias = native.type_alias(*id); if let TypeAliasTarget::DataType(id) = alias.target - && let Some(base) = type_binding::bind(id, tree, context)? + && let Some(base) = type_binding::bind(id, tree, session, context)? { - let mut ty = type_with_dimensions(base, &alias.dimensions, tree, context)?; + let mut ty = type_with_dimensions(base, &alias.dimensions, tree, session, context)?; // The typedef names its type, as when the scope's typedefs // are bound; that of a generate block is named by the path // of its elaborated scope. @@ -326,7 +332,7 @@ fn declaration( ty.name_declaration(|| types::declaration_name(tree, alias, None)); } context.type_aliases.insert(name(&alias.name), ty); - publish(&tree.state.dimensions, key, context); + publish(&mut session.dimensions, key, context); } } _ => {} @@ -336,6 +342,7 @@ fn declaration( fn formal_types( subroutine: &celox_sv_syntax::Subroutine, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted> { let mut result = Vec::new(); @@ -363,7 +370,8 @@ fn formal_types( let mut base = if port.direction.is_none() && omitted && previous.is_some() { previous.clone().unwrap() } else { - let Some(mut ty) = type_binding::bind(port.data_type, tree, &local)? else { + let Some(mut ty) = type_binding::bind(port.data_type, tree, session, &local)? + else { return Err(unsupported("unsupported function formal data type")); }; if matches!(data.kind, DataTypeKind::Implicit) { @@ -372,7 +380,7 @@ fn formal_types( ty }; previous = Some(base.clone()); - base = type_with_dimensions(base, &port.dimensions, tree, &local)?; + base = type_with_dimensions(base, &port.dimensions, tree, session, &local)?; let n = port .name .as_ref() @@ -458,11 +466,12 @@ fn return_metadata( fn signature( id: SubroutineId, tree: &AnalysisContext<'_>, + session: &mut Session, context: &mut PackedDimensions, ) -> Converted<()> { let subroutine = tree.declarations().subroutine(id); - let formals = formal_types(subroutine, tree, context)?; - let result = return_type(subroutine, tree, context)?; + let formals = formal_types(subroutine, tree, session, context)?; + let result = return_type(subroutine, tree, session, context)?; publish_signature(name(&subroutine.name), formals, result, tree, context); Ok(()) } @@ -470,6 +479,7 @@ fn signature( fn return_type( subroutine: &celox_sv_syntax::Subroutine, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted>> { if subroutine.kind != SubroutineKind::Function { @@ -477,7 +487,7 @@ fn return_type( } let mut ty = subroutine .return_type - .map(|id| type_binding::bind(id, tree, context)) + .map(|id| type_binding::bind(id, tree, session, context)) .transpose()? .flatten(); if subroutine.return_type.is_some_and(|id| { @@ -499,10 +509,11 @@ fn class_signatures( class: &celox_sv_syntax::ClassDeclaration, class_name: &str, tree: &AnalysisContext<'_>, + session: &mut Session, context: &mut PackedDimensions, scopes: &mut classes::specializations::ClassScopes, ) -> Converted<()> { - let Some(handle) = classes::handle_type(tree, class_name) else { + let Some(handle) = classes::handle_type(tree, session, class_name) else { return Ok(()); }; let this = ( @@ -516,25 +527,40 @@ fn class_signatures( let mut constructor = false; // Formals and results are bound in the scope of the specialization. let (env, aliases) = (context.const_env.clone(), context.type_aliases.clone()); - let signatures = scopes.with(tree, class_name, &env, &aliases, |env, aliases| { - let mut scope = context.clone(); - scope.const_env = env.clone(); - scope.type_aliases = aliases.clone(); - method_signatures( - class, - class_name, - tree, - &scope, - &this, - &handle, - &mut constructor, - ) - })?; + let signatures = scopes.with( + session, + class_name, + &env, + &aliases, + |session: &mut Session, env: &SharedMap, aliases: &SharedMap| { + let mut scope = context.clone(); + scope.const_env = env.clone(); + scope.type_aliases = aliases.clone(); + method_signatures( + class, + class_name, + tree, + &scope, + &this, + &handle, + &mut constructor, + session, + ) + }, + )?; drop((env, aliases)); for (name, formals, result) in signatures { publish_signature(name, formals, result, tree, context); } - class_builtin_signatures(class, class_name, tree, context, &handle, constructor) + class_builtin_signatures( + class, + class_name, + tree, + context, + &handle, + constructor, + session, + ) } type Signature = ( @@ -553,11 +579,12 @@ fn method_signatures( this: &(FunctionArgumentMetadata, Type), handle: &Type, constructor: &mut bool, + session: &mut Session, ) -> Converted> { let mut signatures = Vec::new(); for method in &class.methods { let subroutine = tree.declarations().subroutine(method.subroutine); - let mut formals = formal_types(subroutine, tree, scope)?; + let mut formals = formal_types(subroutine, tree, session, scope)?; if !method.qualifiers.is_static { formals.insert(0, this.clone()); } @@ -565,7 +592,7 @@ fn method_signatures( *constructor = true; Some(Some(handle.clone())) } else { - return_type(subroutine, tree, scope)? + return_type(subroutine, tree, session, scope)? }; // A method that may be virtual also has a dispatcher (8.20). if !method.qualifiers.is_static && subroutine.kind != SubroutineKind::Constructor { @@ -593,6 +620,7 @@ fn class_builtin_signatures( context: &mut PackedDimensions, handle: &Type, constructor: bool, + session: &mut Session, ) -> Converted<()> { for method in ["randomize", "srandom", "rand_mode"] { let mut formals = vec![( @@ -609,11 +637,17 @@ fn class_builtin_signatures( // Signature discovery must not require an otherwise unused class // to have a supported layout. A call validates the layout before // using this selection formal; lowering reports layout errors. - classes::shared_class(tree, class_name, &context.const_env, &context.type_aliases) - .map_or_else( - |_| classes::unsigned_type(1), - |layout| layout.selection_type(), - ), + classes::shared_class( + tree, + class_name, + &context.const_env, + &context.type_aliases, + session, + ) + .map_or_else( + |_| classes::unsigned_type(1), + |layout| layout.selection_type(), + ), ), "srandom" => ("seed", procedural::int_type()), _ => ("on_off", classes::unsigned_type(1)), @@ -679,24 +713,30 @@ fn class_builtin_signatures( /// names (IEEE 1800-2023 8.25). pub(in crate::ast) fn all_class_signatures( tree: &AnalysisContext<'_>, + session: &mut Session, context: &mut PackedDimensions, ) { - bind_class_signatures(tree, context, false); + bind_class_signatures(tree, context, false, session); } /// [`all_class_signatures`]; with `retry`, the classes whose signatures fail /// are bound again while that publishes more of them, as a signature may /// name a method of a class bound after it. A class publishes its /// signatures only when all of them bind. -fn bind_class_signatures(tree: &AnalysisContext<'_>, context: &mut PackedDimensions, retry: bool) { - classes::specializations::collect(tree, context); +fn bind_class_signatures( + tree: &AnalysisContext<'_>, + context: &mut PackedDimensions, + retry: bool, + session: &mut Session, +) { + classes::specializations::collect(tree, session, context); // The classes of other scopes keep the signatures their scopes publish. let mut scopes = classes::specializations::ClassScopes::new(&context.const_env, &context.type_aliases); let mut failed = Vec::new(); for class in classes::scope_declarations(tree) { - for class_name in classes::specializations_of(tree, class) { - if class_signatures(class, &class_name, tree, context, &mut scopes).is_err() { + for class_name in classes::specializations_of(tree, session, class) { + if class_signatures(class, &class_name, tree, session, context, &mut scopes).is_err() { failed.push((class, class_name)); } } @@ -704,13 +744,13 @@ fn bind_class_signatures(tree: &AnalysisContext<'_>, context: &mut PackedDimensi while retry && !failed.is_empty() { let before = failed.len(); failed.retain(|(class, class_name)| { - class_signatures(class, class_name, tree, context, &mut scopes).is_err() + class_signatures(class, class_name, tree, session, context, &mut scopes).is_err() }); if failed.len() == before { break; } } - tree.state.class_specializations_frozen.set(true); + session.class_specializations_frozen = true; } /// The signatures of the classes of the current scope and of its other @@ -720,6 +760,7 @@ fn bind_class_signatures(tree: &AnalysisContext<'_>, context: &mut PackedDimensi /// passes publishes them again instead of binding every class again. fn scope_class_signatures( tree: &AnalysisContext<'_>, + session: &mut Session, scope: &[BodyItemId], key: &Key, base: &PackedDimensions, @@ -728,12 +769,10 @@ fn scope_class_signatures( tree.declarations() as *const _ as usize, tree.scope_handle(), ); - let specializations = tree.state.class_specializations.borrow().len(); - if let Some(cached) = tree - .state + let specializations = session.class_specializations.len(); + if let Some(cached) = session .dimensions .class_signatures - .borrow() .get(&cache_key) .filter(|cached| { cached.specializations == specializations @@ -751,12 +790,19 @@ fn scope_class_signatures( #[cfg(test)] super::CLASS_SIGNATURE_BINDINGS.with(|count| count.set(count.get() + 1)); let mut bound = base.clone(); - settle(&[scope.to_vec()], tree, key, &mut bound, Classes::Bind)?; + settle( + &[scope.to_vec()], + tree, + session, + key, + &mut bound, + Classes::Bind, + )?; // Only the methods of the scope's classes, `class::method`: the scope's // other subroutines are discovered with each query, where a generate // block may hide them. let classes = classes::scope_declarations(tree) - .flat_map(|class| classes::specializations_of(tree, class)) + .flat_map(|class| classes::specializations_of(tree, session, class)) .collect::>(); fn changed( classes: &HashSet, @@ -777,7 +823,7 @@ fn scope_class_signatures( const_env: base.const_env.clone(), type_aliases: base.type_aliases.clone(), function_return_types: base.function_return_types.clone(), - specializations: tree.state.class_specializations.borrow().len(), + specializations: session.class_specializations.len(), shapes: changed( &classes, &base.subroutine_param_shapes, @@ -794,16 +840,15 @@ fn scope_class_signatures( &bound.function_return_types, ), }); - tree.state + session .dimensions .class_signatures - .borrow_mut() .insert(cache_key, signatures.clone()); Ok(signatures) } impl ClassSignatures { - fn publish(&self, tree: &AnalysisContext<'_>, context: &mut PackedDimensions) { + fn publish(&self, session: &mut Session, context: &mut PackedDimensions) { if !self.shapes.is_empty() { Arc::make_mut(&mut context.subroutine_param_shapes).extend(self.shapes.iter().cloned()); } @@ -815,7 +860,7 @@ impl ClassSignatures { .function_return_types .extend(self.returns.iter().cloned()); } - tree.state.class_specializations_frozen.set(true); + session.class_specializations_frozen = true; } } @@ -824,6 +869,7 @@ impl ClassSignatures { fn settle( frames: &[Vec], tree: &AnalysisContext<'_>, + session: &mut Session, key: &Key, context: &mut PackedDimensions, classes: Classes<'_>, @@ -835,10 +881,10 @@ fn settle( let Classes::Bind = classes else { for _ in 0..=declarations { let before = context.clone(); - subroutine_signatures(frames, tree, key, context); - classes.publish(tree, context); - publish(&tree.state.dimensions, key, context); - declare(frames, tree, key, context)?; + subroutine_signatures(frames, tree, key, context, session); + classes.publish(session, context); + publish(&mut session.dimensions, key, context); + declare(frames, tree, key, context, session)?; if *context == before { break; } @@ -853,37 +899,38 @@ fn settle( // The first pass makes the specializations the declarations may name // before declaring them, as binding the signatures does. let mut bound: Option<(PackedDimensions, usize)> = None; - let specializations = || tree.state.class_specializations.borrow().len(); - let unchanged = |bound: &Option<(PackedDimensions, usize)>, context: &PackedDimensions| { + let unchanged = |bound: &Option<(PackedDimensions, usize)>, + context: &PackedDimensions, + specializations: usize| { bound .as_ref() - .is_some_and(|(after, count)| after == context && *count == specializations()) + .is_some_and(|(after, count)| after == context && *count == specializations) }; for pass in 0..=2 * declarations + 1 { let before = context.clone(); - subroutine_signatures(frames, tree, key, context); + subroutine_signatures(frames, tree, key, context, session); if pass == 0 { - classes::specializations::collect(tree, context); - tree.state.class_specializations_frozen.set(true); + classes::specializations::collect(tree, session, context); + session.class_specializations_frozen = true; } - declare(frames, tree, key, context)?; + declare(frames, tree, key, context, session)?; if *context != before { continue; } - if unchanged(&bound, context) { + if unchanged(&bound, context, session.class_specializations.len()) { return Ok(()); } #[cfg(test)] super::SETTLE_CLASS_BINDINGS.with(|count| count.set(count.get() + 1)); - bind_class_signatures(tree, context, true); - publish(&tree.state.dimensions, key, context); - bound = Some((context.clone(), specializations())); + bind_class_signatures(tree, context, true, session); + publish(&mut session.dimensions, key, context); + bound = Some((context.clone(), session.class_specializations.len())); } // Declarations that never settle still get the signatures of the last // pass, as every pass binds them. - if !unchanged(&bound, context) { - bind_class_signatures(tree, context, true); - publish(&tree.state.dimensions, key, context); + if !unchanged(&bound, context, session.class_specializations.len()) { + bind_class_signatures(tree, context, true, session); + publish(&mut session.dimensions, key, context); } Ok(()) } @@ -894,6 +941,7 @@ fn subroutine_signatures( tree: &AnalysisContext<'_>, key: &Key, context: &mut PackedDimensions, + session: &mut Session, ) { let native = tree.declarations(); for frame in frames { @@ -901,8 +949,8 @@ fn subroutine_signatures( if let BodyItemKind::Subroutine(id) = native.body_item(*id).kind && native.subroutine(id).scope.is_empty() { - let _ = signature(id, tree, context); - publish(&tree.state.dimensions, key, context); + let _ = signature(id, tree, session, context); + publish(&mut session.dimensions, key, context); } else if let BodyItemKind::Dpi(id) = native.body_item(*id).kind && let Ok(import) = dpi::import(id, native) && let Some(ty) = import.return_type() @@ -923,7 +971,7 @@ fn subroutine_signatures( virtual_interface: None, }, ); - publish(&tree.state.dimensions, key, context); + publish(&mut session.dimensions, key, context); } } } @@ -936,27 +984,28 @@ fn declare( tree: &AnalysisContext<'_>, key: &Key, context: &mut PackedDimensions, + session: &mut Session, ) -> Converted<()> { if let Ok(unit) = tree.root_unit() { if let Some(parameters) = &unit.parameters { for parameter_node in parameters { - let _ = parameter(parameter_node, tree, context, key, false); + let _ = parameter(parameter_node, tree, session, context, key, false); } } for index in tree.header_port_ids()? { let port = &unit.ports[index]; if let Some(id) = port.data_type - && let Ok(Some(base)) = type_binding::bind(id, tree, context) - && let Ok(ty) = type_with_dimensions(base, &port.dimensions, tree, context) + && let Ok(Some(base)) = type_binding::bind(id, tree, session, context) + && let Ok(ty) = type_with_dimensions(base, &port.dimensions, tree, session, context) && let celox_sv_syntax::PortKind::Named(n) = &port.kind { - publish_shape(tree, key, context, name(n), &ty, false); + publish_shape(session, key, context, name(n), &ty, false); } } } for (depth, frame) in frames.iter().enumerate() { for id in frame { - let _ = declaration(*id, tree, context, key, depth == 0); + let _ = declaration(*id, tree, session, context, key, depth == 0); } } Ok(()) @@ -972,9 +1021,9 @@ enum Classes<'a> { } impl Classes<'_> { - fn publish(self, tree: &AnalysisContext<'_>, context: &mut PackedDimensions) { + fn publish(self, session: &mut Session, context: &mut PackedDimensions) { if let Self::Published(signatures) = self { - signatures.publish(tree, context); + signatures.publish(session, context); } } } @@ -1016,24 +1065,25 @@ fn publish_signature( fn local_declaration( item: &LocalDeclaration, tree: &AnalysisContext<'_>, + session: &mut Session, context: &mut PackedDimensions, key: &Key, ) -> Converted<()> { match item { LocalDeclaration::Variables(data) | LocalDeclaration::Constructed(data) => { - variables(data, tree, context, key, true)? + variables(data, tree, session, context, key, true)? } LocalDeclaration::Parameters(id) => { for parameter_node in &tree.declarations().parameter_declaration(*id).parameters { - parameter(parameter_node, tree, context, key, true)?; + parameter(parameter_node, tree, session, context, key, true)?; } } LocalDeclaration::TypeAlias(id) => { let alias = tree.declarations().type_alias(*id); if let TypeAliasTarget::DataType(id) = alias.target - && let Some(ty) = type_binding::bind(id, tree, context)? + && let Some(ty) = type_binding::bind(id, tree, session, context)? { - let ty = type_with_dimensions(ty, &alias.dimensions, tree, context)?; + let ty = type_with_dimensions(ty, &alias.dimensions, tree, session, context)?; context.type_aliases.insert(name(&alias.name), ty); } } @@ -1045,6 +1095,7 @@ fn statement_scope( ids: &[StatementId], target: TokenRange, tree: &AnalysisContext<'_>, + session: &mut Session, context: &mut PackedDimensions, key: &Key, ) -> Converted<()> { @@ -1097,16 +1148,18 @@ fn statement_scope( if let StatementKind::Declaration(item) = &tree.declarations().statement(id).kind { - local_declaration(item, tree, context, key)?; - publish(&tree.state.dimensions, key, context); + local_declaration(item, tree, session, context, key)?; + publish(&mut session.dimensions, key, context); } } } Lexical::For(declarations) => { for declaration in declarations { - if let Some(ty) = type_binding::bind(declaration.data_type, tree, context)? { + if let Some(ty) = + type_binding::bind(declaration.data_type, tree, session, context)? + { for variable in declaration.variables { - publish_shape(tree, key, context, name(&variable.name), &ty, true); + publish_shape(session, key, context, name(&variable.name), &ty, true); } } } @@ -1115,7 +1168,7 @@ fn statement_scope( let ty = type_binding::builtin_type("int", None) .ok_or_else(|| unsupported("foreach index type"))?; for n in names { - publish_shape(tree, key, context, name(&n), &ty, true); + publish_shape(session, key, context, name(&n), &ty, true); } } } @@ -1155,6 +1208,7 @@ fn finish(mut context: PackedDimensions) -> PackedDimensions { /// from `input`, before the parts that depend on the query's operand. fn settle_scope( tree: &AnalysisContext<'_>, + session: &mut Session, owners: &Owners, key: &Key, input: &PackedDimensions, @@ -1170,8 +1224,20 @@ fn settle_scope( } extend_interface_dimensions(tree, &mut context); extend_variable_dimensions_from_const_env(&mut context, &input.const_env); - publish(&tree.state.dimensions, key, &context); - let _guard = Guard(&tree.state.dimensions, key.clone()); + publish(&mut session.dimensions, key, &context); + // Reentrant queries see the published prefix until the scope settles. + let settled = settle_published(tree, session, owners, key, context); + session.dimensions.partial.remove(key); + settled +} + +fn settle_published( + tree: &AnalysisContext<'_>, + session: &mut Session, + owners: &Owners, + key: &Key, + mut context: PackedDimensions, +) -> Converted { let frames = owners .frames .iter() @@ -1182,12 +1248,13 @@ fn settle_scope( let base = context.clone(); // Without classes of its own, the scope has no signatures to bind once. if classes::scope_declarations(tree).next().is_none() { - settle(&frames, tree, key, &mut context, Classes::Bind)?; + settle(&frames, tree, session, key, &mut context, Classes::Bind)?; } else { - let classes = scope_class_signatures(tree, &frames[0], key, &base)?; + let classes = scope_class_signatures(tree, session, &frames[0], key, &base)?; settle( &frames, tree, + session, key, &mut context, Classes::Published(&classes), @@ -1200,6 +1267,7 @@ fn settle_scope( pub(in crate::ast) fn query_operand_dimensions_id( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, input: &PackedDimensions, ) -> Converted { if input.scope_types_complete { @@ -1215,18 +1283,16 @@ pub(in crate::ast) fn query_operand_dimensions_id( scope: tree.scope_handle(), path: owners.path.clone(), }; - if let Some(mut partial) = tree.state.dimensions.partial.borrow().get(&key).cloned() { + if let Some(mut partial) = session.dimensions.partial.get(&key).cloned() { overlay(&mut partial, input); return Ok(finish(partial)); } // Every query of a scope with the same input discovers the same // declarations: a scope's queries settle them once. - let specializations = tree.state.class_specializations.borrow().len(); - let settled = tree - .state + let specializations = session.class_specializations.len(); + let settled = session .dimensions .settled - .borrow() .get(&key) .filter(|settled| { !unshared_discovery() @@ -1234,41 +1300,64 @@ pub(in crate::ast) fn query_operand_dimensions_id( && same_tables(&settled.input, input) }) .map(|settled| settled.context.clone()); - let mut context = match settled { + let context = match settled { Some(context) => context, None => { - let context = settle_scope(tree, &owners, &key, input)?; - tree.state.dimensions.settled.borrow_mut().insert( + let context = settle_scope(tree, session, &owners, &key, input)?; + session.dimensions.settled.insert( key.clone(), Settled { input: input.clone(), - specializations: tree.state.class_specializations.borrow().len(), + specializations: session.class_specializations.len(), context: context.clone(), }, ); context } }; - publish(&tree.state.dimensions, &key, &context); - let _guard = Guard(&tree.state.dimensions, key.clone()); + publish(&mut session.dimensions, &key, &context); + // Reentrant queries see the published prefix until this one finishes. + let result = query_published(root, tree, session, input, &owners, &key, context); + session.dimensions.partial.remove(&key); + result +} + +fn query_published( + root: ExprId, + tree: &AnalysisContext<'_>, + session: &mut Session, + input: &PackedDimensions, + owners: &Owners, + key: &Key, + mut context: PackedDimensions, +) -> Converted { + let native = tree.declarations(); + let target = native.expression(root).tokens; overlay(&mut context, input); if let Some(id) = owners.subroutine { let subroutine = native.subroutine(id); - for (argument, ty) in formal_types(subroutine, tree, &context)? { - publish_shape(tree, &key, &mut context, argument.name, &ty, true); + for (argument, ty) in formal_types(subroutine, tree, session, &context)? { + publish_shape(session, key, &mut context, argument.name, &ty, true); } if contains(subroutine.body_tokens, target) && subroutine.kind == SubroutineKind::Function && let Some(id) = subroutine.return_type - && let Some(mut ty) = type_binding::bind(id, tree, &context)? + && let Some(mut ty) = type_binding::bind(id, tree, session, &context)? { if matches!(native.data_type(id).kind, DataTypeKind::Implicit) { ty.kind = TypeKind::Logic; } - publish_shape(tree, &key, &mut context, name(&subroutine.name), &ty, true); + publish_shape( + session, + key, + &mut context, + name(&subroutine.name), + &ty, + true, + ); } } - statement_scope(&owners.statements, target, tree, &mut context, &key)?; + statement_scope(&owners.statements, target, tree, session, &mut context, key)?; // A hierarchical operand can name a declaration in an active generate // branch. Use the same explicit specialization as normal elaboration; // typed wide/four-state overrides must remain parameter literals. @@ -1276,7 +1365,7 @@ pub(in crate::ast) fn query_operand_dimensions_id( && wanted.contains('.') && context.get(&wanted).is_none() { - for item in generate::items(tree, &context.const_env, &context.type_aliases)? { + for item in generate::items(tree, session, &context.const_env, &context.type_aliases)? { if !matches!( native.body_item(item.id).kind, BodyItemKind::Data(_) | BodyItemKind::Net(_) @@ -1295,6 +1384,7 @@ pub(in crate::ast) fn query_operand_dimensions_id( declarations::signals_from_body_item( item.id, tree, + session, &item.type_aliases(&context.type_aliases), &item.env, Some(&declared), @@ -1306,7 +1396,7 @@ pub(in crate::ast) fn query_operand_dimensions_id( procedural::dimensions_from_type(signal.r#type()), ); } - publish(&tree.state.dimensions, &key, &context); + publish(&mut session.dimensions, key, &context); } } Ok(finish(context)) @@ -1341,6 +1431,7 @@ mod tests { } #[test] fn native_query_formals_shadow_outer_constant_values() { + let session = &mut Session::default(); let tree = parse( "module M;parameter N=16;function int f(input logic[3:0]N);return $bits(N);endfunction endmodule", ); @@ -1350,7 +1441,7 @@ mod tests { &[("N".to_string(), 16)].into_iter().collect(), &HashMap::default(), ); - let context = query_operand_dimensions_id(argument(&tree), &tree, &input).unwrap(); + let context = query_operand_dimensions_id(argument(&tree), &tree, session, &input).unwrap(); assert_eq!( width(&tree.functions, context.get("N").unwrap(), &context), Some(4) @@ -1368,26 +1459,28 @@ mod tests { } #[test] fn native_generate_ancestor_dpi_shadows_root_return_metadata() { + let session = &mut Session::default(); let tree = parse( "module M;import \"DPI-C\" function int f();if(1)begin:g import \"DPI-C\" function byte f();localparam N=$bits(f());end endmodule", ); let tree = AnalysisContext::unspecialized(&tree); let input = PackedDimensions::new(HashMap::default(), &HashMap::default(), &HashMap::default()); - let context = query_operand_dimensions_id(argument(&tree), &tree, &input).unwrap(); + let context = query_operand_dimensions_id(argument(&tree), &tree, session, &input).unwrap(); assert_eq!(context.function_return_types["f"].width, Some(8)); assert!(context.functions.is_empty()); assert!(context.type_query); } #[test] fn native_function_local_array_shapes_survive_preliminary_queries() { + let session = &mut Session::default(); let tree = parse( "module M;function int f();logic[7:0]a[0:3];begin logic[2:0]a[0:1];return $bits(a);end endfunction endmodule", ); let tree = AnalysisContext::unspecialized(&tree); let input = PackedDimensions::new(HashMap::default(), &HashMap::default(), &HashMap::default()); - let context = query_operand_dimensions_id(argument(&tree), &tree, &input).unwrap(); + let context = query_operand_dimensions_id(argument(&tree), &tree, session, &input).unwrap(); let shape = context.get("a").unwrap(); assert_eq!(width(&tree.functions, shape, &context), Some(3)); assert_eq!( @@ -1401,13 +1494,18 @@ mod tests { } #[test] fn native_query_discovery_retains_ordinary_constructed_siblings() { + let session = &mut Session::default(); let tree = parse( "module M; function int f(); int dyn[]=new[2], ordinary=3; return $bits(ordinary); endfunction endmodule", ); let tree = AnalysisContext::unspecialized(&tree); - let context = - query_operand_dimensions_id(argument(&tree), &tree, &PackedDimensions::default()) - .unwrap(); + let context = query_operand_dimensions_id( + argument(&tree), + &tree, + session, + &PackedDimensions::default(), + ) + .unwrap(); assert_eq!( width(&tree.functions, context.get("ordinary").unwrap(), &context), Some(32) diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/queries.rs b/crates/celox-sv-analyzer/src/ast/dimensions/queries.rs index a3914e75ca2..f67f1f19d66 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/queries.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/queries.rs @@ -3,12 +3,12 @@ use super::*; pub(super) fn bound_query( tree: &AnalysisContext<'_>, + session: &mut Session, 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; @@ -29,7 +29,7 @@ pub(super) fn bound_query( }) }; let dimension = dimension.unwrap_or_else(|| integer(1)); - if let Some(index) = expr_to_const(state, dimension.clone()) + if let Some(index) = expr_to_const(session, dimension.clone()) .and_then(|expr| eval_ast_const_expr(functions, &expr, env)) { return Some( 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 4d753b80597..b4ecd046bf8 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/query_binding.rs @@ -56,6 +56,7 @@ fn literal_operand(root: ExprId, native: &celox_sv_syntax::Declarations) -> bool pub(in crate::ast) fn query_context_for_operand( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted { // Aggregate port defaults commonly repeat literal arithmetic. Rediscovering @@ -64,7 +65,7 @@ pub(in crate::ast) fn query_context_for_operand( return Ok(query_context(context)); } Ok(query_context(&query_operand_dimensions_id( - root, tree, context, + root, tree, session, context, )?)) } @@ -80,6 +81,7 @@ pub(in crate::ast) fn validate_data_operand( pub(in crate::ast) fn query_value( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted> { let native = tree.declarations(); @@ -120,7 +122,7 @@ pub(in crate::ast) fn query_value( return Err(unsupported(format!("arguments of `{}`", name.spelling))); } let argument = arguments[0].value.unwrap(); - let context = query_context_for_operand(argument, tree, context)?; + let context = query_context_for_operand(argument, tree, session, context)?; reject_unbounded(argument, function, tree, &context)?; if function == SystemFunction::Size && let Some(value) = interface_array_size( @@ -128,16 +130,18 @@ pub(in crate::ast) fn query_value( argument, arguments.get(1).and_then(|a| a.value), tree, + session, &context, )? { return Ok(Some(value)); } - let shape = shape(argument, tree, &context)?; + let shape = shape(argument, tree, session, &context)?; let dimension = if let Some(argument) = arguments.get(1) { Some(expression_binding::bind( argument.value.unwrap(), tree, + session, &context, )?) } else { @@ -162,7 +166,7 @@ pub(in crate::ast) fn query_value( ) }) } else { - type_binding::expression_type(argument, tree, &context)?.map(|ty| ty.width) + type_binding::expression_type(argument, tree, session, &context)?.map(|ty| ty.width) }; width.map(|width| integer(width as i128)) } @@ -189,7 +193,7 @@ pub(in crate::ast) fn query_value( } SystemFunction::Size => { let index = dimension - .map(|value| expr_to_const(&tree.state, value)) + .map(|value| expr_to_const(session, value)) .unwrap_or_else(|| Some(ConstExpr::Literal("1".into()))) .and_then(|value| eval_ast_const_expr(&tree.functions, &value, &context.const_env)); let width = if let (Some(shape), Some(index)) = (&shape, index) { @@ -251,7 +255,7 @@ pub(in crate::ast) fn query_value( .collect::>>() }); bounds.and_then(|bounds| { - super::queries::bound_query(tree, query, &bounds, dimension, &context) + super::queries::bound_query(tree, session, query, &bounds, dimension, &context) }) } _ => unreachable!(), @@ -268,6 +272,7 @@ fn interface_array_size( mut argument: ExprId, dimension: Option, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted> { let native = tree.declarations(); @@ -291,6 +296,7 @@ fn interface_array_size( let Ok(handle) = interface_binding::actual_handle_key( argument, tree, + session, &context.const_env, &context.type_aliases, ) else { @@ -315,10 +321,10 @@ fn interface_array_size( return Ok(None); }; for index in selected { - validate_index(index, tree, context)?; + validate_index(index, tree, session, context)?; } let dimension = match dimension { - Some(id) => constant_binding::bind(id, tree, context)? + Some(id) => constant_binding::bind(id, tree, session, context)? .and_then(|value| eval_ast_const_expr(&tree.functions, &value, &context.const_env)) .ok_or_else(|| unsupported("nonconstant interface array query dimension"))?, None => 1, @@ -330,7 +336,7 @@ fn interface_array_size( .map(|size| integer(*size as i128)) .unwrap_or_else(|| Expr::Literal("32'sbx".into())); warnings::append( - &mut tree.state.diagnostics.borrow_mut(), + &mut session.diagnostics, [warnings::AnalyzerWarning::InterfaceArrayQuery { site: procedural::source_span(native.expression(call).tokens, tree), }], @@ -514,10 +520,11 @@ fn dimension_jobs(dimension: &DimensionKind, jobs: &mut Vec) { fn validate_index( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted<()> { let native = tree.declarations(); - let value = expression_binding::bind(root, tree, context)?; + let value = expression_binding::bind(root, tree, session, context)?; if expr_static_width(tree, &value, context).is_none() { return Err(unsupported("query index type")); } @@ -525,12 +532,12 @@ fn validate_index( while let Some(id) = jobs.pop() { match &native.expression(id).kind { ExprKind::Name(_) | ExprKind::Literal(_) => { - if type_binding::expression_type(id, tree, context)?.is_none() { + if type_binding::expression_type(id, tree, session, context)?.is_none() { return Err(unsupported("query index type")); } } ExprKind::Member { .. } | ExprKind::Select { .. } => { - if type_binding::expression_type(id, tree, context)?.is_none() { + if type_binding::expression_type(id, tree, session, context)?.is_none() { return Err(unsupported("query index type")); } let mut base = id; @@ -701,6 +708,7 @@ fn scalar(width: usize, signed: bool, packed: bool) -> VariableDimensions { pub(in crate::ast) fn shape( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted> { enum Job { @@ -715,7 +723,9 @@ pub(in crate::ast) fn shape( while let Some(job) = jobs.pop() { match job { Job::Enter(id) => { - if let Some((_, shape)) = array_reductions::bind(id, native, tree, context)? { + if let Some((_, shape)) = + array_reductions::bind(id, native, tree, session, context)? + { values.push(shape); continue; } @@ -727,12 +737,12 @@ pub(in crate::ast) fn shape( expression, name, .. } = &native.expression(callee).kind && let Some(container) = - containers::native_type(*expression, native, tree, context)? + containers::native_type(*expression, native, tree, session, context)? { // Validate the call without executing it. Pop returns the // declared element type, including packed dimensions and // authored bounds, rather than a flattened bit vector. - let value = expression_binding::bind(id, tree, context)?; + let value = expression_binding::bind(id, tree, session, context)?; let shape = if matches!(name.spelling.as_str(), "pop_front" | "pop_back") { procedural::dimensions_from_type(&container.element) } else { @@ -817,7 +827,7 @@ pub(in crate::ast) fn shape( match &native.expression(id).kind { ExprKind::Group(inner) => jobs.push(Job::Enter(*inner)), ExprKind::Type(ty) => { - let Some(ty) = type_binding::bind(*ty, tree, context)? else { + let Some(ty) = type_binding::bind(*ty, tree, session, context)? else { return Ok(None); }; values.push(procedural::dimensions_from_type(&ty)); @@ -858,13 +868,13 @@ pub(in crate::ast) fn shape( left, right, } if matches!(operator.as_str(), "<<" | ">>" | "<<<" | ">>>") => { - expression_binding::bind(*right, tree, context)?; + expression_binding::bind(*right, tree, session, context)?; jobs.push(Job::Enter(*left)); } ExprKind::Cast { target, .. } => { - expression_binding::bind(id, tree, context)?; + expression_binding::bind(id, tree, session, context)?; let ty = match native.expression(*target).kind { - ExprKind::Type(ty) => type_binding::bind(ty, tree, context)?, + ExprKind::Type(ty) => type_binding::bind(ty, tree, session, context)?, _ => type_binding::argument_alias(*target, native) .filter(|(_, dimensions)| dimensions.is_empty()) .and_then(|(name, _)| context.type_aliases.get(&name).cloned()), @@ -872,7 +882,7 @@ pub(in crate::ast) fn shape( if let Some(ty) = ty { values.push(procedural::dimensions_from_type(&ty)); } else { - let value = expression_binding::bind(id, tree, context)?; + let value = expression_binding::bind(id, tree, session, context)?; let Some(ty) = bound_bits_type(tree, &value, context) else { return Ok(None); }; @@ -883,7 +893,7 @@ pub(in crate::ast) fn shape( if special_dimension_count(id, tree, SystemFunction::Dimensions).is_some() { return Ok(None); } - let value = expression_binding::bind(id, tree, context)?; + let value = expression_binding::bind(id, tree, session, context)?; let Some(ty) = bound_bits_type(tree, &value, context) else { return Ok(None); }; @@ -915,7 +925,7 @@ pub(in crate::ast) fn shape( } } Job::Index(index) => { - validate_index(index, tree, context)?; + validate_index(index, tree, session, context)?; let shape = values .last_mut() .ok_or_else(|| unsupported("query shape"))?; @@ -932,12 +942,12 @@ pub(in crate::ast) fn shape( } Job::Range(left, right, indexed) => { let left = if indexed { - validate_index(left, tree, context)?; + validate_index(left, tree, session, context)?; None } else { - constant_binding::bind(left, tree, context)? + constant_binding::bind(left, tree, session, context)? }; - let right = constant_binding::bind(right, tree, context)? + let right = constant_binding::bind(right, tree, session, context)? .and_then(|v| eval_ast_const_expr(&tree.functions, &v, &context.const_env)); let width = if indexed { right @@ -994,6 +1004,7 @@ mod tests { use super::*; #[test] fn native_queries_preserve_declared_shape_without_running_operands() { + let session = &mut Session::default(); let source = "module M; logic[1:0][3:0] a; logic[7:0] memory[2:5]; int counter;function automatic logic[1:0][3:0] f();counter++;return '0;endfunction assign y=$bits(a)+$size(a)+$dimensions(a)+$left(a)+$right(a)+$low(a)+$high(a)+$increment(a)+$bits(memory)+$size(memory)+$dimensions(memory)+$unpacked_dimensions(memory)+$bits(memory[2])+$size(memory[2])+$dimensions(memory[2])+$unpacked_dimensions(memory[2])+$dimensions(1'b1)+$dimensions(1.25)+$unpacked_dimensions(memory[2+:1])+$bits(a[1:0])+$dimensions(a[1:0])+$size(a[1:0])+$bits(f())+$size(f())+$dimensions(f())+$bits(type(logic[3:0]))+$bits(type(int'(0)));endmodule"; let tree = crate::source_tree::parse_source( source, @@ -1025,14 +1036,19 @@ mod tests { let celox_sv_syntax::DataDeclaration::Variables(declaration) = declaration else { continue; }; - let base = type_binding::bind(declaration.data_type, &tree, &context) + let base = type_binding::bind(declaration.data_type, &tree, session, &context) .unwrap() .unwrap(); for variable in &declaration.variables { let ty = types::type_with_unpacked_ranges( base.clone(), - constant_binding::bind_unpacked_ranges(&variable.dimensions, &tree, &context) - .unwrap(), + constant_binding::bind_unpacked_ranges( + &variable.dimensions, + &tree, + session, + &context, + ) + .unwrap(), ); context.insert( instances::normalize_identifier(&variable.name.spelling), @@ -1062,8 +1078,10 @@ mod tests { let actual = calls .into_iter() .map(|(root, _)| { - let value = query_value(root, &tree, &context).unwrap().unwrap(); - expr_to_const(&tree.state, value) + let value = query_value(root, &tree, session, &context) + .unwrap() + .unwrap(); + expr_to_const(session, value) .and_then(|value| { eval_ast_const_expr(&tree.functions, &value, &context.const_env) }) diff --git a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs index 36aeadabe2f..90e49ad658a 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions/tests.rs @@ -28,6 +28,7 @@ fn native_calls(tree: &SyntaxTree) -> Vec { fn query_number( root: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, context: Option<&PackedDimensions>, @@ -37,10 +38,10 @@ fn query_number( .unwrap_or_else(|| PackedDimensions::new(HashMap::default(), env, aliases)); context.const_env = env.clone().into(); context.type_aliases = aliases.clone().into(); - query_value(root, tree, &context) + query_value(root, tree, session, &context) .ok() .flatten() - .and_then(|value| expr_to_const(&tree.state, value)) + .and_then(|value| expr_to_const(session, value)) .and_then(|value| eval_ast_const_expr(&tree.functions, &value, env)) .and_then(|value| usize::try_from(value).ok()) } @@ -70,6 +71,7 @@ fn repeated_literal_port_defaults_do_not_rediscover_declarations() { #[test] fn literal_arithmetic_queries_keep_widths_and_skip_scope_discovery() { + let session = &mut Session::default(); let code = "module Top; assign y=$bits(8'd60-1)+$bits(-8'sd1+16'sd2)+$bits(1'b0 ? 8'hff : 16'hffff)+$bits(~8'hff)+$bits(32'd1<<64'd40); endmodule"; let tree = crate::source_tree::parse_scope_fixture(code, Path::new("literal-query-types.sv")).unwrap(); @@ -82,6 +84,7 @@ fn literal_arithmetic_queries_keep_widths_and_skip_scope_discovery() { query_number( root, &tree, + session, &HashMap::default(), &HashMap::default(), Some(&input), @@ -94,6 +97,7 @@ fn literal_arithmetic_queries_keep_widths_and_skip_scope_discovery() { #[test] fn queries_still_discover_names_in_unselected_conditional_arms() { + let session = &mut Session::default(); let code = "module Top; logic [15:0] data; assign y=$bits(1'b0 ? data : 8'hff); endmodule"; let tree = crate::source_tree::parse_scope_fixture(code, Path::new("conditional-query-types.sv")) @@ -104,9 +108,10 @@ fn queries_still_discover_names_in_unselected_conditional_arms() { query_number( native_calls(&tree)[0], &tree, + session, &HashMap::default(), &HashMap::default(), - Some(&PackedDimensions::default()) + Some(&PackedDimensions::default()), ), Some(16) ); @@ -115,6 +120,7 @@ fn queries_still_discover_names_in_unselected_conditional_arms() { #[test] fn function_result_queries_preserve_expression_bodies() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( r#" module Top(output int y); @@ -133,18 +139,20 @@ 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, module.parameters()); - let aliases = type_aliases_from_scope_with_env(&tree, &env).unwrap(); + let env = const_env_from_parameters(&tree, session, module.parameters()); + let aliases = type_aliases_from_scope_with_env(&tree, session, &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, module.parameters(), &env).into(); - let functions = functions_from_scope(&tree, &env, &dimensions).unwrap(); + dimensions.parameter_values = + parameter_value_env(&tree, session, module.parameters(), &env).into(); + let functions = functions_from_scope(&tree, session, &env, &dimensions).unwrap(); assert!(functions["f"].body.is_some(), "{:?}", functions["f"]); } #[test] fn complete_scope_queries_match_syntax_discovery_without_rewalking_declarations() { + let session = &mut Session::default(); let code = r#" module Top(input logic signed [1:0][3:0] a, input logic [7:0] b); typedef struct packed { logic signed [3:0] nibble; logic flag; } pair_t; @@ -171,13 +179,14 @@ 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, module.parameters()); - let aliases = type_aliases_from_scope_with_env(&tree, &env).unwrap(); + let env = const_env_from_parameters(&tree, session, module.parameters()); + let aliases = type_aliases_from_scope_with_env(&tree, session, &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, module.parameters(), &env).into(); - let functions = functions_from_scope(&tree, &env, &dimensions).unwrap(); + dimensions.parameter_values = + parameter_value_env(&tree, session, module.parameters(), &env).into(); + let functions = functions_from_scope(&tree, session, &env, &dimensions).unwrap(); dimensions .function_return_types .extend(functions.iter().map(|(name, f)| { @@ -200,10 +209,10 @@ fn complete_scope_queries_match_syntax_discovery_without_rewalking_declarations( })); dimensions.functions = Arc::new(functions); let calls: Vec<_> = native_calls(&tree); - let query = |dimensions: &PackedDimensions| { + let mut query = |dimensions: &PackedDimensions| { calls .iter() - .map(|call| query_number(*call, &tree, &env, &aliases, Some(dimensions))) + .map(|call| query_number(*call, &tree, session, &env, &aliases, Some(dimensions))) .collect::>() }; SYNTAX_TYPE_DISCOVERIES.with(|count| count.set(0)); @@ -249,6 +258,7 @@ fn complete_scope_queries_match_syntax_discovery_without_rewalking_declarations( #[test] fn preliminary_function_scope_discovers_shadowing_formals() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( r#" module Top; @@ -269,6 +279,7 @@ fn preliminary_function_scope_discovers_shadowing_formals() { let ty = query_number( call, &tree, + session, &HashMap::default(), &HashMap::default(), Some(&dimensions), @@ -306,6 +317,7 @@ fn completed_query_metadata_is_local_to_each_specialization() { #[test] fn local_values_shadow_outer_typedefs_in_completed_generate_scopes() { + let session = &mut Session::default(); for (declaration, expected_width) in [ ("logic [3:0] T;", 4), ("localparam T = 1;", 32), @@ -327,15 +339,15 @@ 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, module.parameters()); - let aliases = type_aliases_from_scope_with_env(&tree, &env).unwrap(); + let env = const_env_from_parameters(&tree, session, module.parameters()); + let aliases = type_aliases_from_scope_with_env(&tree, session, &env).unwrap(); let dimensions = packed_dimensions_from_ports_and_signals( module.ports(), module.signals(), &env, &aliases, ); - let item = generate::items(&tree, &env, &aliases) + let item = generate::items(&tree, session, &env, &aliases) .unwrap() .into_iter() .find(|item| { @@ -347,8 +359,8 @@ fn local_values_shadow_outer_typedefs_in_completed_generate_scopes() { .unwrap(); let call = native_calls(&tree)[0]; let mut local = item.dimensions(&dimensions); - let query = |dimensions: &PackedDimensions| { - query_number(call, &tree, &item.env, &aliases, Some(dimensions)) + let mut query = |dimensions: &PackedDimensions| { + query_number(call, &tree, session, &item.env, &aliases, Some(dimensions)) }; let discovered = query(&local); local.scope_types_complete = true; @@ -366,6 +378,7 @@ fn local_values_shadow_outer_typedefs_in_completed_generate_scopes() { #[test] fn nonansi_validation_leaves_generate_queries_to_elaboration() { + let session = &mut Session::default(); let code = r#" module Top(y); output y; @@ -382,6 +395,7 @@ fn nonansi_validation_leaves_generate_queries_to_elaboration() { let tree = AnalysisContext::unspecialized(&tree); crate::ast::validation::reject_silently_ignored_constructs( &tree, + session, &HashMap::default(), &HashMap::default(), &ScopedMap::default(), @@ -392,6 +406,7 @@ fn nonansi_validation_leaves_generate_queries_to_elaboration() { #[test] fn unpacked_dimensions_discovers_local_dpi_return_types() { + let session = &mut Session::default(); let source = r#" module Top(output int y); import "DPI-C" function int f(); @@ -404,7 +419,14 @@ fn unpacked_dimensions_discovers_local_dpi_return_types() { Source::from_syntax(&tree).unwrap(); for call in native_calls(&tree) { assert_eq!( - query_number(call, &tree, &HashMap::default(), &HashMap::default(), None), + query_number( + call, + &tree, + session, + &HashMap::default(), + &HashMap::default(), + None + ), Some(0) ); } @@ -412,6 +434,7 @@ fn unpacked_dimensions_discovers_local_dpi_return_types() { #[test] fn unpacked_dimensions_preserves_runtime_indexed_range_types() { + let session = &mut Session::default(); let source = r#" module Top(input int index_value, output int y); logic [7:0] a [0:1][0:2]; @@ -424,13 +447,21 @@ fn unpacked_dimensions_preserves_runtime_indexed_range_types() { Source::from_syntax(&tree).unwrap(); let call = native_calls(&tree)[0]; assert_eq!( - query_number(call, &tree, &HashMap::default(), &HashMap::default(), None), + query_number( + call, + &tree, + session, + &HashMap::default(), + &HashMap::default(), + None + ), Some(1) ); } #[test] fn preliminary_unpacked_queries_resolve_preceding_declaration_ranges() { + let session = &mut Session::default(); for declaration in [ "module Top; logic [7:0] a [0:1]; logic [$unpacked_dimensions(a):0] b;", "module Top(input logic [7:0] a [0:1], output logic [$unpacked_dimensions(a):0] b);", @@ -442,15 +473,29 @@ fn preliminary_unpacked_queries_resolve_preceding_declaration_ranges() { let tree = crate::source_tree::parse_scope_fixture(&code, Path::new("preceding_query.sv")) .unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let aliases = type_aliases_from_scope(&tree).unwrap(); + let aliases = type_aliases_from_scope(&tree, session).unwrap(); let calls = native_calls(&tree); assert_eq!( - query_number(calls[0], &tree, &HashMap::default(), &aliases, None), + query_number( + calls[0], + &tree, + session, + &HashMap::default(), + &aliases, + None + ), Some(1), "{declaration}", ); assert_eq!( - query_number(calls[1], &tree, &HashMap::default(), &aliases, None), + query_number( + calls[1], + &tree, + session, + &HashMap::default(), + &aliases, + None + ), Some(if declaration.contains("b [") { 16 } else { 2 }), "{declaration}", ); @@ -459,6 +504,7 @@ fn preliminary_unpacked_queries_resolve_preceding_declaration_ranges() { #[test] fn preliminary_unpacked_queries_discover_array_parameters_before_dependent_ranges() { + let session = &mut Session::default(); for declaration in [ "module Top #(parameter logic [7:0] A [0:1] = '{default:0}) (output logic [$unpacked_dimensions(A):0] b);", "module Top; localparam logic [7:0] A [0:1] = '{default:0}; logic [$unpacked_dimensions(A):0] b;", @@ -474,9 +520,10 @@ fn preliminary_unpacked_queries_discover_array_parameters_before_dependent_range query_number( calls[0], &tree, + session, &HashMap::default(), &HashMap::default(), - None + None, ), Some(1), "{declaration}" @@ -485,9 +532,10 @@ fn preliminary_unpacked_queries_discover_array_parameters_before_dependent_range query_number( calls[1], &tree, + session, &HashMap::default(), &HashMap::default(), - None + None, ), Some(2), "{declaration}" @@ -497,6 +545,7 @@ fn preliminary_unpacked_queries_discover_array_parameters_before_dependent_range #[test] fn preliminary_unpacked_queries_prefer_values_over_imported_typedefs() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( r#" package P; @@ -512,7 +561,7 @@ fn preliminary_unpacked_queries_prefer_values_over_imported_typedefs() { ) .unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let aliases = type_aliases_from_scope(&tree).unwrap(); + let aliases = type_aliases_from_scope(&tree, session).unwrap(); // The aliases came from P; the query belongs to Top's native source unit. let module_scope = tree .root_scopes() @@ -526,13 +575,14 @@ fn preliminary_unpacked_queries_prefer_values_over_imported_typedefs() { let tree = AnalysisContext::unspecialized(&tree); let call = native_calls(&tree)[0]; assert_eq!( - query_number(call, &tree, &HashMap::default(), &aliases, None), + query_number(call, &tree, session, &HashMap::default(), &aliases, None), Some(0) ); } #[test] fn recursive_generate_dimension_discovery_uses_explicit_specialization() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( r#" module Top #(parameter logic [255:0] P = '0, @@ -578,7 +628,8 @@ fn recursive_generate_dimension_discovery_uses_explicit_specialization() { (&default_context, 5), ] { let dimensions = - query_context_for_operand(operand, context, &PackedDimensions::default()).unwrap(); + query_context_for_operand(operand, context, session, &PackedDimensions::default()) + .unwrap(); let data = dimensions.get("g.data").unwrap(); assert_eq!( eval_ast_const_expr( @@ -593,6 +644,7 @@ fn recursive_generate_dimension_discovery_uses_explicit_specialization() { #[test] fn preliminary_literal_queries_do_not_discover_scope_declarations() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( r#"module Top; logic [7:0] unrelated [0:31]; @@ -619,10 +671,12 @@ fn preliminary_literal_queries_do_not_discover_scope_declarations() { unreachable!() }; let context = - query_operand_dimensions_id(arguments[0].value.unwrap(), &tree, &input).unwrap(); + query_operand_dimensions_id(arguments[0].value.unwrap(), &tree, session, &input) + .unwrap(); query_number( *call, &tree, + session, &HashMap::default(), &HashMap::default(), Some(&context), @@ -636,6 +690,7 @@ fn preliminary_literal_queries_do_not_discover_scope_declarations() { query_number( *call, &tree, + session, &HashMap::default(), &HashMap::default(), Some(&input), @@ -649,6 +704,7 @@ fn preliminary_literal_queries_do_not_discover_scope_declarations() { #[test] fn discovery_prefix_does_not_copy_a_growing_symbol_overlay() { + let session = &mut Session::default(); const COUNT: usize = 128; let declarations = (0..COUNT) .map(|index| format!("logic [7:0] v{index};")) @@ -669,9 +725,10 @@ fn discovery_prefix_does_not_copy_a_growing_symbol_overlay() { query_number( calls[0], &tree, + session, &HashMap::default(), &HashMap::default(), - None + None, ), Some(8) ); diff --git a/crates/celox-sv-analyzer/src/ast/dpi.rs b/crates/celox-sv-analyzer/src/ast/dpi.rs index d8ec4d5cc03..384a1af075a 100644 --- a/crates/celox-sv-analyzer/src/ast/dpi.rs +++ b/crates/celox-sv-analyzer/src/ast/dpi.rs @@ -21,6 +21,7 @@ const MAX_DPI_ARGUMENTS: usize = 16; pub(super) fn imports( items: &[generate::Item], tree: &AnalysisContext<'_>, + session: &mut Session, type_aliases: &HashMap, ) -> Result, AnalyzerError> { let syntax = tree.declarations(); @@ -33,7 +34,15 @@ pub(super) fn imports( if declaration.import { imports.push(import(id, syntax)?); } else { - export(declaration, item, items, tree, type_aliases, &mut exports)?; + export( + declaration, + item, + items, + tree, + session, + type_aliases, + &mut exports, + )?; } } } @@ -48,6 +57,7 @@ fn export( item: &generate::Item, items: &[generate::Item], tree: &AnalysisContext<'_>, + session: &mut Session, type_aliases: &HashMap, exports: &mut HashMap<(String, String), String>, ) -> Result<(), AnalyzerError> { @@ -89,8 +99,8 @@ fn export( // scope of the export, as its subroutine's are. let aliases = item.type_aliases(type_aliases); let context = PackedDimensions::new(HashMap::default(), &item.env, &aliases); - let class_handle = |id| -> Result { - Ok(type_binding::bind(id, tree, &context)?.is_some_and(|ty| ty.class().is_some())) + let mut class_handle = |id| -> Result { + Ok(type_binding::bind(id, tree, session, &context)?.is_some_and(|ty| ty.class().is_some())) }; let ports = subroutine.ports.iter().flatten().chain( subroutine diff --git a/crates/celox-sv-analyzer/src/ast/events.rs b/crates/celox-sv-analyzer/src/ast/events.rs index 513a4dd1613..3a61cee8de9 100644 --- a/crates/celox-sv-analyzer/src/ast/events.rs +++ b/crates/celox-sv-analyzer/src/ast/events.rs @@ -34,6 +34,7 @@ pub(super) fn call(op: ProcessOp, events: Vec) -> Expr { /// Subroutines returning events are rejected, so a call is never one. pub(super) fn is_handle( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -52,17 +53,19 @@ pub(super) fn is_handle( ExprKind::Literal(value) if value == "null" ) }; - let event = |id| is_handle(tree, id, native, dimensions); + let mut event = |id| is_handle(tree, session, id, native, dimensions); return (event(*then_expression) || null(*then_expression)) && (event(*else_expression) || null(*else_expression)) && !(null(*then_expression) && null(*else_expression)); } - expression_binding::object_native_class(tree, id, native, dimensions).as_deref() == Some(CLASS) + expression_binding::object_native_class(tree, session, id, native, dimensions).as_deref() + == Some(CLASS) } /// The event of `e.triggered` or `e.triggered()` (15.5.3). pub(super) fn triggered( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -93,7 +96,7 @@ pub(super) fn triggered( }; Ok((separator == "." && instances::normalize_identifier(&name.spelling) == "triggered" - && is_handle(tree, *expression, native, dimensions)) + && is_handle(tree, session, *expression, native, dimensions)) .then_some(*expression)) } diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 1acd7446106..04c9142c6ed 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -48,15 +48,17 @@ fn disagreement() -> AnalyzerError { pub(super) fn bind( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted { - bind_value(root, tree.declarations(), tree, dimensions, None) + bind_value(root, tree.declarations(), tree, session, dimensions, None) } pub(super) fn expression( root: ExprId, native: &Declarations, lhs: &LValue, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted { let shape = match lhs { @@ -79,10 +81,10 @@ pub(super) fn expression( dimensions, ), }; - return streams::pack(root, Some(receiver), native, tree, dimensions); + return streams::pack(root, Some(receiver), native, tree, session, dimensions); } if let Some(target) = shape.and_then(|shape| shape.container.as_deref()) { - return containers::assignment(root, tree, dimensions, target); + return containers::assignment(root, tree, session, dimensions, target); } // `new` creates an object of the class of the variable or of the // element of an array of handles (IEEE 1800-2023 8.7). @@ -99,14 +101,14 @@ pub(super) fn expression( LValue::Select { .. } => None, }; if let Some(class) = class { - if let Some(call) = objects::constructor(tree, root, native, dimensions, class)? { + if let Some(call) = objects::constructor(tree, session, root, native, dimensions, class)? { return Ok(call); } - objects::check_assignment(tree, root, native, dimensions, class, || { + objects::check_assignment(tree, session, root, native, dimensions, class, || { "assignment".to_owned() })?; } - let value = bind_value(root, native, tree, dimensions, shape)?; + let value = bind_value(root, native, tree, session, dimensions, shape)?; // A string literal or integral value assigned to a string becomes its // bytes (IEEE 1800-2023 6.16). Ok(if shape.is_some_and(|shape| shape.string) { @@ -119,15 +121,17 @@ pub(super) fn value( root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted { - bind_value(root, native, tree, dimensions, None) + bind_value(root, native, tree, session, dimensions, None) } #[cfg(test)] mod tests { use super::*; #[test] fn deep_native_runtime_groups_and_native_literal_values() { + let session = &mut Session::default(); let path = Path::new("native-runtime-groups.sv"); let tree = crate::source_tree::parse_source("module M(output int y); assign y=7; endmodule", path) @@ -142,7 +146,15 @@ mod tests { let native = celox_sv_syntax::Declarations::parse(&source, path).unwrap(); let root = native.assign_statements[0].assignments[0].right; assert_eq!( - expression(root, &native, &lhs, &tree, &PackedDimensions::default()).unwrap(), + expression( + root, + &native, + &lhs, + &tree, + session, + &PackedDimensions::default() + ) + .unwrap(), Expr::Literal("7".into()) ); for (text, expected) in [("8", 8), ("7+8", 15)] { @@ -152,10 +164,17 @@ mod tests { ) .unwrap(); let root = native.assign_statements[0].assignments[0].right; - let value = - expression(root, &native, &lhs, &tree, &PackedDimensions::default()).unwrap(); + let value = expression( + root, + &native, + &lhs, + &tree, + session, + &PackedDimensions::default(), + ) + .unwrap(); assert_eq!( - expr_to_const(&tree.state, value).and_then(|value| eval_ast_const_expr( + expr_to_const(session, value).and_then(|value| eval_ast_const_expr( &tree.functions, &value, &HashMap::default() @@ -171,6 +190,7 @@ mod query_depth_tests { use super::*; #[test] fn deeply_nested_bits_uses_native_jobs_on_default_stack() { + let session = &mut Session::default(); let tree = std::thread::Builder::new() .stack_size(128 * 1024 * 1024) .spawn(|| { @@ -196,7 +216,7 @@ mod query_depth_tests { scope_types_complete: true, ..PackedDimensions::default() }; - let value = bind(root, &tree, &context); + let value = bind(root, &tree, session, &context); drop(tree); assert_eq!(value.unwrap(), Expr::Literal("32".into())); } diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/calls.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/calls.rs index 594a2909c7d..0352e80637c 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/calls.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/calls.rs @@ -1,12 +1,15 @@ use super::*; pub(super) fn callee_name( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, ) -> Converted> { - Ok(direct::bound_callable_name(tree, id, native, dimensions)? - .filter(|name| !name.starts_with('$') || name.contains("::"))) + Ok( + direct::bound_callable_name(tree, session, id, native, dimensions)? + .filter(|name| !name.starts_with('$') || name.contains("::")), + ) } pub(in crate::ast) fn statement_root( @@ -46,6 +49,7 @@ pub(in crate::ast) fn statement( discarded: bool, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, signatures: &HashMap>, ) -> Converted> { @@ -54,7 +58,7 @@ pub(in crate::ast) fn statement( ExprKind::Call { expression, .. } => expression, _ => root, }; - if callee_name(tree, callee, native, dimensions)?.is_none() { + if callee_name(tree, session, callee, native, dimensions)?.is_none() { return match &native.expression(callee).kind { ExprKind::Name(name) if name.spelling.starts_with('$') => Ok(None), ExprKind::Member { separator, .. } if separator == "." => Ok(None), @@ -67,14 +71,15 @@ pub(in crate::ast) fn statement( native.expression(root).kind, ExprKind::Name(_) | ExprKind::Member { .. } ) { - let name = callee_name(tree, root, native, dimensions)?.ok_or_else(disagreement)?; + let name = + callee_name(tree, session, root, native, dimensions)?.ok_or_else(disagreement)?; return Ok(Some(Expr::Call { callee: Callee::Subroutine(name), args: Vec::new(), arg_order: Vec::new(), })); } - super::bind_value(root, native, tree, &context, None).map(Some) + super::bind_value(root, native, tree, session, &context, None).map(Some) } #[cfg(test)] 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 2ae02fbd929..c5b56bb1a4d 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -61,6 +61,7 @@ pub(in crate::ast) fn callable_name( /// Resolve interface selections with the constant environment of the call site. pub(super) fn bound_callable_name( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -69,7 +70,7 @@ pub(super) fn bound_callable_name( return Ok(Some(name)); } if let Some((name, _, objects::Receiver::Static)) = - objects::method(tree, id, native, dimensions)? + objects::method(tree, session, id, native, dimensions)? { return Ok(Some(name)); } @@ -87,6 +88,7 @@ pub(super) fn bound_callable_name( let handle = interface_binding::actual_handle_key( *expression, tree, + session, &dimensions.const_env, &dimensions.type_aliases, )?; @@ -172,6 +174,7 @@ pub(in crate::ast) fn cast_target_native( operand: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted { let target = ungroup(target, native); @@ -181,7 +184,7 @@ pub(in crate::ast) fn cast_target_native( return Ok(casts::RuntimeCastTarget::String); } if let ExprKind::Type(id) = native.expression(target).kind - && let Some(ty) = type_binding::binding::bind_in(id, native, tree, dimensions)? + && let Some(ty) = type_binding::binding::bind_in(id, native, tree, session, dimensions)? && matches!(ty.kind(), TypeKind::Real | TypeKind::Shortreal) { return Ok(casts::RuntimeCastTarget::Real { @@ -214,7 +217,7 @@ pub(in crate::ast) fn cast_target_native( celox_sv_syntax::DataTypeKind::Named(_) => {} _ => return Err(unsupported("cast target type")), } - let ty = type_binding::binding::bind_in(id, native, tree, dimensions)? + let ty = type_binding::binding::bind_in(id, native, tree, session, dimensions)? .ok_or_else(|| unsupported("cast target type"))?; ( casts::expr_type_from_type(&tree.functions, &ty, &dimensions.const_env) @@ -223,8 +226,8 @@ pub(in crate::ast) fn cast_target_native( ty.kind() == TypeKind::Bit, ) } else { - let value = super::bind_value(target, native, tree, dimensions, None)?; - let value = expr_to_const(&tree.state, value) + let value = super::bind_value(target, native, tree, session, dimensions, None)?; + let value = expr_to_const(session, value) .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) @@ -340,6 +343,7 @@ fn check_written_container( position: usize, actual: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted<()> { use crate::procedural::ParamDirection; @@ -358,6 +362,7 @@ fn check_written_container( containers::check_written_actual( actual, tree, + session, dimensions, container, direction == ParamDirection::Inout, @@ -370,6 +375,7 @@ pub(in crate::ast) fn bind_value( root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, target: Option<&VariableDimensions>, ) -> Converted { @@ -383,7 +389,7 @@ pub(in crate::ast) fn bind_value( values.push(value.clone()); continue; } - unpacked_structs::check_operands(id, native, tree, dimensions)?; + unpacked_structs::check_operands(id, native, tree, session, dimensions)?; // An argument, result or other value received as an unpacked // structure is a pattern or a value of its type (6.22.3). if let Some(aggregate) = target @@ -391,11 +397,14 @@ pub(in crate::ast) fn bind_value( .filter(|shape| shape.unpacked.is_empty()) .and_then(|shape| shape.unpacked_struct.as_deref()) { - unpacked_structs::check_value(aggregate, id, native, tree, dimensions)?; + unpacked_structs::check_value( + aggregate, id, native, tree, session, dimensions, + )?; } else if target .as_deref() .is_some_and(|shape| shape.unpacked.is_empty() && shape.container.is_none()) - && unpacked_structs::native_struct(id, native, tree, dimensions)?.is_some() + && unpacked_structs::native_struct(id, native, tree, session, dimensions)? + .is_some() { return Err(unsupported( "unpacked structure value received by a destination that is not of its type", @@ -407,7 +416,9 @@ pub(in crate::ast) fn bind_value( .as_deref() .filter(|_| shape.unpacked.is_empty() && shape.container.is_none()) }) { - virtual_interfaces::check_assignment(tree, id, native, dimensions, ty)?; + virtual_interfaces::check_assignment( + tree, session, id, native, dimensions, ty, + )?; } if let Some(ty) = target.as_deref().and_then(|shape| { shape @@ -428,10 +439,10 @@ pub(in crate::ast) fn bind_value( ) { let actual = if let ExprKind::Cast { target, .. } = native.expression(id).kind { - cast_shape(target, native, tree, dimensions)? + cast_shape(target, native, tree, session, dimensions)? .and_then(|shape| shape.pattern_type(&tree.functions, dimensions)) } else { - bound_patterns::native_value_type(id, tree, dimensions)? + bound_patterns::native_value_type(id, tree, session, dimensions)? }; if !actual.is_some_and(|ty| { ty.members @@ -459,14 +470,16 @@ pub(in crate::ast) fn bind_value( .into(), )); } - values.push(containers::assignment(id, tree, dimensions, container)?); + values.push(containers::assignment( + id, tree, session, dimensions, container, + )?); continue; } - if let Some(value) = locators::index(id, native, tree, dimensions)? { + if let Some(value) = locators::index(id, native, tree, session, dimensions)? { values.push(value); continue; } - if let Some(value) = locators::bind(id, native, tree, dimensions)? { + if let Some(value) = locators::bind(id, native, tree, session, dimensions)? { values.push(value); continue; } @@ -474,10 +487,11 @@ pub(in crate::ast) fn bind_value( ExprKind::Call { expression, arguments, - } => enums::method(tree, *expression, native, dimensions)? + } => enums::method(tree, session, *expression, native, dimensions)? .map(|method| (method, arguments.as_slice())), ExprKind::Member { .. } => { - enums::method(tree, id, native, dimensions)?.map(|method| (method, &[][..])) + enums::method(tree, session, id, native, dimensions)? + .map(|method| (method, &[][..])) } _ => None, }; @@ -517,25 +531,31 @@ pub(in crate::ast) fn bind_value( ); continue; } - if let Some(call) = scheduler_call(tree, id, native, dimensions)? { + if let Some(call) = scheduler_call(tree, session, id, native, dimensions)? { values.push(*call); continue; } - if let Some((value, _)) = array_reductions::bind(id, native, tree, dimensions)? { + if let Some((value, _)) = + array_reductions::bind(id, native, tree, session, dimensions)? + { values.push(value); continue; } - if let Some(value) = containers::value(id, native, tree, dimensions, false)? { + if let Some(value) = + containers::value(id, native, tree, session, dimensions, false)? + { values.push(value); continue; } if let Some(call) = - objects::constraint_mode_call(tree, id, native, dimensions, false)? + objects::constraint_mode_call(tree, session, id, native, dimensions, false)? { values.push(call); continue; } - if let Some(call) = objects::rand_mode_call(tree, id, native, dimensions, false)? { + if let Some(call) = + objects::rand_mode_call(tree, session, id, native, dimensions, false)? + { values.push(call); continue; } @@ -628,7 +648,7 @@ pub(in crate::ast) fn bind_value( continue; } if let Some((aggregate, class, _)) = - objects::aggregate_property(tree, id, native, dimensions)? + objects::aggregate_property(tree, session, id, native, dimensions)? { values.push(objects::aggregate_load( &aggregate, @@ -637,12 +657,14 @@ pub(in crate::ast) fn bind_value( )?); continue; } - if let Some(value) = objects::unqualified_property(tree, dimensions, &name)? + if let Some(value) = + objects::unqualified_property(tree, session, dimensions, &name)? { values.push(value); continue; } - if let Some(value) = virtual_interfaces::identity(tree, &name, dimensions)? + if let Some(value) = + virtual_interfaces::identity(tree, session, &name, dimensions)? { values.push(value); continue; @@ -664,7 +686,7 @@ pub(in crate::ast) fn bind_value( } if operator != "inside" => { if matches!(operator.as_str(), "==" | "!=" | "===" | "!==") { virtual_interfaces::check_equality( - tree, *left, *right, native, dimensions, + tree, session, *left, *right, native, dimensions, )?; } ( @@ -700,9 +722,9 @@ pub(in crate::ast) fn bind_value( let ty = match call_name(tree, *target, native) { Some(name) => dimensions.type_aliases.get(&name).cloned(), None => match native.expression(ungroup(*target, native)).kind { - ExprKind::Type(ty) => { - type_binding::binding::bind_in(ty, native, tree, dimensions)? - } + ExprKind::Type(ty) => type_binding::binding::bind_in( + ty, native, tree, session, dimensions, + )?, _ => None, }, }; @@ -721,12 +743,19 @@ pub(in crate::ast) fn bind_value( Some(receiver), native, tree, + session, dimensions, )?); continue; } - let cast = - cast_target_native(*target, *expression, native, tree, dimensions)?; + let cast = cast_target_native( + *target, + *expression, + native, + tree, + session, + dimensions, + )?; let receiver = match &cast { casts::RuntimeCastTarget::String => { values.push(streams::pack( @@ -734,6 +763,7 @@ pub(in crate::ast) fn bind_value( Some(streams::Receiver::String), native, tree, + session, dimensions, )?); continue; @@ -754,24 +784,29 @@ pub(in crate::ast) fn bind_value( *expression, native, tree, + session, dimensions, )?), vec![( *expression, - cast_shape(*target, native, tree, dimensions)?.map(Rc::new), + cast_shape(*target, native, tree, session, dimensions)?.map(Rc::new), )], ), ExprKind::Call { expression, arguments: args, - } if objects::method(tree, *expression, native, dimensions)?.is_some() => { + } if objects::method(tree, session, *expression, native, dimensions)? + .is_some() => + { let (name, formals, receiver) = - objects::method(tree, *expression, native, dimensions)? + objects::method(tree, session, *expression, native, dimensions)? .expect("checked by the guard"); let selection = name .ends_with("::randomize") .then(|| { - objects::random_selection(tree, dimensions, &name, args, native) + objects::random_selection( + tree, session, dimensions, &name, args, native, + ) }) .transpose()?; if name.ends_with("::srandom") @@ -803,6 +838,7 @@ pub(in crate::ast) fn bind_value( value, native, tree, + session, dimensions, )?; check_written_container( @@ -810,6 +846,7 @@ pub(in crate::ast) fn bind_value( first + position, value, tree, + session, dimensions, )?; let shape = shapes.and_then(|shapes| shapes.get(first + position)); @@ -820,7 +857,7 @@ pub(in crate::ast) fn bind_value( .and_then(|shape| shape.virtual_interface.as_deref()) { virtual_interfaces::check_copy_out( - tree, value, native, dimensions, formal, + tree, session, value, native, dimensions, formal, )?; } let shape = shape @@ -849,9 +886,12 @@ pub(in crate::ast) fn bind_value( ExprKind::Call { expression, arguments: args, - } if strings::method(tree, *expression, native, dimensions).is_some() => { - let (op, base) = strings::method(tree, *expression, native, dimensions) - .expect("checked by the guard"); + } if strings::method(tree, session, *expression, native, dimensions) + .is_some() => + { + let (op, base) = + strings::method(tree, session, *expression, native, dimensions) + .expect("checked by the guard"); if op.updates_receiver() { return Err(unsupported(format!( "string method `{op}` used as a value" @@ -937,10 +977,11 @@ pub(in crate::ast) fn bind_value( ); continue; } - let name = bound_callable_name(tree, *expression, native, dimensions)? - .ok_or_else(|| unsupported("method or randomize call"))?; + let name = + bound_callable_name(tree, session, *expression, native, dimensions)? + .ok_or_else(|| unsupported("method or randomize call"))?; let cast = match name.as_str() { - "$cast" => objects::cast(tree, args, native, dimensions)?, + "$cast" => objects::cast(tree, session, args, native, dimensions)?, _ => None, }; if let Some(cast) = cast { @@ -994,6 +1035,7 @@ pub(in crate::ast) fn bind_value( values.push(type_names::query_value( argument, tree, + session, scope.as_deref().unwrap_or(dimensions), )?); continue; @@ -1016,7 +1058,7 @@ pub(in crate::ast) fn bind_value( let context = match &scope { Some(scope) => scope.clone(), None => Rc::new(dimensions::query_context_for_operand( - argument, tree, dimensions, + argument, tree, session, dimensions, )?), }; if scope.is_none() { @@ -1038,9 +1080,10 @@ pub(in crate::ast) fn bind_value( | SystemFunction::ArrayQuery(_) ) { values.push( - dimensions::query_value(id, tree, dimensions)?.ok_or_else( - || unsupported(format!("operand of `{name}`")), - )?, + dimensions::query_value(id, tree, session, dimensions)? + .ok_or_else(|| { + unsupported(format!("operand of `{name}`")) + })?, ); continue; } @@ -1089,7 +1132,7 @@ pub(in crate::ast) fn bind_value( if function.writes_argument(position) && let Some(id) = id { - check_tagged_copyout(*id, None, tree, dimensions)?; + check_tagged_copyout(*id, None, tree, session, dimensions)?; } } ( @@ -1106,10 +1149,10 @@ pub(in crate::ast) fn bind_value( for (position, id) in actuals.iter().enumerate() { if let Some(id) = id { references::check_actual( - &name, position, *id, native, tree, dimensions, + &name, position, *id, native, tree, session, dimensions, )?; check_written_container( - &name, position, *id, tree, dimensions, + &name, position, *id, tree, session, dimensions, )?; } if let Some(id) = id @@ -1124,7 +1167,13 @@ pub(in crate::ast) fn bind_value( .and_then(|directions| directions.get(position)) .is_some_and(|direction| direction.is_written()) { - check_tagged_copyout(*id, Some(shape), tree, dimensions)?; + check_tagged_copyout( + *id, + Some(shape), + tree, + session, + dimensions, + )?; // The formal is copied out to the actual. if let Some(formal) = shape .virtual_interface @@ -1132,12 +1181,13 @@ pub(in crate::ast) fn bind_value( .filter(|_| shape.unpacked.is_empty()) { virtual_interfaces::check_copy_out( - tree, *id, native, dimensions, formal, + tree, session, *id, native, dimensions, formal, )?; } } array_compatibility::check_native_unpacked_assignment( tree, + session, *id, shape, || format!("argument {} of `{name}`", position + 1), @@ -1208,7 +1258,7 @@ pub(in crate::ast) fn bind_value( ExprKind::Select { expression, dimension, - } if strings::native_string(tree, *expression, native, dimensions) => { + } if strings::native_string(tree, session, *expression, native, dimensions) => { let celox_sv_syntax::DimensionKind::Index(index) = dimension.kind else { return Err(unsupported("part-select of a string")); }; @@ -1218,49 +1268,58 @@ pub(in crate::ast) fn bind_value( ) } ExprKind::Member { .. } - if objects::class_parameter(tree, id, native, dimensions)?.is_some() => + if objects::class_parameter(tree, session, id, native, dimensions)? + .is_some() => { values.push( - objects::class_parameter(tree, id, native, dimensions)? + objects::class_parameter(tree, session, id, native, dimensions)? .expect("checked by the guard"), ); continue; } ExprKind::Member { .. } - if virtual_interfaces::native_member(tree, id, native, dimensions) - .is_some() => + if virtual_interfaces::native_member( + tree, session, id, native, dimensions, + ) + .is_some() => { - let (handle, ty, member) = - virtual_interfaces::native_member(tree, id, native, dimensions) - .expect("checked by the guard"); + let (handle, ty, member) = virtual_interfaces::native_member( + tree, session, id, native, dimensions, + ) + .expect("checked by the guard"); ( Finish::VirtualMember(Box::new((ty.as_ref().clone(), member))), vec![(handle, None)], ) } ExprKind::Member { .. } - if containers::element_member(id, native, tree, dimensions)?.is_some() => + if containers::element_member(id, native, tree, session, dimensions)? + .is_some() => { - let (_, value) = containers::element_member(id, native, tree, dimensions)? - .expect("checked by the guard"); + let (_, value) = + containers::element_member(id, native, tree, session, dimensions)? + .expect("checked by the guard"); values.push(value); continue; } ExprKind::Member { .. } - if objects::aggregate_property(tree, id, native, dimensions)?.is_some() => + if objects::aggregate_property(tree, session, id, native, dimensions)? + .is_some() => { let (aggregate, class, receiver) = - objects::aggregate_property(tree, id, native, dimensions)? + objects::aggregate_property(tree, session, id, native, dimensions)? .expect("checked by the guard"); - let handle = objects::receiver(tree, receiver, native, dimensions)?; + let handle = + objects::receiver(tree, session, receiver, native, dimensions)?; values.push(objects::aggregate_load(&aggregate, &class, &handle)?); continue; } ExprKind::Member { .. } - if objects::property(tree, id, native, dimensions)?.is_some() => + if objects::property(tree, session, id, native, dimensions)?.is_some() => { - let (property, receiver) = objects::property(tree, id, native, dimensions)? - .expect("checked by the guard"); + let (property, receiver) = + objects::property(tree, session, id, native, dimensions)? + .expect("checked by the guard"); match receiver { Some(receiver) => ( Finish::ObjectLoad(Box::new(property)), @@ -1273,10 +1332,11 @@ pub(in crate::ast) fn bind_value( } } ExprKind::Member { .. } | ExprKind::Select { .. } - if virtual_interfaces::native_identity(tree, id, dimensions).is_some() => + if virtual_interfaces::native_identity(tree, session, id, dimensions) + .is_some() => { values.push( - virtual_interfaces::native_identity(tree, id, dimensions) + virtual_interfaces::native_identity(tree, session, id, dimensions) .expect("checked by the guard"), ); continue; @@ -1284,18 +1344,18 @@ pub(in crate::ast) fn bind_value( ExprKind::Select { .. } if let Some((handle, ty, member)) = virtual_interfaces::native_selected_member( - tree, id, native, dimensions, + tree, session, id, native, dimensions, ) => { - let selected = selected_value(id, native, tree, dimensions)?; - let handle = bind_value(handle, native, tree, dimensions, None)?; + let selected = selected_value(id, native, tree, session, dimensions)?; + let handle = bind_value(handle, native, tree, session, dimensions, None)?; values.push(virtual_interfaces::selected_read( - tree, handle, &ty, &member, selected, dimensions, + tree, session, handle, &ty, &member, selected, dimensions, )?); continue; } ExprKind::Member { .. } | ExprKind::Select { .. } => { - values.push(selected_value(id, native, tree, dimensions)?); + values.push(selected_value(id, native, tree, session, dimensions)?); continue; } ExprKind::Pattern { .. } => { @@ -1303,6 +1363,7 @@ pub(in crate::ast) fn bind_value( id, native, tree, + session, dimensions, target.as_deref(), )?); @@ -1367,7 +1428,14 @@ pub(in crate::ast) fn bind_value( )); }; let receiver = streams::receiver(shape, &tree.functions, dimensions)?; - values.push(streams::pack(id, Some(receiver), native, tree, dimensions)?); + values.push(streams::pack( + id, + Some(receiver), + native, + tree, + session, + dimensions, + )?); continue; } ExprKind::Concatenation(_) => { @@ -1379,6 +1447,7 @@ pub(in crate::ast) fn bind_value( } => { values.push(objects::randomize_with( tree, + session, *expression, constraints.as_deref(), native, @@ -1402,7 +1471,9 @@ pub(in crate::ast) fn bind_value( } Job::Stream(id, receiver, scope) => { let dimensions = scope.as_deref().unwrap_or(dimensions); - values.push(streams::pack(id, receiver, native, tree, dimensions)?); + values.push(streams::pack( + id, receiver, native, tree, session, dimensions, + )?); } Job::Finish(finish, count, scope) => { let dimensions = scope.as_deref().unwrap_or(dimensions); @@ -1410,7 +1481,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, plan, operands.pop(), dimensions)? + packed_structs::construct(tree, session, plan, operands.pop(), dimensions)? } Finish::Unary(op) => { let operand = operands.pop().ok_or_else(disagreement)?; @@ -1536,7 +1607,15 @@ pub(in crate::ast) fn bind_value( count, } => { let count = count.then(|| operands.pop()).flatten(); - enums::call(tree, method, &domain, operands.pop(), count, dimensions)? + enums::call( + tree, + session, + method, + &domain, + operands.pop(), + count, + dimensions, + )? } Finish::StringCall(op) => { strings::call(op, strings::operands(op, operands, dimensions)) @@ -1549,6 +1628,7 @@ pub(in crate::ast) fn bind_value( &ids, operands, tree, + session, native, dimensions, )?, @@ -1599,7 +1679,9 @@ 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, handle, &ty, &member, dimensions, Ok)? + virtual_interfaces::read( + tree, session, handle, &ty, &member, dimensions, Ok, + )? } Finish::MethodCall(call) => { let MethodCall { @@ -1646,16 +1728,22 @@ pub(in crate::ast) fn bind_value( } Finish::Cast(target) => { let operand = remove_real_division_guards( - guard_zero_divisions(tree, operands.pop().ok_or_else(disagreement)?), + guard_zero_divisions( + tree, + session, + operands.pop().ok_or_else(disagreement)?, + ), dimensions, ); if dimensions.constant_indexed_base { - let operand = - selects::indexed_expression_value(tree, operand, dimensions) - .ok_or_else(|| unsupported("constant cast operand"))?; + let operand = selects::indexed_expression_value( + tree, session, operand, dimensions, + ) + .ok_or_else(|| unsupported("constant cast operand"))?; const_expr_to_expr( casts::cast_constant_target( tree, + session, operand, target, &dimensions.const_env, @@ -1683,8 +1771,8 @@ 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, count, dimensions)) + let count = expr_to_const(session, count.clone()) + .or_else(|| expr_to_index_const(tree, session, count, dimensions)) .ok_or_else(|| unsupported("replication count"))?; Expr::RepeatConcat { count, @@ -1793,7 +1881,7 @@ pub(in crate::ast) fn bind_value( .flatten() .and_then(|id| { array_compatibility::native_unpacked_shape( - id, tree, dimensions, + id, tree, session, dimensions, ) }) .is_some() @@ -1835,7 +1923,7 @@ pub(in crate::ast) fn bind_value( operands.insert(1, Expr::Literal("1".into())); } expressions::numeric_system_function( - tree, function, operands, dimensions, + tree, session, function, operands, dimensions, )? } } else { @@ -1870,7 +1958,7 @@ pub(in crate::ast) fn bind_value( return Err(disagreement()); } Ok(remove_real_division_guards( - guard_zero_divisions(tree, values.pop().unwrap()), + guard_zero_divisions(tree, session, values.pop().unwrap()), dimensions, )) } @@ -1879,9 +1967,10 @@ fn index_value( id: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted { - let value = bind_value(id, native, tree, dimensions, None)?; + let value = bind_value(id, native, tree, session, dimensions, None)?; if real_value(&value, dimensions) { return Err(unsupported("real-valued select index")); } @@ -1892,7 +1981,8 @@ fn index_value( 0, true, ); - if let Some(folded) = selects::indexed_expression_value(tree, value.clone(), dimensions) + if let Some(folded) = + selects::indexed_expression_value(tree, session, value.clone(), dimensions) && (matches!(folded, ConstExpr::Literal(_)) || eval_ast_const_expr(&tree.functions, &folded, &dimensions.const_env).is_some()) { @@ -1903,9 +1993,9 @@ fn index_value( return Ok(folded); } (if dimensions.constant_indexed_base { - selects::indexed_expression_value(tree, value, dimensions) + selects::indexed_expression_value(tree, session, value, dimensions) } else { - expr_to_index_const(tree, value, dimensions) + expr_to_index_const(tree, session, value, dimensions) }) .ok_or_else(|| unsupported("index expression")) } @@ -1914,16 +2004,17 @@ fn read_index_value( id: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted { - let value = index_value(id, native, tree, dimensions)?; + let value = index_value(id, native, tree, session, dimensions)?; if !dimensions.constant_indexed_base && matches!( native.expression(ungroup(id, native)).kind, ExprKind::Conditional { .. } ) && eval_ast_const_expr(&tree.functions, &value, &dimensions.const_env).is_none() - && !inlining::calls_subroutine(&bind_value(id, native, tree, dimensions, None)?) + && !inlining::calls_subroutine(&bind_value(id, native, tree, session, dimensions, None)?) { return Err(unsupported(format!( "select index `{}`", @@ -1937,26 +2028,28 @@ pub(super) fn path( mut root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted<(Vec, Option)> { let authored = root; // A member through a virtual interface is selected in its template, // which the caller applies to the member of each instance. - if let Some((_, ty, member)) = virtual_interfaces::native_member(tree, root, native, dimensions) + if let Some((_, ty, member)) = + virtual_interfaces::native_member(tree, session, root, native, dimensions) { - virtual_interfaces::member(&tree.state, &ty, &member)?; + virtual_interfaces::member(session, &ty, &member)?; return Ok(( vec![virtual_interfaces::template(&ty.interface, &member)], None, )); } // A static class property is a variable of the module. - if let Some(variable) = objects::static_property(tree, root, native, dimensions)? { + if let Some(variable) = objects::static_property(tree, session, root, native, dimensions)? { return Ok((vec![variable], None)); } // The property whose select is being bound is bound as its template. if dimensions.property_select_base == Some(ungroup(root, native)) - && let Some((property, _)) = objects::property(tree, root, native, dimensions)? + && let Some((property, _)) = objects::property(tree, session, root, native, dimensions)? { return Ok((vec![objects::select_template(&property)], None)); } @@ -1986,16 +2079,17 @@ pub(super) fn path( let DimensionKind::Index(index) = dimension.kind else { unreachable!() }; - let value = index_value(index, native, tree, dimensions)?; + let value = index_value(index, native, tree, session, dimensions)?; 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 (mut prefix, base) = path(*expression, native, tree, session, dimensions)?; let last = prefix.last_mut().ok_or_else(disagreement)?; last.push_str(&format!("[{value}]")); prefix.extend(parts.into_iter().rev()); if base.is_none() - && let Some(name) = - interface_binding::unindexed_parameter(&prefix, tree, dimensions, authored) + && let Some(name) = interface_binding::unindexed_parameter( + &prefix, tree, session, dimensions, authored, + ) { return Ok((vec![name], None)); } @@ -2010,7 +2104,7 @@ pub(super) fn path( } if qualified.is_none() && let Some(name) = - interface_binding::unindexed_parameter(&parts, tree, dimensions, authored) + interface_binding::unindexed_parameter(&parts, tree, session, dimensions, authored) { return Ok((vec![name], None)); } @@ -2031,6 +2125,7 @@ fn selected_value( root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted { let mut base = root; @@ -2056,7 +2151,8 @@ fn selected_value( // replaces: the select keeps the semantics of a variable select // (IEEE 1800-2023 11.5.1). if !suffix.is_empty() - && let Some((property, receiver)) = objects::property(tree, base, native, dimensions)? + && let Some((property, receiver)) = + objects::property(tree, session, base, native, dimensions)? && property.field.handle.is_none() && property.r#type.container.is_none() && property.r#type.unpacked_struct().is_none() @@ -2076,8 +2172,8 @@ fn selected_value( procedural::dimensions_from_type(&property.r#type), ); scope.property_select_base = Some(base); - let selected = selected_value(root, native, tree, &scope)?; - let handle = objects::receiver(tree, receiver, native, dimensions)?; + let selected = selected_value(root, native, tree, session, &scope)?; + let handle = objects::receiver(tree, session, receiver, native, dimensions)?; return Ok(crate::ast::inlining::substitute_expr_idents( selected, &HashMap::from_iter([(template, objects::load(&property, handle))]), @@ -2106,7 +2202,7 @@ fn selected_value( scope .expression_signedness .insert(name.clone(), container.element.is_signed()); - let selected = selected_value(root, native, tree, &scope)?; + let selected = selected_value(root, native, tree, session, &scope)?; return Ok(crate::ast::inlining::substitute_expr_idents( selected, &HashMap::from_iter([(name, containers::element_read(&container, handle))]), @@ -2136,7 +2232,7 @@ fn selected_value( let element_member = if suffix.is_empty() { None } else { - containers::element_member(base, native, tree, dimensions)? + containers::element_member(base, native, tree, session, dimensions)? }; if element_member.is_some() || matches!( @@ -2168,7 +2264,7 @@ fn selected_value( } value } - None => bind_value(base, native, tree, dimensions, None)?, + None => bind_value(base, native, tree, session, dimensions, None)?, }; if suffix.len() != 1 { return Err(unsupported("concatenation select")); @@ -2176,27 +2272,27 @@ fn selected_value( let selection = match suffix[0] { DimensionKind::Range { left, right } => { selects::AggregateSelection::Range(selects::ParameterRange::Bounds( - read_index_value(*left, native, tree, dimensions)?, - read_index_value(*right, native, tree, dimensions)?, + read_index_value(*left, native, tree, session, dimensions)?, + read_index_value(*right, native, tree, session, dimensions)?, )) } - DimensionKind::Index(id) => { - selects::AggregateSelection::Index(read_index_value(*id, native, tree, dimensions)?) - } + DimensionKind::Index(id) => selects::AggregateSelection::Index(read_index_value( + *id, native, tree, session, dimensions, + )?), DimensionKind::Indexed { base, operator, width, } => selects::AggregateSelection::Range(selects::ParameterRange::Indexed { - base: read_index_value(*base, native, tree, dimensions)?, - width: read_index_value(*width, native, tree, dimensions)?, + base: read_index_value(*base, native, tree, session, dimensions)?, + width: read_index_value(*width, native, tree, session, dimensions)?, plus: operator == "+:", }), _ => return Err(unsupported("concatenation select")), }; return selects::aggregate_selection_value(tree, expr, selection, dimensions); } - let (parts, qualified) = path(base, native, tree, dimensions)?; + let (parts, qualified) = path(base, native, tree, session, dimensions)?; if dimensions.constant_indexed_base && parts.len() == 1 { let name = qualified.clone().unwrap_or_else(|| parts[0].clone()); let mut indices = Vec::new(); @@ -2209,12 +2305,12 @@ fn selected_value( ranged = !matches!(dimension, DimensionKind::Index(_)); match dimension { DimensionKind::Index(id) => { - indices.push(read_index_value(*id, native, tree, dimensions)?) + indices.push(read_index_value(*id, native, tree, session, dimensions)?) } DimensionKind::Range { left, right } => { range = Some(selects::ParameterRange::Bounds( - read_index_value(*left, native, tree, dimensions)?, - read_index_value(*right, native, tree, dimensions)?, + read_index_value(*left, native, tree, session, dimensions)?, + read_index_value(*right, native, tree, session, dimensions)?, )) } DimensionKind::Indexed { @@ -2223,8 +2319,8 @@ fn selected_value( width, } => { range = Some(selects::ParameterRange::Indexed { - base: read_index_value(*base, native, tree, dimensions)?, - width: read_index_value(*width, native, tree, dimensions)?, + base: read_index_value(*base, native, tree, session, dimensions)?, + width: read_index_value(*width, native, tree, session, dimensions)?, plus: operator == "+:", }) } @@ -2244,20 +2340,17 @@ fn selected_value( ExprKind::Conditional { .. } ) { - read_index_value(*id, native, tree, dimensions)?; + read_index_value(*id, native, tree, session, dimensions)?; } } - let value = expr_from_lvalue( - tree, - &selected_lvalue(root, native, tree, dimensions, false)?, - dimensions, - ); + let lvalue = selected_lvalue(root, native, tree, session, dimensions, false)?; + let value = expr_from_lvalue(tree, &lvalue, dimensions); if let Expr::Ident(name) = &value && let Some(value) = unpacked_structs::whole(name, dimensions) { return Ok(value); } - let guards = member_context(root, native, tree, dimensions)? + let guards = member_context(root, native, tree, session, dimensions)? .map(|(guards, _)| guards) .unwrap_or_default(); packed_structs::checked_value(guards, value, tree, dimensions) @@ -2267,6 +2360,7 @@ pub(in crate::ast) fn selected_lvalue( root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, net: bool, ) -> Converted { @@ -2281,11 +2375,14 @@ pub(in crate::ast) fn selected_lvalue( base = *expression; } suffix.reverse(); - let (parts, qualified) = path(base, native, tree, dimensions)?; + let (parts, qualified) = path(base, native, tree, session, dimensions)?; if suffix.is_empty() && parts.len() > 1 { return packed_structs::whole_member(tree, parts, qualified, dimensions); } - let finish = |name: String, context: &PackedDimensions, strict: bool| -> Converted { + let mut finish = |name: String, + context: &PackedDimensions, + strict: bool| + -> Converted { if context.get(&name).is_some_and(|ty| { ty.members .first() @@ -2309,15 +2406,14 @@ pub(in crate::ast) fn selected_lvalue( } ranged = !matches!(dimension, DimensionKind::Index(_)); match dimension { - DimensionKind::Index(id) => indices.push(selects::self_determined_index( - tree, - index_value(*id, native, tree, context)?, - context, - )), + DimensionKind::Index(id) => { + let index = index_value(*id, native, tree, session, context)?; + indices.push(selects::self_determined_index(tree, index, context)) + } DimensionKind::Range { left, right } => { range = Some(( - index_value(*left, native, tree, context)?, - index_value(*right, native, tree, context)?, + index_value(*left, native, tree, session, context)?, + index_value(*right, native, tree, session, context)?, false, )) } @@ -2326,8 +2422,8 @@ pub(in crate::ast) fn selected_lvalue( operator, width, } => { - let start = index_value(*base, native, tree, context)?; - let width = index_value(*width, native, tree, context)?; + let start = index_value(*base, native, tree, session, context)?; + let width = index_value(*width, native, tree, session, context)?; let ((msb, lsb), dynamic) = if net { let width = eval_ast_const_expr(&tree.functions, &width, &context.const_env) @@ -2622,6 +2718,7 @@ pub(in crate::ast) fn member_context( mut root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted, Type)>> { while let ExprKind::Select { expression, .. } = native.expression(root).kind { @@ -2630,7 +2727,7 @@ pub(in crate::ast) fn member_context( if !matches!(native.expression(root).kind, ExprKind::Member { .. }) { return Ok(None); } - let (mut parts, qualified) = path(root, native, tree, dims)?; + let (mut parts, qualified) = path(root, native, tree, session, dims)?; if let Some(name) = qualified { parts[0] = name; } @@ -2641,12 +2738,13 @@ fn cast_shape( target: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { let ty = if let Some(name) = call_name(tree, target, native) { dims.type_aliases.get(&name).cloned() } else if let ExprKind::Type(id) = native.expression(target).kind { - type_binding::binding::bind_in(id, native, tree, dims)? + type_binding::binding::bind_in(id, native, tree, session, dims)? } else { None }; @@ -2661,6 +2759,7 @@ fn check_tagged_copyout( root: ExprId, formal: Option<&VariableDimensions>, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted<()> { let native = tree.declarations(); @@ -2671,7 +2770,7 @@ fn check_tagged_copyout( pending.extend(parts.iter().map(|id| (*id, None))); continue; } - let Some(actual) = bound_patterns::native_value_type(root, tree, dims)? else { + let Some(actual) = bound_patterns::native_value_type(root, tree, session, dims)? else { continue; }; if actual.tagged_identity().is_some() @@ -2694,22 +2793,29 @@ fn check_tagged_copyout( #[inline(never)] fn scheduler_call( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, ) -> Converted>> { - if let Some(call) = super::super::processes::value(tree, id, native, dimensions, false)? { + if let Some(call) = + super::super::processes::value(tree, session, id, native, dimensions, false)? + { return Ok(Some(Box::new(call))); } - if let Some(call) = super::super::semaphores::value(tree, id, native, dimensions, false)? { + if let Some(call) = + super::super::semaphores::value(tree, session, id, native, dimensions, false)? + { return Ok(Some(Box::new(call))); } - if let Some(call) = super::super::mailboxes::value(tree, id, native, dimensions, false)? { + if let Some(call) = + super::super::mailboxes::value(tree, session, id, native, dimensions, false)? + { return Ok(Some(Box::new(call))); } // `e.triggered` (IEEE 1800-2023 15.5.3). - if let Some(event) = super::super::events::triggered(tree, id, native, dimensions)? { - let event = super::value(event, native, tree, dimensions)?; + if let Some(event) = super::super::events::triggered(tree, session, id, native, dimensions)? { + let event = super::value(event, native, tree, session, dimensions)?; return Ok(Some(Box::new(super::super::events::call( celox_design::ProcessOp::Triggered, vec![event], 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 813de9312be..95d3f74e5cf 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/enums.rs @@ -56,6 +56,7 @@ impl Method { /// with the expression it is called on and that expression's type. pub(super) fn method( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -74,7 +75,8 @@ pub(super) fn method( let Some(method) = Method::parse(&instances::normalize_identifier(&name.spelling)) else { return Ok(None); }; - Ok(domain(tree, *expression, native, dimensions)?.map(|domain| (method, *expression, domain))) + Ok(domain(tree, session, *expression, native, dimensions)? + .map(|domain| (method, *expression, domain))) } /// The enumerated type of native expression `id`, judged before it is @@ -83,12 +85,13 @@ pub(super) fn method( /// process. pub(super) fn domain( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, ) -> Converted>> { // `process::state` (9.7). - if let Some(domain) = processes::state(tree, id, native, dimensions) { + if let Some(domain) = processes::state(tree, session, id, native, dimensions) { return Ok(Some(domain)); } Ok(match &native.expression(ungroup(id, native)).kind { @@ -96,16 +99,16 @@ pub(super) fn domain( let name = instances::normalize_identifier(&name.spelling); match dimensions.get(&name) { Some(shape) => variable(shape), - None => match objects::property(tree, id, native, dimensions)? { + None => match objects::property(tree, session, id, native, dimensions)? { Some((property, _)) => scalar(&property.r#type), None => constant(tree, &name, dimensions), }, } } - ExprKind::Member { .. } => match method(tree, id, native, dimensions)? { + ExprKind::Member { .. } => match method(tree, session, id, native, dimensions)? { // A method called without parentheses (6.19.5.7). Some((method, _, domain)) => method.returns_member().then_some(domain), - None => match objects::static_property(tree, id, native, dimensions)? + None => match objects::static_property(tree, session, id, native, dimensions)? .or_else(|| call_name(tree, id, native)) .and_then(|name| dimensions.get(&name)) { @@ -117,7 +120,7 @@ pub(super) fn domain( { Some(domain) } - None => match objects::property(tree, id, native, dimensions)? { + None => match objects::property(tree, session, id, native, dimensions)? { Some((property, _)) => scalar(&property.r#type), // A member of a container element of unpacked structure // type. @@ -125,22 +128,25 @@ pub(super) fn domain( ungroup(id, native), native, tree, + session, dimensions, )? => { scalar(&ty) } // A member of a packed struct. - None => dimensions::operand_shape(id, tree, dimensions) + None => dimensions::operand_shape(id, tree, session, dimensions) .ok() .flatten() .and_then(|shape| variable(&shape)), }, }, }, - ExprKind::Select { .. } => element(tree, id, native, dimensions)?, + ExprKind::Select { .. } => element(tree, session, id, native, dimensions)?, ExprKind::Call { expression, .. } => { - if let Some((method, _, domain)) = method(tree, *expression, native, dimensions)? { + if let Some((method, _, domain)) = + method(tree, session, *expression, native, dimensions)? + { method.returns_member().then_some(domain) } else if let ExprKind::Member { expression: base, @@ -148,12 +154,13 @@ pub(super) fn domain( .. } = &native.expression(ungroup(*expression, native)).kind && matches!(name.spelling.as_str(), "pop_front" | "pop_back") - && let Some(container) = containers::native_type(*base, native, tree, dimensions)? + && let Some(container) = + containers::native_type(*base, native, tree, session, dimensions)? { // An element popped from a queue (7.10.2.4, 7.10.2.5). scalar(&container.element) } else { - let name = match objects::method(tree, *expression, native, dimensions)? { + let name = match objects::method(tree, session, *expression, native, dimensions)? { Some((name, _, _)) => Some(name), None => call_name(tree, *expression, native), }; @@ -171,7 +178,7 @@ pub(super) fn domain( }) } } - ExprKind::Cast { target, .. } => cast_type(tree, *target, native, dimensions)? + ExprKind::Cast { target, .. } => cast_type(tree, session, *target, native, dimensions)? .as_ref() .and_then(scalar), ExprKind::Conditional { @@ -179,8 +186,8 @@ pub(super) fn domain( else_expression, .. } => { - let then_domain = domain(tree, *then_expression, native, dimensions)?; - let else_domain = domain(tree, *else_expression, native, dimensions)?; + let then_domain = domain(tree, session, *then_expression, native, dimensions)?; + let else_domain = domain(tree, session, *else_expression, native, dimensions)?; then_domain.filter(|domain| else_domain.as_ref() == Some(domain)) } _ => None, @@ -191,6 +198,7 @@ pub(super) fn domain( /// type rather than a width or signedness. pub(super) fn cast_type( tree: &AnalysisContext<'_>, + session: &mut Session, target: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -199,7 +207,7 @@ pub(super) fn cast_type( Ok(if let Some(name) = call_name(tree, target, native) { dimensions.type_aliases.get(&name).cloned() } else if let ExprKind::Type(id) = native.expression(target).kind { - type_binding::binding::bind_in(id, native, tree, dimensions)? + type_binding::binding::bind_in(id, native, tree, session, dimensions)? } else { None }) @@ -266,6 +274,7 @@ fn constant( /// container whose elements are of one. fn element( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -281,7 +290,8 @@ fn element( return Ok(None); } if selects == 0 - && let Some(container) = containers::native_type(*expression, native, tree, dimensions)? + && let Some(container) = + containers::native_type(*expression, native, tree, session, dimensions)? { return Ok(scalar(&container.element)); } @@ -304,9 +314,10 @@ fn element( } // A static property or a package variable. ExprKind::Member { .. } - if let Some(shape) = objects::static_property(tree, root, native, dimensions)? - .or_else(|| call_name(tree, root, native)) - .and_then(|name| dimensions.get(&name)) => + if let Some(shape) = + objects::static_property(tree, session, root, native, dimensions)? + .or_else(|| call_name(tree, root, native)) + .and_then(|name| dimensions.get(&name)) => { if shape.container.is_some() { return Ok(None); @@ -318,7 +329,7 @@ fn element( ) } ExprKind::Name(_) | ExprKind::Member { .. } => { - match objects::property(tree, root, native, dimensions)? { + match objects::property(tree, session, root, native, dimensions)? { Some((property, _)) if property.r#type.container.is_none() => ( property.r#type.unpacked_ranges.len(), property.r#type.enum_domain.clone(), @@ -340,13 +351,13 @@ fn element( /// The value of `method` of `domain` called on `receiver` with `count`. pub(super) fn call( tree: &AnalysisContext<'_>, + session: &mut Session, 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| { @@ -413,7 +424,7 @@ pub(super) fn call( count.unwrap_or_else(|| int(1)), dimensions, )?; - let constant = expr_to_const(state, count.clone()) + let constant = expr_to_const(session, count.clone()) .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 { diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/format_patterns.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/format_patterns.rs index e8707aeb34f..176af55e5ba 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/format_patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/format_patterns.rs @@ -85,6 +85,7 @@ pub(in crate::ast) fn rewrite_template( /// names are renamed). pub(in crate::ast) fn pattern( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, value: &Expr, native: &Declarations, @@ -106,20 +107,22 @@ pub(in crate::ast) fn pattern( // A string literal is integral unless the other operand is a string // (5.9, 6.16), and an enum operand is integral unless the other // operand has the same enumerated type (11.4.11). - let enum_valued = enums::domain(tree, id, native, dimensions)?.is_some(); - let operand = |id, value| { - if !enum_valued && enums::domain(tree, id, native, dimensions)?.is_some() { + let enum_valued = enums::domain(tree, session, id, native, dimensions)?.is_some(); + let mut operand = |id, value| { + if !enum_valued && enums::domain(tree, session, id, native, dimensions)?.is_some() { return Ok(Pattern::Integral); } - Ok(match pattern(tree, id, value, native, dimensions)? { - Pattern::String - if matches!(&native.expression(ungroup(id, native)).kind, + Ok( + match pattern(tree, session, id, value, native, dimensions)? { + Pattern::String + if matches!(&native.expression(ungroup(id, native)).kind, ExprKind::Literal(text) if text.starts_with('"')) => - { - Pattern::Integral - } - pattern => pattern, - }) + { + Pattern::Integral + } + pattern => pattern, + }, + ) }; let then_pattern = operand(*then_expression, then_expr)?; let else_pattern = operand(*else_expression, else_expr)?; @@ -137,12 +140,12 @@ pub(in crate::ast) fn pattern( if matches!(expression, ExprKind::Call { expression, .. } if direct::call_name(tree, *expression, native) .is_some_and(|name| returns_enum(&name, dimensions))) - || enums::domain(tree, id, native, dimensions)?.is_some() + || enums::domain(tree, session, id, native, dimensions)?.is_some() { return Err(unsupported("%p of an enum value")); } if strings::string_value(value, dimensions) - || strings::native_string(tree, id, native, dimensions) + || strings::native_string(tree, session, id, native, dimensions) || matches!(expression, ExprKind::Literal(text) if text.starts_with('"')) { return Ok(Pattern::String); @@ -150,7 +153,7 @@ pub(in crate::ast) fn pattern( if matches!(expression, ExprKind::Literal(text) if text == "null") { return Ok(Pattern::Handle(None)); } - if let Some(container) = containers::native_type(id, native, tree, dimensions)? { + if let Some(container) = containers::native_type(id, native, tree, session, dimensions)? { let element = &container.element; if element.is_enum || element.enum_domain.is_some() || element.packed_enum { return Err(unsupported("%p of a container of enum values")); @@ -188,7 +191,7 @@ pub(in crate::ast) fn pattern( } return Ok(Pattern::Handle(Some(container.layout))); } - if objects::native_class(tree, id, native, dimensions).is_some() + if objects::native_class(tree, session, id, native, dimensions).is_some() || handle_value(value, dimensions) || matches!(expression, ExprKind::Call { expression, .. } if direct::call_name(tree, *expression, native) @@ -212,7 +215,7 @@ pub(in crate::ast) fn pattern( _ => None, }; if let Some(base) = base { - if let Some(container) = containers::native_type(base, native, tree, dimensions)? { + if let Some(container) = containers::native_type(base, native, tree, session, dimensions)? { let element = &container.element; if element.is_enum || element.enum_domain.is_some() || element.packed_enum { return Err(unsupported("%p of an enum value")); @@ -254,7 +257,8 @@ pub(in crate::ast) fn pattern( }; let aggregate_value = match expression { ExprKind::Cast { target, .. } => { - enums::cast_type(tree, *target, native, dimensions)?.is_some_and(|ty| aggregate(&ty)) + enums::cast_type(tree, session, *target, native, dimensions)? + .is_some_and(|ty| aggregate(&ty)) } ExprKind::Call { expression, .. } => direct::call_name(tree, *expression, native) .is_some_and(|name| returns_aggregate(&name, dimensions, aggregate)), @@ -262,8 +266,8 @@ pub(in crate::ast) fn pattern( }; // A value of unpacked structure type: a variable, member or property. if aggregate_value - || unpacked_structs::native_struct(id, native, tree, dimensions)?.is_some() - || objects::aggregate_property(tree, id, native, dimensions)?.is_some() + || unpacked_structs::native_struct(id, native, tree, session, dimensions)?.is_some() + || objects::aggregate_property(tree, session, id, native, dimensions)?.is_some() { return Err(unsupported("%p of a structure or unpacked array")); } @@ -286,7 +290,7 @@ pub(in crate::ast) fn pattern( || !shape.unpacked.is_empty(), ); } - if let Some((property, _)) = objects::property(tree, id, native, dimensions)? { + if let Some((property, _)) = objects::property(tree, session, id, native, dimensions)? { let ty = &property.r#type; return checked( ty.is_enum || ty.enum_domain.is_some() || ty.packed_enum, @@ -433,6 +437,7 @@ pub(in crate::ast) fn rewrite_format( ids: &[ExprId], values: &mut [Expr], tree: &AnalysisContext<'_>, + session: &mut Session, native: &Declarations, dimensions: &PackedDimensions, ) -> Converted> { @@ -441,7 +446,7 @@ pub(in crate::ast) fn rewrite_format( // A conversion without an argument prints nothing. return Ok(&b"%0d"[..]); }; - let pattern = pattern(tree, id, value, native, dimensions)?; + let pattern = pattern(tree, session, id, value, native, dimensions)?; let (conversion, argument) = pattern_argument( pattern, std::mem::replace(value, Expr::Literal("0".into())), @@ -470,6 +475,7 @@ pub(in crate::ast) fn format( ids: &[ExprId], mut operands: Vec, tree: &AnalysisContext<'_>, + session: &mut Session, native: &Declarations, dimensions: &PackedDimensions, ) -> Converted { @@ -479,7 +485,7 @@ pub(in crate::ast) fn format( && has_pattern(&bytes) && let Some((first, rest)) = operands.split_first_mut() { - let template = rewrite_format(&bytes, values, rest, tree, native, dimensions)?; + let template = rewrite_format(&bytes, values, rest, tree, session, native, dimensions)?; *first = bytes_literal(&template); } Ok(strings::call(StringOp::Format { ticks_per_unit }, operands)) diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/lvalues.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/lvalues.rs index 786694befd8..ef6d636ec88 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/lvalues.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/lvalues.rs @@ -4,22 +4,24 @@ pub(in crate::ast) fn variable_lvalue( root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted { - direct::selected_lvalue(root, native, tree, dimensions, false) + direct::selected_lvalue(root, native, tree, session, dimensions, false) } pub(in crate::ast) fn net_lvalue( root: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted { - if direct::member_context(root, native, tree, dimensions)? + if direct::member_context(root, native, tree, session, dimensions)? .is_some_and(|(guards, _)| !guards.is_empty()) { return Err(unsupported("continuous driver of a tagged union member")); } - let target = direct::selected_lvalue(root, native, tree, dimensions, true)?; + let target = direct::selected_lvalue(root, native, tree, session, dimensions, true)?; crate::ast::virtual_interfaces::check_target(&target)?; Ok(target) } @@ -28,6 +30,7 @@ mod tests { use super::*; #[test] fn deep_native_target_range_bounds_and_widths_use_worklists() { + let session = &mut Session::default(); let path = Path::new("deep-native-target-range.sv"); for continuous in [false, true] { let prefix = if continuous { "assign" } else { "initial" }; @@ -61,9 +64,9 @@ mod tests { .unwrap() }; let target = if continuous { - net_lvalue(root, &native, &tree, &PackedDimensions::default()) + net_lvalue(root, &native, &tree, session, &PackedDimensions::default()) } else { - variable_lvalue(root, &native, &tree, &PackedDimensions::default()) + variable_lvalue(root, &native, &tree, session, &PackedDimensions::default()) } .unwrap(); let LValue::Select { msb, lsb, .. } = target else { @@ -79,6 +82,7 @@ mod tests { } #[test] fn deep_native_target_indices_bind_without_recursive_native_traversal() { + let session = &mut Session::default(); let path = Path::new("deep-native-target.sv"); for continuous in [false, true] { let prefix = if continuous { "assign" } else { "initial" }; @@ -110,9 +114,9 @@ mod tests { .unwrap() }; let target = if continuous { - net_lvalue(root, &native, &tree, &PackedDimensions::default()) + net_lvalue(root, &native, &tree, session, &PackedDimensions::default()) } else { - variable_lvalue(root, &native, &tree, &PackedDimensions::default()) + variable_lvalue(root, &native, &tree, session, &PackedDimensions::default()) } .unwrap(); let LValue::Select { msb, lsb, .. } = target else { 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 0b4a5027ef1..8711a964cb7 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/objects.rs @@ -14,10 +14,17 @@ use crate::system_functions::ObjectOp; /// The class `name`, laid out. pub(in crate::ast) fn class( tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, name: &str, ) -> Converted> { - classes::shared_class(tree, name, &dimensions.const_env, &dimensions.type_aliases) + classes::shared_class( + tree, + name, + &dimensions.const_env, + &dimensions.type_aliases, + session, + ) } /// The class of native expression `id` when it is an object handle, judged @@ -25,6 +32,7 @@ pub(in crate::ast) fn class( /// handles, or a handle property. pub(in crate::ast) fn native_class( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -38,14 +46,14 @@ pub(in crate::ast) fn native_class( } = &native.expression(*expression).kind && separator == "::" && name.spelling == "self" - && super::super::processes::scope(tree, *base, native, dimensions) + && super::super::processes::scope(tree, session, *base, native, dimensions) { return Some(super::super::processes::CLASS.to_owned()); } // The result of a function or method that returns a class handle, whose // members the call may select (IEEE 1800-2023 8.4). if let ExprKind::Call { expression, .. } = &native.expression(id).kind { - let name = match method(tree, *expression, native, dimensions) { + let name = match method(tree, session, *expression, native, dimensions) { Ok(Some((name, ..))) => name, Ok(None) => super::direct::callable_name(tree, *expression, native)?, Err(_) => return None, @@ -57,7 +65,7 @@ pub(in crate::ast) fn native_class( return dimensions.get(&name)?.class.clone(); } // A class handle member of a container element of unpacked structure type. - if let Ok(Some((ty, _))) = containers::element_member(id, native, tree, dimensions) { + if let Ok(Some((ty, _))) = containers::element_member(id, native, tree, session, dimensions) { return ty.class().map(str::to_owned); } let expression = native.expression(ungroup(id, native)); @@ -67,7 +75,7 @@ pub(in crate::ast) fn native_class( } = &expression.kind && matches!(dimension.kind, celox_sv_syntax::DimensionKind::Index(_)) { - if let Some(ty) = containers::native_type(*expression, native, tree, dimensions) + if let Some(ty) = containers::native_type(*expression, native, tree, session, dimensions) .ok() .flatten() { @@ -89,7 +97,7 @@ pub(in crate::ast) fn native_class( return ty.class.clone(); } if name == "super" { - return super_class(tree, dimensions); + return super_class(tree, session, dimensions); } } // The receiver of `h.p` is resolved once for both kinds of property, so @@ -102,30 +110,31 @@ pub(in crate::ast) fn native_class( && separator == "." // Otherwise a member of a property of unpacked structure type, found // as a property below. - && let Some(owner) = native_class(tree, *receiver, native, dimensions) + && let Some(owner) = native_class(tree, session, *receiver, native, dimensions) { let member = instances::normalize_identifier(&name.spelling); let receiver = (!is_super(*receiver, native)).then_some(*receiver); if let Some((property, _)) = - property_in(tree, dimensions, &owner, &member, receiver).ok()? + property_in(tree, session, dimensions, &owner, &member, receiver).ok()? { return property.r#type.class().map(str::to_owned); } - return class(tree, dimensions, &owner) + return class(tree, session, dimensions, &owner) .ok()? .static_property(&member) .and_then(|property| property.r#type.class().map(str::to_owned)); } - if let Some(class) = static_property_class(tree, id, native, dimensions).ok()? { + if let Some(class) = static_property_class(tree, session, id, native, dimensions).ok()? { return Some(class); } - let (property, _) = property(tree, id, native, dimensions).ok()??; + let (property, _) = property(tree, session, id, native, dimensions).ok()??; property.r#type.class().map(str::to_owned) } /// Access depends on the lexical class, not the class of the receiver (8.18). pub(in crate::ast) fn check_access( tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, owner: &str, name: &str, @@ -138,8 +147,9 @@ pub(in crate::ast) fn check_access( if let Some(scope) = dimensions.class_scope.as_deref() { if scope == owner || (!local - && class(tree, dimensions, scope)?.derives_from( + && class(tree, session, dimensions, scope)?.derives_from( tree, + session, owner, &dimensions.const_env, &dimensions.type_aliases, @@ -163,9 +173,13 @@ pub(in crate::ast) fn scope_class(dimensions: &PackedDimensions) -> Option, dimensions: &PackedDimensions) -> Option { +fn super_class( + tree: &AnalysisContext<'_>, + session: &mut Session, + dimensions: &PackedDimensions, +) -> Option { dimensions.get(THIS)?; - class(tree, dimensions, &scope_class(dimensions)?) + class(tree, session, dimensions, &scope_class(dimensions)?) .ok()? .base .clone() @@ -183,6 +197,7 @@ fn is_super(id: ExprId, native: &Declarations) -> bool { /// defaults of a parameterized class make (IEEE 1800-2023 8.25.1). pub(in crate::ast) fn named_class( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -203,9 +218,9 @@ pub(in crate::ast) fn named_class( .type_aliases .get(&scope_name) .and_then(|ty| ty.class().map(str::to_owned)) - .or_else(|| classes::resolve(tree, &scope_name)) + .or_else(|| classes::resolve(tree, session, &scope_name)) && let Some(ty) = - classes::specializations::member_type(tree, &scope_class, &member_name) + classes::specializations::member_type(tree, session, &scope_class, &member_name) && let Some(class) = ty.class() { return Ok(Some(class.to_owned())); @@ -219,13 +234,13 @@ pub(in crate::ast) fn named_class( { return Ok(Some(aliased)); } - if classes::handle_type(tree, &class).is_some() { + if classes::handle_type(tree, session, &class).is_some() { return Ok(Some(class)); } // Inside its package, `p::C` is a name of the package itself, // whose classes are declared under their qualified names. - return Ok(classes::resolve(tree, &class) - .filter(|class| classes::handle_type(tree, class).is_some())); + return Ok(classes::resolve(tree, session, &class) + .filter(|class| classes::handle_type(tree, session, class).is_some())); } ExprKind::Name(name) => (instances::normalize_identifier(&name.spelling), None), ExprKind::Parameterized { @@ -268,7 +283,7 @@ pub(in crate::ast) fn named_class( .get(&classes::specializations::scope_key(&name)) .or_else(|| { // A class of a package is declared under its qualified name. - let class = classes::resolve(tree, &name)?; + let class = classes::resolve(tree, session, &name)?; dimensions .type_aliases .get(&classes::specializations::scope_key(&class)) @@ -278,10 +293,10 @@ pub(in crate::ast) fn named_class( { return Ok(Some(class)); } - let Some(name) = classes::resolve(tree, &name) else { + let Some(name) = classes::resolve(tree, session, &name) else { return Ok(None); }; - if !classes::is_parameterized(tree, &name) { + if !classes::is_parameterized(tree, session, &name) { if arguments.is_some_and(|arguments| !arguments.is_empty()) { return Err(unsupported(format!( "parameter value assignment of class `{name}`, which has no parameters" @@ -294,13 +309,14 @@ pub(in crate::ast) fn named_class( let Some(arguments) = arguments else { return Err(AnalyzerError::UnspecializedClassScope { class: name }); }; - classes::specializations::specialize(tree, &name, arguments, dimensions).map(Some) + classes::specializations::specialize(tree, session, &name, arguments, dimensions).map(Some) } /// The value of the class parameter that native expression `id` names, /// `h.p` or `C::p` (IEEE 1800-2023 8.25), as a literal. pub(in crate::ast) fn class_parameter( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -314,13 +330,13 @@ pub(in crate::ast) fn class_parameter( return Ok(None); }; let class = match separator.as_str() { - "." => native_class(tree, *expression, native, dimensions), - "::" => named_class(tree, *expression, native, dimensions)?, + "." => native_class(tree, session, *expression, native, dimensions), + "::" => named_class(tree, session, *expression, native, dimensions)?, _ => None, }; Ok(class.and_then(|class| { classes::specializations::parameter( - tree, + session, &class, &instances::normalize_identifier(&name.spelling), ) @@ -332,12 +348,13 @@ pub(in crate::ast) fn class_parameter( /// method of the class is renamed to it where the method's scope begins. pub(in crate::ast) fn static_property( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, ) -> Converted> { Ok( - static_property_declaration(tree, id, native, dimensions)? + static_property_declaration(tree, session, id, native, dimensions)? .map(|property| property.variable), ) } @@ -346,6 +363,7 @@ pub(in crate::ast) fn static_property( /// as its class declares it. pub(in crate::ast) fn static_property_declaration( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -359,8 +377,8 @@ pub(in crate::ast) fn static_property_declaration( return Ok(None); }; let class_name = match separator.as_str() { - "." => native_class(tree, *expression, native, dimensions), - "::" => named_class(tree, *expression, native, dimensions)?, + "." => native_class(tree, session, *expression, native, dimensions), + "::" => named_class(tree, session, *expression, native, dimensions)?, _ => None, }; let Some(class_name) = class_name else { @@ -369,13 +387,14 @@ pub(in crate::ast) fn static_property_declaration( if classes::builtin(&class_name) { return Ok(None); } - let class = class(tree, dimensions, &class_name)?; + let class = class(tree, session, dimensions, &class_name)?; let Some(property) = class.static_property(&instances::normalize_identifier(&name.spelling)) else { return Ok(None); }; check_access( tree, + session, dimensions, &property.owner, &property.name, @@ -389,6 +408,7 @@ pub(in crate::ast) fn static_property_declaration( /// names holds, `h.p` or `C::p`. fn static_property_class( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -402,14 +422,14 @@ fn static_property_class( return Ok(None); }; let class_name = match separator.as_str() { - "." => native_class(tree, *expression, native, dimensions), - "::" => named_class(tree, *expression, native, dimensions)?, + "." => native_class(tree, session, *expression, native, dimensions), + "::" => named_class(tree, session, *expression, native, dimensions)?, _ => None, }; let Some(class_name) = class_name else { return Ok(None); }; - Ok(class(tree, dimensions, &class_name)? + Ok(class(tree, session, dimensions, &class_name)? .static_property(&instances::normalize_identifier(&name.spelling)) .and_then(|property| property.r#type.class().map(str::to_owned))) } @@ -419,20 +439,22 @@ fn static_property_class( /// the handle, or `None` for the enclosing method's `this`. pub(in crate::ast) fn property( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, ) -> Converted)>> { - let Some((class, name, receiver)) = member_chain(tree, id, native, dimensions)? else { + let Some((class, name, receiver)) = member_chain(tree, session, id, native, dimensions)? else { return Ok(None); }; - property_of(tree, dimensions, &class, &name, receiver) + property_of(tree, session, dimensions, &class, &name, receiver) } /// The instance property `name` of class `class_name`, read through /// `receiver` as [`property`] returns it. fn property_in( tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, class_name: &str, name: &str, @@ -441,14 +463,15 @@ fn property_in( if classes::builtin(class_name) { return Ok(None); } - let class = class(tree, dimensions, class_name)?; - property_of(tree, dimensions, &class, name, receiver) + let class = class(tree, session, dimensions, class_name)?; + property_of(tree, session, dimensions, &class, name, receiver) } /// The instance property `name` of `class`, read through `receiver` as /// [`property`] returns it. fn property_of( tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, class: &Class, name: &str, @@ -458,6 +481,7 @@ fn property_of( if let Some(property) = class.static_property(name) { check_access( tree, + session, dimensions, &property.owner, &property.name, @@ -469,6 +493,7 @@ fn property_of( }; check_access( tree, + session, dimensions, &property.owner, &property.name, @@ -488,11 +513,12 @@ fn property_of( /// expression `id` names, with the receiver as for [`property`]. pub(in crate::ast) fn aggregate_property( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, ) -> Converted, Option)>> { - let Some((class, name, receiver)) = member_chain(tree, id, native, dimensions)? else { + let Some((class, name, receiver)) = member_chain(tree, session, id, native, dimensions)? else { return Ok(None); }; let Some(aggregate) = class.aggregate(&name).cloned() else { @@ -500,6 +526,7 @@ pub(in crate::ast) fn aggregate_property( }; check_access( tree, + session, dimensions, &aggregate.owner, &aggregate.name, @@ -552,6 +579,7 @@ pub(in crate::ast) fn aggregate_load( /// member of a property of unpacked structure type. fn member_chain( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -566,7 +594,7 @@ fn member_chain( name, } if separator == "." => { names.push(instances::normalize_identifier(&name.spelling)); - if let Some(class) = native_class(tree, *expression, native, dimensions) { + if let Some(class) = native_class(tree, session, *expression, native, dimensions) { break ( class, (!is_super(*expression, native)).then_some(*expression), @@ -595,7 +623,7 @@ fn member_chain( return Ok(None); } Ok(Some(( - class(tree, dimensions, &class_name)?, + class(tree, session, dimensions, &class_name)?, names.join("."), receiver, ))) @@ -604,12 +632,13 @@ fn member_chain( /// The handle of the object that `receiver` of [`property`] refers to. pub(in crate::ast) fn receiver( tree: &AnalysisContext<'_>, + session: &mut Session, receiver: Option, native: &Declarations, dimensions: &PackedDimensions, ) -> Converted { match receiver { - Some(receiver) => bind_value(receiver, native, tree, dimensions, None), + Some(receiver) => bind_value(receiver, native, tree, session, dimensions, None), None => Ok(this()), } } @@ -629,6 +658,7 @@ pub(in crate::ast) fn load(property: &classes::Property, handle: Expr) -> Expr { /// names one of its properties: a read through `this`. pub(in crate::ast) fn unqualified_property( tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, name: &str, ) -> Converted> { @@ -641,11 +671,12 @@ pub(in crate::ast) fn unqualified_property( if classes::builtin(&class_name) { return Ok(None); } - let class = class(tree, dimensions, &class_name)?; + let class = class(tree, session, dimensions, &class_name)?; let Some(property) = class.property(name) else { if let Some(property) = class.static_property(name) { check_access( tree, + session, dimensions, &property.owner, &property.name, @@ -657,6 +688,7 @@ pub(in crate::ast) fn unqualified_property( }; check_access( tree, + session, dimensions, &property.owner, &property.name, @@ -690,6 +722,7 @@ pub(in crate::ast) enum Receiver { /// 1800-2023 8.15, 8.20). pub(in crate::ast) fn method( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -700,7 +733,8 @@ pub(in crate::ast) fn method( expression, separator, name, - } if separator == "." => match native_class(tree, *expression, native, dimensions) { + } if separator == "." => match native_class(tree, session, *expression, native, dimensions) + { Some(class) if is_super(*expression, native) => { through_super = true; (class, name, Receiver::This) @@ -712,10 +746,12 @@ pub(in crate::ast) fn method( expression, separator, name, - } if separator == "::" => match named_class(tree, *expression, native, dimensions)? { - Some(class) => (class, name, Receiver::Static), - None => return Ok(None), - }, + } if separator == "::" => { + match named_class(tree, session, *expression, native, dimensions)? { + Some(class) => (class, name, Receiver::Static), + None => return Ok(None), + } + } ExprKind::Name(name) => { let normalized = instances::normalize_identifier(&name.spelling); if dimensions.get(&normalized).is_some() { @@ -731,7 +767,7 @@ pub(in crate::ast) fn method( if classes::builtin(&class_name) { return Ok(None); } - let class = class(tree, dimensions, &class_name)?; + let class = class(tree, session, dimensions, &class_name)?; let method_name = instances::normalize_identifier(&method_name.spelling); if method_name == "new" { return match receiver { @@ -764,6 +800,7 @@ pub(in crate::ast) fn method( }; check_access( tree, + session, dimensions, &method.owner, &method.name, @@ -810,16 +847,17 @@ pub(in crate::ast) fn method( /// binding (IEEE 1800-2023 8.16, 8.26.5). pub(in crate::ast) fn check_assignment( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, target: &str, context: impl FnOnce() -> String, ) -> Converted<()> { - let Some(source) = native_class(tree, id, native, dimensions) else { + let Some(source) = native_class(tree, session, id, native, dimensions) else { return Ok(()); }; - if derives_from(tree, dimensions, &source, target)? { + if derives_from(tree, session, dimensions, &source, target)? { return Ok(()); } Err(AnalyzerError::IncompatibleClassHandle { @@ -832,6 +870,7 @@ pub(in crate::ast) fn check_assignment( /// Whether class `class_name` derives from or implements `ancestor`. fn derives_from( tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, class_name: &str, ancestor: &str, @@ -842,8 +881,9 @@ fn derives_from( if classes::builtin(class_name) || classes::builtin(ancestor) { return Ok(false); } - Ok(class(tree, dimensions, class_name)?.derives_from( + Ok(class(tree, session, dimensions, class_name)?.derives_from( tree, + session, ancestor, &dimensions.const_env, &dimensions.type_aliases, @@ -869,6 +909,7 @@ pub(in crate::ast) enum Cast { /// array element of a class handle type. pub(in crate::ast) fn cast( tree: &AnalysisContext<'_>, + session: &mut Session, arguments: &[celox_sv_syntax::Argument], native: &Declarations, dimensions: &PackedDimensions, @@ -884,20 +925,20 @@ pub(in crate::ast) fn cast( ) else { return Ok(None); }; - let Some(target) = native_class(tree, destination, native, dimensions) else { + let Some(target) = native_class(tree, session, destination, native, dimensions) else { return Ok(None); }; - if property(tree, destination, native, dimensions)?.is_some() { + if property(tree, session, destination, native, dimensions)?.is_some() { return Err(unsupported("`$cast` to a class property")); } - class(tree, dimensions, &target)?; + class(tree, session, dimensions, &target)?; // The source's class may be a base of the destination's, or an interface // class, whose object the call checks; any other class's cannot be // assigned (8.16). - if let Some(source_class) = native_class(tree, source, native, dimensions) - && !derives_from(tree, dimensions, &source_class, &target)? - && !derives_from(tree, dimensions, &target, &source_class)? - && !class(tree, dimensions, &source_class)?.is_interface + if let Some(source_class) = native_class(tree, session, source, native, dimensions) + && !derives_from(tree, session, dimensions, &source_class, &target)? + && !derives_from(tree, session, dimensions, &target, &source_class)? + && !class(tree, session, dimensions, &source_class)?.is_interface { return Ok(Some(Cast::Fails)); } @@ -920,6 +961,7 @@ pub(in crate::ast) fn this() -> Expr { /// it and returns it. pub(in crate::ast) fn constructor( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -933,23 +975,23 @@ pub(in crate::ast) fn constructor( return Err(unsupported("copying a process or event with new")); } - let source_class = match native_class(tree, *source, native, dimensions) { + let source_class = match native_class(tree, session, *source, native, dimensions) { Some(class) => Some(class), - None => static_property_class(tree, *source, native, dimensions)?, + None => static_property_class(tree, session, *source, native, dimensions)?, }; let Some(source_class) = source_class else { return Err(unsupported( "shallow copy of a value that is not a class handle", )); }; - if !derives_from(tree, dimensions, &source_class, class_name)? { + if !derives_from(tree, session, dimensions, &source_class, class_name)? { return Err(AnalyzerError::IncompatibleClassHandle { context: "shallow copy".to_owned(), actual: source_class, target: class_name.to_owned(), }); } - let handle = bind_value(*source, native, tree, dimensions, None)?; + let handle = bind_value(*source, native, tree, session, dimensions, None)?; return Ok(Some(classes::object_call(ObjectOp::Copy, vec![handle]))); } let (callee, arguments): (ExprId, &[celox_sv_syntax::Argument]) = @@ -967,9 +1009,9 @@ pub(in crate::ast) fn constructor( separator, name, } if separator == "::" && name.spelling == "new" => { - match named_class(tree, *expression, native, dimensions)? { + match named_class(tree, session, *expression, native, dimensions)? { Some(class) => { - if !derives_from(tree, dimensions, &class, class_name)? { + if !derives_from(tree, session, dimensions, &class, class_name)? { return Err(AnalyzerError::IncompatibleClassHandle { context: format!("`{class}::new`"), actual: class, @@ -984,19 +1026,28 @@ pub(in crate::ast) fn constructor( _ => return Ok(None), }; if class_name == super::super::semaphores::CLASS { - return super::super::semaphores::new(tree, arguments, native, dimensions).map(Some); + return super::super::semaphores::new(tree, session, arguments, native, dimensions) + .map(Some); } if super::super::mailboxes::is_class(&class_name) { - return super::super::mailboxes::new(tree, arguments, native, dimensions, &class_name) - .map(Some); + return super::super::mailboxes::new( + tree, + session, + arguments, + native, + dimensions, + &class_name, + ) + .map(Some); } if classes::builtin(&class_name) { return Err(unsupported("constructing a process or event with new")); } - let class = class(tree, dimensions, &class_name)?; + let class = class(tree, session, dimensions, &class_name)?; if let Some(method) = class.method("new") { check_access( tree, + session, dimensions, &method.owner, &method.name, @@ -1024,7 +1075,7 @@ pub(in crate::ast) fn constructor( }); args.push( actual - .map(|value| bind_value(value, native, tree, dimensions, target)) + .map(|value| bind_value(value, native, tree, session, dimensions, target)) .transpose()?, ); } @@ -1043,13 +1094,14 @@ pub(in crate::ast) fn constructor( /// the caller's scope (18.11). Bit zero distinguishes an explicit empty set. pub(super) fn random_selection( tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, name: &str, arguments: &[celox_sv_syntax::Argument], native: &Declarations, ) -> Converted { let owner = name.strip_suffix("::randomize").expect("randomize method"); - let class = class(tree, dimensions, owner)?; + let class = class(tree, session, dimensions, owner)?; let mut bits = vec!['0'; class.properties.len() + 1]; if !arguments.is_empty() { bits[0] = '1'; @@ -1073,7 +1125,7 @@ pub(super) fn random_selection( )) })?; let property = &class.properties[index]; - check_random_access(tree, dimensions, property)?; + check_random_access(tree, session, dimensions, property)?; if property.constant { return Err(unsupported("randomize argument is a const property")); } @@ -1109,6 +1161,7 @@ pub(super) fn random_selection( /// Constraint block modes are independent of member rand_mode and inline constraints (18.9). pub(in crate::ast) fn constraint_mode_call( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -1127,11 +1180,11 @@ pub(in crate::ast) fn constraint_mode_call( separator, name, } if separator == "." && name.spelling == "constraint_mode" => { - if let Some(owner) = native_class(tree, *expression, native, dimensions) { + if let Some(owner) = native_class(tree, session, *expression, native, dimensions) { ( owner, None, - receiver(tree, Some(*expression), native, dimensions)?, + receiver(tree, session, Some(*expression), native, dimensions)?, ) } else { match &native.expression(ungroup(*expression, native)).kind { @@ -1140,13 +1193,14 @@ pub(in crate::ast) fn constraint_mode_call( separator, name, } if separator == "." => { - let Some(owner) = native_class(tree, *object, native, dimensions) else { + let Some(owner) = native_class(tree, session, *object, native, dimensions) + else { return Ok(None); }; ( owner, Some(name.spelling.clone()), - receiver(tree, Some(*object), native, dimensions)?, + receiver(tree, session, Some(*object), native, dimensions)?, ) } ExprKind::Name(name) @@ -1178,7 +1232,7 @@ pub(in crate::ast) fn constraint_mode_call( } _ => return Ok(None), }; - let class = class(tree, dimensions, &owner)?; + let class = class(tree, session, dimensions, &owner)?; if class.constraints.iter().any(|(_, block)| { block .as_ref() @@ -1216,7 +1270,14 @@ pub(in crate::ast) fn constraint_mode_call( "constraint_mode setter requires one on_off argument", )); } - let enabled = bind_value(args[0].value.unwrap(), native, tree, dimensions, None)?; + let enabled = bind_value( + args[0].value.unwrap(), + native, + tree, + session, + dimensions, + None, + )?; Ok(Some(classes::object_call( ObjectOp::ConstraintModeSet(index), vec![handle, enabled], @@ -1227,6 +1288,7 @@ pub(in crate::ast) fn constraint_mode_call( /// A getter requires one random property; only the setter accepts an object. pub(in crate::ast) fn rand_mode_call( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -1245,24 +1307,25 @@ pub(in crate::ast) fn rand_mode_call( separator, name, } if separator == "." && name.spelling == "rand_mode" => { - let property_target = property(tree, *expression, native, dimensions)?; + let property_target = property(tree, session, *expression, native, dimensions)?; if let Some((property, object)) = property_target.filter(|(property, _)| { property.rand || property.randc || property.r#type.class().is_none() }) { - check_random_access(tree, dimensions, &property)?; + check_random_access(tree, session, dimensions, &property)?; if !property.rand && !property.randc { return Err(unsupported("rand_mode requires a rand or randc property")); } ( Some(property), None, - receiver(tree, object, native, dimensions)?, + receiver(tree, session, object, native, dimensions)?, ) - } else if let Some(owner) = native_class(tree, *expression, native, dimensions) { + } else if let Some(owner) = native_class(tree, session, *expression, native, dimensions) + { ( None, Some(owner), - bind_value(*expression, native, tree, dimensions, None)?, + bind_value(*expression, native, tree, session, dimensions, None)?, ) } else { return Err(unsupported( @@ -1299,7 +1362,14 @@ pub(in crate::ast) fn rand_mode_call( if args.len() != 1 || args[0].name.is_some() || args[0].value.is_none() { return Err(unsupported("rand_mode setter requires one on_off argument")); } - let enabled = bind_value(args[0].value.unwrap(), native, tree, dimensions, None)?; + let enabled = bind_value( + args[0].value.unwrap(), + native, + tree, + session, + dimensions, + None, + )?; Ok(Some(match property { Some(property) => classes::object_call( ObjectOp::ModeSet(property.field.offset), @@ -1315,11 +1385,13 @@ pub(in crate::ast) fn rand_mode_call( fn check_random_access( tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, property: &classes::Property, ) -> Converted<()> { check_access( tree, + session, dimensions, &property.owner, &property.name, @@ -1330,6 +1402,7 @@ fn check_random_access( pub(super) fn randomize_with( tree: &AnalysisContext<'_>, + session: &mut Session, expression: ExprId, constraints: Option<&[ExprId]>, native: &Declarations, @@ -1342,11 +1415,11 @@ pub(super) fn randomize_with( } => (*expression, arguments.as_slice()), _ => (expression, &[][..]), }; - let (method_name, _, receiver) = method(tree, callee, native, dimensions)? + let (method_name, _, receiver) = method(tree, session, callee, native, dimensions)? .filter(|(name, _, _)| name.ends_with("::randomize")) .ok_or_else(|| unsupported("inline constraints require class randomize"))?; let owner = method_name.strip_suffix("::randomize").unwrap(); - let class = class(tree, dimensions, owner)?; + let class = class(tree, session, dimensions, owner)?; // Inline constraints need the solver even on otherwise unconstrained classes. class.constraint_program()?; let constraint_ids = constraints.ok_or_else(|| unsupported("inline constraint form"))?; @@ -1434,6 +1507,7 @@ pub(super) fn randomize_with( classes::constraints::bind_inputs( id, tree, + session, &class.properties, &dimensions.const_env, &inputs, @@ -1441,14 +1515,14 @@ pub(super) fn randomize_with( .map_err(|reason| unsupported(format!("inline constraints: {reason}"))) }) .collect::>>()?; - let selection = random_selection(tree, dimensions, &method_name, arguments, native)?; + let selection = random_selection(tree, session, dimensions, &method_name, arguments, native)?; let handle = match receiver { - Receiver::Handle(id) => bind_value(id, native, tree, dimensions, None)?, + Receiver::Handle(id) => bind_value(id, native, tree, session, dimensions, None)?, Receiver::This => this(), Receiver::Static => return Err(unsupported("inline randomize object receiver")), }; - let key = tree.state.next_call_site.get(); - tree.state.next_call_site.set(key + 1); + let key = session.next_call_site; + session.next_call_site = key + 1; let inline = classes::constraints::Inline { key, class, @@ -1468,7 +1542,7 @@ pub(super) fn randomize_with( arg_order: Vec::new(), } }; - tree.state.inline_randomizations.borrow_mut().push(inline); + session.inline_randomizations.push(inline); Ok(Expr::Call { callee: Callee::Subroutine(name), args: [vec![Some(handle), Some(selection)], input_values].concat(), @@ -1480,6 +1554,7 @@ pub(super) fn randomize_with( /// `id` names (`h.m`, `C::m`, or unqualified inside a method), when known. pub(in crate::ast) fn method_result( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -1490,8 +1565,14 @@ pub(in crate::ast) fn method_result( separator, name, } => match separator.as_str() { - "." => (native_class(tree, *expression, native, dimensions), name), - "::" => (named_class(tree, *expression, native, dimensions)?, name), + "." => ( + native_class(tree, session, *expression, native, dimensions), + name, + ), + "::" => ( + named_class(tree, session, *expression, native, dimensions)?, + name, + ), _ => return Ok(None), }, ExprKind::Name(name) @@ -1506,7 +1587,7 @@ pub(in crate::ast) fn method_result( let Some(class_name) = class_name.filter(|name| !classes::builtin(name)) else { return Ok(None); }; - Ok(class(tree, dimensions, &class_name)? + Ok(class(tree, session, dimensions, &class_name)? .method(&instances::normalize_identifier(&name.spelling)) .and_then(|method| method.result.clone().flatten())) } 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 51f6273d0ed..170879d450a 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/references.rs @@ -12,6 +12,7 @@ pub(super) fn check_actual( actual: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted<()> { if !dimensions @@ -48,14 +49,16 @@ pub(super) fn check_actual( "a constant is not a variable (IEEE 1800-2023 13.5.2)", )); } - None => property_shape(tree, actual, native, dimensions)?, + None => property_shape(tree, session, actual, native, dimensions)?, } } - ExprKind::Member { .. } => match property_shape(tree, actual, native, dimensions)? { + ExprKind::Member { .. } => match property_shape(tree, session, actual, native, dimensions)? + { Some(shape) => Some(shape), // A member of a variable of unpacked structure type is a // variable of its own (see `unpacked_structs`). - None if let (parts, None) = direct::path(actual, native, tree, dimensions)? + None if let (parts, None) = + direct::path(actual, native, tree, session, dimensions)? && let [variable] = parts.as_slice() && let Some(shape) = dimensions.get(variable) && !dimensions.const_env.contains_key(variable) => @@ -64,7 +67,7 @@ pub(super) fn check_actual( } // A static property is a variable of its class's scope. None if let Some(variable) = - objects::static_property(tree, actual, native, dimensions)? => + objects::static_property(tree, session, actual, native, dimensions)? => { match dimensions.get(&variable) { Some(shape) => Some(shape.clone()), @@ -169,16 +172,18 @@ pub(super) fn check_actual( /// The shape of class property `actual`, also of unpacked structure type. fn property_shape( tree: &AnalysisContext<'_>, + session: &mut Session, actual: ExprId, native: &Declarations, dimensions: &PackedDimensions, ) -> Converted> { - if let Some((property, _)) = objects::property(tree, actual, native, dimensions)? { + if let Some((property, _)) = objects::property(tree, session, actual, native, dimensions)? { return Ok(Some(procedural::dimensions_from_type(&property.r#type))); } // `objects::aggregate_load` rejects a receiver that calls a subroutine, // which each member would evaluate again. - let Some((aggregate, _, _)) = objects::aggregate_property(tree, actual, native, dimensions)? + let Some((aggregate, _, _)) = + objects::aggregate_property(tree, session, actual, native, dimensions)? else { return Ok(None); }; 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 fff3c622339..7947d614859 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/selected.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/selected.rs @@ -5,6 +5,7 @@ mod tests { use super::*; #[test] fn native_index_operators_and_selected_names_are_authoritative() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_source( "module M;assign y=a[i+1];endmodule", Path::new("native-index.sv"), @@ -19,7 +20,7 @@ mod tests { } let root = native.assign_statements[0].assignments[0].right; let Expr::Select { msb, lsb, .. } = - value(root, &native, &tree, &PackedDimensions::default()).unwrap() + value(root, &native, &tree, session, &PackedDimensions::default()).unwrap() else { panic!() }; @@ -40,7 +41,7 @@ mod tests { } } let Expr::Select { expr, .. } = - value(root, &native, &tree, &PackedDimensions::default()).unwrap() + value(root, &native, &tree, session, &PackedDimensions::default()).unwrap() else { panic!() }; @@ -48,6 +49,7 @@ mod tests { } #[test] fn nested_native_indices_keep_typed_selection_values() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_source( "module M;assign y=a[b[i+1]];endmodule", Path::new("nested-index.sv"), @@ -57,7 +59,7 @@ mod tests { let native = tree.declarations(); let root = native.assign_statements[0].assignments[0].right; let Expr::Select { lsb, .. } = - value(root, native, &tree, &PackedDimensions::default()).unwrap() + value(root, native, &tree, session, &PackedDimensions::default()).unwrap() else { panic!() }; @@ -94,6 +96,7 @@ mod tests { } #[test] fn deep_native_index_groups_use_the_explicit_worklists() { + let session = &mut Session::default(); let path = Path::new("native-index-groups.sv"); let tree = crate::source_tree::parse_source("module M;assign y=a[7];endmodule", path).unwrap(); @@ -106,7 +109,7 @@ mod tests { let native = celox_sv_syntax::Declarations::parse(&source, path).unwrap(); let root = native.assign_statements[0].assignments[0].right; let Expr::Select { lsb, .. } = - value(root, &native, &tree, &PackedDimensions::default()).unwrap() + value(root, &native, &tree, session, &PackedDimensions::default()).unwrap() else { panic!() }; @@ -119,6 +122,7 @@ mod range_tests { use super::*; #[test] fn deep_native_constant_and_indexed_range_groups_use_worklists() { + let session = &mut Session::default(); for (shallow, deep, high, low) in [ ( "a[7:0]".to_string(), @@ -159,7 +163,7 @@ mod range_tests { .unwrap(); let root = native.assign_statements[0].assignments[0].right; let Expr::Select { msb, lsb, .. } = - value(root, &native, &tree, &PackedDimensions::default()).unwrap() + value(root, &native, &tree, session, &PackedDimensions::default()).unwrap() else { panic!() }; 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 317d99915df..325febbde6e 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/streams.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/streams.rs @@ -38,10 +38,11 @@ pub(in crate::ast) fn is_stream(id: ExprId, native: &Declarations) -> bool { fn constant( id: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, what: &str, ) -> Converted { - constant_binding::bind(id, tree, dims)? + constant_binding::bind(id, tree, session, dims)? .and_then(|value| eval_ast_const_expr(&tree.functions, &value, &dims.const_env)) .ok_or_else(|| { unsupported(format!( @@ -56,10 +57,11 @@ fn slice_size( slice: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted { let ty = match native.expression(slice).kind { - ExprKind::Type(ty) => type_binding::bind(ty, tree, dims)?, + ExprKind::Type(ty) => type_binding::bind(ty, tree, session, dims)?, _ => type_binding::argument_alias(slice, native) .and_then(|(name, dimensions)| dimensions.is_empty().then_some(name)) .and_then(|name| dims.type_aliases.get(&name).cloned()), @@ -70,7 +72,7 @@ fn slice_size( .filter(|width| *width > 0) .ok_or_else(|| unsupported("streaming concatenation slice type of unknown width")); } - let size = constant(slice, tree, dims, "slice size")?; + let size = constant(slice, tree, session, dims, "slice size")?; usize::try_from(size) .ok() .filter(|size| *size > 0) @@ -228,9 +230,10 @@ fn dynamic_range( range: &Dimension, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted<(Expr, Expr, StreamRange)> { - let value = |id| bind_value(id, native, tree, dims, None); + let mut value = |id| bind_value(id, native, tree, session, dims, None); Ok(match range.kind { DimensionKind::Index(id) => (value(id)?, Expr::Literal("32'sd1".into()), StreamRange::Up), DimensionKind::Range { left, right } => (value(left)?, value(right)?, StreamRange::Bounds), @@ -259,9 +262,10 @@ fn with_positions( range: &Dimension, (left, right): (i128, i128), tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted<(i128, i128)> { - let index = |id| constant(id, tree, dims, "with range"); + let mut index = |id| constant(id, tree, session, dims, "with range"); let (low, high) = match range.kind { DimensionKind::Index(id) => { let index = index(id)?; @@ -311,6 +315,7 @@ fn operand( id: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { let (id, range) = match &native.expression(ungroup(id, native)).kind { @@ -324,15 +329,15 @@ fn operand( if range.is_some() { return Err(invalid("with applies to a one-dimensional unpacked array")); } - return Ok(vec![match packed(id, native, tree, dims)? { + return Ok(vec![match packed(id, native, tree, session, dims)? { Packed::Fixed(value, width) => Item::Fixed(value, StreamArg::packed(width)), Packed::Dynamic(stream) => Item::Dynamic(StreamItem::Stream, vec![stream]), }]); } - let shape = dimensions::operand_shape(id, tree, dims)?; + let shape = dimensions::operand_shape(id, tree, session, dims)?; // A container variable, or any expression of container type, such as a // bit-stream cast to a queue type. - let container = match containers::native_type(id, native, tree, dims)? { + let container = match containers::native_type(id, native, tree, session, dims)? { Some(container) => Some(container), None => shape.as_ref().and_then(|shape| shape.container.clone()), }; @@ -343,7 +348,7 @@ fn operand( "streaming concatenation of class handles or structures in a container", )); } - let value = bind_value(id, native, tree, dims, None)?; + let value = bind_value(id, native, tree, session, dims, None)?; let Some(range) = range else { return Ok(vec![Item::Dynamic( StreamItem::Container { @@ -358,7 +363,7 @@ fn operand( "streaming concatenation with range on an associative array", )); } - let (first, second, form) = dynamic_range(range, native, tree, dims)?; + let (first, second, form) = dynamic_range(range, native, tree, session, dims)?; return Ok(vec![Item::Dynamic( StreamItem::Container { layout, @@ -372,7 +377,7 @@ fn operand( { check_fixed(shape)?; } - let value = bind_value(id, native, tree, dims, None)?; + let value = bind_value(id, native, tree, session, dims, None)?; if real_value(&value, dims) { return Err(invalid("a real value is not of bit-stream type")); } @@ -438,7 +443,7 @@ fn operand( .ok_or_else(|| unsupported("streaming concatenation with an array of unknown bounds")) }; let bounds = (bound(&dimension.left)?, bound(&dimension.right)?); - let (first, last) = with_positions(range, bounds, tree, dims)?; + let (first, last) = with_positions(range, bounds, tree, session, dims)?; // A pack streams the selected elements, and the value of a nonexistent // entry (Table 7-1) for each position past the array (11.4.14.4). let missing = Expr::Literal(if shape.is_2state { @@ -474,6 +479,7 @@ fn parts( id: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted<(Option, Vec)> { let ExprKind::Streaming { @@ -485,7 +491,7 @@ fn parts( unreachable!("checked by the caller"); }; let size = slice - .map(|slice| slice_size(slice, native, tree, dims)) + .map(|slice| slice_size(slice, native, tree, session, dims)) .transpose()?; // `>>` streams the blocks left to right, ignoring the slice size. Ok(( @@ -544,12 +550,13 @@ fn packed( id: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted { - let (slice, expressions) = parts(id, native, tree, dims)?; + let (slice, expressions) = parts(id, native, tree, session, dims)?; let mut items = Vec::new(); for expression in expressions { - items.extend(operand(expression, native, tree, dims)?); + items.extend(operand(expression, native, tree, session, dims)?); } if items.iter().any(|item| matches!(item, Item::Dynamic(..))) { return Ok(Packed::Dynamic(heap_stream(items, slice, false, None))); @@ -583,9 +590,10 @@ pub(in crate::ast) fn pack( receiver: Option, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted { - Ok(match (packed(id, native, tree, dims)?, receiver) { + Ok(match (packed(id, native, tree, session, dims)?, receiver) { (Packed::Fixed(value, _), None | Some(Receiver::Cast(_))) => value, (Packed::Fixed(_, width), Some(Receiver::Fixed(target))) if target.width < width => { return Err(invalid(format!( @@ -755,12 +763,13 @@ pub(in crate::ast) fn unpack( right: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { if !is_stream(left, native) { return Ok(None); } - let (slice, expressions) = parts(left, native, tree, dims)?; + let (slice, expressions) = parts(left, native, tree, session, dims)?; let mut lvalues = Vec::new(); let mut takes = Vec::new(); let mut greedy = false; @@ -778,7 +787,7 @@ pub(in crate::ast) fn unpack( return Err(invalid("with applies to a one-dimensional unpacked array")); } // A stream that keeps its order unpacks as its operands do. - let (slice, inner) = parts(id, native, tree, dims)?; + let (slice, inner) = parts(id, native, tree, session, dims)?; if slice.is_some() { return Err(unsupported( "re-ordering streaming concatenation in an unpack target", @@ -787,7 +796,7 @@ pub(in crate::ast) fn unpack( pending.extend(inner.into_iter().rev()); continue; } - let shape = dimensions::operand_shape(id, tree, dims)? + let shape = dimensions::operand_shape(id, tree, session, dims)? .ok_or_else(|| unsupported("streaming concatenation unpack target"))?; let dynamic = shape.container.is_some() || shape.string; if let Some(range) = range { @@ -799,13 +808,17 @@ pub(in crate::ast) fn unpack( }); }; let layout = stream_container(container)?; - let (first, second, form) = dynamic_range(range, native, tree, dims)?; + let (first, second, form) = dynamic_range(range, native, tree, session, dims)?; takes.push(Take::Range { layout, form, - operands: Box::new([bind_value(id, native, tree, dims, None)?, first, second]), + operands: Box::new([ + bind_value(id, native, tree, session, dims, None)?, + first, + second, + ]), }); - lvalues.push(variable_lvalue(id, native, tree, dims)?); + lvalues.push(variable_lvalue(id, native, tree, session, dims)?); continue; } if dynamic { @@ -820,7 +833,7 @@ pub(in crate::ast) fn unpack( }, None => Take::String { reserve }, }); - lvalues.push(variable_lvalue(id, native, tree, dims)?); + lvalues.push(variable_lvalue(id, native, tree, session, dims)?); continue; } check_fixed(&shape)?; @@ -856,15 +869,15 @@ pub(in crate::ast) fn unpack( unreachable!("a fixed-size variable receives fixed-size data"); }; takes.push(Take::Fixed(target)); - lvalues.push(variable_lvalue(id, native, tree, dims)?); + lvalues.push(variable_lvalue(id, native, tree, session, dims)?); } let source = if is_stream(right, native) { - vec![match packed(right, native, tree, dims)? { + vec![match packed(right, native, tree, session, dims)? { Packed::Fixed(value, width) => Item::Fixed(value, StreamArg::packed(width)), Packed::Dynamic(stream) => Item::Dynamic(StreamItem::Stream, vec![stream]), }] } else { - operand(right, native, tree, dims)? + operand(right, native, tree, session, dims)? }; let fixed = takes.iter().all(|take| matches!(take, Take::Fixed(_))); if !fixed || source.iter().any(|item| matches!(item, Item::Dynamic(..))) { diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs index 79ab0753f61..06d558cc8a6 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs @@ -146,28 +146,29 @@ pub(in crate::ast) fn operands( /// bound: a string variable, or a method of a string value that returns one. pub(in crate::ast) fn native_string( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, ) -> bool { match &native.expression(ungroup(id, native)).kind { - ExprKind::Call { expression, .. } if matches!(&native.expression(*expression).kind, ExprKind::Member { expression: base, name, separator } if separator == "." && name.spelling == "get_randstate" && objects::native_class(tree, *base, native, dimensions).as_deref() == Some(super::super::processes::CLASS)) => { + ExprKind::Call { expression, .. } if matches!(&native.expression(*expression).kind, ExprKind::Member { expression: base, name, separator } if separator == "." && name.spelling == "get_randstate" && objects::native_class(tree, session, *base, native, dimensions).as_deref() == Some(super::super::processes::CLASS)) => { true } ExprKind::Select { expression, .. } - if containers::native_type(*expression, native, tree, dimensions) + if containers::native_type(*expression, native, tree, session, dimensions) .ok() .flatten() .is_some() => { - containers::native_type(*expression, native, tree, dimensions) + containers::native_type(*expression, native, tree, session, dimensions) .ok() .flatten() .is_some_and(|ty| { ty.layout.handle == Some(crate::system_functions::HandleProperty::String) }) } - ExprKind::Call { expression, .. } if matches!(&native.expression(*expression).kind, ExprKind::Member { expression: base, name, .. } if matches!(name.spelling.as_str(), "pop_front" | "pop_back") && containers::native_type(*base, native, tree, dimensions).ok().flatten().is_some_and(|ty| ty.layout.handle == Some(crate::system_functions::HandleProperty::String))) => { + ExprKind::Call { expression, .. } if matches!(&native.expression(*expression).kind, ExprKind::Member { expression: base, name, .. } if matches!(name.spelling.as_str(), "pop_front" | "pop_back") && containers::native_type(*base, native, tree, session, dimensions).ok().flatten().is_some_and(|ty| ty.layout.handle == Some(crate::system_functions::HandleProperty::String))) => { true } ExprKind::Name(name) @@ -182,21 +183,27 @@ pub(in crate::ast) fn native_string( ExprKind::Call { expression, .. } => { matches!(&native.expression(ungroup(*expression, native)).kind, ExprKind::Name(name) if matches!(name.spelling.as_str(), "$sformatf" | "$typename")) - || method(tree, *expression, native, dimensions) + || method(tree, session, *expression, native, dimensions) .is_some_and(|(op, _)| op.returns_string()) - || enum_name(tree, *expression, native, dimensions) - || returns_string(tree, *expression, native, dimensions) + || enum_name(tree, session, *expression, native, dimensions) + || returns_string(tree, session, *expression, native, dimensions) } // `e.name` without parentheses (6.19.5.6, 6.19.5.7). - ExprKind::Member { .. } if enum_name(tree, id, native, dimensions) => true, + ExprKind::Member { .. } if enum_name(tree, session, id, native, dimensions) => true, // A string member of a container element of unpacked structure type. ExprKind::Member { .. } - if containers::element_member(ungroup(id, native), native, tree, dimensions) - .ok() - .flatten() - .is_some() => + if containers::element_member( + ungroup(id, native), + native, + tree, + session, + dimensions, + ) + .ok() + .flatten() + .is_some() => { - containers::element_member(ungroup(id, native), native, tree, dimensions) + containers::element_member(ungroup(id, native), native, tree, session, dimensions) .ok() .flatten() .is_some_and(|(ty, _)| ty.kind() == TypeKind::String) @@ -211,7 +218,7 @@ pub(in crate::ast) fn native_string( .is_some_and(|ty| ty.string) } // A string property of a class object. - _ => objects::property(tree, id, native, dimensions) + _ => objects::property(tree, session, id, native, dimensions) .ok() .flatten() .is_some_and(|(property, _)| { @@ -224,11 +231,12 @@ pub(in crate::ast) fn native_string( /// returns a `string`. fn returns_string( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, ) -> bool { - let name = match objects::method(tree, id, native, dimensions) { + let name = match objects::method(tree, session, id, native, dimensions) { Ok(Some((name, ..))) => name, Ok(None) => match super::direct::callable_name(tree, id, native) { Some(name) => name, @@ -250,11 +258,12 @@ fn returns_string( /// enumerated type (6.19.5.6). fn enum_name( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, ) -> bool { - enums::method(tree, id, native, dimensions) + enums::method(tree, session, id, native, dimensions) .ok() .flatten() .is_some_and(|(method, _, _)| method.returns_string()) @@ -264,6 +273,7 @@ fn enum_name( /// expression it is called on. pub(in crate::ast) fn method( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -276,7 +286,7 @@ pub(in crate::ast) fn method( else { return None; }; - if separator != "." || !native_string(tree, *expression, native, dimensions) { + if separator != "." || !native_string(tree, session, *expression, native, dimensions) { return None; } let (op, _) = StringOp::method(&name.spelling)?; diff --git a/crates/celox-sv-analyzer/src/ast/expressions.rs b/crates/celox-sv-analyzer/src/ast/expressions.rs index 86932654c18..c1eb93e999d 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -2,8 +2,11 @@ use super::*; -pub(super) fn guard_zero_divisions(tree: &AnalysisContext<'_>, expr: Expr) -> Expr { - let state = &*tree.state; +pub(super) fn guard_zero_divisions( + tree: &AnalysisContext<'_>, + session: &mut Session, + expr: Expr, +) -> Expr { 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 @@ -21,7 +24,7 @@ pub(super) fn guard_zero_divisions(tree: &AnalysisContext<'_>, expr: Expr) -> Ex lsb, signed, } => Expr::Select { - expr: Box::new(guard_zero_divisions(tree, *expr)), + expr: Box::new(guard_zero_divisions(tree, session, *expr)), msb, lsb, signed, @@ -29,14 +32,14 @@ pub(super) fn guard_zero_divisions(tree: &AnalysisContext<'_>, expr: Expr) -> Ex Expr::Concat(parts) => Expr::Concat( parts .into_iter() - .map(|expr| guard_zero_divisions(tree, expr)) + .map(|expr| guard_zero_divisions(tree, session, expr)) .collect(), ), Expr::RepeatConcat { count, parts } => Expr::RepeatConcat { count, parts: parts .into_iter() - .map(|expr| guard_zero_divisions(tree, expr)) + .map(|expr| guard_zero_divisions(tree, session, expr)) .collect(), }, Expr::Resize { @@ -44,23 +47,23 @@ pub(super) fn guard_zero_divisions(tree: &AnalysisContext<'_>, expr: Expr) -> Ex width, signed, } => Expr::Resize { - expr: Box::new(guard_zero_divisions(tree, *expr)), + expr: Box::new(guard_zero_divisions(tree, session, *expr)), width, signed, }, Expr::Unary { op, expr } => Expr::Unary { op, - expr: Box::new(guard_zero_divisions(tree, *expr)), + expr: Box::new(guard_zero_divisions(tree, session, *expr)), }, Expr::Binary { left, op, right } => { - let left = Box::new(guard_zero_divisions(tree, *left)); - let right = Box::new(guard_zero_divisions(tree, *right)); + let left = Box::new(guard_zero_divisions(tree, session, *left)); + let right = Box::new(guard_zero_divisions(tree, session, *right)); let operation = Expr::Binary { left, op, right: right.clone(), }; - let divisor_is_nonzero = expr_to_const(state, (*right).clone()) + let divisor_is_nonzero = expr_to_const(session, (*right).clone()) .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 { @@ -82,15 +85,15 @@ pub(super) fn guard_zero_divisions(tree: &AnalysisContext<'_>, expr: Expr) -> Ex then_expr, else_expr, } => Expr::Mux { - 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)), + condition: Box::new(guard_zero_divisions(tree, session, *condition)), + then_expr: Box::new(guard_zero_divisions(tree, session, *then_expr)), + else_expr: Box::new(guard_zero_divisions(tree, session, *else_expr)), }, Expr::Inside { expr, items } => Expr::Inside { - expr: Box::new(guard_zero_divisions(tree, *expr)), + expr: Box::new(guard_zero_divisions(tree, session, *expr)), items: items .into_iter() - .map(|item| item.map(&mut |operand| guard_zero_divisions(tree, operand))) + .map(|item| item.map(&mut |operand| guard_zero_divisions(tree, session, operand))) .collect(), }, Expr::Call { @@ -102,7 +105,7 @@ pub(super) fn guard_zero_divisions(tree: &AnalysisContext<'_>, expr: Expr) -> Ex callee, args: args .into_iter() - .map(|arg| arg.map(|expr| guard_zero_divisions(tree, expr))) + .map(|arg| arg.map(|expr| guard_zero_divisions(tree, session, expr))) .collect(), }, } @@ -125,11 +128,11 @@ pub(super) fn identifier_expression( /// Numeric system-function semantics for already-bound native arguments. pub(super) fn numeric_system_function( tree: &AnalysisContext<'_>, + session: &mut Session, 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 { @@ -163,7 +166,7 @@ pub(super) fn numeric_system_function( // reads as a literal. if function == SystemFunction::Past && let Some(ticks) = arguments.get_mut(1) - && let Some(constant) = expr_to_const(state, ticks.clone()) + && let Some(constant) = expr_to_const(session, ticks.clone()) && let Some(value) = eval_ast_const_expr(functions, &constant, &dimensions.const_env) { @@ -222,7 +225,7 @@ pub(super) fn numeric_system_function( | SystemFunction::Countbits => { if function == SystemFunction::Clog2 && let [argument] = arguments.as_slice() - && let Some(argument) = expr_to_const(state, argument.clone()) + && let Some(argument) = expr_to_const(session, argument.clone()) && let Some(value) = eval_ast_const_expr( functions, &ConstExpr::Function { diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index ae16e160777..a174aac40e6 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -4,13 +4,19 @@ use super::*; pub(super) fn ff_processes_from_scope( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, parameter_literals: &HashMap, packed_dimensions: &PackedDimensions, state: &mut procedural::BodyState<'_>, ) -> Result, AnalyzerError> { let mut processes = Vec::new(); - let active = generate::items(syntax_tree, const_env, &packed_dimensions.type_aliases)?; + let active = generate::items( + syntax_tree, + session, + const_env, + &packed_dimensions.type_aliases, + )?; let mut views = generate::ScopeViews::with_literals(packed_dimensions, parameter_literals); for (creation_order, item) in active.iter().enumerate() { let syntax_tree = &item.scoped(syntax_tree); @@ -23,6 +29,7 @@ pub(super) fn ff_processes_from_scope( if let Some(process) = ff_process_from_procedure( procedure, syntax_tree, + session, &item.env, literals, dimensions, @@ -55,6 +62,7 @@ pub(super) fn ff_processes_from_scope( fn ff_process_from_procedure( procedure: &celox_sv_syntax::Procedure, syntax_tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, parameter_literals: &HashMap, packed_dimensions: &PackedDimensions, @@ -70,7 +78,7 @@ fn ff_process_from_procedure( return Ok(None); } let Some((events, body)) = - ff_event_control_and_body(procedure.body, syntax_tree, packed_dimensions)? + ff_event_control_and_body(procedure.body, syntax_tree, session, packed_dimensions)? else { if procedure.kind == celox_sv_syntax::ProcedureKind::AlwaysFf { return Err(unsupported("always_ff event expression")); @@ -81,13 +89,20 @@ fn ff_process_from_procedure( local_dimensions.const_env = const_env.clone().into(); let mut builder = procedural::BodyBuilder::new( syntax_tree, + session, &local_dimensions, state, system_functions::Body::Always, ); let mut body = builder.native_body(&[body], &procedure.authored_statements)?; for stmt in &mut body { - procedural::substitute_stmt_constants(syntax_tree, stmt, const_env, parameter_literals); + procedural::substitute_stmt_constants( + syntax_tree, + builder.session, + stmt, + const_env, + parameter_literals, + ); } Ok((!events.is_empty()).then(|| { let mut process = FfProcess::new(events, body); @@ -104,11 +119,12 @@ fn ff_process_from_procedure( pub(super) fn always_falls_back_to_process( procedure: &celox_sv_syntax::Procedure, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Result { Ok(procedure.kind == celox_sv_syntax::ProcedureKind::Always && always_kind(procedure, tree.declarations())? == AlwaysKind::Ff - && ff_event_control_and_body(procedure.body, tree, dimensions)?.is_none()) + && ff_event_control_and_body(procedure.body, tree, session, dimensions)?.is_none()) } /// The events of a flip-flop shaped event control and the body it controls, @@ -117,6 +133,7 @@ pub(super) fn always_falls_back_to_process( fn ff_event_control_and_body( root: celox_sv_syntax::StatementId, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Result, celox_sv_syntax::StatementId)>, AnalyzerError> { use celox_sv_syntax::{EventControl, StatementKind, TimingControlKind, TimingEdge}; @@ -138,11 +155,18 @@ fn ff_event_control_and_body( TimingEdge::Neg => FfEdge::Neg, _ => return Ok(None), }; - if virtual_interfaces::native_member(tree, item.expression, native, dimensions).is_some() { + if virtual_interfaces::native_member(tree, session, item.expression, native, dimensions) + .is_some() + { return Ok(None); } - let expression = - expression_binding::value(item.expression, native, tree, &PackedDimensions::default())?; + let expression = expression_binding::value( + item.expression, + native, + tree, + session, + &PackedDimensions::default(), + )?; let Some(signal) = expr_ident_name(&expression) else { return Ok(None); }; diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index b1f0839afde..270715cd883 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -6,14 +6,16 @@ mod symbolic; pub(super) fn functions_from_scope( tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, dimensions: &PackedDimensions, ) -> Converted> { - let aliases = type_aliases_from_scope_with_env(tree, env)?; - let items = generate::items(tree, env, &aliases)?; + let aliases = type_aliases_from_scope_with_env(tree, session, env)?; + let items = generate::items(tree, session, env, &aliases)?; native_functions( &items, tree, + session, dimensions, lifetimes::automatic_by_default(tree), ) @@ -22,6 +24,7 @@ pub(super) fn functions_from_scope( pub(super) fn native_functions( items: &[generate::Item], tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, automatic: bool, ) -> Converted> { @@ -64,8 +67,12 @@ pub(super) fn native_functions( let mut signature_context = item.dimensions(dimensions); signature_context.const_env = item.env.clone(); signature_context.type_aliases = aliases.as_ref().clone().into(); - let mut function = - native_signature(tree.declarations().subroutine(id), tree, &signature_context)?; + let mut function = native_signature( + tree.declarations().subroutine(id), + tree, + session, + &signature_context, + )?; let mut locals = Vec::new(); let mut counter = 0; let mut state = procedural::BodyState { @@ -84,6 +91,7 @@ pub(super) fn native_functions( match procedural::lower_subroutine( id, tree, + session, &item.env, &aliases, &dims, @@ -174,6 +182,7 @@ pub(super) fn case_item_condition(case_expr: Expr, item_expr: Expr, wildcard: bo fn native_signature( native: &celox_sv_syntax::Subroutine, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted { let mut params = Vec::new(); @@ -196,9 +205,9 @@ fn native_signature( let ty = if port.direction.is_none() && omitted { previous .clone() - .or(type_binding::bind(port.data_type, tree, context)?) + .or(type_binding::bind(port.data_type, tree, session, context)?) } else { - type_binding::bind(port.data_type, tree, context)? + type_binding::bind(port.data_type, tree, session, context)? }; previous = ty.clone(); let expr_type = ty @@ -219,7 +228,7 @@ fn native_signature( }); } let ty = match native.return_type { - Some(id) => type_binding::bind(id, tree, context)?, + Some(id) => type_binding::bind(id, tree, session, context)?, None => None, }; let result = ty diff --git a/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs b/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs index a11db6eb4f2..e5622f87934 100644 --- a/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs +++ b/crates/celox-sv-analyzer/src/ast/functions/symbolic.rs @@ -376,10 +376,12 @@ mod tests { Source::from_syntax(&tree).unwrap() } fn evaluate(expr: Expr, bindings: &HashMap) -> i128 { + let session = &mut Session::default(); let expr = substitute_expr_idents(expr, bindings); let syntax = crate::source_tree::SourceTree::empty(); let expr = expr_to_index_const( &AnalysisContext::unspecialized(&syntax), + session, expr, &PackedDimensions::default(), ) @@ -404,17 +406,22 @@ mod tests { } #[test] fn native_task_outputs_keep_formal_fit_and_two_state_coercion() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( "module M;task automatic t(input logic[3:0]x,output bit[2:0]y);y=x+1;endtask endmodule", Path::new("native-task-symbolic.sv"), ) .unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let function = - functions_from_scope(&tree, &HashMap::default(), &PackedDimensions::default()) - .unwrap() - .remove("t") - .unwrap(); + let function = functions_from_scope( + &tree, + session, + &HashMap::default(), + &PackedDimensions::default(), + ) + .unwrap() + .remove("t") + .unwrap(); assert!(function.body.is_some()); assert_eq!(function.outputs[0].0, "y"); for input in ["4'd7", "4'bxxxx"] { diff --git a/crates/celox-sv-analyzer/src/ast/generate.rs b/crates/celox-sv-analyzer/src/ast/generate.rs index 3fb23b0e406..170fbebc2a9 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, memoize}; +pub(super) use memo::{CallSites, memoize, restore}; mod dependency_order; use dependency_order::DependencyOrder; @@ -507,7 +507,6 @@ impl Item { #[derive(Clone, Default)] struct Scope { - state: std::rc::Rc, imported: Arc, path: String, in_loop: bool, @@ -551,6 +550,7 @@ struct Elaborator<'a, 'b> { /// The context of the scope being elaborated, whose constant functions /// change with the imports of each generate block. tree: AnalysisContext<'a>, + session: &'b mut Session, module_aliases: &'b HashMap, /// The type aliases of the scope being elaborated. aliases: Cow<'b, HashMap>, @@ -564,21 +564,24 @@ pub(super) type Memo = memo::State; pub(super) fn items( tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Result, AnalyzerError> { - items_with_literal_use(tree, env, aliases, LiteralUse::All) + items_with_literal_use(tree, session, env, aliases, LiteralUse::All) } /// Elaborate the same scopes and diagnostics, retaining module parameter /// literals needed by subroutines, declarations and generate constructs. pub(super) fn subroutine_items( tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Result, AnalyzerError> { items_with_literal_use( tree, + session, env, aliases, if tree.root_subroutines { @@ -598,40 +601,40 @@ enum LiteralUse { fn items_with_literal_use( tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, literal_use: LiteralUse, ) -> Result, AnalyzerError> { - memo::items(tree, env, aliases, literal_use, || { - elaborate(tree, env, aliases, literal_use) + memo::items(tree, session, env, aliases, literal_use, |session| { + elaborate(tree, session, env, aliases, literal_use) }) } fn elaborate( tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, literal_use: LiteralUse, ) -> Result, AnalyzerError> { - let mut elaborator = Elaborator { - tree: tree.clone(), - module_aliases: aliases, - aliases: Cow::Borrowed(aliases), - remaining: MAX_GENERATE_LOOP_EXPANSION, - functions: HashMap::default(), - items: Vec::new(), - }; - let parameters = parameters_from_scope(tree, aliases, env, &tree.parameter_overrides)?; + let parameters = parameters_from_scope(tree, session, aliases, env, &tree.parameter_overrides)?; let references = parameter_literal_references(tree, literal_use)?; - let mut literals = - parameters::parameter_value_env_for_references(tree, ¶meters, env, &references); - if elaboration::needs_functions(tree)? { - elaborator.functions = module_constant_functions(tree, env, aliases, &literals)?; - } + let mut literals = parameters::parameter_value_env_for_references( + tree, + session, + ¶meters, + env, + &references, + ); + let functions = if elaboration::needs_functions(tree)? { + module_constant_functions(tree, session, env, aliases, &literals)? + } else { + HashMap::default() + }; // Numeric values and their type markers are already carried by `env`. literals.retain(|name, _| !env.contains_key(name)); let scope = Scope { - state: tree.state.clone(), imported: scope::imported(tree), env: env.clone().into(), literals: literals.into(), @@ -639,6 +642,15 @@ fn elaborate( parameters, ..Scope::default() }; + let mut elaborator = Elaborator { + tree: tree.clone(), + session, + module_aliases: aliases, + aliases: Cow::Borrowed(aliases), + remaining: MAX_GENERATE_LOOP_EXPANSION, + functions, + items: Vec::new(), + }; let is_package = tree .scope_handle() .unit(tree.declarations()) @@ -717,11 +729,16 @@ fn parameter_literal_references( impl<'a> Elaborator<'a, '_> { /// A constant expression in this scope, or `None` when it has no /// constant value Celox can determine. - fn expression(&self, root: ExprId, scope: &Scope) -> Result, AnalyzerError> { + fn expression( + &mut self, + root: ExprId, + scope: &Scope, + ) -> Result, AnalyzerError> { let Some(expr) = constant_binding::expression( root, self.tree.declarations(), &self.tree, + self.session, &scope.env, &self.aliases, )? @@ -734,27 +751,35 @@ impl<'a> Elaborator<'a, '_> { }; let Some(mut expr) = expr_to_index_const( &self.tree, + self.session, substitute_expr_idents(const_expr_to_expr(expr), &scope.literals), &dimensions, ) else { return Ok(None); }; - Ok(self - .expand_constant_calls(&self.tree, &mut expr, scope) - .map(|()| expr)) + Ok( + Self::expand_constant_calls( + &self.functions, + &self.tree, + self.session, + &mut expr, + scope, + ) + .map(|()| expr), + ) } fn expand_constant_calls( - &self, + functions: &HashMap, tree: &AnalysisContext<'_>, + session: &mut Session, expr: &mut ConstExpr, scope: &Scope, ) -> Option<()> { - let state = &*tree.state; match expr { ConstExpr::Function { callee, args, .. } => { for arg in args { - self.expand_constant_calls(tree, arg, scope)?; + Self::expand_constant_calls(functions, tree, session, arg, scope)?; } // A block import binds the call to the qualified declaration, // which the installed constant functions evaluate. @@ -767,7 +792,7 @@ impl<'a> Elaborator<'a, '_> { *name = target.clone(); } if let Callee::Subroutine(name) = callee - && self.functions.contains_key(name) + && functions.contains_key(name) { if scope.shadowed.contains(name) { return None; @@ -778,57 +803,63 @@ impl<'a> Elaborator<'a, '_> { .collect(); let expanded = expand_expr_calls( const_expr_to_expr(expr.clone()), - &self.functions, + functions, &signedness, 0, true, ); - let expanded = simplify_constant_mux_conditions(tree, expanded, &scope.env); + let expanded = + simplify_constant_mux_conditions(tree, session, expanded, &scope.env); + let folded = fold_const_integral_expr_preserving_mask( + tree, session, 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(tree, expanded, &scope.env), - )?; + *expr = expr_to_const(session, folded)?; } } ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => { - self.expand_constant_calls(tree, expr, scope)? + Self::expand_constant_calls(functions, tree, session, expr, scope)? } ConstExpr::SelectRange { expr, msb, lsb, .. } => { - self.expand_constant_calls(tree, expr, scope)?; - self.expand_constant_calls(tree, msb, scope)?; - self.expand_constant_calls(tree, lsb, scope)?; + Self::expand_constant_calls(functions, tree, session, expr, scope)?; + Self::expand_constant_calls(functions, tree, session, msb, scope)?; + Self::expand_constant_calls(functions, tree, session, lsb, scope)?; } ConstExpr::Select { expr, bit } => { - self.expand_constant_calls(tree, expr, scope)?; - self.expand_constant_calls(tree, bit, scope)?; + Self::expand_constant_calls(functions, tree, session, expr, scope)?; + Self::expand_constant_calls(functions, tree, session, bit, scope)?; } ConstExpr::Binary { left, right, .. } => { - self.expand_constant_calls(tree, left, scope)?; - self.expand_constant_calls(tree, right, scope)?; + Self::expand_constant_calls(functions, tree, session, left, scope)?; + Self::expand_constant_calls(functions, tree, session, right, scope)?; } ConstExpr::Mux { condition, then_expr, else_expr, } => { - self.expand_constant_calls(tree, condition, scope)?; - self.expand_constant_calls(tree, then_expr, scope)?; - self.expand_constant_calls(tree, else_expr, scope)?; + Self::expand_constant_calls(functions, tree, session, condition, scope)?; + Self::expand_constant_calls(functions, tree, session, then_expr, scope)?; + Self::expand_constant_calls(functions, tree, session, else_expr, scope)?; } ConstExpr::Ident(_) | ConstExpr::Literal(_) => {} } Some(()) } - fn value(&self, root: ExprId, scope: &Scope, detail: &str) -> Result { + fn value(&mut self, root: ExprId, scope: &Scope, detail: &str) -> Result { self.expression(root, scope)? .and_then(|expr| eval_ast_const_expr(&self.tree.functions, &expr, &scope.env)) .ok_or_else(|| AnalyzerError::Unsupported(detail.to_string())) } - fn condition(&self, root: ExprId, scope: &Scope, detail: &str) -> Result { + fn condition( + &mut self, + root: ExprId, + scope: &Scope, + detail: &str, + ) -> Result { let types = parameter_types_from_const_env(&scope.env) .into_iter() .map(|(name, ty)| (name, (ty.width, ty.signed))) @@ -872,7 +903,7 @@ impl<'a> Elaborator<'a, '_> { } fn constants_and_signal_types( - &self, + &mut self, children: &[celox_sv_syntax::BodyItemId], scope: &mut Scope, declared: &mut HashSet, @@ -1037,6 +1068,7 @@ impl<'a> Elaborator<'a, '_> { signals_from_body_item( id, &self.tree, + self.session, &self.aliases, &scope.env, Some(&name), @@ -1086,6 +1118,7 @@ impl<'a> Elaborator<'a, '_> { let base = scope.env.clone(); let mut environment = parameters::ParameterEnvironment::new( &self.tree, + self.session, &scope.parameters, &base, &pending @@ -1104,6 +1137,7 @@ impl<'a> Elaborator<'a, '_> { parameters::parameters_from_native_with_environment( ¶meters::ownership::body(id, &self.tree)?, &self.tree, + self.session, &mut scope.parameters, true, &base, @@ -1123,6 +1157,7 @@ impl<'a> Elaborator<'a, '_> { })?; constants::bind_generate_parameter_with_types( &self.tree, + self.session, parameter, &mut scope.env, &mut scope.literals, @@ -1154,6 +1189,7 @@ impl<'a> Elaborator<'a, '_> { parameters::parameters_from_native( ¶meters::ownership::body(id, &self.tree)?, &self.tree, + self.session, &mut scope.parameters, true, &scope.env, @@ -1168,7 +1204,13 @@ impl<'a> Elaborator<'a, '_> { AnalyzerError::Unsupported(format!("generate-local parameter `{name}`")) })?; scope.parameters.push(parameter.clone()); - bind_generate_parameter(&self.tree, parameter, &mut scope.env, &mut scope.literals); + bind_generate_parameter( + &self.tree, + self.session, + parameter, + &mut scope.env, + &mut scope.literals, + ); } order.complete(index); } @@ -1235,6 +1277,7 @@ impl<'a> Elaborator<'a, '_> { } let mut aliases = types::type_aliases_of_generate_scope( &self.tree, + self.session, children, &scope.env, &self.aliases, @@ -1242,6 +1285,7 @@ impl<'a> Elaborator<'a, '_> { )?; let enums = parameters::enum_member_constants_from_items( &self.tree, + self.session, children, &scope.env, &aliases, @@ -1323,6 +1367,7 @@ impl<'a> Elaborator<'a, '_> { signals_from_body_item( *id, &self.tree, + self.session, &self.aliases, &scope.env, None, @@ -1357,7 +1402,7 @@ impl<'a> Elaborator<'a, '_> { /// Make `name` in `scope` denote the package item `target`, as an import of /// the generate block does. -fn bind_import(scope: &mut Scope, name: &str, target: &str) { +fn bind_import(scope: &mut Scope, name: &str, target: &str, session: &mut Session) { let imported = scope.imported.clone(); Arc::make_mut(&mut scope.shadowed).insert(name.to_string()); scope.names.insert(name.to_string(), target.to_string()); @@ -1408,7 +1453,7 @@ fn bind_import(scope: &mut Scope, name: &str, target: &str) { // The exported literal is already evaluated in the package scope. // Keep that snapshot when rebuilding declaration-order environments; // the initializer may name a package dependency absent from this scope. - if let Some(value) = literal.and_then(|expr| expr_to_const(&scope.state, expr)) { + if let Some(value) = literal.and_then(|expr| expr_to_const(session, expr)) { parameter.value = Some(value); } scope.parameters.push(parameter); @@ -1419,6 +1464,7 @@ fn bind_import(scope: &mut Scope, name: &str, target: &str) { // itself elaborate generate blocks and recurse into the conditions being decided. fn module_constant_functions( tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, literals: &HashMap, @@ -1461,6 +1507,7 @@ fn module_constant_functions( let mut functions = functions::native_functions( &roots, tree, + session, &dimensions, lifetimes::automatic_by_default(tree), )?; @@ -1683,6 +1730,7 @@ mod tests { #[test] fn consecutive_parameter_runs_bind_each_prefix_once() { + let session = &mut Session::default(); for count in [16, 64, 256] { let mut code = String::from("module Top(); if (1) begin : g\n"); for index in 0..count { @@ -1702,7 +1750,7 @@ mod tests { .unwrap(); let tree = AnalysisContext::unspecialized(&tree); parameters::PARAMETER_BINDINGS.with(|bindings| bindings.set(0)); - let active = items(&tree, &HashMap::default(), &HashMap::default()).unwrap(); + let active = items(&tree, session, &HashMap::default(), &HashMap::default()).unwrap(); let bindings = parameters::PARAMETER_BINDINGS.with(|bindings| bindings.get()); assert!( bindings <= 3 * count, @@ -1725,6 +1773,7 @@ mod tests { #[test] fn cached_generate_types_match_rebuilt_types_for_imports_and_four_state_values() { + let session = &mut Session::default(); let syntax = crate::source_tree::SourceTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); let mut base = HashMap::from_iter([("pkg::IMPORTED".into(), -1)]); @@ -1767,12 +1816,14 @@ mod tests { ); bind_generate_parameter( &tree, + session, parameter.clone(), &mut rebuilt_env, &mut rebuilt_literals, ); constants::bind_generate_parameter_with_types( &tree, + session, parameter, &mut cached_env, &mut cached_literals, @@ -1786,13 +1837,14 @@ mod tests { #[test] fn generated_items_share_names_but_keep_mutations_in_their_own_snapshot() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( "module Top(); if (1) begin : g logic x; logic y; end endmodule", Path::new("generate_name_snapshots.sv"), ) .unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let active = items(&tree, &HashMap::default(), &HashMap::default()).unwrap(); + let active = items(&tree, session, &HashMap::default(), &HashMap::default()).unwrap(); assert_eq!(active.len(), 2); assert!(std::ptr::eq(&*active[0].names, &*active[1].names)); assert!(Arc::ptr_eq(&active[0].shadowed, &active[1].shadowed)); @@ -1828,6 +1880,7 @@ mod tests { let tree = AnalysisContext::unspecialized(&tree); let active = items( &tree, + &mut Session::default(), &HashMap::from_iter([("B".into(), 99)]), &HashMap::default(), ) @@ -2054,6 +2107,7 @@ mod tests { #[test] fn scopes_all_function_return_metadata_and_keeps_hidden_outer_binding() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( r#" module Top(); @@ -2066,7 +2120,7 @@ mod tests { ) .unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let active = items(&tree, &HashMap::default(), &HashMap::default()).unwrap(); + let active = items(&tree, session, &HashMap::default(), &HashMap::default()).unwrap(); let outer = FunctionReturnMetadata { arguments: None, width: Some(8), @@ -2141,6 +2195,7 @@ mod tests { #[test] fn genvar_scopes_discard_all_inherited_packed_bounds() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( "module Top(output logic [1:0] y); localparam logic signed [2:1][4:0] i=9; for (genvar i=0; i<2; i++) begin : g assign y[i]=i; end endmodule", Path::new("genvar_packed_bounds.sv"), @@ -2148,15 +2203,16 @@ mod tests { let tree = AnalysisContext::unspecialized(&tree); let parameters = parameters_from_scope( &tree, + session, &HashMap::default(), &HashMap::default(), &HashMap::default(), ) .unwrap(); let mut env = HashMap::default(); - extend_const_env_with_parameters(&tree, &mut env, ¶meters); + extend_const_env_with_parameters(&tree, session, &mut env, ¶meters); assert_eq!(env[¶meter_dimensions_marker("i")], 2); - let active = items(&tree, &env, &HashMap::default()).unwrap(); + let active = items(&tree, &mut Session::default(), &env, &HashMap::default()).unwrap(); let iterations: Vec<_> = active .iter() .filter(|item| !item.scope.is_empty()) @@ -2468,6 +2524,7 @@ mod tests { #[test] fn unused_unresolved_chains_do_not_populate_item_literals() { + let session = &mut Session::default(); use std::fmt::Write; for count in [16, 64, 256] { @@ -2495,7 +2552,8 @@ mod tests { crate::source_tree::parse_scope_fixture(&code, Path::new("unused_chain.sv")) .unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let active = items(&tree, &HashMap::default(), &HashMap::default()).unwrap(); + let active = + items(&tree, session, &HashMap::default(), &HashMap::default()).unwrap(); assert!(active.iter().all(|item| item.literals.is_empty())); let ir = crate::analyze::analyze_source(Source::from_syntax(&tree).unwrap()).unwrap(); @@ -2515,15 +2573,17 @@ mod tests { #[test] fn referenced_four_state_dependencies_keep_their_full_values() { + let session = &mut Session::default(); let code = "module Top(output logic [7:0] out); localparam logic [7:0] A=8'bxz010101; localparam logic [7:0] B=A; localparam logic [7:0] UNUSED='x; assign out=B; endmodule"; let tree = crate::source_tree::parse_scope_fixture(code, Path::new("needed_literals.sv")).unwrap(); let tree = AnalysisContext::unspecialized(&tree); 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, ¶meters, &env); - let active = items(&tree, &env, &aliases).unwrap(); + let parameters = + parameters_from_scope(&tree, session, &aliases, &env, &HashMap::default()).unwrap(); + let full = parameter_value_env(&tree, session, ¶meters, &env); + let active = items(&tree, session, &env, &aliases).unwrap(); for item in active { assert_eq!(item.literals.get("B"), full.get("B")); assert_eq!(item.literals.get("A"), full.get("A")); @@ -2604,6 +2664,7 @@ mod tests { #[test] fn subroutine_literals_preserve_functions_tasks_and_generate_scopes() { + let session = &mut Session::default(); let code = r#" module Top(output logic [7:0] out); localparam logic [7:0] A = 8'bxz010101; @@ -2625,8 +2686,8 @@ mod tests { let tree = AnalysisContext::unspecialized(&tree); let env = HashMap::default(); let aliases = HashMap::default(); - let full = items(&tree, &env, &aliases).unwrap(); - let projected = subroutine_items(&tree, &env, &aliases).unwrap(); + let full = items(&tree, session, &env, &aliases).unwrap(); + let projected = subroutine_items(&tree, session, &env, &aliases).unwrap(); assert_eq!(projected.len(), full.len()); for (full, projected) in full.iter().zip(&projected) { assert_eq!(projected.env, full.env); @@ -2653,6 +2714,7 @@ mod tests { #[test] fn rtl_referenced_unresolved_chains_do_not_expand_during_subroutine_discovery() { + let session = &mut Session::default(); use std::fmt::Write; for count in [16, 64, 256] { @@ -2678,7 +2740,8 @@ mod tests { .unwrap(); let tree = AnalysisContext::unspecialized(&tree); let active = - subroutine_items(&tree, &HashMap::default(), &HashMap::default()).unwrap(); + subroutine_items(&tree, session, &HashMap::default(), &HashMap::default()) + .unwrap(); assert!(active.iter().all(|item| item.literals.is_empty())); let ir = crate::analyze::analyze_source(Source::from_syntax(&tree).unwrap()).unwrap(); @@ -2715,6 +2778,7 @@ mod tests { #[test] fn subroutine_projection_preserves_generate_diagnostics() { + let session = &mut Session::default(); for body in [ "if (UNKNOWN) begin : g logic x; end", "if (1) begin : g parameter type T=logic; end", @@ -2728,12 +2792,13 @@ mod tests { ) .unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let full = items(&tree, &HashMap::default(), &HashMap::default()) - .err() - .expect(body); - let projected = subroutine_items(&tree, &HashMap::default(), &HashMap::default()) + let full = items(&tree, session, &HashMap::default(), &HashMap::default()) .err() .expect(body); + let projected = + subroutine_items(&tree, session, &HashMap::default(), &HashMap::default()) + .err() + .expect(body); assert_eq!(projected.to_string(), full.to_string(), "{body}"); } } diff --git a/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs b/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs index 2a7ba37ab39..cdc76a2362b 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/elaboration.rs @@ -1,8 +1,11 @@ //! Native generate control and scope worklist. use super::*; use celox_sv_syntax::{BodyItemId, BodyItemKind, ExprKind, ForStep}; -use std::{cell::Cell, rc::Rc}; -type Ordinal = Rc>; +use std::rc::Rc; +/// The index of a scope's count of the generate constructs it has seen so +/// far, which numbers its unnamed blocks (IEEE 1800-2023 27.6), in the +/// counts of an elaboration. +type Ordinal = usize; enum Job { ExitScope, Item { @@ -171,7 +174,8 @@ impl<'a, 'b> Elaborator<'a, 'b> { pending.extend(nested); } let scope = Rc::new(scope); - let ordinal = Rc::new(Cell::new(0)); + let mut ordinals = vec![0]; + let ordinal = 0; let mut jobs = ids .into_iter() .rev() @@ -182,12 +186,12 @@ impl<'a, 'b> Elaborator<'a, 'b> { .map(|id| Job::Item { id, scope: scope.clone(), - ordinal: ordinal.clone(), + ordinal, }) .collect::>(); let mut contexts = Contexts(Vec::new()); while let Some(job) = jobs.pop() { - if let Err(error) = self.execute_job(job, &mut jobs, &mut contexts) { + if let Err(error) = self.execute_job(job, &mut jobs, &mut contexts, &mut ordinals) { while let Some(context) = contexts.0.pop() { self.leave(context); } @@ -204,6 +208,7 @@ impl<'a, 'b> Elaborator<'a, 'b> { job: Job, jobs: &mut Vec, contexts: &mut Contexts<'b>, + ordinals: &mut Vec, ) -> Result<(), AnalyzerError> { match job { Job::ExitScope => { @@ -211,13 +216,13 @@ impl<'a, 'b> Elaborator<'a, 'b> { self.leave(context); Ok(()) } - Job::Item { id, scope, ordinal } => self.item_job(id, scope, ordinal, jobs), + Job::Item { id, scope, ordinal } => self.item_job(id, scope, ordinal, jobs, ordinals), Job::Block { id, parent, ordinal, index, - } => self.block_job(id, parent, ordinal, index, jobs, contexts), + } => self.block_job(id, parent, ordinal, index, jobs, contexts, ordinals), Job::Loop { id, parent, @@ -248,14 +253,15 @@ impl<'a, 'b> Elaborator<'a, 'b> { scope: Rc, ordinal: Ordinal, jobs: &mut Vec, + ordinals: &mut [usize], ) -> Result<(), AnalyzerError> { - let kind = &self.tree.declarations().body_item(id).kind; + let kind = &self.tree.syntax_tree.declarations().body_item(id).kind; if let BodyItemKind::Region(items) = kind { for id in items.iter().rev() { jobs.push(Job::Item { id: *id, scope: scope.clone(), - ordinal: ordinal.clone(), + ordinal, }); } return Ok(()); @@ -269,8 +275,8 @@ impl<'a, 'b> Elaborator<'a, 'b> { | BodyItemKind::Case { .. } | BodyItemKind::Loop { .. } ) { - let number = ordinal.get() + 1; - ordinal.set(number); + ordinals[ordinal] += 1; + let number = ordinals[ordinal]; match kind { BodyItemKind::Conditional { condition, @@ -344,18 +350,20 @@ impl<'a, 'b> Elaborator<'a, 'b> { index: Option<(String, i128)>, jobs: &mut Vec, contexts: &mut Contexts<'b>, + ordinals: &mut Vec, ) -> Result<(), AnalyzerError> { - let kind = &self.tree.declarations().body_item(id).kind; + let kind = &self.tree.syntax_tree.declarations().body_item(id).kind; if index.is_none() && matches!( kind, BodyItemKind::Conditional { .. } | BodyItemKind::Case { .. } ) { + ordinals.push(ordinal - 1); jobs.push(Job::Item { id, scope: parent, - ordinal: Rc::new(Cell::new(ordinal - 1)), + ordinal: ordinals.len() - 1, }); return Ok(()); } @@ -388,7 +396,7 @@ impl<'a, 'b> Elaborator<'a, 'b> { 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); + bind_import(&mut scope, name, target, self.session); } } let index_ref = index.as_ref().map(|(name, value)| (name.as_str(), *value)); @@ -404,12 +412,13 @@ impl<'a, 'b> Elaborator<'a, 'b> { }); let scope = Rc::new(self.prepare_block_contents(&children, scope, index_ref)?); jobs.push(Job::ExitScope); - let counter = Rc::new(Cell::new(0)); + ordinals.push(0); + let counter = ordinals.len() - 1; for id in children.into_iter().rev() { jobs.push(Job::Item { id, scope: scope.clone(), - ordinal: counter.clone(), + ordinal: counter, }); } Ok(()) @@ -427,7 +436,7 @@ impl<'a, 'b> Elaborator<'a, 'b> { condition, body, .. - } = &self.tree.declarations().body_item(id).kind + } = &self.tree.syntax_tree.declarations().body_item(id).kind else { return Err(mismatch()); }; @@ -479,18 +488,20 @@ impl<'a, 'b> Elaborator<'a, 'b> { Ok(()) } fn next_value( - &self, + &mut self, id: BodyItemId, value: i128, scope: &Scope, ) -> Result { - let BodyItemKind::Loop { step, .. } = &self.tree.declarations().body_item(id).kind else { + let BodyItemKind::Loop { step, .. } = + &self.tree.syntax_tree.declarations().body_item(id).kind + else { return Err(mismatch()); }; let result = match step { ForStep::Expression(id) => { let ExprKind::Unary { operator, .. } = - &self.tree.declarations().expression(*id).kind + &self.tree.syntax_tree.declarations().expression(*id).kind else { return Err(mismatch()); }; @@ -512,7 +523,7 @@ impl<'a, 'b> Elaborator<'a, 'b> { result.ok_or_else(|| unsupported("genvar update operator")) } fn case_block( - &self, + &mut self, selector: ExprId, arms: &[celox_sv_syntax::GenerateCaseArm], scope: &Scope, @@ -632,13 +643,16 @@ mod tests { use super::*; #[test] fn root_function_seeding_defers_explicit_region_declarations() { + let session = &mut Session::default(); let tree=crate::source_tree::parse_scope_fixture("module M;function automatic int rootf();return 1;endfunction generate function automatic int regionf();return 2;endfunction endgenerate endmodule",Path::new("native-root-seeding.sv")).unwrap(); let tree = AnalysisContext::unspecialized(&tree); let env = HashMap::default(); let aliases = HashMap::default(); let seeded = - items_with_literal_use(&tree, &env, &aliases, LiteralUse::RootSubroutines).unwrap(); - let all = items_with_literal_use(&tree, &env, &aliases, LiteralUse::Subroutines).unwrap(); + items_with_literal_use(&tree, session, &env, &aliases, LiteralUse::RootSubroutines) + .unwrap(); + let all = items_with_literal_use(&tree, session, &env, &aliases, LiteralUse::Subroutines) + .unwrap(); assert_eq!(seeded.len(), 1); assert_eq!(all.len(), 2); assert!( diff --git a/crates/celox-sv-analyzer/src/ast/generate/memo.rs b/crates/celox-sv-analyzer/src/ast/generate/memo.rs index 20d8c016721..732ef54c728 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/memo.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/memo.rs @@ -8,17 +8,16 @@ //! 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; +/// The window of the module being analyzed, if one is open. #[derive(Default)] -pub(in crate::ast) struct State(RefCell>); +pub(in crate::ast) struct State(Option); -struct Window { - /// The syntax tree of the module, borrowed by the [`Memoized`] guard. +pub(in crate::ast) struct Window { + /// The syntax tree of the module. tree: usize, entries: Vec, } @@ -40,32 +39,19 @@ struct Entry { sites: usize, } -/// Keeps elaborations of `tree` until dropped; the previous window, of an -/// enclosing analysis, is restored then. -pub(in crate::ast) struct Memoized<'a> { - state: std::rc::Rc, - previous: Option, - _tree: &'a SyntaxTree, -} - -impl Drop for Memoized<'_> { - fn drop(&mut self) { - // The items retain the state; release them outside the borrow. - let window = self.state.generate_items.0.replace(self.previous.take()); - drop(window); - } -} - -pub(in crate::ast) fn memoize<'a>(tree: &AnalysisContext<'a>) -> Memoized<'a> { +/// Opens a window that keeps the elaborations of `tree`, giving back the +/// window of an enclosing analysis for [`restore`]. +pub(in crate::ast) fn memoize(tree: &AnalysisContext<'_>, session: &mut Session) -> Option { let window = Window { tree: address(tree.syntax_tree), entries: Vec::new(), }; - Memoized { - state: tree.state.clone(), - previous: tree.state.generate_items.0.replace(Some(window)), - _tree: tree.syntax_tree, - } + session.generate_items.0.replace(window) +} + +/// Closes the window [`memoize`] opened, reopening `previous`. +pub(in crate::ast) fn restore(session: &mut Session, previous: Option) { + session.generate_items.0 = previous; } fn address(tree: &SyntaxTree) -> usize { @@ -75,55 +61,60 @@ fn address(tree: &SyntaxTree) -> usize { /// The items `elaborate` gives for these arguments, elaborated once per window. pub(super) fn items( tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, literal_use: LiteralUse, - elaborate: impl FnOnce() -> Result, AnalyzerError>, + elaborate: impl FnOnce(&mut Session) -> Result, AnalyzerError>, ) -> Result, AnalyzerError> { #[cfg(test)] - let elaborate = || { + let elaborate = |session: &mut Session| { tests::ELABORATIONS.with(|count| count.set(count.get() + 1)); - elaborate() + elaborate(session) }; #[cfg(test)] - if tests::DISABLED.with(Cell::get) { - return elaborate(); + if tests::DISABLED.with(std::cell::Cell::get) { + return elaborate(session); } - let state = &tree.state; let applies = |window: &Window| window.tree == address(tree.syntax_tree); - { - let window = state.generate_items.0.borrow(); - let Some(window) = window.as_ref().filter(|window| applies(window)) else { - drop(window); - return elaborate(); - }; - if let Some(entry) = window.entries.iter().find(|entry| { - 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 - && entry.aliases == *aliases - }) { - let next = state.next_call_site.get() + entry.sites; - state.next_call_site.set(next); - return Ok(entry.items.clone()); - } + let Some(window) = session + .generate_items + .0 + .as_ref() + .filter(|window| applies(window)) + else { + return elaborate(session); + }; + if let Some(entry) = window.entries.iter().find(|entry| { + 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 + && entry.aliases == *aliases + }) { + let items = entry.items.clone(); + session.next_call_site += entry.sites; + return Ok(items); } - let first_site = state.next_call_site.get(); - let items = elaborate()?; - let sites = first_site..state.next_call_site.get(); + let first_site = session.next_call_site; + let items = elaborate(session)?; + let sites = first_site..session.next_call_site; // Effectful calls the items retain must get new sites when they are // elaborated again. if !sites.is_empty() && sites::refer_to(&items, sites.clone()) { return Ok(items); } - let mut window = state.generate_items.0.borrow_mut(); - if let Some(window) = window.as_mut().filter(|window| applies(window)) { + if let Some(window) = session + .generate_items + .0 + .as_mut() + .filter(|window| applies(window)) + { window.entries.push(Entry { imported: tree.imported.clone(), package: tree.package.clone(), @@ -145,6 +136,7 @@ pub(super) fn items( #[cfg(test)] mod tests { use super::*; + use std::cell::Cell; thread_local! { pub(super) static DISABLED: Cell = const { Cell::new(false) }; diff --git a/crates/celox-sv-analyzer/src/ast/generate/scope_views.rs b/crates/celox-sv-analyzer/src/ast/generate/scope_views.rs index bbe7e925066..f5626d4b795 100644 --- a/crates/celox-sv-analyzer/src/ast/generate/scope_views.rs +++ b/crates/celox-sv-analyzer/src/ast/generate/scope_views.rs @@ -71,6 +71,7 @@ mod tests { #[test] fn builds_one_view_for_a_growing_block_of_siblings() { + let session = &mut Session::default(); for count in [16, 64, 256] { let mut code = String::from("module Top(); if (1) begin : g\n"); for index in 0..count { @@ -81,7 +82,7 @@ mod tests { crate::source_tree::parse_scope_fixture(&code, Path::new("scope_scaling.sv")) .unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let active = items(&tree, &HashMap::default(), &HashMap::default()).unwrap(); + let active = items(&tree, session, &HashMap::default(), &HashMap::default()).unwrap(); let dimensions = PackedDimensions::default(); let mut views = ScopeViews::new(&dimensions); for item in &active { @@ -95,13 +96,14 @@ mod tests { #[test] fn preserves_nested_and_interrupted_scopes_and_detaches_changed_snapshots() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( "module Top(); if (1) begin : g localparam int P=2; logic [P-1:0] x; if (1) begin : inner localparam int P=3; logic [P-1:0] x; end logic y; end if (1) begin : h localparam int P=4; logic [P-1:0] x; end endmodule", Path::new("scope_views.sv"), ).unwrap(); let tree = AnalysisContext::unspecialized(&tree); let source = Source::from_syntax(&tree).unwrap(); - let active = items(&tree, &HashMap::default(), &HashMap::default()).unwrap(); + let active = items(&tree, session, &HashMap::default(), &HashMap::default()).unwrap(); let dimensions = packed_dimensions_from_ports_and_signals( source.modules()[0].ports(), source.modules()[0].signals(), diff --git a/crates/celox-sv-analyzer/src/ast/instances.rs b/crates/celox-sv-analyzer/src/ast/instances.rs index 6c133eccaff..b0cbac88c8d 100644 --- a/crates/celox-sv-analyzer/src/ast/instances.rs +++ b/crates/celox-sv-analyzer/src/ast/instances.rs @@ -5,12 +5,13 @@ mod connections; pub(super) fn instances_from_scope( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, packed_dimensions: &PackedDimensions, interfaces: &InterfaceLookup<'_>, ) -> Result, AnalyzerError> { - let type_aliases = type_aliases_from_scope(syntax_tree)?; - let active = generate::items(syntax_tree, const_env, &type_aliases)?; + let type_aliases = type_aliases_from_scope(syntax_tree, session)?; + let active = generate::items(syntax_tree, session, const_env, &type_aliases)?; let mut instances = Vec::new(); let mut views = generate::ScopeViews::new(packed_dimensions); for item in &active { @@ -35,6 +36,7 @@ pub(super) fn instances_from_scope( native, None, syntax_tree, + session, &item.env, dimensions, interfaces, @@ -46,6 +48,7 @@ pub(super) fn instances_from_scope( connection.map_expressions(|expr| { let mut expr = substitute_expr_constants_with_parameter_literals( syntax_tree, + session, expr, &item.env, &item.literals, @@ -65,6 +68,7 @@ fn instances_from_native_declaration( native: &celox_sv_syntax::Instantiation, condition: Option, syntax_tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, packed_dimensions: &PackedDimensions, interfaces: &InterfaceLookup<'_>, @@ -76,6 +80,7 @@ fn instances_from_native_declaration( let mut parameter_overrides = parameter_overrides( native.parameters.as_deref(), syntax_tree, + session, interface, packed_dimensions, false, @@ -89,6 +94,7 @@ fn instances_from_native_declaration( ); let value = expr_to_index_const( syntax_tree, + session, substitute_expr_idents( const_expr_to_expr(value), &packed_dimensions.parameter_values, @@ -118,6 +124,7 @@ fn instances_from_native_declaration( (id, index), authored, syntax_tree, + session, packed_dimensions, interface, )?; @@ -125,6 +132,7 @@ fn instances_from_native_declaration( connection.map_expressions(|expr| { substitute_expr_constants_with_parameter_literals( syntax_tree, + session, expr, const_env, &HashMap::default(), @@ -146,6 +154,7 @@ fn instances_from_native_declaration( let ranges = instance_ranges( authored, syntax_tree, + session, const_env, &packed_dimensions.type_aliases, )?; @@ -194,6 +203,7 @@ fn instances_from_native_declaration( pub(super) fn parameter_overrides( native: Option<&[celox_sv_syntax::Argument]>, syntax_tree: &AnalysisContext<'_>, + session: &mut Session, interface: Option<&ModuleInterface>, packed_dimensions: &PackedDimensions, bind_values: bool, @@ -240,6 +250,7 @@ pub(super) fn parameter_overrides( name, value, syntax_tree, + session, packed_dimensions, bind_values, )?); @@ -251,10 +262,18 @@ pub(super) fn port_connections( key: interface_binding::InstanceKey, native: &celox_sv_syntax::InstanceDeclarator, syntax_tree: &AnalysisContext<'_>, + session: &mut Session, packed_dimensions: &PackedDimensions, interface: Option<&ModuleInterface>, ) -> Result, AnalyzerError> { - connections::connections(key, native, syntax_tree, packed_dimensions, interface) + connections::connections( + key, + native, + syntax_tree, + session, + packed_dimensions, + interface, + ) } pub(super) fn declaration_from_item<'a>( @@ -292,10 +311,11 @@ fn validate_native_instances(native: &celox_sv_syntax::Instantiation) -> Convert pub(super) fn instance_ranges( native: &celox_sv_syntax::InstanceDeclarator, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Result, AnalyzerError> { - constant_binding::unpacked_ranges(&native.dimensions, tree, env, aliases) + constant_binding::unpacked_ranges(&native.dimensions, tree, session, env, aliases) } pub(super) fn expr_ident_name(expr: &Expr) -> Option { @@ -328,6 +348,7 @@ pub(crate) fn normalize_identifier(text: &str) -> String { fn array_argument_shape( root: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Option { use celox_sv_syntax::{ExprId, ExprKind}; @@ -352,7 +373,9 @@ fn array_argument_shape( jobs.push(Job::Enter(else_expression)); jobs.push(Job::Enter(then_expression)); } else { - values.push(array_compatibility::native_unpacked_shape(id, tree, dims)?); + values.push(array_compatibility::native_unpacked_shape( + id, tree, session, dims, + )?); } } Job::Conditional => { @@ -381,6 +404,7 @@ fn parameter_override( name: String, native: celox_sv_syntax::ExprId, syntax_tree: &AnalysisContext<'_>, + session: &mut Session, packed_dimensions: &PackedDimensions, bind_values: bool, ) -> Result { @@ -391,6 +415,7 @@ fn parameter_override( let ty = type_binding::argument_type( native, syntax_tree, + session, &packed_dimensions.const_env, &packed_dimensions.type_aliases, )? @@ -407,14 +432,15 @@ fn parameter_override( continue; } if matches!(declarations.expression(id).kind, ExprKind::Pattern { .. }) { - let pattern = bound_patterns::from_param(native, syntax_tree, packed_dimensions)?; + let pattern = + bound_patterns::from_param(native, syntax_tree, session, packed_dimensions)?; let mut bound = ParameterOverride::new(name, None); bound.bound_pattern = Some(pattern); return Ok(bound); } pending.extend(parameters::skipped::children(id, declarations)); } - if let Some(shape) = array_argument_shape(native, syntax_tree, packed_dimensions) { + if let Some(shape) = array_argument_shape(native, syntax_tree, session, packed_dimensions) { // Aggregate conditional expressions require equivalent branch types // (11.4.11). A known condition selects a whole array before element // binding; treating it as a packed mux would use the wrong X merge rule. @@ -425,17 +451,20 @@ fn parameter_override( else_expression, } = declarations.expression(selected).kind { - let condition = constant_binding::bind(condition, syntax_tree, packed_dimensions)? - .and_then(|value| { - eval_ast_const_expr( - &syntax_tree.functions, - &value, - &packed_dimensions.const_env, - ) - }) - .ok_or_else(|| { - unsupported("nonconstant or ambiguous condition in array parameter argument") - })?; + let condition = + constant_binding::bind(condition, syntax_tree, session, packed_dimensions)? + .and_then(|value| { + eval_ast_const_expr( + &syntax_tree.functions, + &value, + &packed_dimensions.const_env, + ) + }) + .ok_or_else(|| { + unsupported( + "nonconstant or ambiguous condition in array parameter argument", + ) + })?; selected = expression_binding::ungroup( if condition != 0 { then_expression @@ -445,8 +474,13 @@ fn parameter_override( declarations, ); } - let pattern = - bound_patterns::from_array_parameter(selected, syntax_tree, packed_dimensions, &shape)?; + let pattern = bound_patterns::from_array_parameter( + selected, + syntax_tree, + session, + packed_dimensions, + &shape, + )?; let mut bound = ParameterOverride::new(name, None); bound.bound_pattern = Some(pattern); return Ok(bound); @@ -464,6 +498,7 @@ fn parameter_override( let ty = type_binding::argument_type( native, syntax_tree, + session, &packed_dimensions.const_env, &packed_dimensions.type_aliases, )? @@ -495,14 +530,24 @@ fn parameter_override( .ok_or_else(|| unsupported(format!("parameter type override `{name}`")))?; return Ok(ParameterOverride::type_override(name, ty)); } - expr_to_const( - &syntax_tree.state, - expression_binding::value(native, declarations, syntax_tree, packed_dimensions)?, - ) - .ok_or_else(|| unsupported("constant interface parameter override"))? + let value = expression_binding::value( + native, + declarations, + syntax_tree, + session, + packed_dimensions, + )?; + expr_to_const(session, value) + .ok_or_else(|| unsupported("constant interface parameter override"))? } else { - constant_binding::value_expression(native, declarations, syntax_tree, packed_dimensions)? - .ok_or_else(|| unsupported("parameter override expression"))? + constant_binding::value_expression( + native, + declarations, + syntax_tree, + session, + packed_dimensions, + )? + .ok_or_else(|| unsupported("parameter override expression"))? }; // A bare name that denotes a type (a typedef, or the instantiating // module's own `parameter type`) is passed on as that type. diff --git a/crates/celox-sv-analyzer/src/ast/instances/connections.rs b/crates/celox-sv-analyzer/src/ast/instances/connections.rs index 39e1bdcee89..1f2ca403164 100644 --- a/crates/celox-sv-analyzer/src/ast/instances/connections.rs +++ b/crates/celox-sv-analyzer/src/ast/instances/connections.rs @@ -6,6 +6,7 @@ pub(super) fn connections( key: interface_binding::InstanceKey, native: &InstanceDeclarator, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, interface: Option<&ModuleInterface>, ) -> Result, AnalyzerError> { @@ -50,7 +51,13 @@ pub(super) fn connections( continue; } if let Some(id) = value { - lowered.push(expression_connection(formal.clone(), id, tree, dimensions)?); + lowered.push(expression_connection( + formal.clone(), + id, + tree, + session, + dimensions, + )?); } } } else { @@ -66,7 +73,9 @@ pub(super) fn connections( continue; } if let ConnectionValue::Expression(id) = value { - lowered.push(expression_connection(formal, *id, tree, dimensions)?); + lowered.push(expression_connection( + formal, *id, tree, session, dimensions, + )?); continue; } let actual_expr = match value { @@ -76,6 +85,7 @@ pub(super) fn connections( *id, tree.declarations(), tree, + session, dimensions, )?), }; @@ -96,6 +106,7 @@ fn expression_connection( formal: String, root: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted { let native = tree.declarations(); @@ -105,10 +116,10 @@ fn expression_connection( celox_sv_syntax::ExprKind::Pattern { target: None, .. } ) { let mut connection = PortConnection::new(formal.clone(), formal, None); - connection.bound_pattern = Some(bound_patterns::from_port(root, tree, dims)?); + connection.bound_pattern = Some(bound_patterns::from_port(root, tree, session, dims)?); return Ok(connection); } - let expr = expression_binding::value(root, native, tree, dims)?; + let expr = expression_binding::value(root, native, tree, session, dims)?; let actual = unpacked_structs::native_member(root, native, dims) .or_else(|| match &native.expression(root).kind { celox_sv_syntax::ExprKind::Name(name) diff --git a/crates/celox-sv-analyzer/src/ast/interface_ast.rs b/crates/celox-sv-analyzer/src/ast/interface_ast.rs index 44819e5ac28..dc146f1c47f 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_ast.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_ast.rs @@ -12,6 +12,7 @@ pub(super) type ActiveInstance = ( /// source location, including the lexical time scope of processes/functions. pub(super) fn analyze( tree: &AnalysisContext<'_>, + session: &mut Session, path: &Path, packages: &packages::Packages, overrides: &HashMap, @@ -54,6 +55,7 @@ pub(super) fn analyze( }; let nested = interface_binding::analyze_module( tree, + session, path, packages, interface_binding::Bindings { @@ -68,7 +70,15 @@ pub(super) fn analyze( let mut module = if let Some(module) = nested { module } else { - Module::from_scope_with_symbols(tree, &name, overrides, &lookup, Arc::new(imported), true)? + Module::from_scope_with_symbols( + tree, + session, + &name, + overrides, + &lookup, + Arc::new(imported), + true, + )? }; let symbols = module.symbols.as_mut().unwrap(); let mut parameters = module.imported_parameters.clone(); @@ -96,6 +106,7 @@ pub(super) fn signature( members: &[String], names: &HashSet, ) -> Converted { + let session = &mut Session::default(); let projected_tree = interface_binding::declaration_view(tree)?; let context = AnalysisContext::unspecialized(&projected_tree); let tree = &context; @@ -112,6 +123,7 @@ pub(super) fn signature( }; let mut module = Module::from_scope_with_parameter_overrides( tree, + session, "", &HashMap::default(), &interfaces, @@ -123,10 +135,11 @@ pub(super) fn signature( let tree = &tree.importing(Arc::new(imported.clone())); let tree = &tree.with_functions(module.constant_functions.clone()); let mut env = imported.const_env.clone(); - 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)?; + extend_const_env_with_parameters(tree, session, &mut env, &module.parameters); + let aliases = type_aliases_from_scope_with_env(tree, session, &env)?; + let declarations = declarations::signals_from_scope_with_declaration_ranges( + tree, session, &env, &aliases, true, + )?; let names = names .iter() .map(|name| (name.clone(), format!("h${name}"))) diff --git a/crates/celox-sv-analyzer/src/ast/interface_binding.rs b/crates/celox-sv-analyzer/src/ast/interface_binding.rs index bcc86cd9ff1..17739f1cde2 100644 --- a/crates/celox-sv-analyzer/src/ast/interface_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/interface_binding.rs @@ -39,6 +39,7 @@ pub(super) struct ArrayBinding { pub(super) fn unindexed_parameter( path: &[String], tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, root: celox_sv_syntax::ExprId, ) -> Option { @@ -60,7 +61,7 @@ pub(super) fn unindexed_parameter( return None; } warnings::append( - &mut tree.state.diagnostics.borrow_mut(), + &mut session.diagnostics, [warnings::AnalyzerWarning::InterfaceArrayParameter { path: path.join("."), element: element.clone(), @@ -72,6 +73,7 @@ pub(super) fn unindexed_parameter( pub(super) fn analyze_module( tree: &AnalysisContext<'_>, + session: &mut Session, path: &Path, packages: &packages::Packages, bindings: Bindings<'_>, @@ -161,6 +163,7 @@ pub(super) fn analyze_module( header_imports.declarations_only = true; Some(Module::from_selected_scope( &tree.child(&header_tree, &overrides), + session, &name, &overrides, interfaces, @@ -201,6 +204,7 @@ pub(super) fn analyze_module( &port.name, &dimensions, tree, + session, &array_symbols.const_env, &array_symbols.type_aliases, )?; @@ -232,7 +236,7 @@ pub(super) fn analyze_module( imported .state_signals .extend(virtual_interfaces::port_identity_signal( - &tree.state, + session, handle, &port.interface, )); @@ -251,6 +255,7 @@ pub(super) fn analyze_module( }; interface_ast::analyze( &tree.child(definition_tree, &values), + session, definition_path, packages, &values, @@ -343,6 +348,7 @@ pub(super) fn analyze_module( header_imports.declarations_only = true; let caller = Module::from_selected_scope( &tree.child(&header_tree, &overrides), + session, &name, &overrides, interfaces, @@ -371,6 +377,7 @@ pub(super) fn analyze_module( header_imports.declarations_only = true; let caller = Module::from_selected_scope( &tree.child(&header_tree, &overrides), + session, &name, &overrides, interfaces, @@ -385,7 +392,7 @@ pub(super) fn analyze_module( current.extend(&imported); let tree = &tree.importing(Arc::new(current.clone())); let tree = &tree.with_functions(current.constant_functions.clone()); - for item in generate::items(tree, ¤t.const_env, ¤t.type_aliases)? { + for item in generate::items(tree, session, ¤t.const_env, ¤t.type_aliases)? { if let celox_sv_syntax::BodyItemKind::Instance(native) = tree.declarations().body_item(item.id).kind && definitions.contains_key(&instances::normalize_identifier( @@ -414,6 +421,7 @@ pub(super) fn analyze_module( header_imports.declarations_only = true; let caller = Module::from_selected_scope( &tree.child(&header_tree, &overrides), + session, &name, &overrides, interfaces, @@ -460,6 +468,7 @@ pub(super) fn analyze_module( let bindings = instances::parameter_overrides( native.parameters.as_deref(), tree, + session, Some(&interface), &dimensions, true, @@ -487,6 +496,7 @@ pub(super) fn analyze_module( &handle, &authored.dimensions, tree, + session, ¤t.const_env, ¤t.type_aliases, )?; @@ -528,7 +538,7 @@ pub(super) fn analyze_module( imported .state_signals .extend(virtual_interfaces::identity_signal( - &tree.state, + session, &handle, &interface_name, )); @@ -536,6 +546,7 @@ pub(super) fn analyze_module( (id, index), authored, tree, + session, &dimensions, Some(&interface), )?; @@ -549,6 +560,7 @@ pub(super) fn analyze_module( }; interface_ast::analyze( &tree.child(definition_tree, &values), + session, definition_path, packages, &values, @@ -594,6 +606,7 @@ pub(super) fn analyze_module( pattern.map_expressions(&mut |expr| { let mut expr = substitute_expr_constants_with_parameter_literals( tree, + session, expr, &dimensions.const_env, ¤t.parameter_values, @@ -606,7 +619,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_tree, shape, &port_dimensions)? + pattern.lower(&port_tree, session, shape, &port_dimensions)? } else if let Some(actual) = connection.actual_expr.clone() { actual } else { @@ -631,7 +644,7 @@ pub(super) fn analyze_module( let actual_shape = if let Some(root) = connection_expression(authored, &port.name, Some(&interface))? { - dimensions::operand_shape(root, tree, &dimensions)? + dimensions::operand_shape(root, tree, session, &dimensions)? } else if let Expr::Ident(name) = &actual { dimensions.get(name).cloned() } else { @@ -723,7 +736,7 @@ pub(super) fn analyze_module( current.extend(&imported); let tree = &tree.importing(Arc::new(current.clone())); let tree = &tree.with_functions(current.constant_functions.clone()); - for item in generate::items(tree, ¤t.const_env, ¤t.type_aliases)? { + for item in generate::items(tree, session, ¤t.const_env, ¤t.type_aliases)? { let tree = &item.scoped(tree); let active_scope = scope::imported(tree); let celox_sv_syntax::BodyItemKind::Instance(native) = @@ -744,7 +757,8 @@ pub(super) fn analyze_module( let actual = connection_expression(authored, &port.name, interfaces.get(&original))?; let env = &item.env; - let actuals = connection_array(actual, &port.name, tree, env, &active_scope)?; + let actuals = + connection_array(actual, &port.name, tree, session, env, &active_scope)?; if actuals.shape.len() != port.array_rank { return Err(unsupported(format!( "interface array rank mismatch at `{original}.{}`", @@ -813,7 +827,7 @@ pub(super) fn analyze_module( .parameter_values .get(bound) .cloned() - .and_then(|expr| expr_to_const(&tree.state, expr)) + .and_then(|expr| expr_to_const(session, expr)) .ok_or_else(|| { unsupported(format!("interface parameter `{handle}.{parameter}`")) })?; @@ -862,6 +876,7 @@ pub(super) fn analyze_module( } let module = Module::from_selected_scope( tree, + session, &name, &overrides, interfaces, @@ -1328,11 +1343,12 @@ fn instance_elements( handle: &str, dimensions: &[celox_sv_syntax::Dimension], tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Converted { let context = PackedDimensions::new(HashMap::default(), env, aliases); - let ranges = constant_binding::bind_unpacked_ranges(dimensions, tree, &context)?; + let ranges = constant_binding::bind_unpacked_ranges(dimensions, tree, session, &context)?; validate_unpacked_dimension_sizes(&tree.functions, &ranges, env)?; let mut shape = Vec::new(); let mut bounds = Vec::new(); @@ -1382,6 +1398,7 @@ fn connection_array( actual: Option, implicit: &str, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, scope: &scope::ScopeSymbols, ) -> Converted { @@ -1404,7 +1421,7 @@ fn connection_array( } } let handle = match root { - Some(root) => actual_handle_key(root, tree, env, &scope.type_aliases)?, + Some(root) => actual_handle_key(root, tree, session, env, &scope.type_aliases)?, None => implicit.to_string(), }; let Some(array) = scope.interface_arrays.get(&handle) else { @@ -1412,7 +1429,7 @@ fn connection_array( // retain the existing scalar-handle resolution for that case. return Ok(ArrayBinding { elements: vec![match actual { - Some(actual) => actual_handle_key(actual, tree, env, &scope.type_aliases)?, + Some(actual) => actual_handle_key(actual, tree, session, env, &scope.type_aliases)?, None => handle, }], shape: Vec::new(), @@ -1440,8 +1457,8 @@ fn connection_array( return Err(unsupported("interface array slices in multiple dimensions")); } let context = PackedDimensions::new(HashMap::default(), env, &scope.type_aliases); - let evaluate = |root| -> Converted { - constant_binding::bind(root, tree, &context)? + let mut evaluate = |root| -> Converted { + constant_binding::bind(root, tree, session, &context)? .and_then(|value| eval_ast_const_expr(&tree.functions, &value, env)) .ok_or_else(|| unsupported("nonconstant interface array selection")) }; @@ -1457,7 +1474,7 @@ fn connection_array( (index, index, false) } Some(selection) => { - let (start, end) = selection_range(selection, left <= right, &evaluate)?; + let (start, end) = selection_range(selection, left <= right, &mut evaluate)?; (start, end, true) } }; @@ -1499,7 +1516,7 @@ fn connection_array( fn selection_range( selection: &celox_sv_syntax::DimensionKind, ascending: bool, - evaluate: &impl Fn(celox_sv_syntax::ExprId) -> Converted, + evaluate: &mut impl FnMut(celox_sv_syntax::ExprId) -> Converted, ) -> Converted<(i128, i128)> { use celox_sv_syntax::DimensionKind; match selection { @@ -1532,6 +1549,7 @@ fn selection_range( pub(super) fn actual_handle_key( root: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Converted { @@ -1578,7 +1596,7 @@ pub(super) fn actual_handle_key( handle.push_str(&name); } Suffix::Index(root) => { - let value = constant_binding::bind(root, tree, &context)? + let value = constant_binding::bind(root, tree, session, &context)? .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/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index 252c08c0f49..b0e42cdb6d5 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -979,9 +979,14 @@ struct Design<'a> { modules: HashMap, /// The ports of every subroutine declared or imported, by name. subroutines: HashMap>, - expansions: std::cell::RefCell>, +} + +/// The interface port expansions a plan computes, each once. +#[derive(Default)] +struct Expansions { + done: HashMap, /// The expansions being computed, to reject a recursive instantiation. - expanding: std::cell::RefCell>, + expanding: HashSet, } impl<'a> Design<'a> { @@ -1147,8 +1152,6 @@ impl<'a> Design<'a> { interfaces, modules, subroutines, - expansions: Default::default(), - expanding: Default::default(), }) } @@ -1167,6 +1170,7 @@ impl<'a> Design<'a> { fn expansion( &self, + expansions: &mut Expansions, module: &str, port: &str, interface: &str, @@ -1178,23 +1182,24 @@ impl<'a> Design<'a> { interface.to_string(), bindings.to_vec(), ); - if let Some(expansion) = self.expansions.borrow().get(&key) { + if let Some(expansion) = expansions.done.get(&key) { return Ok(expansion.clone()); } - if !self.expanding.borrow_mut().insert(key.clone()) { + if !expansions.expanding.insert(key.clone()) { return Err(unsupported(format!( "recursive instantiation through interface port `{port}` of module `{module}`" ))); } - let expansion = self.compute_expansion(module, port, interface, bindings); - self.expanding.borrow_mut().remove(&key); + let expansion = self.compute_expansion(expansions, module, port, interface, bindings); + expansions.expanding.remove(&key); let expansion = expansion?; - self.expansions.borrow_mut().insert(key, expansion.clone()); + expansions.done.insert(key, expansion.clone()); Ok(expansion) } fn compute_expansion( &self, + expansions: &mut Expansions, module_name: &str, port_name: &str, interface_name: &str, @@ -1281,6 +1286,7 @@ impl<'a> Design<'a> { .filter(|child| child.handle == port_name) { let child_expansion = self.expansion( + expansions, &child.module, &child.formal, interface_name, @@ -1357,6 +1363,7 @@ impl<'a> Design<'a> { .filter(|child| child.handle == port_name) { let child_expansion = self.expansion( + expansions, &child.module, &child.formal, interface_name, @@ -3197,6 +3204,8 @@ pub fn plan_interfaces_with_member_paths( } else { Design::collect(&files)? }; + let mut expansions = Expansions::default(); + let expansions = &mut expansions; let mut result = NativeInterfacePlan::default(); let mut reflected_paths = HashMap::default(); if design.interfaces.is_empty() { @@ -3280,7 +3289,8 @@ pub fn plan_interfaces_with_member_paths( port.name )) })?; - let expansion = design.expansion(&name, &port.name, interface, &bindings)?; + let expansion = + design.expansion(expansions, &name, &port.name, interface, &bindings)?; let uses = design.module_uses(&name, (&port.name, interface), &bindings)?; let declaration = &design.interfaces[interface]; for (handle, member, _) in &uses.references { @@ -3489,6 +3499,7 @@ pub fn plan_interfaces_with_member_paths( }) .collect::>(); let child_expansion = design.expansion( + expansions, &child_name, &formal, &handle.interface, diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index ef0d91c5afd..64fb2ef8af2 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -37,6 +37,7 @@ enum Entry { /// every static local keeps its value. pub(super) fn keep_static_locals<'b, T>( tree: &AnalysisContext<'_>, + session: &mut Session, statics: &HashMap, directions: &Directions, bodies: impl IntoIterator, bool)>, @@ -50,7 +51,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(tree, statics, explicit, &bodies), + Some(explicit) => initialized_at_time_zero(tree, session, statics, explicit, &bodies), None => HashSet::default(), }; for (body, _) in &mut bodies { @@ -60,6 +61,7 @@ pub(super) fn keep_static_locals<'b, T>( } keep_in( tree, + session, body, statics, &initialized, @@ -86,6 +88,7 @@ pub(super) fn keep_static_locals<'b, T>( /// rejected, like one that reads an automatic variable. fn initialized_at_time_zero( tree: &AnalysisContext<'_>, + session: &mut Session, statics: &HashMap, explicit: &HashSet, bodies: &[(&mut Vec, bool)], @@ -106,19 +109,21 @@ fn initialized_at_time_zero( }); } } - let runtime = |init: &Expr| { - !expr_is_constant(tree, init) && !automatic.iter().any(|name| expr_reads(init, name)) + let runtime = |session: &mut Session, init: &Expr| { + !expr_is_constant(tree, session, init) + && !automatic.iter().any(|name| expr_reads(init, name)) }; let mut pending = initializers .iter() - .filter(|(_, (init, allowed))| *allowed && init.is_some_and(runtime)) + .filter(|(_, (init, allowed))| *allowed && init.is_some_and(|init| runtime(session, init))) .map(|(name, _)| *name) .collect::>(); 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(tree, init) && !(allowed && runtime(init))) - || !initialized.insert(name.to_string()) + if init.is_some_and(|init| { + !expr_is_constant(tree, session, init) && !(allowed && runtime(session, init)) + }) || !initialized.insert(name.to_string()) { continue; } @@ -137,6 +142,7 @@ fn initialized_at_time_zero( #[allow(clippy::too_many_arguments)] fn keep_in( tree: &AnalysisContext<'_>, + session: &mut Session, stmts: &mut Vec, statics: &HashMap, initialized: &HashSet, @@ -156,6 +162,7 @@ fn keep_in( || sampled_reads(&stmts[index + 1..], name) || entry( tree, + session, name, init.as_ref(), &stmts[index + 1..], @@ -184,6 +191,7 @@ fn keep_in( } => { keep_in( tree, + session, then_body, statics, initialized, @@ -194,6 +202,7 @@ fn keep_in( )?; keep_in( tree, + session, else_body, statics, initialized, @@ -207,6 +216,7 @@ fn keep_in( for item in items { keep_in( tree, + session, &mut item.body, statics, initialized, @@ -219,6 +229,7 @@ fn keep_in( if let Some(default) = default { keep_in( tree, + session, default, statics, initialized, @@ -234,6 +245,7 @@ fn keep_in( } => { keep_in( tree, + session, init, statics, initialized, @@ -244,6 +256,7 @@ fn keep_in( )?; keep_in( tree, + session, step, statics, initialized, @@ -254,6 +267,7 @@ fn keep_in( )?; keep_in( tree, + session, body, statics, initialized, @@ -267,6 +281,7 @@ fn keep_in( for branch in branches { keep_in( tree, + session, branch, statics, initialized, @@ -287,6 +302,7 @@ fn keep_in( /// Reject a static local of `subroutine` that keeps its value between calls. pub(super) fn check_subroutine_statics( tree: &AnalysisContext<'_>, + session: &mut Session, subroutine: &Subroutine, constants: &HashMap, locals: &[LocalVariable], @@ -306,6 +322,7 @@ pub(super) fn check_subroutine_statics( { result = entry( tree, + session, name, init.as_ref(), &stmts[index + 1..], @@ -318,6 +335,7 @@ pub(super) fn check_subroutine_statics( if init.is_none() && bit_result::proves_local( tree, + session, name, &stmts[index + 1..], constants, @@ -373,6 +391,7 @@ pub(super) fn check_subroutine_statics( /// that does not assign it returns the result of an earlier call. pub(super) fn check_static_result( tree: &AnalysisContext<'_>, + session: &mut Session, constants: &HashMap, locals: &[LocalVariable], subroutine: &Subroutine, @@ -391,7 +410,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(tree, subroutine, constants, locals) => Ok(()), + _ if bit_result::proves(tree, session, 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`)", @@ -435,6 +454,7 @@ fn source_name(name: &str) -> &str { /// [`entry`] does for a local whose entry value it examines. pub(super) fn check_constant_initializers( tree: &AnalysisContext<'_>, + session: &mut Session, body: &[Stmt], statics: &HashSet, ) -> Result<(), AnalyzerError> { @@ -448,7 +468,7 @@ pub(super) fn check_constant_initializers( && statics.contains(name) && result.is_ok() { - result = constant_initializer(tree, name, init); + result = constant_initializer(tree, session, name, init); } }); } @@ -457,10 +477,11 @@ pub(super) fn check_constant_initializers( fn constant_initializer( tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, init: &Expr, ) -> Result<(), AnalyzerError> { - if expr_is_constant(tree, init) { + if expr_is_constant(tree, session, init) { return Ok(()); } Err(AnalyzerError::Unsupported(format!( @@ -474,6 +495,7 @@ fn constant_initializer( /// read the value it holds on entry. fn entry( tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, init: Option<&Expr>, after: &[Stmt], @@ -483,7 +505,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(tree, name, init)?; + constant_initializer(tree, session, name, init)?; } let flow = Flow { name, @@ -1108,8 +1130,7 @@ 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(tree: &AnalysisContext<'_>, expr: &Expr) -> bool { - let state = &*tree.state; +fn expr_is_constant(tree: &AnalysisContext<'_>, session: &mut Session, expr: &Expr) -> bool { fn constant(expr: &ConstExpr) -> bool { match expr { ConstExpr::Ident(_) | ConstExpr::Function { .. } => false, @@ -1134,8 +1155,8 @@ fn expr_is_constant(tree: &AnalysisContext<'_>, expr: &Expr) -> bool { Expr::Call { args, .. } => { args.iter() .flatten() - .all(|expr| expr_is_constant(tree, expr)) - && expr_to_const(state, expr.clone()) + .all(|expr| expr_is_constant(tree, session, expr)) + && expr_to_const(session, expr.clone()) .and_then(|call| { eval_ast_const_expr(&tree.functions, &call, &HashMap::default()) }) @@ -1143,31 +1164,39 @@ fn expr_is_constant(tree: &AnalysisContext<'_>, expr: &Expr) -> bool { } Expr::Literal(_) => true, Expr::Select { expr, msb, lsb, .. } => { - expr_is_constant(tree, expr) && constant(msb) && constant(lsb) + expr_is_constant(tree, session, expr) && constant(msb) && constant(lsb) } - Expr::Concat(parts) => parts.iter().all(|expr| expr_is_constant(tree, expr)), + Expr::Concat(parts) => parts + .iter() + .all(|expr| expr_is_constant(tree, session, expr)), Expr::RepeatConcat { count, parts } => { - constant(count) && parts.iter().all(|expr| expr_is_constant(tree, expr)) + constant(count) + && parts + .iter() + .all(|expr| expr_is_constant(tree, session, expr)) + } + Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => { + expr_is_constant(tree, session, expr) } - Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => expr_is_constant(tree, expr), Expr::Binary { left, right, .. } => { - expr_is_constant(tree, left) && expr_is_constant(tree, right) + expr_is_constant(tree, session, left) && expr_is_constant(tree, session, right) } Expr::Mux { condition, then_expr, else_expr, } => { - expr_is_constant(tree, condition) - && expr_is_constant(tree, then_expr) - && expr_is_constant(tree, else_expr) + expr_is_constant(tree, session, condition) + && expr_is_constant(tree, session, then_expr) + && expr_is_constant(tree, session, else_expr) } Expr::Inside { expr, items } => { - expr_is_constant(tree, expr) + expr_is_constant(tree, session, expr) && items.iter().all(|item| match item { - InsideItem::Value(value) => expr_is_constant(tree, value), + InsideItem::Value(value) => expr_is_constant(tree, session, value), InsideItem::Range { low, high } => { - expr_is_constant(tree, low) && expr_is_constant(tree, high) + expr_is_constant(tree, session, low) + && expr_is_constant(tree, session, 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 ef6a3e7d59e..4ec92de8653 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes/bit_result.rs @@ -1,5 +1,6 @@ //! Bounded bit coverage for static results and scratch locals filled by constant loops. use super::*; +use crate::ast::Session; use num_bigint::BigUint; const MAX_BITS: usize = 65536; @@ -7,6 +8,7 @@ const MAX_STEPS: usize = 65536; pub(super) fn proves( tree: &AnalysisContext<'_>, + session: &mut Session, subroutine: &Subroutine, constants: &HashMap, locals: &[LocalVariable], @@ -22,11 +24,20 @@ pub(super) fn proves( else { return false; }; - proves_variable(tree, name, width, &subroutine.body, constants, locals) + proves_variable( + tree, + session, + name, + width, + &subroutine.body, + constants, + locals, + ) } pub(super) fn proves_local( tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, body: &[Stmt], constants: &HashMap, @@ -39,11 +50,12 @@ pub(super) fn proves_local( let Some(width) = local.r#type.resolved_width() else { return false; }; - proves_variable(tree, name, width, body, constants, locals) + proves_variable(tree, session, name, width, body, constants, locals) } pub(super) fn proves_variable( tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, width: usize, body: &[Stmt], @@ -85,7 +97,7 @@ pub(super) fn proves_variable( types, remaining: MAX_STEPS, }; - proof.block(body) == Some(true) + proof.block(session, body) == Some(true) } struct Proof<'a> { @@ -104,12 +116,12 @@ impl Proof<'_> { pure(expression) && (self.written == self.full || !expr_reads(expression, self.name)) } - fn value(&self, expression: &Expr) -> Option { + fn value(&self, session: &mut Session, expression: &Expr) -> Option { if !self.readable(expression) { return None; } let dims = PackedDimensions::new(HashMap::default(), &self.env, &HashMap::default()); - let value = expr_to_index_const(self.tree, expression.clone(), &dims)?; + let value = expr_to_index_const(self.tree, session, expression.clone(), &dims)?; eval_ast_const_expr(&self.tree.functions, &value, &self.env) } @@ -135,12 +147,12 @@ impl Proof<'_> { /// `true` means no entry bit can subsequently be observed. Unknown control /// flow or calls give no proof; the ordinary lifetime check requires persistent storage. - fn block(&mut self, statements: &[Stmt]) -> Option { + fn block(&mut self, session: &mut Session, statements: &[Stmt]) -> Option { for statement in statements { self.remaining = self.remaining.checked_sub(1)?; match statement { Stmt::Local { name, init } if name != self.name => { - let value = init.as_ref().and_then(|value| self.value(value)); + let value = init.as_ref().and_then(|value| self.value(session, value)); if let Some(init) = init { if !self.readable(init) { return None; @@ -178,7 +190,7 @@ impl Proof<'_> { } } } else if let LValue::Ident(name) = lhs { - let value = self.value(rhs); + let value = self.value(session, rhs); self.store(name, value)?; } else if let LValue::Select { name, msb, lsb, .. } = lhs { // A partial store loses our numeric value for this @@ -200,12 +212,12 @@ impl Proof<'_> { step, body, } => { - if self.block(init)? { + if self.block(session, init)? { return Some(true); } - while self.value(condition)? != 0 { + while self.value(session, condition)? != 0 { self.remaining = self.remaining.checked_sub(1)?; - if self.block(body)? || self.block(step)? { + if self.block(session, body)? || self.block(session, step)? { return Some(true); } } @@ -215,12 +227,12 @@ impl Proof<'_> { then_body, else_body, } => { - let branch = if self.value(condition)? != 0 { + let branch = if self.value(session, condition)? != 0 { then_body } else { else_body }; - if self.block(branch)? { + if self.block(session, branch)? { return Some(true); } } @@ -277,6 +289,7 @@ fn pure(expression: &Expr) -> bool { #[cfg(test)] mod tests { + #[test] fn incomplete_or_entry_dependent_scratch_arrays_retain_storage() { for body in [ diff --git a/crates/celox-sv-analyzer/src/ast/locators.rs b/crates/celox-sv-analyzer/src/ast/locators.rs index d4cceb302c1..29dec868117 100644 --- a/crates/celox-sv-analyzer/src/ast/locators.rs +++ b/crates/celox-sv-analyzer/src/ast/locators.rs @@ -180,6 +180,7 @@ fn parse( id: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { let (method_call, predicate) = match &native.expression(id).kind { @@ -211,7 +212,7 @@ fn parse( if separator != "." { return Ok(None); } - let Some(array) = array(*base, native, tree, dims)? else { + let Some(array) = array(*base, native, tree, session, dims)? else { return Ok(None); }; // `a.min()` lists one empty argument. @@ -264,9 +265,10 @@ fn array( base: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { - if let Some(container) = containers::native_type(base, native, tree, dims)? { + if let Some(container) = containers::native_type(base, native, tree, session, dims)? { if matches!(container.layout.kind, ContainerKind::Associative { .. }) && container.key.is_none() { @@ -357,9 +359,10 @@ pub(super) fn result_type( id: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted>> { - let Some(call) = parse(id, native, tree, dims)? else { + let Some(call) = parse(id, native, tree, session, dims)? else { return Ok(None); }; let record = match &call.array { @@ -383,9 +386,10 @@ pub(super) fn bind( id: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { - let Some(call) = parse(id, native, tree, dims)? else { + let Some(call) = parse(id, native, tree, session, dims)? else { return Ok(None); }; let sink = dims @@ -461,7 +465,7 @@ pub(super) fn bind( scope .expression_signedness .insert(index.clone(), index_type.is_signed()); - let mut value = expression_binding::value(predicate, native, tree, &scope)?; + let mut value = expression_binding::value(predicate, native, tree, session, &scope)?; let key = if call.method.finds() { None } else if expression_binding::string_value(&value, &scope) { @@ -527,7 +531,7 @@ pub(super) fn bind( let (source, array) = match &call.array { Array::Container(container) => ( LocatorSource::Container(container.layout), - expression_binding::value(call.base, native, tree, dims)?, + expression_binding::value(call.base, native, tree, session, dims)?, ), Array::Fixed { left, right, .. } => { let ExprKind::Name(name) = &native @@ -591,6 +595,7 @@ pub(super) fn index( id: ExprId, native: &Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { if dims.locator_iterators.is_empty() { @@ -640,9 +645,11 @@ 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.functions, &value, &dims.const_env) - }), + Some(value) => { + constant_binding::bind(value, tree, session, 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 c8b1948d2f9..5ce21117aaa 100644 --- a/crates/celox-sv-analyzer/src/ast/mailboxes.rs +++ b/crates/celox-sv-analyzer/src/ast/mailboxes.rs @@ -128,12 +128,13 @@ impl Message { pub(super) fn named_type( path: &[TypeSegment], tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted>> { let segment = match path { [segment] if segment.name.spelling == "mailbox" - && classes::resolve(tree, "mailbox").is_none() => + && classes::resolve(tree, session, "mailbox").is_none() => { segment } @@ -150,7 +151,8 @@ pub(super) fn named_type( }; let argument = argument.ok_or_else(|| unsupported("mailbox message type"))?; // The type may name a constant that `context` does not know yet. - let Some(message) = classes::specializations::type_argument(tree, argument, context)? else { + let Some(message) = classes::specializations::type_argument(tree, session, argument, context)? + else { return Ok(None); }; let name = Message::of(&tree.functions, &message, &context.const_env)?.class_name(&message); @@ -160,6 +162,7 @@ pub(super) fn named_type( /// `new(bound)` of mailbox class `class` (15.4.1). pub(super) fn new( tree: &AnalysisContext<'_>, + session: &mut Session, arguments: &[Argument], native: &Declarations, dimensions: &PackedDimensions, @@ -180,7 +183,7 @@ pub(super) fn new( .is_none_or(|name| name.spelling == "bound") => { match argument.value { - Some(value) => expression_binding::value(value, native, tree, dimensions)?, + Some(value) => expression_binding::value(value, native, tree, session, dimensions)?, None => Expr::Literal("32'sd0".into()), } } @@ -196,6 +199,7 @@ pub(super) fn new( /// the methods that are functions, as a value. pub(super) fn value( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -220,8 +224,9 @@ pub(super) fn value( if separator != "." { return Ok(None); } - let Some(class) = expression_binding::object_native_class(tree, *receiver, native, dimensions) - .filter(|class| is_class(class)) + let Some(class) = + expression_binding::object_native_class(tree, session, *receiver, native, dimensions) + .filter(|class| is_class(class)) else { return Ok(None); }; @@ -252,7 +257,7 @@ pub(super) fn value( [argument] if argument.name.is_none() && argument.value.is_none() => &[], arguments => arguments, }; - let mailbox = expression_binding::value(*receiver, native, tree, dimensions)?; + let mailbox = expression_binding::value(*receiver, native, tree, session, dimensions)?; if op == ProcessOp::MailboxNum { if !arguments.is_empty() { return Err(unsupported("arguments of mailbox num")); @@ -271,37 +276,41 @@ pub(super) fn value( return Err(unsupported(format!("arguments of mailbox {method}"))); }; // A message has the type of the mailbox (15.4.9). - let class_matches = - |id| expression_binding::object_native_class(tree, id, native, dimensions) == message.class; - let string = expression_binding::native_string(tree, argument, native, dimensions); + let class_matches = |session: &mut Session, id| { + expression_binding::object_native_class(tree, session, id, native, dimensions) + == message.class + }; + let string = expression_binding::native_string(tree, session, argument, native, dimensions); let message_value = if matches!(op, ProcessOp::MailboxPut | ProcessOp::MailboxTryPut) { match message.handle { Some(HandleProperty::Object) => { let class = message.class.as_deref().unwrap_or_default(); if let Some(call) = expression_binding::object_constructor( - tree, argument, native, dimensions, class, + tree, session, argument, native, dimensions, class, )? { call } else { expression_binding::check_handle_assignment( tree, + session, argument, native, dimensions, class, || "mailbox message".to_owned(), )?; - expression_binding::value(argument, native, tree, dimensions)? + expression_binding::value(argument, native, tree, session, dimensions)? } } Some(HandleProperty::String) => { - let value = expression_binding::value(argument, native, tree, dimensions)?; + let value = expression_binding::value(argument, native, tree, session, dimensions)?; expression_binding::string_operand(value, dimensions) } None => { if let Some(class) = &message.class { expression_binding::check_handle_assignment( tree, + session, argument, native, dimensions, @@ -310,7 +319,7 @@ pub(super) fn value( )?; } // The lowering converts it to the message type. - expression_binding::value(argument, native, tree, dimensions)? + expression_binding::value(argument, native, tree, session, dimensions)? } } } else { @@ -318,12 +327,14 @@ pub(super) fn value( Some(HandleProperty::String) => string, // A process or event message has its built-in class. Some(HandleProperty::Object) | None if message.class.is_some() => { - class_matches(argument) + class_matches(session, argument) } _ => { !string - && expression_binding::object_native_class(tree, argument, native, dimensions) - .is_none() + && expression_binding::object_native_class( + tree, session, argument, native, dimensions, + ) + .is_none() } }; if !compatible { @@ -331,7 +342,7 @@ pub(super) fn value( "mailbox {method} into a variable of another type than its messages" ))); } - expression_binding::value(argument, native, tree, dimensions)? + expression_binding::value(argument, native, tree, session, dimensions)? }; // The lowering takes the message shape from the layout, which it does // not pass on to the scheduler, and copies a message out as a value of diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index 97ce42acf11..59a21d804a6 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -23,9 +23,9 @@ use super::*; /// The analyzed packages of a design. #[derive(Debug, Clone, Default)] pub struct Packages { - pub(super) foreign: std::rc::Rc, - /// Source-call identities shared with modules importing these package bodies. - pub(super) call_sites: std::rc::Rc>, + /// What analyzing the packages made that modules analyzed with them + /// continue from. + design: Design, pub(crate) interface_plan: Arc, /// All interface declaration names, including unsupported non-ANSI bodies. /// Namespace validation must not depend on sources selected for binding. @@ -42,9 +42,18 @@ pub struct Packages { /// The virtual interfaces of the design, which the modules that use the /// packages are analyzed with. pub(crate) virtual_interfaces: Option>, - /// The semantic types of the design, which every scope analyzed with - /// the packages shares. - pub(super) types: std::rc::Rc, +} + +/// What the analyses of the modules of a design add to the packages they +/// use: the specializations of package class templates the modules request, +/// the semantic types of the design and its call sites. Each analysis takes +/// it as `&mut`, starting from [`Packages::design`]. +#[derive(Clone, Debug, Default)] +pub struct Design { + pub(super) foreign: classes::foreign::Registry, + /// Source-call identities shared with modules importing these package bodies. + pub(super) call_sites: usize, + pub(super) types: semantic_types::TyTable, } /// The compilation-unit scope of a source file. @@ -198,8 +207,14 @@ impl Packages { } /// Package state after specialization requests made by importing scopes. - pub fn specialized_state_modules(&self) -> Vec { - let specialized = self.foreign.states(); + /// The state of the design that analyzing the packages left, which the + /// analyses of its modules continue. + pub fn design(&self) -> Design { + self.design.clone() + } + + pub fn specialized_state_modules(&self, design: &Design) -> Vec { + let specialized = design.foreign.states(); // Different compilation units may each have a state module named // `$unit`; preserve every one rather than indexing them by name. let mut states = self @@ -207,7 +222,7 @@ impl Packages { .filter(|module| !specialized.contains_key(module.name())) .cloned() .collect::>(); - states.extend(specialized.into_values()); + states.extend(specialized.values().cloned()); states.sort_by(|left, right| { left.name().cmp(right.name()).then_with(|| { left.signals() @@ -282,21 +297,17 @@ impl Packages { } let mixed_timescales = timescales.has_mixed_timescales(); let timescales = Arc::new(timescales); - let state = std::rc::Rc::new(AnalysisState { + let session = &mut Session { virtual_interfaces: options.virtual_interfaces.clone(), - ..AnalysisState::default() - }); - state - .foreign - .set_virtual_interfaces(options.virtual_interfaces.clone()); - let mut packages = Self::analyze_packages(trees, timescales, &state)?; + ..Session::default() + }; + let mut packages = Self::analyze_packages(trees, timescales, session)?; packages.virtual_interfaces = options.virtual_interfaces; if mixed_timescales { packages .warnings .push(super::warnings::AnalyzerWarning::MixedTimescale); } - packages.call_sites = state.next_call_site.clone(); let units: Vec<_> = trees .iter() .map(|(tree, path)| (tree.compilation_scope(), *path)) @@ -308,12 +319,12 @@ impl Packages { let visibility = unit_visibility(tree)?; // The classes of each compilation unit are its own, though those // of two sources may share a name. - state.classes.borrow_mut().clear(); - state.class_specializations.borrow_mut().clear(); - state.class_specialization_names.borrow_mut().clear(); - state.class_declaration_scopes.borrow_mut().clear(); - state.class_declarations_repeated.borrow_mut().clear(); - let scope = analyze_package(UNIT, tree, &packages, &state); + session.classes.clear(); + session.class_specializations.clear(); + session.class_specialization_names.clear(); + session.class_declaration_scopes.clear(); + session.class_declarations_repeated.clear(); + let scope = analyze_package(UNIT, tree, &packages, session); if scope .as_ref() .is_ok_and(|scope| scope.state_module.is_some()) @@ -339,13 +350,20 @@ impl Packages { .units .insert(path.to_path_buf(), Arc::new(Unit { visibility, scope })); } + // Modules analyzed with the packages start from what analyzing + // them made. + packages.design = Design { + call_sites: session.next_call_site, + foreign: std::mem::take(&mut session.foreign), + types: std::mem::take(&mut session.types), + }; Ok(packages) } fn analyze_packages( trees: &[(&SyntaxTree, &Path)], timescales: Arc, - state: &std::rc::Rc, + session: &mut Session, ) -> Result { let mut declarations: Vec<(String, SyntaxTree)> = Vec::new(); for (tree, _) in trees { @@ -382,8 +400,6 @@ impl Packages { } if declarations.is_empty() { return Ok(Self { - foreign: state.foreign.clone(), - types: state.types.clone(), timescales, ..Self::default() }); @@ -410,14 +426,12 @@ impl Packages { // Package bodies can query selected hierarchy roots while they are // collected, before any module is analyzed. let mut packages = Self { - foreign: state.foreign.clone(), - types: state.types.clone(), timescales, ..Self::default() }; for index in order { let (name, tree) = &declarations[index]; - let package = analyze_package(name, tree, &packages, state)?; + let package = analyze_package(name, tree, &packages, session)?; packages.packages.insert( name.clone(), Arc::new(Package { @@ -510,11 +524,10 @@ fn analyze_package( name: &str, tree: &SyntaxTree, packages: &Packages, - state: &std::rc::Rc, + session: &mut Session, ) -> Result { let context = AnalysisContext { syntax_tree: tree, - state: state.clone(), parameter_overrides: Cow::Owned(HashMap::default()), imported: Arc::default(), package: None, @@ -532,7 +545,7 @@ fn analyze_package( 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)? + analyze_package_scope(name, &tree.in_package(name), session, packages, None)? }; if !imports::ScopeImports::from_scope(tree)? .qualified @@ -544,12 +557,13 @@ fn analyze_package( // A self-qualified reference `p::x` is not hidden by a local `x` of a // function (IEEE 1800-2023 26.3). Analyze the package again with its // items from the first analysis under their qualified names. - analyze_package_scope(name, tree, packages, Some(&first.symbols)) + analyze_package_scope(name, tree, session, packages, Some(&first.symbols)) } fn analyze_package_scope( name: &str, tree: &AnalysisContext<'_>, + session: &mut Session, packages: &Packages, own_items: Option<&ScopeSymbols>, ) -> Result { @@ -558,20 +572,20 @@ fn analyze_package_scope( exports, } = imports::resolve_imports(tree, packages, None)?; if own_items.is_none() && name != UNIT { - tree.state.foreign.register( + session.foreign.register( name, tree.syntax_tree, &imported, - tree.state.next_call_site.clone(), packages.timescales.clone(), ); } - analyze_package_with_symbols(name, tree, imported, exports, own_items) + analyze_package_with_symbols(name, tree, session, imported, exports, own_items) } pub(super) fn analyze_package_with_symbols( name: &str, tree: &AnalysisContext<'_>, + session: &mut Session, mut imported: ScopeSymbols, exports: HashMap, own_items: Option<&ScopeSymbols>, @@ -587,6 +601,7 @@ pub(super) fn analyze_package_with_symbols( let mut variables = package_variables(name, tree)?; let mut module = Module::from_scope_with_parameter_overrides( tree, + session, "", &HashMap::default(), &InterfaceLookup { 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 f6dc84b895e..abba48af04e 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/tagged.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/tagged.rs @@ -37,6 +37,7 @@ pub(in crate::ast) fn construction_member( pub(in crate::ast) fn construct( tree: &AnalysisContext<'_>, + session: &mut Session, plan: Construction, value: Option, dims: &PackedDimensions, @@ -64,7 +65,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( - tree, &value, signed, None, &shape, dims, false, + tree, session, &value, signed, None, &shape, dims, false, )?); } (None, None) => {} diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs index 5611d331d71..9c8c542e039 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/tests.rs @@ -204,7 +204,7 @@ fn rejects_empty_tagged_union_without_panicking() { assert!( analyze_source( "module Top; union tagged packed {} item; endmodule", - Path::new("empty_tagged.sv") + Path::new("empty_tagged.sv"), ) .is_err() ); diff --git a/crates/celox-sv-analyzer/src/ast/parameters.rs b/crates/celox-sv-analyzer/src/ast/parameters.rs index b1ceced0dbf..588df4d2d23 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters.rs @@ -143,6 +143,7 @@ pub(super) fn const_expr_from_i128(value: i128) -> ConstExpr { pub(super) fn parameters_from_native( authored: &[&celox_sv_syntax::Parameter], syntax_tree: &AnalysisContext<'_>, + session: &mut Session, parameters: &mut Vec, is_local: bool, base_const_env: &HashMap, @@ -151,6 +152,7 @@ pub(super) fn parameters_from_native( ) -> Result<(), AnalyzerError> { let mut environment = ParameterEnvironment::new( syntax_tree, + session, parameters, base_const_env, &authored @@ -161,6 +163,7 @@ pub(super) fn parameters_from_native( parameters_from_native_with_environment( authored, syntax_tree, + session, parameters, is_local, base_const_env, @@ -193,6 +196,7 @@ pub(super) struct ParameterEnvironment<'a> { impl<'a> ParameterEnvironment<'a> { pub(super) fn new( tree: &AnalysisContext<'_>, + session: &mut Session, parameters: &[Parameter], base: &'a HashMap, shadowed: &[String], @@ -225,7 +229,14 @@ impl<'a> ParameterEnvironment<'a> { .map(|(name, value)| (name.clone(), value.clone())) .collect(); for parameter in parameters { - bind_parameter(tree, &mut bindings, &mut types, &mut literals, parameter); + bind_parameter( + tree, + session, + &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); @@ -253,9 +264,10 @@ impl<'a> ParameterEnvironment<'a> { } } - fn append(&mut self, tree: &AnalysisContext<'_>, parameter: &Parameter) { + fn append(&mut self, tree: &AnalysisContext<'_>, session: &mut Session, parameter: &Parameter) { let bound = bind_parameter( tree, + session, &mut self.bindings, &mut self.types, &mut self.literals, @@ -334,6 +346,7 @@ impl<'a> ParameterEnvironment<'a> { pub(super) fn parameters_from_native_with_environment( authored: &[&celox_sv_syntax::Parameter], syntax_tree: &AnalysisContext<'_>, + session: &mut Session, parameters: &mut Vec, is_local: bool, base_const_env: &HashMap, @@ -351,6 +364,7 @@ pub(super) fn parameters_from_native_with_environment( let parameter_width = parameter_declared_width( authored, syntax_tree, + session, base_const_env, environment, type_aliases, @@ -370,7 +384,8 @@ pub(super) fn parameters_from_native_with_environment( .unwrap_or_else(|| native_prefix.signed()) }); let parameter_signed_element_depth = native_prefix.signed_element_depth(); - let parameter_ranges = native_prefix.ranges(syntax_tree, base_const_env, type_aliases)?; + let parameter_ranges = + native_prefix.ranges(syntax_tree, session, base_const_env, type_aliases)?; let simple_bit_vector = parameter_ranges.len() <= 1 && declared_alias .as_ref() @@ -391,6 +406,7 @@ pub(super) fn parameters_from_native_with_environment( if array_parameters::uses_signal_representation( native, syntax_tree, + session, &environment.constants, type_aliases, )? || scope::imported(syntax_tree) @@ -442,6 +458,7 @@ pub(super) fn parameters_from_native_with_environment( .parameter_values .extend(parameter_value_env_filtered( syntax_tree, + session, parameters, const_env, Some(&resolved_numeric), @@ -457,6 +474,7 @@ pub(super) fn parameters_from_native_with_environment( AnalyzerError::Parse("native parameter default is missing".into()) })?, syntax_tree, + session, &proof_context, )? { Some(value) @@ -475,6 +493,7 @@ pub(super) fn parameters_from_native_with_environment( ); dimensions.parameter_values = parameter_value_env_with_imported( syntax_tree, + session, parameters, const_env, &imported, @@ -488,6 +507,7 @@ pub(super) fn parameters_from_native_with_environment( AnalyzerError::Parse("native parameter default is missing".into()) })?, syntax_tree, + session, &dimensions, parameter_width, ) { @@ -504,6 +524,7 @@ pub(super) fn parameters_from_native_with_environment( AnalyzerError::Parse("native parameter default is missing".into()) })?, syntax_tree, + session, &proof_context, )? } @@ -536,7 +557,7 @@ pub(super) fn parameters_from_native_with_environment( &environment.literals, ); if !matches!( - fold_const_integral_expr_preserving_mask(syntax_tree, lowered, const_env), + fold_const_integral_expr_preserving_mask(syntax_tree, session, lowered, const_env), Expr::Literal(_) ) { return Err(AnalyzerError::Unsupported(format!( @@ -567,7 +588,7 @@ pub(super) fn parameters_from_native_with_environment( const_expr_to_expr(parameter.value()?.clone()), &environment.literals, ); - let expr = expr_to_const(&syntax_tree.state, expanded)?; + let expr = expr_to_const(session, expanded)?; typecheck::const_expr_has_real_type(&expr.into()).then_some(TypeKind::Real) }); parameter.packed_ranges = parameter_ranges.clone(); @@ -582,7 +603,7 @@ pub(super) fn parameters_from_native_with_environment( .resolved_type(&environment.types) .map(|ty| ty.width), )?; - environment.append(syntax_tree, ¶meter); + environment.append(syntax_tree, session, ¶meter); parameters.push(parameter); } Ok(()) @@ -603,6 +624,7 @@ fn validate_parameter_materialization_width(width: Option) -> Result<(), fn parameter_declared_width( authored: &[&celox_sv_syntax::Parameter], syntax_tree: &AnalysisContext<'_>, + session: &mut Session, base_const_env: &HashMap, environment: &ParameterEnvironment<'_>, type_aliases: &HashMap, @@ -620,6 +642,7 @@ fn parameter_declared_width( if std::ptr::eq(environment.base, base_const_env) && !environment.has_inherited_literal_shadow { return parameter_width_from_environments( syntax_tree, + session, type_aliases, &environment.constants, &environment.constants, @@ -644,6 +667,7 @@ fn parameter_declared_width( ownership::default(native)?, syntax_tree.declarations(), syntax_tree, + session, &range_env, type_aliases, ) @@ -670,18 +694,19 @@ fn parameter_declared_width( .iter() .map(|(name, value)| (name.clone(), *value)), ); - parameter_width_from_environments(syntax_tree, type_aliases, &range_env, &env, native) + parameter_width_from_environments(syntax_tree, session, type_aliases, &range_env, &env, native) } fn parameter_width_from_environments( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, type_aliases: &HashMap, range_env: &HashMap, env: &HashMap, native: &declaration_types::Prefix<'_>, ) -> Converted> { let prefix = native; - let ranges = prefix.ranges(syntax_tree, range_env, type_aliases)?; + let ranges = prefix.ranges(syntax_tree, session, range_env, type_aliases)?; if ranges.is_empty() { return Ok(if prefix.alias.is_some() { Some(1) @@ -741,27 +766,37 @@ fn normalize_unbased_unsized_parameter_value( pub(super) fn const_env_from_parameters( tree: &AnalysisContext<'_>, + session: &mut Session, parameters: &[Parameter], ) -> HashMap { let mut env = HashMap::default(); - extend_const_env_with_parameters(tree, &mut env, parameters); + extend_const_env_with_parameters(tree, session, &mut env, parameters); env } pub(super) fn extend_const_env_with_parameters( tree: &AnalysisContext<'_>, + session: &mut Session, 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(tree, env, &mut parameter_types, &mut literals, parameter); + bind_parameter( + tree, + session, + env, + &mut parameter_types, + &mut literals, + parameter, + ); } } pub(super) fn bind_parameter( tree: &AnalysisContext<'_>, + session: &mut Session, env: &mut HashMap, types: &mut HashMap, literals: &mut HashMap, @@ -802,7 +837,8 @@ pub(super) fn bind_parameter( insert_parameter_dimension_markers(functions, env, parameter); return true; } - let (value, literal) = parameter.resolved_value_and_literal(tree, env, types, literals); + let (value, literal) = + parameter.resolved_value_and_literal(tree, session, env, types, literals); if value.is_none() && literal.is_none() { return false; } @@ -985,6 +1021,7 @@ pub(super) fn enum_initializer_fits_base_type( /// implicit successors and type coercion retain the existing semantic kernel. pub(super) fn enum_member_constants_from_scope( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, base_const_env: &HashMap, type_aliases: &HashMap, parameter_overrides: &HashMap, @@ -992,6 +1029,7 @@ pub(super) fn enum_member_constants_from_scope( let items = syntax_tree.body_membership()?; enum_member_constants_from_items( syntax_tree, + session, &items, base_const_env, type_aliases, @@ -1001,6 +1039,7 @@ pub(super) fn enum_member_constants_from_scope( pub(super) fn enum_member_constants_from_items( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, declarations: &[celox_sv_syntax::BodyItemId], base_const_env: &HashMap, type_aliases: &HashMap, @@ -1032,6 +1071,7 @@ pub(super) fn enum_member_constants_from_items( parameters_from_native( &authored, syntax_tree, + session, &mut parameters, local, &eval_env, @@ -1042,9 +1082,10 @@ pub(super) fn enum_member_constants_from_items( parameter_overrides }, )?; - extend_const_env_with_parameters(syntax_tree, &mut eval_env, ¶meters); + extend_const_env_with_parameters(syntax_tree, session, &mut eval_env, ¶meters); resolved_type_aliases = types::type_aliases_from_body_with_env( syntax_tree, + session, declarations, &eval_env, &resolved_type_aliases, @@ -1061,6 +1102,7 @@ pub(super) fn enum_member_constants_from_items( Some(id) => type_binding::enum_constant_base( *id, syntax_tree, + session, &eval_env, &resolved_type_aliases, )?, @@ -1071,6 +1113,7 @@ pub(super) fn enum_member_constants_from_items( id, native, syntax_tree, + session, &PackedDimensions::new(HashMap::default(), &eval_env, &resolved_type_aliases), &member_base, )?; @@ -1087,6 +1130,7 @@ pub(super) fn enum_member_constants_from_items( id, syntax_tree.declarations(), syntax_tree, + session, &eval_env, &resolved_type_aliases, )? @@ -1144,6 +1188,7 @@ pub(super) fn enum_member_constants_from_items( // before resolving a subsequent enum base through that typedef. resolved_type_aliases = types::type_aliases_from_body_with_env( syntax_tree, + session, declarations, &eval_env, &resolved_type_aliases, @@ -1154,16 +1199,18 @@ pub(super) fn enum_member_constants_from_items( pub(super) fn parameter_value_env( tree: &AnalysisContext<'_>, + session: &mut Session, parameters: &[Parameter], const_env: &HashMap, ) -> HashMap { - parameter_value_env_filtered(tree, parameters, const_env, None) + parameter_value_env_filtered(tree, session, 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( tree: &AnalysisContext<'_>, + session: &mut Session, parameters: &[Parameter], const_env: &HashMap, references: &HashSet, @@ -1177,7 +1224,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(tree, parameters, const_env, Some(&needed)); + return parameter_value_env_filtered(tree, session, 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 +1280,12 @@ pub(super) fn parameter_value_env_for_references( } } } - parameter_value_env_filtered(tree, parameters, const_env, Some(&needed)) + parameter_value_env_filtered(tree, session, parameters, const_env, Some(&needed)) } fn parameter_value_env_filtered( tree: &AnalysisContext<'_>, + session: &mut Session, parameters: &[Parameter], const_env: &HashMap, needed: Option<&HashSet>, @@ -1309,6 +1357,7 @@ fn parameter_value_env_filtered( let value = replace_oob_const_selects_with_unknown(tree, value, const_env); let value = substitute_expr_constants_with_parameter_literals( tree, + session, const_expr_to_expr(value), const_env, &values, @@ -1349,7 +1398,7 @@ fn parameter_value_env_filtered( expr: Box::new(value), }; } - value = fold_const_integral_expr_preserving_mask(tree, value, const_env); + value = fold_const_integral_expr_preserving_mask(tree, session, value, const_env); values.insert(parameter.name().to_string(), value); } values @@ -1863,7 +1912,7 @@ pub(super) fn real_literal( literals: &HashMap, ) -> Option { let expanded = substitute_expr_idents(const_expr_to_expr(expr.clone()), literals); - let expr = expr_to_const(&AnalysisState::default(), expanded)?; + let expr = expr_to_const(&mut Session::default(), expanded)?; let value = typecheck::eval_real_const_expr(&expr.into(), constants)?; let value = if kind == TypeKind::Shortreal { f64::from(value as f32) 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 498cfd89521..5ee5ed7b395 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs @@ -90,11 +90,17 @@ impl Prefix<'_> { pub fn ranges( &self, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Converted> { - let mut ranges = - constant_binding::packed_ranges(&self.data.packed_dimensions, tree, env, aliases)?; + let mut ranges = constant_binding::packed_ranges( + &self.data.packed_dimensions, + tree, + session, + env, + aliases, + )?; if let Some(base) = self.alias.as_ref().or(self.primitive.as_ref()) { ranges.extend(base.packed_ranges.iter().cloned()); } diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index 236bf97ac6a..b7a5b7745d0 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -3,8 +3,13 @@ use super::*; use celox_sv_syntax::{DimensionKind, ExprId, ExprKind}; -fn integer(root: ExprId, tree: &AnalysisContext<'_>, dims: &PackedDimensions) -> Converted { - constant_binding::bind(root, tree, dims)? +fn integer( + root: ExprId, + tree: &AnalysisContext<'_>, + session: &mut Session, + dims: &PackedDimensions, +) -> Converted { + constant_binding::bind(root, tree, session, dims)? .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")) } @@ -13,9 +18,10 @@ fn bound( root: ExprId, unknown: bool, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted<()> { - let value = constant_binding::bind(root, tree, dims)? + let value = constant_binding::bind(root, tree, session, dims)? .ok_or_else(|| unsupported("parameter selection bound that is not constant"))?; if eval_ast_const_expr(&tree.functions, &value, &dims.const_env).is_none() && !(unknown && selects::const_index_has_unknown_value(&value, dims)) @@ -31,26 +37,27 @@ fn dimension( kind: &DimensionKind, stream: bool, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted<()> { match kind { - DimensionKind::Index(index) => bound(*index, !stream, tree, dims), + DimensionKind::Index(index) => bound(*index, !stream, tree, session, dims), DimensionKind::Range { left, right } => { - bound(*left, false, tree, dims)?; - bound(*right, false, tree, dims) + bound(*left, false, tree, session, dims)?; + bound(*right, false, tree, session, dims) } DimensionKind::Indexed { base, width, operator, } => { - bound(*base, !stream, tree, dims)?; - let width = integer(*width, tree, dims)?; + bound(*base, !stream, tree, session, dims)?; + let width = integer(*width, tree, session, dims)?; if width <= 0 { return Err(unsupported("indexed selection width must be positive")); } if stream { - let start = integer(*base, tree, dims)?; + let start = integer(*base, tree, session, dims)?; let end = if operator == "+:" { start.checked_add(width - 1) } else { @@ -109,12 +116,13 @@ fn value_name( pub(in crate::ast) fn validate( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, unavailable: &HashSet, names: bool, ) -> Converted<()> { let native = tree.declarations(); - let mut context = dimensions::query_context_for_operand(root, tree, dims)?; + let mut context = dimensions::query_context_for_operand(root, tree, session, dims)?; context.constant_indexed_base = true; let dims = &context; // Receiving shapes propagate only through groups, casts and function actuals. @@ -226,7 +234,7 @@ pub(in crate::ast) fn validate( expression, dimension: selection, } => { - dimension(&selection.kind, false, tree, dims)?; + dimension(&selection.kind, false, tree, session, dims)?; // Named aggregate selectors need declared rank/member checks. A // concatenation's huge payload remains unevaluated. let mut base = *expression; @@ -239,7 +247,7 @@ pub(in crate::ast) fn validate( } } if matches!(native.expression(base).kind, ExprKind::Name(_)) { - dimensions::operand_shape(id, tree, dims)? + dimensions::operand_shape(id, tree, session, dims)? .ok_or_else(|| unsupported("parameter selection shape"))?; } push(&mut jobs, *expression); @@ -249,8 +257,8 @@ pub(in crate::ast) fn validate( expression, dimension: selection, } => { - dimension(&selection.kind, true, tree, dims)?; - let shape = dimensions::operand_shape(*expression, tree, dims)? + dimension(&selection.kind, true, tree, session, dims)?; + let shape = dimensions::operand_shape(*expression, tree, session, dims)? .ok_or_else(|| unsupported("streaming with operand shape"))?; if shape.unpacked.len() != 1 { return Err(unsupported( @@ -266,6 +274,7 @@ pub(in crate::ast) fn validate( *expression, native, tree, + session, dims, )?; let shape = @@ -300,7 +309,7 @@ pub(in crate::ast) fn validate( } } ExprKind::Replication { count, expressions } => { - if integer(*count, tree, dims)? < 0 { + if integer(*count, tree, session, dims)? < 0 { return Err(unsupported( "parameter repetition count must be a nonnegative known constant", )); @@ -315,7 +324,7 @@ pub(in crate::ast) fn validate( } => { if let Some(slice) = slice { let valid = if let ExprKind::Type(ty) = native.expression(*slice).kind { - type_binding::bind(ty, tree, dims)? + type_binding::bind(ty, tree, session, dims)? .and_then(|ty| { casts::expr_type_from_type(&tree.functions, &ty, &dims.const_env) }) @@ -328,7 +337,7 @@ pub(in crate::ast) fn validate( 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) + || integer(*slice, tree, session, dims).is_ok_and(|size| size > 0) }; if !valid { return Err(unsupported( @@ -344,7 +353,7 @@ pub(in crate::ast) fn validate( let shape = patterns::typed_shape(id, tree, dims)? .or(receiving) .ok_or_else(|| unsupported("assignment pattern without a target type"))?; - for (value, shape) in pattern_items(id, &shape, tree, dims)? { + for (value, shape) in pattern_items(id, &shape, tree, session, dims)? { jobs.push((value, query, Some(shape))); } } @@ -404,10 +413,11 @@ fn pattern_items( root: ExprId, shape: &VariableDimensions, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { use bound_patterns::{Key, NativeKind}; - let plan = bound_patterns::prepare_native(root, tree, dims, Some(shape))?; + let plan = bound_patterns::prepare_native(root, tree, session, dims, Some(shape))?; let wrong = || unsupported("assignment pattern items do not match the target shape"); if shape.unpacked.is_empty() && shape.packed.len() <= 1 && !shape.members.is_empty() { if shape @@ -579,6 +589,7 @@ fn pattern_items( pub(in crate::ast) fn literal_widths( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { let native = tree.declarations(); @@ -737,8 +748,8 @@ pub(in crate::ast) fn literal_widths( if oversized.is_none() && !replication { return Ok(None); } - let proof = proof(root, tree, dims)?; - if let Some(proof) = expr_to_const(&tree.state, proof) + let proof = proof(root, tree, session, dims)?; + if let Some(proof) = expr_to_const(session, proof) && let Some(ty) = infer_const_expr_type_inner( &proof, ¶meter_types_from_const_env(&dims.const_env), @@ -782,6 +793,7 @@ pub(in crate::ast) fn literal_widths( *expression, native, tree, + session, dims, )?; } @@ -796,7 +808,12 @@ pub(in crate::ast) fn literal_widths( Ok(None) } -fn proof(root: ExprId, tree: &AnalysisContext<'_>, dims: &PackedDimensions) -> Converted { +fn proof( + root: ExprId, + tree: &AnalysisContext<'_>, + session: &mut Session, + dims: &PackedDimensions, +) -> Converted { enum Job { Enter(ExprId), Unary(String), @@ -869,10 +886,10 @@ fn proof(root: ExprId, tree: &AnalysisContext<'_>, dims: &PackedDimensions) -> C values.push(if safe { let mut context = dims.clone(); context.constant_indexed_base = true; - expression_binding::bind(id, tree, &context) + expression_binding::bind(id, tree, session, &context) .ok() .and_then(|value| { - selects::indexed_expression_value(tree, value, &context) + selects::indexed_expression_value(tree, session, value, &context) }) .map(const_expr_to_expr) .unwrap_or_else(unknown) @@ -922,6 +939,7 @@ pub(in crate::ast) fn validate_scope( owner: Option, is_module: bool, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted<()> { use celox_sv_syntax::{BodyItemKind, LocalDeclaration, ParameterKind, StatementKind}; @@ -1049,11 +1067,11 @@ pub(in crate::ast) fn validate_scope( ); } validate_operators(tree, root, native)?; - if literal_widths(root, scope, dimensions)?.is_some() { - validate(root, scope, dimensions, &unavailable, true)?; + if literal_widths(root, scope, session, dimensions)?.is_some() { + validate(root, scope, session, dimensions, &unavailable, true)?; } else if needs_selected(tree, root, native) { - let context = dimensions::query_context_for_operand(root, scope, dimensions)?; - selects::selected_parameter_initializer(root, scope, &context, None)?; + let context = dimensions::query_context_for_operand(root, scope, session, dimensions)?; + selects::selected_parameter_initializer(root, scope, session, &context, None)?; } } Ok(()) @@ -1305,6 +1323,7 @@ mod tests { } #[test] fn skipped_streaming_with_validates_ranges_without_lowering_arrays() { + let session = &mut Session::default(); for (range, valid) in [ ("0", true), ("0:1", true), @@ -1336,6 +1355,7 @@ mod tests { let result = validate( root, &tree, + session, &PackedDimensions::default(), &HashSet::default(), false, @@ -1345,6 +1365,7 @@ mod tests { } #[test] fn skipped_patterns_validate_billion_element_targets_without_expanding_them() { + let session = &mut Session::default(); for (items, valid) in [ ("default:0", true), ("0:1, default:0", true), @@ -1363,6 +1384,7 @@ mod tests { let result = validate( root, &tree, + session, &PackedDimensions::default(), &HashSet::default(), false, @@ -1372,6 +1394,7 @@ mod tests { } #[test] fn native_bounded_proof_retains_precedence_without_parsing_huge_payloads() { + let session = &mut Session::default(); for (value, expected) in [ ("0&&1000000000'd0", 0), ("1||1000000000'bx&&0", 1), @@ -1381,7 +1404,7 @@ mod tests { let tree = AnalysisContext::unspecialized(&tree); let parameter = &tree.declarations().parameter_declarations[0].parameters[0]; let root = ownership::default(parameter).unwrap(); - let value = literal_widths(root, &tree, &PackedDimensions::default()) + let value = literal_widths(root, &tree, session, &PackedDimensions::default()) .unwrap() .unwrap(); assert_eq!( @@ -1392,13 +1415,14 @@ mod tests { } #[test] fn nested_query_type_ranges_keep_materialization_guards() { + let session = &mut Session::default(); let tree = parse( "module M;localparam N=0&&$bits(struct packed{logic[1000000000'd1:0]x;});endmodule", ); let tree = AnalysisContext::unspecialized(&tree); let root = ownership::default(&tree.declarations().parameter_declarations[0].parameters[0]) .unwrap(); - let error = literal_widths(root, &tree, &PackedDimensions::default()).unwrap_err(); + let error = literal_widths(root, &tree, session, &PackedDimensions::default()).unwrap_err(); assert!( error.to_string().contains("constant materialization limit"), "{error}" diff --git a/crates/celox-sv-analyzer/src/ast/parameters/tests.rs b/crates/celox-sv-analyzer/src/ast/parameters/tests.rs index 9fa6207b781..2f9b5fd42fb 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/tests.rs @@ -4,6 +4,7 @@ use super::*; #[test] fn unresolved_local_parameter_masks_imported_bindings() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( "module C #(parameter logic [7:0] W, parameter N = W[3:0]); endmodule", Path::new("required_local_parameter.sv"), @@ -20,6 +21,7 @@ fn unresolved_local_parameter_masks_imported_bindings() { let tree = tree.importing(Arc::new(imported.clone())); let parameters = parameters_from_scope( &tree, + session, &HashMap::default(), &imported.const_env, &HashMap::default(), @@ -30,24 +32,36 @@ fn unresolved_local_parameter_masks_imported_bindings() { parameters[1].value().is_none(), "required W must not use an imported default" ); - let values = - parameter_value_env_with_imported(&tree, ¶meters, &imported.const_env, &imported); + let values = parameter_value_env_with_imported( + &tree, + session, + ¶meters, + &imported.const_env, + &imported, + ); assert!(!values.contains_key("W")); let mut numeric = imported.const_env.clone(); - extend_const_env_with_parameters(&tree, &mut numeric, ¶meters); + extend_const_env_with_parameters(&tree, session, &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(&tree, &specialized); + let specialized = parameters_from_scope( + &tree, + session, + &HashMap::default(), + &imported.const_env, + &overrides, + ) + .unwrap(); + let values = const_env_from_parameters(&tree, session, &specialized); assert_eq!(values["W"], 21); assert_eq!(values["N"], 5); } #[test] fn short_circuit_proof_does_not_inherit_a_required_parameter_literal() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( "module C #(parameter logic FLAG, parameter N = FLAG && 1000000000'd0); endmodule", Path::new("required_short_circuit_flag.sv"), @@ -63,6 +77,7 @@ fn short_circuit_proof_does_not_inherit_a_required_parameter_literal() { let tree = tree.importing(Arc::new(imported)); let error = parameters_from_scope( &tree, + session, &HashMap::default(), &HashMap::default(), &HashMap::default(), @@ -167,6 +182,7 @@ fn typed_constant_lookup_matches_full_tables_and_visits_only_referenced_names() #[test] fn incremental_collection_binds_each_prefix_entry_once() { + let session = &mut Session::default(); let mut code = String::from("module Top;\n"); for i in 0..128 { let value = if i == 0 { @@ -183,6 +199,7 @@ fn incremental_collection_binds_each_prefix_entry_once() { PARAMETER_BINDINGS.with(|count| count.set(0)); let parameters = parameters_from_scope( &tree, + session, &HashMap::default(), &HashMap::default(), &HashMap::default(), @@ -190,10 +207,14 @@ 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(&tree, ¶meters)["P127"], 128); + assert_eq!( + const_env_from_parameters(&tree, session, ¶meters)["P127"], + 128 + ); PARAMETER_BINDINGS.with(|count| count.set(0)); let enums = enum_member_constants_from_scope( &tree, + session, &HashMap::default(), &HashMap::default(), &HashMap::default(), @@ -205,6 +226,7 @@ fn incremental_collection_binds_each_prefix_entry_once() { #[test] fn incremental_prefix_matches_rebuilding_with_inherited_values_and_overrides() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( r#" module Top; @@ -234,10 +256,11 @@ fn incremental_prefix_matches_rebuilding_with_inherited_values_and_overrides() { signed: false, }, ); - let aliases = type_aliases_from_scope_with_env(&tree, &base).unwrap(); + let aliases = type_aliases_from_scope_with_env(&tree, session, &base).unwrap(); for n in [8, 3, 16, 8] { let overrides = HashMap::from_iter([("N".into(), ConstExpr::Literal(n.to_string()))]); - let incremental = parameters_from_scope(&tree, &aliases, &base, &overrides).unwrap(); + let incremental = + parameters_from_scope(&tree, session, &aliases, &base, &overrides).unwrap(); let mut rebuilt = Vec::new(); for id in tree.body_membership().unwrap() { if !matches!( @@ -249,6 +272,7 @@ fn incremental_prefix_matches_rebuilding_with_inherited_values_and_overrides() { parameters_from_native( &ownership::body(id, &tree).unwrap(), &tree, + session, &mut rebuilt, false, &base, @@ -314,6 +338,7 @@ fn parameter_prefix_is_fresh_for_each_specialization() { #[test] fn collects_the_declarations_of_a_package() { + let session = &mut Session::default(); let code = "package p;\n\ localparam int W = 4;\n\ parameter int N = W * 2;\n\ @@ -325,19 +350,21 @@ fn collects_the_declarations_of_a_package() { let tree = AnalysisContext::unspecialized(&tree); let parameters = parameters_from_scope( &tree, + session, &HashMap::default(), &HashMap::default(), &HashMap::default(), ) .unwrap(); - let env = const_env_from_parameters(&tree, ¶meters); + let env = const_env_from_parameters(&tree, session, ¶meters); assert_eq!((env["W"], env["N"]), (4, 8)); - let aliases = type_aliases_from_scope_with_env(&tree, &env).unwrap(); + let aliases = type_aliases_from_scope_with_env(&tree, session, &env).unwrap(); assert_eq!(aliases["word_t"].packed_ranges().len(), 1); let enums = - enum_member_constants_from_scope(&tree, &env, &aliases, &HashMap::default()).unwrap(); + enum_member_constants_from_scope(&tree, session, &env, &aliases, &HashMap::default()) + .unwrap(); assert_eq!((enums.numbers["IDLE"], enums.numbers["RUN"]), (0, 2)); - let items = generate::items(&tree, &env, &aliases).unwrap(); + let items = generate::items(&tree, session, &env, &aliases).unwrap(); assert_eq!(items.len(), 5); let membership = tree.body_membership().unwrap(); assert!(items.iter().all(|item| membership.contains(&item.id))); @@ -345,6 +372,7 @@ fn collects_the_declarations_of_a_package() { #[test] fn numeric_ranged_headers_do_not_copy_the_environment() { + let session = &mut Session::default(); for count in [16, 64, 256] { let mut code = String::from("module Top();\n"); for index in 0..count { @@ -362,6 +390,7 @@ fn numeric_ranged_headers_do_not_copy_the_environment() { DECLARATION_ENV_COPIES.with(|copies| copies.set(0)); let parameters = parameters_from_scope( &tree, + session, &HashMap::default(), &HashMap::default(), &HashMap::default(), @@ -375,7 +404,7 @@ fn numeric_ranged_headers_do_not_copy_the_environment() { .all(|parameter| parameter.declared_width() == Some(32)) ); assert_eq!( - const_env_from_parameters(&tree, ¶meters)[&format!("P{}", count - 1)], + const_env_from_parameters(&tree, session, ¶meters)[&format!("P{}", count - 1)], count as i128 ); } @@ -383,6 +412,7 @@ fn numeric_ranged_headers_do_not_copy_the_environment() { #[test] fn borrowed_range_context_matches_copied_context_with_aliases_and_stale_values() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( "module Top(); parameter N=4; typedef logic signed [3:0] word_t; parameter word_t [N-1:0] A='1; parameter logic [N-1:0] B=A+1; parameter logic [N-1:0] C=LATER+1; parameter LATER=7; endmodule", Path::new("borrowed_ranges.sv"), @@ -390,15 +420,15 @@ fn borrowed_range_context_matches_copied_context_with_aliases_and_stale_values() let tree = AnalysisContext::unspecialized(&tree); let base = HashMap::from_iter([("N".into(), 99), ("LATER".into(), 17)]); let copied_base = base.clone(); - let aliases = type_aliases_from_scope_with_env(&tree, &base).unwrap(); + let aliases = type_aliases_from_scope_with_env(&tree, session, &base).unwrap(); for n in [3, 8, 2, 3] { let overrides = HashMap::from_iter([("N".into(), ConstExpr::Literal(n.to_string()))]); let mut borrowed = Vec::new(); let mut copied = Vec::new(); - let mut borrowed_env = ParameterEnvironment::new(&tree, &borrowed, &base, &[]); + let mut borrowed_env = ParameterEnvironment::new(&tree, session, &borrowed, &base, &[]); // The same contents at a different address deliberately select the // former copy-and-mask path, providing an independent width context. - let mut copied_env = ParameterEnvironment::new(&tree, &copied, &copied_base, &[]); + let mut copied_env = ParameterEnvironment::new(&tree, session, &copied, &copied_base, &[]); DECLARATION_ENV_COPIES.with(|copies| copies.set(0)); for id in tree.body_membership().unwrap() { if !matches!( @@ -410,6 +440,7 @@ fn borrowed_range_context_matches_copied_context_with_aliases_and_stale_values() parameters_from_native_with_environment( &ownership::body(id, &tree).unwrap(), &tree, + session, &mut borrowed, false, &base, @@ -430,6 +461,7 @@ fn borrowed_range_context_matches_copied_context_with_aliases_and_stale_values() parameters_from_native_with_environment( &ownership::body(id, &tree).unwrap(), &tree, + session, &mut copied, false, &base, @@ -446,6 +478,7 @@ fn borrowed_range_context_matches_copied_context_with_aliases_and_stale_values() #[test] fn four_state_prefix_keeps_the_separate_range_projection() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( "module Top(); localparam logic [3:0] P='x; localparam logic [7:0] Q='1; endmodule", Path::new("four_state_ranges.sv"), @@ -454,15 +487,25 @@ fn four_state_prefix_keeps_the_separate_range_projection() { let tree = AnalysisContext::unspecialized(&tree); 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(); + let parameters = parameters_from_scope( + &tree, + session, + &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(&tree, ¶meters)["Q"], 255); + assert_eq!( + const_env_from_parameters(&tree, session, ¶meters)["Q"], + 255 + ); } #[test] fn four_state_parameter_chains_do_not_copy_growing_environments() { + let session = &mut Session::default(); for count in [16, 64, 256] { let mut code = String::from("module Top();\n"); for index in 0..count { @@ -484,11 +527,8 @@ fn four_state_parameter_chains_do_not_copy_growing_environments() { 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( - &tree, - parameters, - &const_env_from_parameters(&tree, parameters), - ); + let constants = const_env_from_parameters(&tree, session, parameters); + let values = parameter_value_env(&tree, session, parameters, &constants); assert_eq!(values.len(), count); for parameter in parameters { assert_eq!(parameter.declared_width(), Some(32)); @@ -514,6 +554,7 @@ fn four_state_parameter_chains_do_not_copy_growing_environments() { #[test] fn literal_prefix_range_contexts_match_copied_projection_and_track_inherited_shadows() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( "module Top(); parameter logic [3:0] P='x; parameter logic [P:0] Q='0; parameter logic [129:0] W='z; parameter logic [7:0] R='1; endmodule", Path::new("literal_prefix_projection.sv"), @@ -526,8 +567,8 @@ fn literal_prefix_range_contexts_match_copied_projection_and_track_inherited_sha let copied_base = base.clone(); let mut borrowed = Vec::new(); let mut copied = Vec::new(); - let mut borrowed_env = ParameterEnvironment::new(&tree, &borrowed, &base, &[]); - let mut copied_env = ParameterEnvironment::new(&tree, &copied, &copied_base, &[]); + let mut borrowed_env = ParameterEnvironment::new(&tree, session, &borrowed, &base, &[]); + let mut copied_env = ParameterEnvironment::new(&tree, session, &copied, &copied_base, &[]); for id in tree.body_membership().unwrap() { if !matches!( tree.declarations().body_item(id).kind, @@ -538,6 +579,7 @@ fn literal_prefix_range_contexts_match_copied_projection_and_track_inherited_sha parameters_from_native_with_environment( &ownership::body(id, &tree).unwrap(), &tree, + session, &mut borrowed, false, &base, @@ -549,6 +591,7 @@ fn literal_prefix_range_contexts_match_copied_projection_and_track_inherited_sha parameters_from_native_with_environment( &ownership::body(id, &tree).unwrap(), &tree, + session, &mut copied, false, &base, @@ -557,7 +600,7 @@ fn literal_prefix_range_contexts_match_copied_projection_and_track_inherited_sha &mut copied_env, ) .unwrap(); - let rebuilt = ParameterEnvironment::new(&tree, &borrowed, &base, &[]); + let rebuilt = ParameterEnvironment::new(&tree, session, &borrowed, &base, &[]); assert_eq!( borrowed_env.has_inherited_literal_shadow, rebuilt.has_inherited_literal_shadow @@ -579,6 +622,7 @@ fn copied_resolved_literal( types: &HashMap, literals: &HashMap, ) -> Option { + let session = &mut Session::default(); let syntax = crate::source_tree::SourceTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); let mut evaluation_constants = constants.clone(); @@ -594,17 +638,20 @@ fn copied_resolved_literal( } let value = parameter_value_env( &tree, + session, 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(&tree, value, &evaluation_constants); + let value = + fold_const_integral_expr_preserving_mask(&tree, session, value, &evaluation_constants); matches!(value, Expr::Literal(_)).then_some(value) } #[test] fn borrowed_literal_environment_matches_self_masked_copy_with_types_and_unknowns() { + let session = &mut Session::default(); let syntax = crate::source_tree::SourceTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); let mut constants = @@ -665,7 +712,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(&tree, &env, &types, &literals); + let borrowed = parameter.resolved_literal(&tree, session, &env, &types, &literals); assert_eq!( LITERAL_ENV_COPIES.with(|copies| copies.get()), usize::from(stale_self.is_some()) @@ -723,19 +770,23 @@ fn separately_resolved_value_and_literal( types: &HashMap, literals: &HashMap, ) -> (Option, Option) { + let session = &mut Session::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(&tree.functions, constants, types) .or_else(|| { - let literal = parameter.resolved_literal(&tree, constants, types, literals)?; - eval_ast_const_expr(&tree.functions, &expr_to_const(state, literal)?, constants) + let literal = parameter.resolved_literal(&tree, session, constants, types, literals)?; + eval_ast_const_expr( + &tree.functions, + &expr_to_const(session, literal)?, + constants, + ) }); let literal = if value.is_none() { - parameter.resolved_literal(&tree, constants, types, literals) + parameter.resolved_literal(&tree, session, constants, types, literals) } else { None }; @@ -744,6 +795,7 @@ fn separately_resolved_value_and_literal( #[test] fn retained_parameter_literals_match_separate_resolution_across_types_and_dependencies() { + let session = &mut Session::default(); let syntax = crate::source_tree::SourceTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); let mut constants = @@ -806,7 +858,8 @@ 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(&tree, &env, &types, &literals); + let retained = + parameter.resolved_value_and_literal(&tree, session, &env, &types, &literals); assert!(LITERAL_RESOLUTIONS.with(|calls| calls.get()) <= 1); assert!(!(retained.0.is_some() && retained.1.is_some())); assert_eq!( @@ -828,7 +881,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(&tree, &constants, &types, &literals), + numeric.resolved_value_and_literal(&tree, session, &constants, &types, &literals), (Some(7), None) ); assert_eq!(LITERAL_RESOLUTIONS.with(|calls| calls.get()), 0); @@ -843,7 +896,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(&tree, &constants, &types, &literals), + two_state.resolved_value_and_literal(&tree, session, &constants, &types, &literals), (Some(-125), None) ); assert_eq!(LITERAL_RESOLUTIONS.with(|calls| calls.get()), 1); @@ -889,6 +942,7 @@ fn module_parameter_bindings_and_ir_resolve_each_unknown_literal_once() { #[test] fn generate_bindings_keep_numeric_literals_and_unresolved_fallback_order() { + let session = &mut Session::default(); let syntax = crate::source_tree::SourceTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); for (initializer, two_state, expected_value) in @@ -909,6 +963,7 @@ fn generate_bindings_keep_numeric_literals_and_unresolved_fallback_order() { LITERAL_RESOLUTIONS.with(|calls| calls.set(0)); constants::bind_generate_parameter_with_types( &tree, + session, parameter, &mut env, &mut literals, @@ -945,6 +1000,7 @@ fn compare_retained_and_repeated_parameter_resolution() { use std::time::Instant; fn replay(parameters: &[Parameter], repeated: bool) { + let session = &mut Session::default(); let syntax = crate::source_tree::SourceTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); let mut env = HashMap::default(); @@ -954,7 +1010,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(&tree, &env, &types, &literals) + parameter.resolved_value_and_literal(&tree, session, &env, &types, &literals) }; assert!(value.is_none()); let ty = parameter.resolved_type(&types).unwrap(); @@ -1020,6 +1076,7 @@ fn compare_retained_and_repeated_parameter_resolution() { #[test] fn referenced_value_projection_matches_full_environment() { + let session = &mut Session::default(); let syntax = crate::source_tree::SourceTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); let p = |name: &str, value: ConstExpr, width: Option, two_state: bool| { @@ -1111,10 +1168,11 @@ fn referenced_value_projection_matches_full_environment() { HashMap::default(), HashMap::from_iter([("B".into(), -3), ("typed_known".into(), -1)]), ] { - let full = parameter_value_env(&tree, ¶meters, &env); + let full = parameter_value_env(&tree, session, ¶meters, &env); for parameter in ¶meters { let wanted = HashSet::from_iter([parameter.name().to_string()]); - let projected = parameter_value_env_for_references(&tree, ¶meters, &env, &wanted); + let projected = + parameter_value_env_for_references(&tree, session, ¶meters, &env, &wanted); assert_eq!( projected.get(parameter.name()), full.get(parameter.name()), @@ -1129,9 +1187,10 @@ fn referenced_value_projection_matches_full_environment() { assert!( parameter_value_env_for_references( &tree, + session, ¶meters, &env, - &HashSet::from_iter(["not_a_parameter".into()]) + &HashSet::from_iter(["not_a_parameter".into()]), ) .is_empty() ); @@ -1141,6 +1200,7 @@ fn referenced_value_projection_matches_full_environment() { #[test] fn numeric_projection_does_not_expand_initializer_dependencies() { + let session = &mut Session::default(); let syntax = crate::source_tree::SourceTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); let parameters = vec![ @@ -1167,6 +1227,7 @@ fn numeric_projection_does_not_expand_initializer_dependencies() { PARAMETER_VALUE_MATERIALIZATIONS.with(|count| count.set(0)); let projected = parameter_value_env_for_references( &tree, + session, ¶meters, &env, &HashSet::from_iter(["B".into()]), @@ -1175,7 +1236,7 @@ fn numeric_projection_does_not_expand_initializer_dependencies() { assert_eq!(projected.len(), 1); assert_eq!( projected["B"], - parameter_value_env(&tree, ¶meters, &env)["B"] + parameter_value_env(&tree, session, ¶meters, &env)["B"] ); } @@ -1186,6 +1247,7 @@ fn compare_full_and_referenced_parameter_values() { std::thread::Builder::new() .stack_size(16 * 1024 * 1024) .spawn(|| { + let session = &mut Session::default(); let syntax = crate::source_tree::SourceTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); use std::{hint::black_box, time::Instant}; @@ -1214,14 +1276,16 @@ fn compare_full_and_referenced_parameter_values() { .collect(); let env = HashMap::default(); let references = HashSet::from_iter(["P0".into()]); - let expected = parameter_value_env(&tree, ¶meters[..1], &env)["P0"].clone(); - let run = |full: bool| { + let expected = + parameter_value_env(&tree, session, ¶meters[..1], &env)["P0"].clone(); + let mut run = |full: bool| { let start = Instant::now(); let values = if full { - parameter_value_env(&tree, black_box(¶meters), &env) + parameter_value_env(&tree, session, black_box(¶meters), &env) } else { parameter_value_env_for_references( &tree, + session, black_box(¶meters), &env, &references, @@ -1255,6 +1319,7 @@ fn compare_full_and_referenced_parameter_values() { #[test] fn unbounded_binding_keeps_declared_rank_without_a_numeric_value() { + let session = &mut Session::default(); let syntax = crate::source_tree::SourceTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); let mut env = HashMap::default(); @@ -1272,6 +1337,7 @@ fn unbounded_binding_keeps_declared_rank_without_a_numeric_value() { ); assert!(bind_parameter( &tree, + session, &mut env, &mut types, &mut literals, @@ -1288,6 +1354,7 @@ fn unbounded_binding_keeps_declared_rank_without_a_numeric_value() { #[test] fn unbounded_generate_binding_clears_inherited_numeric_values() { + let session = &mut Session::default(); let syntax = crate::source_tree::SourceTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); let parameter = Parameter::new( @@ -1306,7 +1373,7 @@ fn unbounded_generate_binding_clears_inherited_numeric_values() { (unbounded_parameter_marker("P"), 0), ]); let mut literals = HashMap::default(); - bind_generate_parameter(&tree, parameter, &mut env, &mut literals); + bind_generate_parameter(&tree, session, parameter, &mut env, &mut literals); assert_eq!(env.get(&unbounded_parameter_marker("P")), Some(&1)); for key in [ "P".to_string(), @@ -1320,6 +1387,7 @@ fn unbounded_generate_binding_clears_inherited_numeric_values() { #[test] fn unbounded_projection_keeps_requested_aliases_and_omits_unused_dollars() { + let session = &mut Session::default(); let syntax = crate::source_tree::SourceTree::empty(); let tree = AnalysisContext::unspecialized(&syntax); let parameters = vec![ @@ -1355,10 +1423,11 @@ 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(&tree, ¶meters, &env); + let full = parameter_value_env(&tree, session, ¶meters, &env); for name in ["U", "ALIAS", "NUMBER"] { let projected = parameter_value_env_for_references( &tree, + session, ¶meters, &env, &HashSet::from_iter([name.into()]), @@ -1393,6 +1462,7 @@ fn logical_type_inference_requires_operand_types_outside_bounded_proofs() { #[test] fn unbased_parameter_overrides_fill_declared_width_before_dependent_parameters() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture( "module Top #(parameter logic [57:0] FILL=0, \ parameter logic signed [57:0] SIGNED_FILL=0, \ @@ -1406,14 +1476,19 @@ fn unbased_parameter_overrides_fill_declared_width_before_dependent_parameters() .into_iter() .map(|name| (name.into(), ConstExpr::Literal(literal.into()))) .collect(); - let mut parameters = - parameters_from_scope(&tree, &HashMap::default(), &HashMap::default(), &overrides) - .unwrap(); + let mut parameters = parameters_from_scope( + &tree, + session, + &HashMap::default(), + &HashMap::default(), + &overrides, + ) + .unwrap(); for reapplied in [false, true] { if reapplied { apply_parameter_overrides(&mut parameters, &overrides).unwrap(); } - let values = const_env_from_parameters(&tree, ¶meters); + let values = const_env_from_parameters(&tree, session, ¶meters); assert_eq!(values["FILL"], unsigned, "{literal}, reapplied={reapplied}"); assert_eq!(values["SIGNED_FILL"], signed); assert_eq!(values["COPY"], unsigned); @@ -1424,6 +1499,7 @@ fn unbased_parameter_overrides_fill_declared_width_before_dependent_parameters() #[test] fn inherited_alias_prefixes_bind_once_without_copying_declaration_environments() { + let session = &mut Session::default(); for count in [16, 64, 256] { let mut code = String::from("module Top;\n"); for index in 0..count { @@ -1444,8 +1520,14 @@ fn inherited_alias_prefixes_bind_once_without_copying_declaration_environments() ); PARAMETER_BINDINGS.with(|count| count.set(0)); DECLARATION_ENV_COPIES.with(|count| count.set(0)); - let parameters = - parameters_from_scope(&tree, &HashMap::default(), &base, &HashMap::default()).unwrap(); + let parameters = parameters_from_scope( + &tree, + session, + &HashMap::default(), + &base, + &HashMap::default(), + ) + .unwrap(); assert_eq!(PARAMETER_BINDINGS.with(|count| count.get()), count); assert_eq!(DECLARATION_ENV_COPIES.with(|count| count.get()), 0); for (index, parameter) in parameters.iter().enumerate() { @@ -1463,6 +1545,7 @@ fn inherited_alias_prefixes_bind_once_without_copying_declaration_environments() #[test] fn inherited_evaluation_masks_pending_local_names_and_their_type_markers() { + let session = &mut Session::default(); let mut base = HashMap::from_iter([("EXTERNAL".into(), 8), ("LOCAL".into(), 99)]); insert_parameter_type_markers( &mut base, @@ -1474,8 +1557,13 @@ fn inherited_evaluation_masks_pending_local_names_and_their_type_markers() { ); let tree = crate::source_tree::parse_source("", Path::new("environment.sv")).unwrap(); let tree = AnalysisContext::unspecialized(&tree); - let mut environment = - ParameterEnvironment::new(&tree, &[], &base, &["LOCAL".into(), "ALIAS".into()]); + let mut environment = ParameterEnvironment::new( + &tree, + session, + &[], + &base, + &["LOCAL".into(), "ALIAS".into()], + ); let alias = Parameter::new( "ALIAS".into(), Some(ConstExpr::Ident("LOCAL".into())), @@ -1485,7 +1573,7 @@ fn inherited_evaluation_masks_pending_local_names_and_their_type_markers() { false, true, ); - environment.append(&tree, &alias); + environment.append(&tree, session, &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 e0a7165ed92..321e08fb699 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns.rs @@ -37,6 +37,7 @@ pub(super) fn shape_width( fn constant_pattern_value( tree: &AnalysisContext<'_>, + session: &mut Session, value: Expr, shape: &VariableDimensions, dims: &PackedDimensions, @@ -48,10 +49,15 @@ fn constant_pattern_value( .map(|(name, value)| (name.clone(), value.clone())) .collect(); let value = substitute_expr_idents(value, &dims.array_parameter_values); - let value = - substitute_expr_constants_with_parameter_literals(tree, value, &dims.const_env, &values); + let value = substitute_expr_constants_with_parameter_literals( + tree, + session, + value, + &dims.const_env, + &values, + ); let Expr::Literal(value) = - fold_const_integral_expr_preserving_mask(tree, value, &dims.const_env) + fold_const_integral_expr_preserving_mask(tree, session, value, &dims.const_env) else { return Err(unsupported("nonconstant typed parameter pattern")); }; @@ -136,6 +142,7 @@ fn dimension_bounds( /// the leaf so mixed bit/logic aggregates preserve their member types. pub(super) fn assignment_value( tree: &AnalysisContext<'_>, + session: &mut Session, value: &Expr, signed: bool, value_type: Option<&Type>, @@ -198,7 +205,7 @@ pub(super) fn assignment_value( .ok_or_else(|| unsupported("pattern target array size"))?; return Ok(Expr::Concat(vec![ assignment_value( - tree, value, signed, value_type, &element, dims, true + tree, session, value, signed, value_type, &element, dims, true )?; count ])); @@ -211,6 +218,7 @@ pub(super) fn assignment_value( .map(|member| { assignment_value( tree, + session, value, signed, value_type, @@ -239,6 +247,7 @@ pub(super) fn assignment_value( .map(|member| { assignment_value( tree, + session, value, signed, value_type, @@ -265,7 +274,7 @@ pub(super) fn assignment_value( 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(tree, actual, shape, dims)) + .and_then(|actual| array_compatibility::incompatible(tree, session, actual, shape, dims)) { return Err(AnalyzerError::IncompatibleUnpackedArray { context: "assignment pattern element".into(), diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index ec0d309230c..070d9a2d04c 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -342,25 +342,28 @@ pub(in crate::ast) fn typed_shape( pub(in crate::ast) fn constant_native( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted { 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, value, &shape, dims) + let value = bind_native(root, tree.declarations(), tree, session, dims, Some(&shape))?; + super::constant_pattern_value(tree, session, value, &shape, dims) } pub(in crate::ast) fn expression( root: ExprId, shape: &VariableDimensions, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted> { - bind_native(root, tree.declarations(), tree, dims, Some(shape)).map(Some) + bind_native(root, tree.declarations(), tree, session, dims, Some(shape)).map(Some) } pub(in crate::ast) fn bind_native( root: ExprId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, shape: Option<&VariableDimensions>, ) -> Converted { @@ -384,7 +387,7 @@ pub(in crate::ast) fn bind_native( while let Some(job) = jobs.pop() { match job { Job::Pattern(id, shape) => { - let plan = bound_patterns::prepare_native(id, tree, dims, Some(&shape))?; + let plan = bound_patterns::prepare_native(id, tree, session, dims, Some(&shape))?; let (items, reverse, keep) = select(&tree.functions, plan.kind, plan.bindings, shape, dims)?; jobs.push(Job::Finish { @@ -431,12 +434,12 @@ pub(in crate::ast) fn bind_native( continue; } if check { - check_native_array(tree, id, &shape, dims)?; + check_native_array(tree, session, id, &shape, dims)?; } // A typed pattern of a member must name the member's // structure type (6.22.3). if pattern && let Some(aggregate) = shape.unpacked_struct.as_deref() { - unpacked_structs::check_value(aggregate, id, native, tree, dims)?; + unpacked_structs::check_value(aggregate, id, native, tree, session, dims)?; } if let Some(aggregate) = shape.unpacked_struct.clone() && !pattern @@ -444,7 +447,7 @@ pub(in crate::ast) fn bind_native( // A default that is not a structure of the member's type // applies to each of its members (IEEE 1800-2023 10.9.2). if default - && !unpacked_structs::native_struct(id, native, tree, dims)? + && !unpacked_structs::native_struct(id, native, tree, session, dims)? .is_some_and(|value| value.same_type(&aggregate)) { let members = aggregate.members(); @@ -465,23 +468,24 @@ pub(in crate::ast) fn bind_native( })); continue; } - unpacked_structs::check_value(&aggregate, id, native, tree, dims)?; + unpacked_structs::check_value(&aggregate, id, native, tree, session, dims)?; values.push(expression_binding::bind_value( - id, native, tree, dims, None, + id, native, tree, session, dims, None, )?); continue; } if let Some(class) = shape.class.as_deref() && !pattern { - if let Some(call) = - expression_binding::object_constructor(tree, id, native, dims, class)? - { + if let Some(call) = expression_binding::object_constructor( + tree, session, id, native, dims, class, + )? { values.push(call); continue; } expression_binding::check_handle_assignment( tree, + session, id, native, dims, @@ -490,7 +494,8 @@ pub(in crate::ast) fn bind_native( )?; } if (shape.string || shape.class.is_some()) && !pattern { - let value = expression_binding::bind_value(id, native, tree, dims, None)?; + let value = + expression_binding::bind_value(id, native, tree, session, dims, None)?; values.push(if shape.string { expression_binding::string_operand(value, dims) } else { @@ -507,17 +512,20 @@ pub(in crate::ast) fn bind_native( .unwrap_or(shape), )); } else { - let value = expression_binding::bind_value(id, native, tree, dims, None)?; - let type_dims = dimensions::query_context_for_operand(id, tree, dims)?; + let value = + expression_binding::bind_value(id, native, tree, session, dims, None)?; + let type_dims = dimensions::query_context_for_operand(id, tree, session, dims)?; let signed = dimensions::expression_signedness(&value, &type_dims, &type_dims.const_env) .ok_or_else(|| unsupported("assignment pattern operand signedness"))?; let descend_default = default && (shape.unpacked.is_empty() || native_rank(id, native, dims) < shape.unpacked.len()); - let value_type = bound_patterns::native_value_type(id, tree, &type_dims)?; + let value_type = + bound_patterns::native_value_type(id, tree, session, &type_dims)?; values.push(assignment_value( tree, + session, &value, signed, value_type.as_ref(), @@ -653,12 +661,14 @@ fn native_rank( } fn check_native_array( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, shape: &VariableDimensions, dims: &PackedDimensions, ) -> Converted<()> { array_compatibility::check_native_unpacked_assignment( tree, + session, id, shape, || "assignment pattern item".into(), @@ -685,6 +695,7 @@ mod tests { } #[test] fn deeply_nested_native_typed_patterns_share_the_job_stack() { + let session = &mut Session::default(); let tree = std::thread::Builder::new() .stack_size(128 * 1024 * 1024) .spawn(|| { @@ -708,7 +719,7 @@ mod tests { &HashMap::default(), &HashMap::from_iter([("T".into(), Type::new(TypeKind::Logic))]), ); - let result = bind_native(root, tree.declarations(), tree, &dims, None).map(Some); + let result = bind_native(root, tree.declarations(), tree, session, &dims, None).map(Some); drop(context); drop(original); assert!(matches!( @@ -718,6 +729,7 @@ mod tests { } #[test] fn deeply_nested_native_scalar_patterns_bind_on_the_default_stack() { + let session = &mut Session::default(); let tree = std::thread::Builder::new() .stack_size(128 * 1024 * 1024) .spawn(|| { @@ -742,7 +754,7 @@ mod tests { let shape = procedural::dimensions_from_type(&Type::new(TypeKind::Logic)); let dims = PackedDimensions::new(HashMap::default(), &HashMap::default(), &HashMap::default()); - let result = expression(root, &shape, tree, &dims); + let result = expression(root, &shape, tree, session, &dims); let mut ty = Type::new(TypeKind::Logic); ty.packed_ranges = vec![ PackedRange::new( @@ -751,7 +763,13 @@ mod tests { ); 500 ]; - let ranked = expression(root, &procedural::dimensions_from_type(&ty), tree, &dims); + let ranked = expression( + root, + &procedural::dimensions_from_type(&ty), + tree, + session, + &dims, + ); drop(context); drop(original); assert!(matches!( diff --git a/crates/celox-sv-analyzer/src/ast/port_owners.rs b/crates/celox-sv-analyzer/src/ast/port_owners.rs index 708cd30c428..ff6a2b5530f 100644 --- a/crates/celox-sv-analyzer/src/ast/port_owners.rs +++ b/crates/celox-sv-analyzer/src/ast/port_owners.rs @@ -118,10 +118,12 @@ mod tests { } #[test] fn explicit_port_without_a_new_header_keeps_native_inherited_type() { + let session = &mut Session::default(); let tree = parse("module M(input wire[7:0] a,.b(a));endmodule"); let tree = AnalysisContext::unspecialized(&tree); let ports = ports_from_scope( &AnalysisContext::unspecialized(&tree), + session, &HashMap::default(), &HashMap::default(), None, @@ -140,6 +142,7 @@ mod tests { } #[test] fn a_structural_header_projection_carries_explicit_native_membership() { + let session = &mut Session::default(); let tree = parse( "module M(input wire[3:0]a,input wire[7:0]b);endmodule module N(input wire z);endmodule", ); @@ -149,6 +152,7 @@ mod tests { assert_eq!(scope(None, &tree).unwrap().len(), 2); let ports = ports_from_scope( &AnalysisContext::unspecialized(&tree), + session, &HashMap::default(), &HashMap::default(), Some(&selection), diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 78ae412ac92..df448b4cef3 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -72,12 +72,11 @@ struct ForHeader { /// Converts the statements of one procedural body. pub(super) struct BodyBuilder<'s, 't, 'a> { tree: &'t AnalysisContext<'t>, + pub(super) session: &'s mut Session, dims: PackedDimensions, - scopes: Vec, + names: Names, state: &'s mut BodyState<'a>, type_aliases: HashMap, - /// The values of the local parameters declared in the body. - local_constants: HashMap, /// The kind of body, for the system tasks it may call. body: system_functions::Body, /// Whether the body's variables are automatic by default. @@ -90,6 +89,84 @@ pub(super) struct BodyBuilder<'s, 't, 'a> { pub(super) sensitivity_body: Vec, } +/// The names a body declares: its scopes of locals, innermost last, and +/// the values of its local parameters. +pub(super) struct Names { + scopes: Vec, + /// The values of the local parameters declared in the body. + local_constants: HashMap, +} + +impl Names { + fn lookup(&self, source: &str) -> Option<&str> { + for scope in self.scopes.iter().rev() { + if let Some(entry) = scope + .entries + .iter() + .rev() + .find(|entry| entry.source == source) + { + // A parameter in an inner block also hides an outer variable. + return entry.unique.as_deref(); + } + } + None + } + + fn rename_name(&self, name: &mut String) { + if let Some(unique) = self.lookup(name) { + *name = unique.to_string(); + } + } + + /// The literal value of a local parameter that `name` refers to. + fn local_constant(&self, name: &str) -> Option<&String> { + if self.lookup(name).is_some() { + return None; + } + self.local_constants.get(name) + } + + fn rename_const(&self, expr: &mut ConstExpr) { + rename_const_idents(expr, &mut |name| self.rename_ident(name)); + } + + fn rename_expr(&self, expr: &mut Expr) { + rename_expr_idents(expr, &mut |name| self.rename_ident(name)); + } + + /// Rename a referenced local, or return the value of a local parameter. + fn rename_ident(&self, name: &mut String) -> Option { + match self.local_constant(name) { + Some(value) => Some(value.clone()), + None => { + self.rename_name(name); + None + } + } + } + + fn rename_lvalue(&self, lvalue: &mut LValue) { + match lvalue { + LValue::Ident(name) => self.rename_name(name), + LValue::Select { + name, + msb, + lsb, + array_slice_width, + .. + } => { + self.rename_name(name); + self.rename_const(msb); + self.rename_const(lsb); + if let Some(width) = array_slice_width { + self.rename_const(width); + } + } + } + } +} + /// The packed and unpacked shape of a declared type, as selects see it. pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions { VariableDimensions { @@ -330,6 +407,7 @@ impl Drop for BodyBuilder<'_, '_, '_> { impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { pub(super) fn new( tree: &'t AnalysisContext<'t>, + session: &'s mut Session, dims: &PackedDimensions, state: &'s mut BodyState<'a>, body: system_functions::Body, @@ -345,13 +423,16 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { stream_return_shape: None, sensitivity_body: Vec::new(), tree, + session, dims, - scopes: vec![Scope { - entries: Vec::new(), - }], + names: Names { + scopes: vec![Scope { + entries: Vec::new(), + }], + local_constants: HashMap::default(), + }, state, type_aliases, - local_constants: HashMap::default(), body, } } @@ -375,13 +456,13 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } fn push_scope(&mut self) { - self.scopes.push(Scope { + self.names.scopes.push(Scope { entries: Vec::new(), }); } fn pop_scope(&mut self) { - let Some(scope) = self.scopes.pop() else { + let Some(scope) = self.names.scopes.pop() else { return; }; for entry in scope.entries.into_iter().rev() { @@ -394,10 +475,12 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } match entry.shadowed_literal { Some(value) => { - self.local_constants.insert(entry.source.clone(), value); + self.names + .local_constants + .insert(entry.source.clone(), value); } None => { - self.local_constants.remove(&entry.source); + self.names.local_constants.remove(&entry.source); } } match entry.shadowed_parameter_value { @@ -451,7 +534,8 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { }, ), }); - self.scopes + self.names + .scopes .last_mut() .expect("a body always has a scope") .entries @@ -478,7 +562,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { (key, value) }) .collect(), - shadowed_literal: self.local_constants.remove(source), + shadowed_literal: self.names.local_constants.remove(source), shadowed_parameter_value: self.dims.parameter_values.remove(source), shadowed_dimensions: self.dims.remove(source), shadowed_signedness: self.dims.expression_signedness.remove(source), @@ -505,7 +589,8 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .chain(aggregates) { let entry = self.take_binding(name, None, 0); - self.scopes + self.names + .scopes .last_mut() .expect("a body always has a scope") .entries @@ -529,7 +614,8 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.dims .expression_signedness .insert(property.name.clone(), property.r#type.is_signed()); - self.scopes + self.names + .scopes .last_mut() .expect("a body always has a scope") .entries @@ -537,89 +623,35 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } } - fn lookup(&self, source: &str) -> Option<&str> { - for scope in self.scopes.iter().rev() { - if let Some(entry) = scope - .entries - .iter() - .rev() - .find(|entry| entry.source == source) - { - // A parameter in an inner block also hides an outer variable. - return entry.unique.as_deref(); - } - } - None - } - - fn rename_name(&self, name: &mut String) { - if let Some(unique) = self.lookup(name) { - *name = unique.to_string(); - } - } - - /// The literal value of a local parameter that `name` refers to. - fn local_constant(&self, name: &str) -> Option<&String> { - if self.lookup(name).is_some() { - return None; - } - self.local_constants.get(name) - } - - fn rename_const(&self, expr: &mut ConstExpr) { - rename_const_idents(expr, &mut |name| self.rename_ident(name)); - } - fn rename_expr(&self, expr: &mut Expr) { - rename_expr_idents(expr, &mut |name| self.rename_ident(name)); - } - - /// Rename a referenced local, or return the value of a local parameter. - fn rename_ident(&self, name: &mut String) -> Option { - match self.local_constant(name) { - Some(value) => Some(value.clone()), - None => { - self.rename_name(name); - None - } - } + self.names.rename_expr(expr); } fn rename_lvalue(&self, lvalue: &mut LValue) { - match lvalue { - LValue::Ident(name) => self.rename_name(name), - LValue::Select { - name, - msb, - lsb, - array_slice_width, - .. - } => { - self.rename_name(name); - self.rename_const(msb); - self.rename_const(lsb); - if let Some(width) = array_slice_width { - self.rename_const(width); - } - } - } + self.names.rename_lvalue(lvalue); } - fn native_value(&self, id: celox_sv_syntax::ExprId) -> Result { - let mut value = - expression_binding::value(id, self.tree.declarations(), self.tree, &self.dims)?; + fn native_value(&mut self, id: celox_sv_syntax::ExprId) -> Result { + let mut value = expression_binding::value( + id, + self.tree.declarations(), + self.tree, + self.session, + &self.dims, + )?; self.rename_expr(&mut value); Ok(value) } fn native_lvalue( - &self, + &mut self, id: celox_sv_syntax::ExprId, ) -> Result<(LValue, LValue), AnalyzerError> { let lowered = expression_binding::variable_lvalue( id, self.tree.declarations(), self.tree, + self.session, &self.dims, )?; virtual_interfaces::check_target(&lowered)?; @@ -629,7 +661,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } /// The parts of a concatenated assignment target, most significant first. - fn concat_lvalue(&self, root: celox_sv_syntax::ExprId) -> Converted>> { + fn concat_lvalue(&mut self, root: celox_sv_syntax::ExprId) -> Converted>> { let native = self.tree.declarations(); let celox_sv_syntax::ExprKind::Concatenation(parts) = &native.expression(root).kind else { return Ok(None); @@ -640,16 +672,27 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { if let celox_sv_syntax::ExprKind::Concatenation(items) = &native.expression(id).kind { pending.extend(items.iter().rev().copied()); } else { - if expression_binding::member_context(id, native, self.tree, &self.dims)? - .is_some_and(|(guards, _)| !guards.is_empty()) + if expression_binding::member_context( + id, + native, + self.tree, + self.session, + &self.dims, + )? + .is_some_and(|(guards, _)| !guards.is_empty()) { return Err(unsupported( "concatenation assignment to a tagged union member", )); } self.reject_tagged_integral_target(id)?; - let mut target = - expression_binding::variable_lvalue(id, native, self.tree, &self.dims)?; + let mut target = expression_binding::variable_lvalue( + id, + native, + self.tree, + self.session, + &self.dims, + )?; virtual_interfaces::check_target(&target)?; self.rename_lvalue(&mut target); parts.push(target); @@ -659,22 +702,34 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } fn assignment_value( - &self, + &mut self, op: &str, nonblocking: bool, native: (celox_sv_syntax::ExprId, celox_sv_syntax::ExprId), ) -> Result { let (left, right) = native; - if containers::element_member(left, self.tree.declarations(), self.tree, &self.dims)? - .is_some() + if containers::element_member( + left, + self.tree.declarations(), + self.tree, + self.session, + &self.dims, + )? + .is_some() { return Err(unsupported( "assignment to a member of a dynamic container element", )); } - if let Some(mut stmt) = - containers::set(left, right, op, nonblocking, self.tree, &self.dims)? - { + if let Some(mut stmt) = containers::set( + left, + right, + op, + nonblocking, + self.tree, + self.session, + &self.dims, + )? { if let Stmt::Eval(expr) = &mut stmt { self.rename_expr(expr); } @@ -699,11 +754,16 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { }); } if op == "=" - && let Some(target) = - array_compatibility::native_unpacked_shape(left, self.tree, &self.dims) + && let Some(target) = array_compatibility::native_unpacked_shape( + left, + self.tree, + self.session, + &self.dims, + ) { array_compatibility::check_native_unpacked_assignment( self.tree, + self.session, right, &target, || "assignment".into(), @@ -715,6 +775,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { if op != "=" && let Some(ty) = virtual_interfaces::native_type( self.tree, + self.session, left, self.tree.declarations(), &self.dims, @@ -727,6 +788,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { if op == "=" && let Some(ty) = virtual_interfaces::native_type( self.tree, + self.session, left, self.tree.declarations(), &self.dims, @@ -734,6 +796,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { { virtual_interfaces::check_assignment( self.tree, + self.session, right, self.tree.declarations(), &self.dims, @@ -759,6 +822,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { if op != "=" && expression_binding::native_string( self.tree, + self.session, left, self.tree.declarations(), &self.dims, @@ -770,6 +834,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { left, self.tree.declarations(), self.tree, + self.session, &self.dims, )?; let mut rhs = if op == "=" @@ -780,13 +845,15 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { right, self.tree.declarations(), self.tree, + self.session, &self.dims, Some(&shape), )? } else if op == "=" && matches!(written, LValue::Select { .. }) && expression_binding::is_stream(right, self.tree.declarations()) - && let Some(shape) = dimensions::operand_shape(left, self.tree, &self.dims)? + && let Some(shape) = + dimensions::operand_shape(left, self.tree, self.session, &self.dims)? { // A stream fills the selected type, whose position may be known // only at run time (IEEE 1800-2023 11.4.14). @@ -794,6 +861,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { right, self.tree.declarations(), self.tree, + self.session, &self.dims, Some(&shape), )? @@ -803,12 +871,18 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.tree.declarations(), &written, self.tree, + self.session, &self.dims, )? } else { - let value = - expression_binding::value(right, self.tree.declarations(), self.tree, &self.dims)?; - assignment_op_expr(self.tree, &written, op, value, &self.dims)? + let value = expression_binding::value( + right, + self.tree.declarations(), + self.tree, + self.session, + &self.dims, + )?; + assignment_op_expr(self.tree, self.session, &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. @@ -839,7 +913,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { /// An assignment to a whole variable or member of unpacked structure /// type, which writes each of its leaf variables (IEEE 1800-2023 7.2). fn aggregate_assignment( - &self, + &mut self, op: &str, nonblocking: bool, left: celox_sv_syntax::ExprId, @@ -849,6 +923,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { left, self.tree.declarations(), self.tree, + self.session, &self.dims, ) else { return Ok(None); @@ -869,9 +944,10 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.tree.declarations(), &written, self.tree, + self.session, &self.dims, )?; - unpacked_structs::check_assignment(name, right, self.tree, &self.dims)?; + unpacked_structs::check_assignment(name, right, self.tree, self.session, &self.dims)?; parts.iter_mut().for_each(|part| self.rename_lvalue(part)); self.rename_expr(&mut rhs); Ok(Some(Stmt::AssignConcat { @@ -884,7 +960,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { /// `str[i] = c`, which replaces one character like `str.putc(i, c)` /// (IEEE 1800-2023 6.16.2). fn string_character_assignment( - &self, + &mut self, op: &str, nonblocking: bool, left: celox_sv_syntax::ExprId, @@ -900,7 +976,13 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { else { return Ok(None); }; - if !expression_binding::native_string(self.tree, *expression, native, &self.dims) { + if !expression_binding::native_string( + self.tree, + self.session, + *expression, + native, + &self.dims, + ) { return Ok(None); } let celox_sv_syntax::DimensionKind::Index(index) = dimension.kind else { @@ -911,8 +993,9 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { "operator `{op}` on a string character" ))); } - let index = expression_binding::value(index, native, self.tree, &self.dims)?; - let character = expression_binding::value(right, native, self.tree, &self.dims)?; + let index = expression_binding::value(index, native, self.tree, self.session, &self.dims)?; + let character = + expression_binding::value(right, native, self.tree, self.session, &self.dims)?; self.string_update( *expression, StringOp::Putc, @@ -995,7 +1078,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { /// Rewrite each `%p` of the format of a display or write task into a /// conversion of the value it prints (IEEE 1800-2023 21.2.1.6). fn rewrite_display_patterns( - &self, + &mut self, task: SystemTask, args: &mut [SystemTaskArg], ids: &[Option], @@ -1021,7 +1104,12 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .flatten() .ok_or_else(|| unsupported("omitted %p argument"))?; let pattern = expression_binding::format_pattern( - self.tree, id, value, native, &self.dims, + self.tree, + self.session, + id, + value, + native, + &self.dims, )?; let (conversion, argument) = expression_binding::format_pattern_argument( pattern, @@ -1054,12 +1142,24 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { value: Expr, ) -> Result, AnalyzerError> { let native = self.tree.declarations(); - let property = expression_binding::object_property(self.tree, output, native, &self.dims)?; + let property = expression_binding::object_property( + self.tree, + self.session, + output, + native, + &self.dims, + )?; let string = match &property { Some((property, _)) => { property.field.handle == Some(system_functions::HandleProperty::String) } - None => expression_binding::native_string(self.tree, output, native, &self.dims), + None => expression_binding::native_string( + self.tree, + self.session, + output, + native, + &self.dims, + ), }; // An integral output takes the string as a string literal assigned // to it (IEEE 1800-2023 21.3.3, 5.9): its characters right-justified, @@ -1070,8 +1170,13 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.string_bits(output, value)? }; if let Some((property, receiver)) = property { - let handle = - expression_binding::object_receiver(self.tree, receiver, native, &self.dims)?; + let handle = expression_binding::object_receiver( + self.tree, + self.session, + receiver, + native, + &self.dims, + )?; stmts.push(self.property_store(&property, handle, "=", value)?); return Ok(stmts); } @@ -1094,8 +1199,13 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { output: celox_sv_syntax::ExprId, value: Expr, ) -> Result<(Vec, Expr), AnalyzerError> { - let current = - expression_binding::value(output, self.tree.declarations(), self.tree, &self.dims)?; + let current = expression_binding::value( + output, + self.tree.declarations(), + self.tree, + self.session, + &self.dims, + )?; if expression_binding::real_value(¤t, &self.dims) { return Err(unsupported("`$sformat` output that is not a string")); } @@ -1178,7 +1288,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { /// An assignment to a property of a class object: `h.p = v`, or `p = v` /// inside a method of its class (IEEE 1800-2023 8.5). fn property_assignment( - &self, + &mut self, op: &str, nonblocking: bool, left: celox_sv_syntax::ExprId, @@ -1186,46 +1296,66 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { ) -> Result, AnalyzerError> { let native = self.tree.declarations(); let Some((property, receiver)) = - expression_binding::object_property(self.tree, left, native, &self.dims)? + expression_binding::object_property(self.tree, self.session, left, native, &self.dims)? else { return Ok(None); }; if nonblocking { return Err(unsupported("nonblocking assignment to a class property")); } - let handle = expression_binding::object_receiver(self.tree, receiver, native, &self.dims)?; + let handle = expression_binding::object_receiver( + self.tree, + self.session, + receiver, + native, + &self.dims, + )?; let target = dimensions_from_type(&property.r#type); - let bind = |right| { - expression_binding::bind_value(right, native, self.tree, &self.dims, Some(&target)) + let bind = |session: &mut Session, right| { + expression_binding::bind_value( + right, + native, + self.tree, + session, + &self.dims, + Some(&target), + ) }; if let Some(container) = property.r#type.container.as_deref() { if op != "=" { return Err(unsupported("compound assignment to a container property")); } - let value = containers::assignment(right, self.tree, &self.dims, container)?; + let value = + containers::assignment(right, self.tree, self.session, &self.dims, container)?; return self.property_store(&property, handle, op, value).map(Some); } let mut value = match property.r#type.class() { Some(class) if op == "=" => { match expression_binding::object_constructor( - self.tree, right, native, &self.dims, class, + self.tree, + self.session, + right, + native, + &self.dims, + class, )? { Some(call) => call, None => { expression_binding::check_handle_assignment( self.tree, + self.session, right, native, &self.dims, class, || format!("assignment to property `{}`", property.name), )?; - bind(right)? + bind(self.session, right)? } } } - _ if op == "=" => bind(right)?, - _ => expression_binding::value(right, native, self.tree, &self.dims)?, + _ if op == "=" => bind(self.session, right)?, + _ => expression_binding::value(right, native, self.tree, self.session, &self.dims)?, }; if property.field.handle == Some(system_functions::HandleProperty::String) { if op != "=" { @@ -1239,33 +1369,46 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { /// An assignment to a member of the interface instance that a virtual /// interface denotes, `h.m = v` or `h.m <= v` (IEEE 1800-2023 25.9). fn virtual_member_assignment( - &self, + &mut self, op: &str, nonblocking: bool, left: celox_sv_syntax::ExprId, right: celox_sv_syntax::ExprId, ) -> Result, AnalyzerError> { let native = self.tree.declarations(); - let (handle, ty, member, selected) = - match virtual_interfaces::native_member(self.tree, left, native, &self.dims) { - Some((handle, ty, member)) => (handle, ty, member, None), - None => match virtual_interfaces::native_selected_member( - self.tree, left, native, &self.dims, - ) { - // The select is bound against the member's template. - Some((handle, ty, member)) => { - let lowered = expression_binding::variable_lvalue( - left, native, self.tree, &self.dims, - )?; - let mut renamed = lowered.clone(); - self.rename_lvalue(&mut renamed); - (handle, ty, member, Some((lowered, renamed))) - } - None => return Ok(None), - }, - }; - let (found, _) = virtual_interfaces::member(&self.tree.state, &ty, &member)?; - virtual_interfaces::check_write(&self.tree.state, &ty, &member)?; + let (handle, ty, member, selected) = match virtual_interfaces::native_member( + self.tree, + self.session, + left, + native, + &self.dims, + ) { + Some((handle, ty, member)) => (handle, ty, member, None), + None => match virtual_interfaces::native_selected_member( + self.tree, + self.session, + left, + native, + &self.dims, + ) { + // The select is bound against the member's template. + Some((handle, ty, member)) => { + let lowered = expression_binding::variable_lvalue( + left, + native, + self.tree, + self.session, + &self.dims, + )?; + let mut renamed = lowered.clone(); + self.rename_lvalue(&mut renamed); + (handle, ty, member, Some((lowered, renamed))) + } + None => return Ok(None), + }, + }; + let (found, _) = virtual_interfaces::member(self.session, &ty, &member)?; + virtual_interfaces::check_write(self.session, &ty, &member)?; if found.is_net { return Err(unsupported(format!( "procedural assignment to net `{member}` through a virtual interface" @@ -1273,20 +1416,31 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } let target = dimensions_from_type(&found.r#type); let mut value = match (&selected, op) { - (Some((written, _)), "=") => { - expression_binding::expression(right, native, written, self.tree, &self.dims)? - } - (None, "=") => { - expression_binding::bind_value(right, native, self.tree, &self.dims, Some(&target))? - } - _ => expression_binding::value(right, native, self.tree, &self.dims)?, + (Some((written, _)), "=") => expression_binding::expression( + right, + native, + written, + self.tree, + self.session, + &self.dims, + )?, + (None, "=") => expression_binding::bind_value( + right, + native, + self.tree, + self.session, + &self.dims, + Some(&target), + )?, + _ => expression_binding::value(right, native, self.tree, self.session, &self.dims)?, }; - let mut handle = expression_binding::value(handle, native, self.tree, &self.dims)?; + let mut handle = + expression_binding::value(handle, native, self.tree, self.session, &self.dims)?; self.rename_expr(&mut handle); self.rename_expr(&mut value); let template = virtual_interfaces::template(&ty.interface, &member); let stmt = - virtual_interfaces::dispatch(&self.tree.state, handle, &ty, &member, |signal| { + virtual_interfaces::dispatch(self.session, handle, &ty, &member, |session, signal| { let lhs = match &selected { Some((_, lhs @ LValue::Select { name, .. })) if *name == template => { let mut lhs = lhs.clone(); @@ -1305,7 +1459,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { let rhs = if op == "=" { value.clone() } else { - assignment_op_expr(self.tree, &lhs, op, value.clone(), &self.dims)? + assignment_op_expr(self.tree, session, &lhs, op, value.clone(), &self.dims)? }; Ok(vec![Stmt::Assign { lhs, @@ -1361,15 +1515,19 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { /// unqualified `m(args)` inside a method of its class (IEEE 1800-2023 /// 8.10). fn method_call_statement( - &self, + &mut self, root: celox_sv_syntax::ExprId, ) -> Result, AnalyzerError> { let native = self.tree.declarations(); - if let Some(mut call) = processes::value(self.tree, root, native, &self.dims, true)? { + if let Some(mut call) = + processes::value(self.tree, self.session, root, native, &self.dims, true)? + { self.rename_expr(&mut call); return Ok(Some(Stmt::Eval(call))); } - if let Some(mut call) = semaphores::value(self.tree, root, native, &self.dims, true)? { + if let Some(mut call) = + semaphores::value(self.tree, self.session, root, native, &self.dims, true)? + { self.rename_expr(&mut call); let stmt = Stmt::Eval(call); if events::blocks(&stmt) { @@ -1377,7 +1535,9 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } return Ok(Some(stmt)); } - if let Some(mut call) = mailboxes::value(self.tree, root, native, &self.dims, true)? { + if let Some(mut call) = + mailboxes::value(self.tree, self.session, root, native, &self.dims, true)? + { self.rename_expr(&mut call); let stmt = Stmt::Eval(call); if events::blocks(&stmt) { @@ -1386,10 +1546,20 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { return Ok(Some(stmt)); } if let Some(mut call) = expression_binding::object_constraint_mode_call( - self.tree, root, native, &self.dims, true, + self.tree, + self.session, + root, + native, + &self.dims, + true, )? .or(expression_binding::object_rand_mode_call( - self.tree, root, native, &self.dims, true, + self.tree, + self.session, + root, + native, + &self.dims, + true, )?) { self.rename_expr(&mut call); return Ok(Some(match call { @@ -1407,23 +1577,40 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } let call = match native.expression(root).kind { celox_sv_syntax::ExprKind::Call { expression, .. } => { - if expression_binding::object_method(self.tree, expression, native, &self.dims)? - .is_none() + if expression_binding::object_method( + self.tree, + self.session, + expression, + native, + &self.dims, + )? + .is_none() { return Ok(None); } - expression_binding::value(root, native, self.tree, &self.dims)? + expression_binding::value(root, native, self.tree, self.session, &self.dims)? } _ => { - let Some((name, formals, receiver)) = - expression_binding::object_method(self.tree, root, native, &self.dims)? + let Some((name, formals, receiver)) = expression_binding::object_method( + self.tree, + self.session, + root, + native, + &self.dims, + )? else { return Ok(None); }; let mut args = match receiver { - expression_binding::ObjectReceiver::Handle(receiver) => vec![Some( - expression_binding::value(receiver, native, self.tree, &self.dims)?, - )], + expression_binding::ObjectReceiver::Handle(receiver) => { + vec![Some(expression_binding::value( + receiver, + native, + self.tree, + self.session, + &self.dims, + )?)] + } expression_binding::ObjectReceiver::This => { vec![Some(expression_binding::object_this())] } @@ -1467,21 +1654,30 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { /// `string = op(string, args)`: a method that updates the string it is /// called on. fn string_update( - &self, + &mut self, string: celox_sv_syntax::ExprId, op: StringOp, args: Vec, nonblocking: bool, ) -> Result { let native = self.tree.declarations(); - if let Some((property, receiver)) = - expression_binding::object_property(self.tree, string, native, &self.dims)? - { + if let Some((property, receiver)) = expression_binding::object_property( + self.tree, + self.session, + string, + native, + &self.dims, + )? { if nonblocking { return Err(unsupported("nonblocking assignment to a class property")); } - let handle = - expression_binding::object_receiver(self.tree, receiver, native, &self.dims)?; + let handle = expression_binding::object_receiver( + self.tree, + self.session, + receiver, + native, + &self.dims, + )?; let receiver = (op == StringOp::Putc).then(|| { classes::object_call( system_functions::ObjectOp::Load(property.field), @@ -1514,8 +1710,8 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { }) } - fn reject_tagged_integral_target(&self, root: celox_sv_syntax::ExprId) -> Converted<()> { - if dimensions::operand_shape(root, self.tree, &self.dims)?.is_some_and(|ty| { + fn reject_tagged_integral_target(&mut self, root: celox_sv_syntax::ExprId) -> Converted<()> { + if dimensions::operand_shape(root, self.tree, self.session, &self.dims)?.is_some_and(|ty| { ty.members .first() .is_some_and(packed_structs::PackedMember::is_tagged) @@ -1618,7 +1814,13 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { if control.is_some() { return Err(unsupported("delayed nonblocking event trigger")); } - if !events::is_handle(self.tree, *target, self.tree.declarations(), &self.dims) { + if !events::is_handle( + self.tree, + self.session, + *target, + self.tree.declarations(), + &self.dims, + ) { return Err(unsupported( "event trigger of a value that is not a named event", )); @@ -1700,6 +1902,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { let signals = type_binding::local_signals( native, self.tree, + self.session, &self.dims.const_env, &self.type_aliases, None, @@ -1718,7 +1921,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { { // A declaration may not repeat a name of its own scope, such as // a subroutine argument (IEEE 1800-2023 6.21). - let scope = self.scopes.last().expect("a body always has a scope"); + let scope = self.names.scopes.last().expect("a body always has a scope"); if scope .entries .iter() @@ -1756,6 +1959,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.tree.declarations(), &target, self.tree, + self.session, &scoped, )?; self.rename_expr(&mut init); @@ -1824,6 +2028,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { root, self.tree.declarations(), self.tree, + self.session, &self.dims, )?; } @@ -1899,7 +2104,8 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { for (name, ty) in unpacked_structs::aggregates(source, r#type) { let entry = self.take_binding(&name, None, 0); self.dims.insert(name.clone(), dimensions_from_type(&ty)); - self.scopes + self.names + .scopes .last_mut() .expect("a body always has a scope") .entries @@ -1935,6 +2141,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { parameters::parameters_from_native( &authored, self.tree, + self.session, &mut parameters, true, &self.dims.const_env, @@ -1948,6 +2155,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { types.remove(name); if !parameters::bind_parameter( self.tree, + self.session, &mut self.dims.const_env, &mut types, &mut self.dims.parameter_values, @@ -1965,7 +2173,8 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } else { return Err(unsupported("local parameter whose value is not constant")); }; - self.local_constants + self.names + .local_constants .insert(name.to_string(), literal.clone()); self.dims .parameter_values @@ -1980,7 +2189,8 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .expression_signedness .insert(name.to_string(), ty.signed); } - self.scopes + self.names + .scopes .last_mut() .expect("a body always has a scope") .entries @@ -1994,11 +2204,15 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { root: celox_sv_syntax::ExprId, ) -> Result, AnalyzerError> { let native = self.tree.declarations(); - if let Some((mut value, _)) = array_reductions::bind(root, native, self.tree, &self.dims)? { + if let Some((mut value, _)) = + array_reductions::bind(root, native, self.tree, self.session, &self.dims)? + { self.rename_expr(&mut value); return Ok(vec![Stmt::Eval(value)]); } - if let Some(mut value) = containers::value(root, native, self.tree, &self.dims, true)? { + if let Some(mut value) = + containers::value(root, native, self.tree, self.session, &self.dims, true)? + { self.rename_expr(&mut value); return Ok(vec![Stmt::Eval(value)]); } @@ -2008,8 +2222,13 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } = &native .expression(expression_binding::ungroup(root, native)) .kind - && let Some((op, string)) = - expression_binding::string_method(self.tree, *expression, native, &self.dims) + && let Some((op, string)) = expression_binding::string_method( + self.tree, + self.session, + *expression, + native, + &self.dims, + ) { let (_, count) = StringOp::method(&op.to_string()).expect("a method name"); let args = arguments @@ -2019,7 +2238,9 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { .filter(|args| args.len() == count) .ok_or_else(|| unsupported(format!("arguments of string method `{op}`")))? .into_iter() - .map(|arg| expression_binding::value(arg, native, self.tree, &self.dims)) + .map(|arg| { + expression_binding::value(arg, native, self.tree, self.session, &self.dims) + }) .collect::, _>>()?; // A method that returns a value has no effect as a statement. return if op.updates_receiver() { @@ -2037,14 +2258,20 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { expression_binding::call_statement_root(root, discarded, self.tree.declarations())?; if discarded && let Some((mut value, _)) = - array_reductions::bind(query_root, native, self.tree, &self.dims)? + array_reductions::bind(query_root, native, self.tree, self.session, &self.dims)? { self.rename_expr(&mut value); return Ok(vec![Stmt::Eval(value)]); } if discarded - && let Some(mut value) = - containers::value(query_root, native, self.tree, &self.dims, true)? + && let Some(mut value) = containers::value( + query_root, + native, + self.tree, + self.session, + &self.dims, + true, + )? { self.rename_expr(&mut value); return Ok(vec![Stmt::Eval(value)]); @@ -2066,7 +2293,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { expression_binding::native_name( self.tree, expression, - self.tree.declarations() + self.tree.declarations(), ) .as_deref(), Some("randomize" | "std::randomize") @@ -2092,6 +2319,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { discarded, self.tree.declarations(), self.tree, + self.session, &self.dims, signatures, )? { @@ -2141,8 +2369,13 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { // (IEEE 1800-2023 6.24.2). if name == "$cast" && !discarded - && let Some(cast) = - expression_binding::object_cast(self.tree, arguments, declarations, &self.dims)? + && let Some(cast) = expression_binding::object_cast( + self.tree, + self.session, + arguments, + declarations, + &self.dims, + )? { let error = Stmt::SystemTask { task: SystemTask::Severity(system_functions::Severity::Error), @@ -2182,6 +2415,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { id, declarations, self.tree, + self.session, &self.dims, None, )?); @@ -2191,6 +2425,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { &ids, values, self.tree, + self.session, declarations, &self.dims, )?; @@ -2235,8 +2470,14 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { text.extend_from_slice(&literal); continue; } - let value = - expression_binding::bind_value(id, declarations, self.tree, &self.dims, None)?; + let value = expression_binding::bind_value( + id, + declarations, + self.tree, + self.session, + &self.dims, + None, + )?; if pending > 0 { pending -= 1; } else { @@ -2259,6 +2500,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { &ids, &mut values, self.tree, + self.session, declarations, &self.dims, )?; @@ -2273,8 +2515,14 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { return self.format_assignment(output, value); } if name == "$sformatf" { - let mut value = - expression_binding::bind_value(root, declarations, self.tree, &self.dims, None)?; + let mut value = expression_binding::bind_value( + root, + declarations, + self.tree, + self.session, + &self.dims, + None, + )?; self.rename_expr(&mut value); return Ok(vec![Stmt::Eval(value)]); } @@ -2293,6 +2541,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { root, declarations, self.tree, + self.session, &self.dims, None, )?; @@ -2324,10 +2573,12 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { let text = dump_selection_name( id, self.tree, + self.session, &self.dims, - &|value| self.rename_const(value), + &|value| self.names.rename_const(value), &|name| { - self.scopes + self.names + .scopes .iter() .any(|scope| scope.entries.iter().any(|entry| entry.source == name)) }, @@ -2347,8 +2598,14 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } // Renamed below, once the types of the source names have // chosen the conversions of the format. - let value = - expression_binding::bind_value(id, declarations, self.tree, &self.dims, None)?; + let value = expression_binding::bind_value( + id, + declarations, + self.tree, + self.session, + &self.dims, + None, + )?; Ok(SystemTaskArg::Expr(value)) }) .collect::, AnalyzerError>>()?; @@ -2364,21 +2621,23 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } // A string literal that %t converts is bound as a value: the binder // handles every literal form, triple quotes and escapes included. + let divisor = timescales::time_divisor(root, self.tree)?; let mut bind = |index: usize| -> Result, AnalyzerError> { let Some(id) = ids.get(index).copied().flatten() else { return Ok(None); }; - let mut value = - expression_binding::bind_value(id, declarations, self.tree, &self.dims, None)?; - self.rename_expr(&mut value); + let mut value = expression_binding::bind_value( + id, + declarations, + self.tree, + self.session, + &self.dims, + None, + )?; + self.names.rename_expr(&mut value); Ok(Some(value)) }; - scale_time_conversions( - task, - &mut args, - timescales::time_divisor(root, self.tree)?, - &mut bind, - )?; + scale_time_conversions(task, &mut args, divisor, &mut bind)?; // Keep Veryl's assertion calls as calls: their message arguments // execute even on success, unlike an SV assertion's fail action. Ok(vec![Stmt::SystemTask { @@ -2402,7 +2661,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { // call's display, output or module-variable effects optional. None } else { - expr_to_const(&self.tree.state, condition.clone()).and_then(|condition| { + expr_to_const(self.session, condition.clone()).and_then(|condition| { eval_ast_const_expr(&self.tree.functions, &condition, &self.dims.const_env) }) }; @@ -2428,7 +2687,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } fn cond_predicate( - &self, + &mut self, predicate: &celox_sv_syntax::Predicate, ) -> Result { let [item] = predicate.items.as_slice() else { @@ -2441,9 +2700,11 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { item.expression, self.tree.declarations(), self.tree, + self.session, &self.dims, )?; - let mut condition = statements::simplify_condition(self.tree, condition, &self.dims); + let mut condition = + statements::simplify_condition(self.tree, self.session, condition, &self.dims); self.rename_expr(&mut condition); Ok(condition) } @@ -2462,6 +2723,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { group.data_type, self.tree.declarations(), self.tree, + self.session, &self.dims.const_env, &self.type_aliases, )? @@ -2477,6 +2739,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.tree.declarations(), &target, self.tree, + self.session, &scoped, )?; self.rename_expr(&mut value); @@ -2750,6 +3013,7 @@ fn attribute_reports( pub(super) fn subroutine_param_declarations( native: &celox_sv_syntax::Subroutine, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Converted< @@ -2763,6 +3027,7 @@ pub(super) fn subroutine_param_declarations( type_binding::subroutine_formals( native, tree, + session, &PackedDimensions::new(HashMap::default(), env, aliases), ) } @@ -2771,6 +3036,7 @@ pub(super) fn subroutine_param_declarations( /// items, in declaration order, keyed by their (qualified) names. pub(super) fn subroutine_argument_names( tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, type_aliases: &HashMap, ) -> Result< @@ -2784,7 +3050,7 @@ pub(super) fn subroutine_argument_names( let mut names = HashMap::default(); let mut shapes = HashMap::default(); let mut directions = HashMap::default(); - for item in generate::subroutine_items(tree, const_env, type_aliases)? { + for item in generate::subroutine_items(tree, session, const_env, type_aliases)? { let tree = &item.scoped(tree); for native_id in subroutine_owners::item(item.id, tree)? { let native = tree.declarations().subroutine(native_id); @@ -2792,6 +3058,7 @@ pub(super) fn subroutine_argument_names( let params = subroutine_param_declarations( native, tree, + session, &item.env, &item.type_aliases(type_aliases), )?; @@ -2809,12 +3076,13 @@ pub(super) fn subroutine_argument_names( names.insert(qualified.clone(), params); shapes.insert(qualified, param_shapes); } - for class in classes::item_classes(item.id, tree) { + for class in classes::item_classes(item.id, tree, session) { 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); - let handle = classes::handle_type(tree, &class) + let (env, aliases) = + classes::specializations::scope(session, &class, &item.env, &aliases); + let handle = classes::handle_type(tree, session, &class) .ok_or_else(|| unsupported(format!("class `{class}`")))?; let mut constructor = false; let this = ( @@ -2823,7 +3091,7 @@ pub(super) fn subroutine_argument_names( handle.clone(), None, ); - let mut methods = classes::declared_methods(tree, &class)? + let mut methods = classes::declared_methods(tree, session, &class)? .into_iter() .map(|(native_id, is_static)| { let name = instances::normalize_identifier( @@ -2838,7 +3106,7 @@ pub(super) fn subroutine_argument_names( .collect::>(); // A class that cannot be laid out reports why where it is // lowered. - let layout = classes::class(tree, &class, &env, &aliases).ok(); + let layout = classes::class(tree, session, &class, &env, &aliases).ok(); if let Some(layout) = &layout { methods.extend(layout.dispatched_methods().map(|method| { ( @@ -2850,7 +3118,8 @@ pub(super) fn subroutine_argument_names( } for (name, native_id, is_static) in methods { let native = tree.declarations().subroutine(native_id); - let mut params = subroutine_param_declarations(native, tree, &env, &aliases)?; + let mut params = + subroutine_param_declarations(native, tree, session, &env, &aliases)?; constructor |= native.kind == celox_sv_syntax::SubroutineKind::Constructor; if !is_static { params.insert(0, this.clone()); @@ -2924,6 +3193,7 @@ pub(super) fn subroutine_argument_names( /// bodies. pub(super) fn subroutines_from_scope( tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, packed_dimensions: &PackedDimensions, parameter_literals: &HashMap, @@ -2931,6 +3201,7 @@ pub(super) fn subroutines_from_scope( ) -> Result, AnalyzerError> { subroutines_from_scope_with( tree, + session, const_env, packed_dimensions, parameter_literals, @@ -2944,6 +3215,7 @@ pub(super) fn subroutines_from_scope( /// failing. pub(super) fn subroutines_from_scope_with( tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, packed_dimensions: &PackedDimensions, parameter_literals: &HashMap, @@ -2952,6 +3224,7 @@ pub(super) fn subroutines_from_scope_with( ) -> Result, AnalyzerError> { subroutines_with_symbolic_parameters( tree, + session, const_env, packed_dimensions, parameter_literals, @@ -2964,6 +3237,7 @@ pub(super) fn subroutines_from_scope_with( #[allow(clippy::too_many_arguments)] pub(super) fn subroutines_with_symbolic_parameters( tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, packed_dimensions: &PackedDimensions, parameter_literals: &HashMap, @@ -2973,7 +3247,7 @@ pub(super) fn subroutines_with_symbolic_parameters( ) -> Result, AnalyzerError> { let module_type_aliases = &packed_dimensions.type_aliases; let mut subroutines = Vec::new(); - let active = generate::subroutine_items(tree, const_env, module_type_aliases)?; + let active = generate::subroutine_items(tree, session, const_env, module_type_aliases)?; let mut views = generate::ScopeViews::with_literals(packed_dimensions, parameter_literals); for item in &active { let tree = &item.scoped(tree); @@ -3014,6 +3288,7 @@ pub(super) fn subroutines_with_symbolic_parameters( let lowered = lower_subroutine( native_id, tree, + session, &declaration_env, &type_aliases, item_dimensions, @@ -3042,7 +3317,7 @@ pub(super) fn subroutines_with_symbolic_parameters( } subroutines.push(subroutine); } - for class in classes::item_classes(item.id, tree) { + for class in classes::item_classes(item.id, tree, session) { let (item_dimensions, literals) = views.get(item); let tree = &item.enter(tree); let type_aliases = item.type_aliases(module_type_aliases); @@ -3050,6 +3325,7 @@ pub(super) fn subroutines_with_symbolic_parameters( lower_class( &class, tree, + session, &item.env, &type_aliases, item_dimensions, @@ -3085,6 +3361,7 @@ pub(super) fn subroutines_with_symbolic_parameters( }; let targets = classes::dispatch_targets( tree, + session, &class.name, &method.name, const_env, @@ -3113,7 +3390,8 @@ pub(super) fn subroutines_with_symbolic_parameters( let Some(cast) = imported.subroutines.iter().find(|known| known.name == name) else { continue; }; - let targets = classes::cast_targets(tree, &class.name, const_env, module_type_aliases)?; + let targets = + classes::cast_targets(tree, session, &class.name, const_env, module_type_aliases)?; let covered = case_ids(&cast.body); if targets.iter().all(|id| covered.contains(id)) { continue; @@ -3155,6 +3433,7 @@ fn case_ids(body: &[Stmt]) -> HashSet { pub(super) fn lower_subroutine( native_id: celox_sv_syntax::SubroutineId, tree: &AnalysisContext<'_>, + session: &mut Session, declaration_env: &HashMap, type_aliases: &HashMap, item_dimensions: &PackedDimensions, @@ -3182,11 +3461,12 @@ pub(super) fn lower_subroutine( }); let handle = class .map(|class| { - classes::handle_type(tree, &class.name) + classes::handle_type(tree, session, &class.name) .ok_or_else(|| unsupported(format!("class `{}`", class.name))) }) .transpose()?; - let params = subroutine_param_declarations(native, tree, declaration_env, type_aliases)?; + let params = + subroutine_param_declarations(native, tree, session, declaration_env, type_aliases)?; let mut formal_names = HashSet::default(); if let Some((name, ..)) = params .iter() @@ -3205,6 +3485,7 @@ pub(super) fn lower_subroutine( Some(type_binding::implicit_subroutine_type( id, tree, + session, declaration_env, type_aliases, )?) @@ -3213,6 +3494,7 @@ pub(super) fn lower_subroutine( id, tree.declarations(), tree, + session, declaration_env, type_aliases, )?, @@ -3228,6 +3510,7 @@ pub(super) fn lower_subroutine( } let mut builder = BodyBuilder::new( tree, + session, item_dimensions, state, system_functions::Body::Subroutine, @@ -3278,6 +3561,7 @@ pub(super) fn lower_subroutine( if !ty.unpacked_ranges.is_empty() { array_compatibility::check_native_unpacked_assignment( tree, + builder.session, root, &dimensions_from_type(ty), || format!("default of `{formal}`"), @@ -3293,10 +3577,11 @@ pub(super) fn lower_subroutine( root, tree.declarations(), tree, + builder.session, &builder.dims, shape.as_ref(), )?; - builder.rename_expr(&mut value); + builder.names.rename_expr(&mut value); Ok(value) }) .transpose() @@ -3433,7 +3718,7 @@ pub(super) fn lower_subroutine( // initializers, with the base call the prologue makes. let arguments = match ( super_new(tree.declarations(), &items), - classes::base_arguments(tree, &class.name), + classes::base_arguments(tree, builder.session, &class.name), ) { (Some(_), Some(_)) => { return Err(unsupported( @@ -3539,13 +3824,14 @@ pub(super) fn lower_subroutine( .chain(&mut subroutine.sensitivity_body) { qualify_stmt(item, stmt); - substitute_stmt_constants(tree, stmt, declaration_env, literals); + substitute_stmt_constants(tree, builder.session, 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, + builder.session, default.clone(), &item.env, literals, @@ -3577,12 +3863,13 @@ pub(super) fn lower_subroutine( } } if suspends { - lifetimes::check_constant_initializers(tree, &subroutine.body, &statics)?; + lifetimes::check_constant_initializers(tree, builder.session, &subroutine.body, &statics)?; } if !builder.state.constant_evaluation { let retain_result = !builder.automatic && lifetimes::check_static_result( tree, + builder.session, &builder.dims.const_env, builder.state.locals, &subroutine, @@ -3596,6 +3883,7 @@ pub(super) fn lower_subroutine( suspends || lifetimes::check_subroutine_statics( tree, + builder.session, &subroutine, &builder.dims.const_env, builder.state.locals, @@ -3608,6 +3896,7 @@ pub(super) fn lower_subroutine( .collect::>(); let (mut kept, mut initializers) = lifetimes::keep_static_locals( tree, + builder.session, &retained_types, builder.state.subroutine_directions, std::iter::once((&mut subroutine.body, false)), @@ -3631,7 +3920,13 @@ pub(super) fn lower_subroutine( } for initializer in &mut initializers { qualify_stmt(item, initializer); - substitute_stmt_constants(tree, initializer, declaration_env, literals); + substitute_stmt_constants( + tree, + builder.session, + initializer, + declaration_env, + literals, + ); } for name in &kept { let ty = static_types @@ -3776,6 +4071,7 @@ impl BodyBuilder<'_, '_, '_> { if let Some(base) = &class.base { let base = classes::class( self.tree, + self.session, base, &self.dims.const_env, &self.dims.type_aliases, @@ -3783,6 +4079,7 @@ impl BodyBuilder<'_, '_, '_> { if let Some(method) = base.method("new") { expression_binding::check_member_access( self.tree, + self.session, &self.dims, &method.owner, &method.name, @@ -3796,8 +4093,13 @@ impl BodyBuilder<'_, '_, '_> { args.push( actual .map(|value| { - let mut value = - expression_binding::value(value, native, self.tree, &self.dims)?; + let mut value = expression_binding::value( + value, + native, + self.tree, + self.session, + &self.dims, + )?; self.rename_expr(&mut value); Ok::<_, AnalyzerError>(value) }) @@ -3827,8 +4129,13 @@ impl BodyBuilder<'_, '_, '_> { continue; }; if let Some(container) = property.r#type.container.as_deref() { - let mut value = - containers::assignment(initializer, self.tree, &self.dims, container)?; + let mut value = containers::assignment( + initializer, + self.tree, + self.session, + &self.dims, + container, + )?; self.rename_expr(&mut value); body.push(Stmt::Eval(classes::object_call( system_functions::ObjectOp::Store(property.field), @@ -3839,6 +4146,7 @@ impl BodyBuilder<'_, '_, '_> { let mut value = match property.r#type.class() { Some(class) => expression_binding::object_constructor( self.tree, + self.session, initializer, native, &self.dims, @@ -3852,6 +4160,7 @@ impl BodyBuilder<'_, '_, '_> { initializer, native, self.tree, + self.session, &self.dims, Some(&dimensions_from_type(&property.r#type)), )?, @@ -3900,15 +4209,21 @@ impl BodyBuilder<'_, '_, '_> { /// hidden local holds the heap stream of the source, from which each /// variable takes its bits in turn. fn stream_assignment( - &self, + &mut self, op: &str, nonblocking: bool, left: celox_sv_syntax::ExprId, right: celox_sv_syntax::ExprId, ) -> Converted>> { let native = self.tree.declarations(); - let Some(unpack) = - expression_binding::stream_unpack(left, right, native, self.tree, &self.dims)? + let Some(unpack) = expression_binding::stream_unpack( + left, + right, + native, + self.tree, + self.session, + &self.dims, + )? else { return Ok(None); }; @@ -4010,7 +4325,7 @@ impl BodyBuilder<'_, '_, '_> { return Ok(None); } let Some((property, receiver)) = - expression_binding::object_property(self.tree, base, native, &self.dims)? + expression_binding::object_property(self.tree, self.session, base, native, &self.dims)? else { return Ok(None); }; @@ -4023,8 +4338,13 @@ impl BodyBuilder<'_, '_, '_> { if nonblocking { return Err(unsupported("nonblocking assignment to a class property")); } - let mut handle = - expression_binding::object_receiver(self.tree, receiver, native, &self.dims)?; + let mut handle = expression_binding::object_receiver( + self.tree, + self.session, + receiver, + native, + &self.dims, + )?; self.rename_expr(&mut handle); let mut body = Vec::new(); // The object is evaluated once, for both the load and the store; an @@ -4053,23 +4373,34 @@ impl BodyBuilder<'_, '_, '_> { property.r#type.clone(), ); self.dims.property_select_base = Some(base); - let lhs = expression_binding::variable_lvalue(left, native, self.tree, &self.dims); + let lhs = + expression_binding::variable_lvalue(left, native, self.tree, self.session, &self.dims); self.dims.property_select_base = None; let lhs = lhs.and_then(|lhs| self.hoist_index_calls(lhs, op != "=", &mut body)); // The width of the selection, which a runtime position leaves unknown // to a constant evaluation, is that of its value. let width = lhs.as_ref().ok().and_then(|_| { self.dims.property_select_base = Some(base); - let target = expression_binding::value(left, native, self.tree, &self.dims); + let target = + expression_binding::value(left, native, self.tree, self.session, &self.dims); self.dims.property_select_base = None; 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) + expression_binding::expression( + right, + native, + &lhs, + self.tree, + self.session, + &self.dims, + ) } else { - expression_binding::value(right, native, self.tree, &self.dims) - .and_then(|value| assignment_op_expr(self.tree, &lhs, op, value, &self.dims)) + expression_binding::value(right, native, self.tree, self.session, &self.dims) + .and_then(|value| { + assignment_op_expr(self.tree, self.session, &lhs, op, value, &self.dims) + }) }; let mut lhs = lhs; self.rename_lvalue(&mut lhs); @@ -4285,8 +4616,13 @@ impl BodyBuilder<'_, '_, '_> { right: celox_sv_syntax::ExprId, ) -> Converted>> { let native = self.tree.declarations(); - let Some((aggregate, class, receiver)) = - expression_binding::object_aggregate_property(self.tree, left, native, &self.dims)? + let Some((aggregate, class, receiver)) = expression_binding::object_aggregate_property( + self.tree, + self.session, + left, + native, + &self.dims, + )? else { return Ok(None); }; @@ -4298,8 +4634,13 @@ impl BodyBuilder<'_, '_, '_> { "operator `{op}` on an unpacked structure" ))); } - let mut handle = - expression_binding::object_receiver(self.tree, receiver, native, &self.dims)?; + let mut handle = expression_binding::object_receiver( + self.tree, + self.session, + receiver, + native, + &self.dims, + )?; self.rename_expr(&mut handle); self.aggregate_store(&aggregate, &class, handle, right) .map(Some) @@ -4320,11 +4661,19 @@ impl BodyBuilder<'_, '_, '_> { .unpacked_struct() .expect("an unpacked structure property") .clone(); - unpacked_structs::check_value(&structure, right, native, self.tree, &self.dims)?; + unpacked_structs::check_value( + &structure, + right, + native, + self.tree, + self.session, + &self.dims, + )?; let mut value = expression_binding::bind_value( right, native, self.tree, + self.session, &self.dims, Some(&dimensions_from_type(&aggregate.r#type)), )?; @@ -4385,6 +4734,7 @@ impl BodyBuilder<'_, '_, '_> { fn lower_class( name: &str, tree: &AnalysisContext<'_>, + session: &mut Session, declaration_env: &HashMap, type_aliases: &HashMap, item_dimensions: &PackedDimensions, @@ -4394,28 +4744,29 @@ fn lower_class( ) -> Converted> { // A specialization's methods see its parameters (IEEE 1800-2023 8.25). let (declaration_env, type_aliases) = - classes::specializations::scope(tree, name, declaration_env, type_aliases); + classes::specializations::scope(session, name, declaration_env, type_aliases); let (item_dimensions, literals) = - classes::specializations::body_scope(tree, name, item_dimensions, literals); + classes::specializations::body_scope(session, name, item_dimensions, literals); let (declaration_env, type_aliases, item_dimensions, literals) = (&declaration_env, &type_aliases, &item_dimensions, &literals); - let class = match classes::class(tree, name, declaration_env, type_aliases) { + let class = match classes::class(tree, session, name, declaration_env, type_aliases) { Ok(class) => class, // An interface class that cannot be laid out has no subroutines; a // use of its handles reports why (IEEE 1800-2023 8.26). - Err(AnalyzerError::Unsupported(_)) if classes::is_interface(tree, name) => { + Err(AnalyzerError::Unsupported(_)) if classes::is_interface(tree, session, name) => { return Ok(Vec::new()); } Err(error) => return Err(error), }; let mut subroutines = Vec::new(); let mut constructor = false; - for (id, _) in classes::declared_methods(tree, name)? { + for (id, _) in classes::declared_methods(tree, session, name)? { constructor |= tree.declarations().subroutine(id).kind == celox_sv_syntax::SubroutineKind::Constructor; subroutines.push(lower_subroutine( id, tree, + session, declaration_env, type_aliases, item_dimensions, @@ -4427,11 +4778,18 @@ fn lower_class( )?); } for method in class.dispatched_methods() { - let targets = - classes::dispatch_targets(tree, name, &method.name, declaration_env, type_aliases)?; + let targets = classes::dispatch_targets( + tree, + session, + name, + &method.name, + declaration_env, + type_aliases, + )?; subroutines.push(lower_subroutine( method.native, tree, + session, declaration_env, type_aliases, item_dimensions, @@ -4443,7 +4801,7 @@ fn lower_class( )?); } if !constructor && !class.is_interface { - let handle = classes::handle_type(tree, name) + let handle = classes::handle_type(tree, session, name) .ok_or_else(|| unsupported(format!("class `{name}`")))?; let ir_type = crate::ir::Type::from_ast( scoped_type(handle.clone(), declaration_env), @@ -4454,6 +4812,7 @@ fn lower_class( ); let mut builder = BodyBuilder::new( tree, + session, item_dimensions, state, system_functions::Body::Subroutine, @@ -4464,12 +4823,9 @@ fn lower_class( builder.enter_class_scope(&class); let this = builder.declare(classes::THIS, handle.clone()); let result = builder.declare("new", handle); - let body = builder.constructor_prologue( - &class, - &this, - &result, - classes::base_arguments(tree, name).unwrap_or_default(), - )?; + let base_arguments = + classes::base_arguments(tree, builder.session, name).unwrap_or_default(); + let body = builder.constructor_prologue(&class, &this, &result, base_arguments)?; builder.pop_scope(); let mut subroutine = Subroutine { name: item.name(&classes::Class::subroutine_name(name, "new")), @@ -4494,13 +4850,14 @@ fn lower_class( }; for stmt in &mut subroutine.body { qualify_stmt(item, stmt); - substitute_stmt_constants(tree, stmt, declaration_env, literals); + substitute_stmt_constants(tree, builder.session, stmt, declaration_env, literals); } subroutines.push(subroutine); } subroutines.push(lower_cast( name, tree, + session, declaration_env, type_aliases, item_dimensions, @@ -4510,6 +4867,7 @@ fn lower_class( subroutines.extend(randomization::lower( &class, tree, + session, item_dimensions, state, item, @@ -4529,6 +4887,7 @@ pub(super) const CAST_SOURCE: &str = "source"; fn lower_cast( name: &str, tree: &AnalysisContext<'_>, + session: &mut Session, declaration_env: &HashMap, type_aliases: &HashMap, item_dimensions: &PackedDimensions, @@ -4539,20 +4898,22 @@ fn lower_cast( constants: &*item.env, functions: &tree.functions, }; - let handle = - classes::handle_type(tree, name).ok_or_else(|| unsupported(format!("class `{name}`")))?; + let handle = classes::handle_type(tree, session, name) + .ok_or_else(|| unsupported(format!("class `{name}`")))?; let ir_handle = crate::ir::Type::from_ast(scoped_type(handle.clone(), declaration_env), &environment); let ir_int = crate::ir::Type::from_ast(int_type(), &environment); let mut labels = vec![0]; labels.extend(classes::cast_targets( tree, + session, name, declaration_env, type_aliases, )?); let mut builder = BodyBuilder::new( tree, + session, item_dimensions, state, system_functions::Body::Subroutine, @@ -4639,6 +5000,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( tree: &AnalysisContext<'_>, + session: &mut Session, stmt: &mut Stmt, const_env: &HashMap, literals: &HashMap, @@ -4647,6 +5009,7 @@ pub(super) fn substitute_stmt_constants( &mut |expr| { *expr = substitute_expr_constants_with_parameter_literals( tree, + session, expr.clone(), const_env, literals, @@ -4662,6 +5025,7 @@ pub(super) fn substitute_stmt_constants( /// Every `initial` process of the active generate items. pub(super) fn initial_processes_from_scope( tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, packed_dimensions: &PackedDimensions, parameter_literals: &HashMap, @@ -4672,7 +5036,7 @@ pub(super) fn initial_processes_from_scope( // `always` procedure (IEEE 1800-2023 10.5). let mut initializers = Vec::new(); let mut processes = Vec::new(); - let active = generate::items(tree, const_env, &type_aliases)?; + let active = generate::items(tree, session, const_env, &type_aliases)?; let mut views = generate::ScopeViews::with_literals(packed_dimensions, parameter_literals); for (creation_order, item) in active.iter().enumerate() { let tree = &item.scoped(tree); @@ -4715,7 +5079,7 @@ pub(super) fn initial_processes_from_scope( } // Static class properties are initialized like variables, in the // scope of the class that declares them (IEEE 1800-2023 8.9, 8.25). - for property in classes::item_statics(item.id, tree, &item.env, &type_aliases) { + for property in classes::item_statics(item.id, tree, session, &item.env, &type_aliases) { if let Some(value) = property.initializer { assignments.push((property.variable, Some(value), Some(property.owner))); } else if events::is_event(&property.r#type) { @@ -4748,7 +5112,7 @@ pub(super) fn initial_processes_from_scope( continue; }; let scoped = owner.map(|owner| { - classes::specializations::body_scope(tree, &owner, item_dimensions, literals) + classes::specializations::body_scope(session, &owner, item_dimensions, literals) }); let (item_dimensions, literals) = match &scoped { Some((dimensions, literals)) => (dimensions, literals), @@ -4758,6 +5122,7 @@ pub(super) fn initial_processes_from_scope( let id = native; array_compatibility::check_native_unpacked_assignment( tree, + session, id, &target, || format!("initializer of `{name}`"), @@ -4770,6 +5135,7 @@ pub(super) fn initial_processes_from_scope( tree.declarations(), &lhs, tree, + session, item_dimensions, )?; let LValue::Ident(name) = lhs else { @@ -4778,7 +5144,13 @@ pub(super) fn initial_processes_from_scope( // A variable of unpacked structure type initializes its leaves. let mut stmt = match unpacked_structs::targets(&name, item_dimensions) { Some(parts) => { - unpacked_structs::check_assignment(&name, native, tree, item_dimensions)?; + unpacked_structs::check_assignment( + &name, + native, + tree, + session, + item_dimensions, + )?; Stmt::AssignConcat { parts, rhs, @@ -4795,6 +5167,7 @@ pub(super) fn initial_processes_from_scope( if scoped.is_some() { substitute_stmt_constants( tree, + session, &mut stmt, &item_dimensions.const_env, literals, @@ -4804,9 +5177,9 @@ pub(super) fn initial_processes_from_scope( } let (_, literals) = views.get(item); for stmt in &mut body { - substitute_stmt_constants(tree, stmt, &item.env, literals); + substitute_stmt_constants(tree, session, stmt, &item.env, literals); qualify_stmt(item, stmt); - substitute_stmt_constants(tree, stmt, const_env, parameter_literals); + substitute_stmt_constants(tree, session, stmt, const_env, parameter_literals); } if !body.is_empty() { initializers.push(InitialProcess { @@ -4844,6 +5217,7 @@ pub(super) fn initial_processes_from_scope( || ff_process::always_falls_back_to_process( procedure, tree, + session, views.get(item).0, )? => { @@ -4855,6 +5229,7 @@ pub(super) fn initial_processes_from_scope( let is_final = procedure.kind == celox_sv_syntax::ProcedureKind::Final; let mut builder = BodyBuilder::new( tree, + session, item_dimensions, state, if is_final { @@ -4881,9 +5256,9 @@ pub(super) fn initial_processes_from_scope( body }; for stmt in body.iter_mut().chain(&mut validation_body) { - substitute_stmt_constants(tree, stmt, &item.env, literals); + substitute_stmt_constants(tree, builder.session, stmt, &item.env, literals); qualify_stmt(item, stmt); - substitute_stmt_constants(tree, stmt, const_env, parameter_literals); + substitute_stmt_constants(tree, builder.session, stmt, const_env, parameter_literals); } processes.push(InitialProcess { creation_order, @@ -5096,6 +5471,7 @@ pub(super) fn source_span( fn dump_selection_name( id: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, rename: &dyn Fn(&mut ConstExpr), is_local: &dyn Fn(&str) -> bool, @@ -5106,6 +5482,7 @@ fn dump_selection_name( fn append( id: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, rename: &dyn Fn(&mut ConstExpr), kind: &mut &'static str, @@ -5127,7 +5504,7 @@ fn dump_selection_name( separator, name, } if separator == "." || separator == "::" => { - append(*expression, tree, dimensions, rename, kind, fields)?; + append(*expression, tree, session, dimensions, rename, kind, fields)?; if separator == "::" { *kind = "package"; } @@ -5145,8 +5522,8 @@ fn dump_selection_name( "$dumpvars hierarchy selection requires a single constant index", )); }; - append(*expression, tree, dimensions, rename, kind, fields)?; - let mut value = constant_binding::bind(*index, tree, dimensions)? + append(*expression, tree, session, dimensions, rename, kind, fields)?; + let mut value = constant_binding::bind(*index, tree, session, dimensions)? .ok_or_else(|| unsupported("$dumpvars hierarchy index must be constant"))?; rename(&mut value); let index = eval_ast_const_expr(&tree.functions, &value, &dimensions.const_env) @@ -5165,7 +5542,15 @@ fn dump_selection_name( } let mut kind = "relative"; let mut fields = Vec::new(); - append(id, tree, dimensions, rename, &mut kind, &mut fields)?; + append( + id, + tree, + session, + dimensions, + rename, + &mut kind, + &mut fields, + )?; // Imports bind declarations, not a module-local spelling. Nested procedural // declarations shadow these aliases just as they do for value expressions. if kind == "relative" && fields.len() == 2 && !is_local(&fields[1]) { diff --git a/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs b/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs index 7769edabdde..d757d4d0962 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs @@ -4,7 +4,7 @@ use celox_sv_syntax::AssertionHeader; impl BodyBuilder<'_, '_, '_> { pub(super) fn native_assertion_condition( - &self, + &mut self, keyword: &str, header: &AssertionHeader, ) -> Result { diff --git a/crates/celox-sv-analyzer/src/ast/procedural/control.rs b/crates/celox-sv-analyzer/src/ast/procedural/control.rs index a1baad37aae..09fba671ca7 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -119,11 +119,11 @@ impl BodyBuilder<'_, '_, '_> { pending.extend(kind.children()); } } - let depth = self.scopes.len(); + let depth = self.names.scopes.len(); let result = self.native_body_machine(ids); // Restore lexical bindings on every diagnostic path, just as the old // recursive block/for wrappers did; no native failure is retried. - while self.scopes.len() > depth { + while self.names.scopes.len() > depth { self.pop_scope(); } result @@ -343,6 +343,7 @@ impl BodyBuilder<'_, '_, '_> { // `wait(e.triggered)` (IEEE 1800-2023 15.5.3). if let Some(event) = events::triggered( self.tree, + self.session, *condition, self.tree.declarations(), &self.dims, @@ -495,6 +496,7 @@ impl BodyBuilder<'_, '_, '_> { { array_compatibility::check_native_unpacked_assignment( self.tree, + self.session, *id, target, || "return value".into(), @@ -508,6 +510,7 @@ impl BodyBuilder<'_, '_, '_> { id, native, self.tree, + self.session, &self.dims, if expression_binding::is_stream(id, native) { self.stream_return_shape.as_ref() @@ -785,7 +788,7 @@ impl BodyBuilder<'_, '_, '_> { Ok(output) } fn native_case_labels( - &self, + &mut self, labels: &[celox_sv_syntax::CaseMatch], inside: bool, ) -> Result>, AnalyzerError> { @@ -815,6 +818,7 @@ mod tests { use super::*; #[test] fn native_scope_jobs_restore_bindings_after_a_typed_leaf_error() { + let session = &mut Session::default(); let tree=crate::source_tree::parse_source("module M;initial begin automatic int outer_value=1;begin automatic int inner_value=2;disable target;end end endmodule",std::path::Path::new("scope-error.sv")).unwrap(); let tree = AnalysisContext::unspecialized(&tree); let mut locals = Vec::new(); @@ -834,6 +838,7 @@ mod tests { }; let mut builder = BodyBuilder::new( &tree, + session, &PackedDimensions::default(), &mut state, system_functions::Body::Initial, @@ -846,11 +851,11 @@ mod tests { ) .unwrap_err(); assert!(error.to_string().contains("disable statement"), "{error}"); - assert_eq!(builder.scopes.len(), 1); + assert_eq!(builder.names.scopes.len(), 1); for name in ["outer_value", "inner_value"] { - assert!(builder.lookup(name).is_none()); + assert!(builder.names.lookup(name).is_none()); assert!(builder.dims.get(name).is_none()); - assert!(!builder.local_constants.contains_key(name)); + assert!(!builder.names.local_constants.contains_key(name)); } } } diff --git a/crates/celox-sv-analyzer/src/ast/procedural/effects.rs b/crates/celox-sv-analyzer/src/ast/procedural/effects.rs index 57c266d0e62..edb536a7726 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/effects.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/effects.rs @@ -284,7 +284,13 @@ impl BodyBuilder<'_, '_, '_> { /// Evaluate the truth of `id` into a hidden 1-bit local, which `id` /// binds to from now on, and return its unique name. fn truth(&mut self, id: ExprId, stmts: &mut Vec) -> Converted { - let value = expression_binding::value(id, self.tree.declarations(), self.tree, &self.dims)?; + let value = expression_binding::value( + id, + self.tree.declarations(), + self.tree, + self.session, + &self.dims, + )?; let (source, unique) = self.hidden(Type::new(TypeKind::Logic)); let truth = |value: Expr| Expr::Unary { op: UnaryOp::LogicNot, @@ -319,21 +325,31 @@ impl BodyBuilder<'_, '_, '_> { let native = self.tree.declarations(); self.reject_tagged_integral_target(operand)?; // A virtual interface is no number to step (IEEE 1800-2023 25.9). - if let Some(ty) = virtual_interfaces::native_type(self.tree, operand, native, &self.dims) { + if let Some(ty) = + virtual_interfaces::native_type(self.tree, self.session, operand, native, &self.dims) + { return Err(virtual_interfaces::arithmetic( if increment { "++" } else { "--" }, &ty, )); } - if expression_binding::native_string(self.tree, operand, native, &self.dims) { + if expression_binding::native_string(self.tree, self.session, operand, native, &self.dims) { return Err(unsupported("increment or decrement of a string")); } - let current = expression_binding::value(operand, native, self.tree, &self.dims)?; + let current = + expression_binding::value(operand, native, self.tree, self.session, &self.dims)?; // The operand is read and then written: a select of it must not // change in between. A member read through a virtual interface checks // for `null`, which changes nothing; its handle is pure. if inlining::effectful(¤t) - && virtual_interfaces::native_member(self.tree, operand, native, &self.dims).is_none() + && virtual_interfaces::native_member( + self.tree, + self.session, + operand, + native, + &self.dims, + ) + .is_none() { return Err(unsupported( "increment or decrement of an operand selected with a side effect", diff --git a/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs b/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs index 02392cf30e6..1890e52cd27 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/foreach.rs @@ -18,7 +18,8 @@ impl BodyBuilder<'_, '_, '_> { header: &ForeachHeader, ) -> Result, AnalyzerError> { let native = self.tree.declarations(); - let container = containers::native_type(header.array, native, self.tree, &self.dims)?; + let container = + containers::native_type(header.array, native, self.tree, self.session, &self.dims)?; let mut array = header.array; let mut unit_member = None; let array = loop { diff --git a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs index 587fd5bb73d..0cd53cd31a6 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/randomization.rs @@ -9,16 +9,27 @@ use crate::system_functions::ObjectOp; pub(super) fn lower( class: &classes::Class, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, state: &mut BodyState<'_>, item: &generate::Item, ) -> Converted> { - lower_methods(class, tree, dimensions, state, Some(item), None, false) + lower_methods( + class, + tree, + session, + dimensions, + state, + Some(item), + None, + false, + ) } fn lower_methods( class: &classes::Class, tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, state: &mut BodyState<'_>, item: Option<&generate::Item>, @@ -41,7 +52,7 @@ fn lower_methods( item.map(|item| item.name(&name)).unwrap_or(name) } }; - let handle = classes::handle_type(tree, &class.name) + let handle = classes::handle_type(tree, session, &class.name) .ok_or_else(|| unsupported("class randomization receiver"))?; let convert_type = |ty| { crate::ir::Type::from_ast( @@ -60,8 +71,13 @@ fn lower_methods( if method == "randomize" && class.check_randomize().is_err() { continue; } - let mut builder = - BodyBuilder::new(tree, dimensions, state, system_functions::Body::Subroutine); + let mut builder = BodyBuilder::new( + tree, + session, + dimensions, + state, + system_functions::Body::Subroutine, + ); builder.automatic = true; let first_local = builder.state.locals.len(); let this = builder.declare(classes::THIS, handle.clone()); @@ -280,11 +296,12 @@ fn lower_methods( // randomize is virtual, while its pre/post hooks are not (18.6.2). // Object-wide rand_mode also covers the dynamic object's members. let mut items = Vec::new(); - for name in classes::visible_classes(tree) { + for name in classes::visible_classes(tree, builder.session) { if name == class.name { continue; } - let Ok(derived) = classes::class(tree, &name, env, &aliases) else { + let Ok(derived) = classes::class(tree, builder.session, &name, env, &aliases) + else { continue; }; if derived.is_abstract || derived.is_interface { @@ -292,7 +309,7 @@ fn lower_methods( } if (inline.is_some() && derived.constraint_program().is_err()) || (method == "randomize" && derived.check_randomize().is_err()) - || !derived.derives_from(tree, &class.name, env, &aliases) + || !derived.derives_from(tree, builder.session, &class.name, env, &aliases) { continue; } @@ -466,10 +483,11 @@ fn random_property( pub(in crate::ast) fn inline_subroutines( tree: &AnalysisContext<'_>, + session: &mut Session, state: &mut BodyState<'_>, dimensions: &PackedDimensions, ) -> Converted<(Vec, Vec)> { - let mut requests = std::mem::take(&mut *tree.state.inline_randomizations.borrow_mut()); + let mut requests = std::mem::take(&mut session.inline_randomizations); for request in &scope::imported(tree).inline_randomizations { if !requests.iter().any(|known| known.key == request.key) { requests.push(classes::constraints::Inline { @@ -489,11 +507,12 @@ pub(in crate::ast) fn inline_subroutines( for inline in requests { let dims = &inline.dimensions; let mut classes = vec![inline.class.clone()]; - for name in classes::visible_classes(tree) { + for name in classes::visible_classes(tree, session) { if name == inline.class.name { continue; } - let Ok(class) = classes::shared_class(tree, &name, &dims.const_env, &dims.type_aliases) + let Ok(class) = + classes::shared_class(tree, &name, &dims.const_env, &dims.type_aliases, session) else { continue; }; @@ -503,6 +522,7 @@ pub(in crate::ast) fn inline_subroutines( && class.constraint_program().is_ok() && class.derives_from( tree, + session, &inline.class.name, &dims.const_env, &dims.type_aliases, @@ -515,6 +535,7 @@ pub(in crate::ast) fn inline_subroutines( result.extend(lower_methods( &class, tree, + session, dims, state, None, @@ -525,6 +546,7 @@ pub(in crate::ast) fn inline_subroutines( result.extend(lower_methods( &class, tree, + session, dims, state, None, diff --git a/crates/celox-sv-analyzer/src/ast/procedural/references.rs b/crates/celox-sv-analyzer/src/ast/procedural/references.rs index 980aae2a0f1..57524f77b7f 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/references.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/references.rs @@ -343,6 +343,7 @@ fn check_formal( #[cfg(test)] mod tests { + use crate::{AnalyzerError, analyze_source}; use std::path::Path; diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs index 9f58b30d9ba..ce861f4b166 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs @@ -5,7 +5,10 @@ use celox_sv_syntax::{ }; impl BodyBuilder<'_, '_, '_> { - pub(super) fn native_timing_control(&self, id: TimingControlId) -> Result { + pub(super) fn native_timing_control( + &mut self, + id: TimingControlId, + ) -> Result { let control = self.tree.declarations().timing_control(id); match &control.kind { TimingControlKind::Delay { @@ -36,6 +39,7 @@ impl BodyBuilder<'_, '_, '_> { if items.iter().any(|item| { events::is_handle( self.tree, + self.session, item.expression, self.tree.declarations(), &self.dims, @@ -50,6 +54,7 @@ impl BodyBuilder<'_, '_, '_> { || item.iff.is_some() || !events::is_handle( self.tree, + self.session, item.expression, self.tree.declarations(), &self.dims, @@ -86,6 +91,7 @@ impl BodyBuilder<'_, '_, '_> { EventControl::Named(id) if events::is_handle( self.tree, + self.session, *id, self.tree.declarations(), &self.dims, @@ -130,8 +136,14 @@ impl BodyBuilder<'_, '_, '_> { return Ok(None); }; if !items.iter().any(|item| { - virtual_interfaces::native_member(self.tree, item.expression, native, &self.dims) - .is_some() + virtual_interfaces::native_member( + self.tree, + self.session, + item.expression, + native, + &self.dims, + ) + .is_some() }) { return Ok(None); } @@ -148,6 +160,7 @@ impl BodyBuilder<'_, '_, '_> { let iff = item.iff.map(|iff| self.native_value(iff)).transpose()?; let expr = match virtual_interfaces::native_member( self.tree, + self.session, item.expression, native, &self.dims, @@ -163,7 +176,7 @@ impl BodyBuilder<'_, '_, '_> { // A write of the selected member is an event at the // write; a change of the selection, at the change. for (signal, denotes) in - virtual_interfaces::watched_writes(&self.tree.state, &handle, &ty, &member)? + virtual_interfaces::watched_writes(self.session, &handle, &ty, &member)? { events.push(EventItemBase { edge, @@ -178,7 +191,7 @@ impl BodyBuilder<'_, '_, '_> { }), }); } - virtual_interfaces::watched(self.tree, handle, &ty, &member)? + virtual_interfaces::watched(self.tree, self.session, handle, &ty, &member)? } None => self.native_value(item.expression)?, }; @@ -241,7 +254,11 @@ impl BodyBuilder<'_, '_, '_> { Ok(true) } - fn native_delay(&self, mut value: ExprId, parenthesized: bool) -> Result { + fn native_delay( + &mut self, + mut value: ExprId, + parenthesized: bool, + ) -> Result { let native = self.tree.declarations(); if parenthesized { value = expression_binding::ungroup(value, native); diff --git a/crates/celox-sv-analyzer/src/ast/processes.rs b/crates/celox-sv-analyzer/src/ast/processes.rs index aabb989692b..14516b76db7 100644 --- a/crates/celox-sv-analyzer/src/ast/processes.rs +++ b/crates/celox-sv-analyzer/src/ast/processes.rs @@ -30,6 +30,7 @@ pub(super) fn state_type() -> Type { /// The built-in scope, also available unambiguously through std (26.7). pub(super) fn scope( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -47,7 +48,7 @@ pub(super) fn scope( return false; } !scope::imported(tree).package_scopes.contains(&name) - && classes::resolve(tree, &name).as_deref() == Some(CLASS) + && classes::resolve(tree, session, &name).as_deref() == Some(CLASS) } ExprKind::Member { expression, @@ -69,6 +70,7 @@ pub(super) fn scope( pub(super) fn builtin_type( path: &[celox_sv_syntax::TypeSegment], tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted>> { if let Some(ty) = qualified_type(path) { @@ -78,7 +80,7 @@ pub(super) fn builtin_type( .last() .is_some_and(|part| part.name.spelling == "mailbox") { - return super::mailboxes::named_type(path, tree, context); + return super::mailboxes::named_type(path, tree, session, context); } Ok(None) } @@ -111,6 +113,7 @@ pub(super) fn qualified_type(path: &[celox_sv_syntax::TypeSegment]) -> Option, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -133,12 +136,14 @@ pub(super) fn state( "::" => { !called && STATES.contains(&member.as_str()) - && scope(tree, *receiver, native, dimensions) + && scope(tree, session, *receiver, native, dimensions) } "." => { member == "status" - && expression_binding::object_native_class(tree, *receiver, native, dimensions) - .as_deref() + && expression_binding::object_native_class( + tree, session, *receiver, native, dimensions, + ) + .as_deref() == Some(CLASS) } _ => false, @@ -148,6 +153,7 @@ pub(super) fn state( pub(super) fn value( tree: &AnalysisContext<'_>, + session: &mut Session, root: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -168,9 +174,10 @@ pub(super) fn value( else { return Ok(None); }; - let static_receiver = separator == "::" && scope(tree, *receiver, native, dimensions); + let static_receiver = separator == "::" && scope(tree, session, *receiver, native, dimensions); let handle_receiver = separator == "." - && expression_binding::object_native_class(tree, *receiver, native, dimensions).as_deref() + && expression_binding::object_native_class(tree, session, *receiver, native, dimensions) + .as_deref() == Some(CLASS); if !static_receiver && !handle_receiver { return Ok(None); @@ -219,7 +226,7 @@ pub(super) fn value( let mut bound = Vec::new(); if op != ProcessOp::SelfHandle { bound.push(Some(expression_binding::value( - *receiver, native, tree, dimensions, + *receiver, native, tree, session, dimensions, )?)); } for arg in args { @@ -240,6 +247,7 @@ pub(super) fn value( arg.value.unwrap(), native, tree, + session, dimensions, )?)); } diff --git a/crates/celox-sv-analyzer/src/ast/selects.rs b/crates/celox-sv-analyzer/src/ast/selects.rs index 29a11fcd9f6..f9a514267be 100644 --- a/crates/celox-sv-analyzer/src/ast/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/selects.rs @@ -1078,19 +1078,19 @@ pub(super) fn indexed_select_bounds_values( /// Bound expressions keep both mux arms until typed folding establishes width. pub(super) fn indexed_expression_value( tree: &AnalysisContext<'_>, + session: &mut Session, expression: Expr, dimensions: &PackedDimensions, ) -> Option { - let state = &*tree.state; - let expression = substitute_indexed_parameter_values(tree, expression, dimensions); - expr_to_const( - state, - fold_const_integral_expr_preserving_mask(tree, expression, &dimensions.const_env), - ) + let expression = substitute_indexed_parameter_values(tree, session, expression, dimensions); + let folded = + fold_const_integral_expr_preserving_mask(tree, session, expression, &dimensions.const_env); + expr_to_const(session, folded) } fn substitute_indexed_parameter_values( tree: &AnalysisContext<'_>, + session: &mut Session, expression: Expr, dimensions: &PackedDimensions, ) -> Expr { @@ -1108,6 +1108,7 @@ fn substitute_indexed_parameter_values( .collect(); substitute_expr_constants_with_parameter_literals( tree, + session, expression, &dimensions.const_env, &values, @@ -1119,6 +1120,7 @@ fn substitute_indexed_parameter_values( pub(super) fn selected_parameter_initializer( native: celox_sv_syntax::ExprId, syntax_tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, assignment_width: Option, ) -> Converted { @@ -1128,18 +1130,26 @@ pub(super) fn selected_parameter_initializer( native, syntax_tree.declarations(), syntax_tree, + session, &dimensions, )?; - fold_parameter_selection(syntax_tree, expression, &dimensions, assignment_width) + fold_parameter_selection( + syntax_tree, + session, + expression, + &dimensions, + assignment_width, + ) } fn fold_parameter_selection( tree: &AnalysisContext<'_>, + session: &mut Session, expression: Expr, dimensions: &PackedDimensions, assignment_width: Option, ) -> Converted { - let expression = substitute_indexed_parameter_values(tree, expression, dimensions); + let expression = substitute_indexed_parameter_values(tree, session, expression, dimensions); if let Expr::Literal(text) = &expression && text.contains(['.', 'e', 'E']) && text.parse::().is_ok() @@ -1155,6 +1165,7 @@ fn fold_parameter_selection( let not_constant = || unsupported("parameter initializer that is not constant"); let constant = constant_folding::constant_with_folded_selections( tree, + session, &expression, &dimensions.const_env, &integral_types, diff --git a/crates/celox-sv-analyzer/src/ast/semantic_types.rs b/crates/celox-sv-analyzer/src/ast/semantic_types.rs index 2dff0d65ce9..95f64014b47 100644 --- a/crates/celox-sv-analyzer/src/ast/semantic_types.rs +++ b/crates/celox-sv-analyzer/src/ast/semantic_types.rs @@ -9,7 +9,6 @@ //! type it renames. use fxhash::FxHashMap as HashMap; -use std::cell::RefCell; use std::sync::Arc; mod conversion; @@ -125,11 +124,8 @@ pub(super) enum TyData { } /// The interned types of an analysis. -#[derive(Debug, Default)] -pub(super) struct TyTable(RefCell); - -#[derive(Debug, Default)] -struct Interned { +#[derive(Clone, Debug, Default)] +pub(super) struct TyTable { /// Each type with the id of the type it matches in canonical form. types: Vec<(TyData, TyId)>, ids: HashMap, @@ -137,24 +133,23 @@ struct Interned { impl TyTable { /// The id of type `data`. - pub fn intern(&self, data: TyData) -> TyId { - if let Some(&id) = self.0.borrow().ids.get(&data) { + pub fn intern(&mut self, data: TyData) -> TyId { + if let Some(&id) = self.ids.get(&data) { return id; } let canonical = match self.canonical_data(&data) { Some(canonical) => self.intern(canonical), - None => TyId(self.0.borrow().types.len() as u32), + None => TyId(self.types.len() as u32), }; - let mut interned = self.0.borrow_mut(); - let id = TyId(interned.types.len() as u32); - interned.types.push((data.clone(), canonical)); - interned.ids.insert(data, id); + let id = TyId(self.types.len() as u32); + self.types.push((data.clone(), canonical)); + self.ids.insert(data, id); id } /// The type `id` names. - pub fn data(&self, id: TyId) -> TyData { - self.0.borrow().types[id.0 as usize].0.clone() + pub fn data(&self, id: TyId) -> &TyData { + &self.types[id.0 as usize].0 } /// Whether `a` and `b` are matching types (IEEE 1800-2023 6.22.1). @@ -164,13 +159,13 @@ impl TyTable { /// The type that every type matching `id` shares. pub fn canonical(&self, id: TyId) -> TyId { - self.0.borrow().types[id.0 as usize].1 + self.types[id.0 as usize].1 } /// How many types the table holds. #[cfg(test)] pub fn len(&self) -> usize { - self.0.borrow().types.len() + self.types.len() } /// The canonical form of `data` if it is not `data` itself: the type 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 fb8bfa1d1ed..aa04dcccf8b 100644 --- a/crates/celox-sv-analyzer/src/ast/semantic_types/conversion.rs +++ b/crates/celox-sv-analyzer/src/ast/semantic_types/conversion.rs @@ -10,7 +10,7 @@ use crate::ast::{ /// The semantic type of `ty`, whose ranges name constants of `env`; `None` /// if a range is not constant or the type has no semantic type yet. pub(in crate::ast) fn of_type( - table: &TyTable, + table: &mut TyTable, functions: &const_functions::ConstantFunctions, ty: &Type, env: &HashMap, @@ -46,7 +46,7 @@ pub(in crate::ast) fn of_type( /// constants of `env`, without the integer type keyword that declared it /// (which only `$typename` tells apart). pub(in crate::ast) fn of_shape( - table: &TyTable, + table: &mut TyTable, functions: &const_functions::ConstantFunctions, shape: &VariableDimensions, env: &HashMap, @@ -115,7 +115,7 @@ impl Parts<'_> { /// varying first (7.4.2), of this element type. fn intern<'b>( &self, - table: &TyTable, + table: &mut TyTable, functions: &const_functions::ConstantFunctions, env: &HashMap, unpacked: impl DoubleEndedIterator, @@ -126,7 +126,8 @@ impl Parts<'_> { right: eval_ast_const_expr(functions, right, env)?, }) }; - let mut id = table.intern(self.element(table, functions, env, &range)?); + let element = self.element(table, functions, env, &range)?; + let mut id = table.intern(element); for (left, right) in unpacked.rev() { id = table.intern(TyData::Array { kind: ArrayKind::Fixed(range(left, right)?), @@ -139,7 +140,7 @@ impl Parts<'_> { /// The type of an element of the fixed-size unpacked dimensions. fn element( &self, - table: &TyTable, + table: &mut TyTable, functions: &const_functions::ConstantFunctions, env: &HashMap, range: &dyn Fn(&ConstExpr, &ConstExpr) -> Option, diff --git a/crates/celox-sv-analyzer/src/ast/semantic_types/relations.rs b/crates/celox-sv-analyzer/src/ast/semantic_types/relations.rs index 7d62313c51a..b0cb92b5902 100644 --- a/crates/celox-sv-analyzer/src/ast/semantic_types/relations.rs +++ b/crates/celox-sv-analyzer/src/ast/semantic_types/relations.rs @@ -38,8 +38,8 @@ impl TyTable { let scalar_enum = |packed: &Packed| { matches!(packed.element, PackedElement::Enum { array: false, .. }) }; - !scalar_enum(&a) - && !scalar_enum(&b) + !scalar_enum(a) + && !scalar_enum(b) && a.bits() == b.bits() && a.four_state == b.four_state && a.signed == b.signed @@ -61,11 +61,11 @@ impl TyTable { (ArrayKind::Dynamic, ArrayKind::Dynamic) | (ArrayKind::Queue { .. }, ArrayKind::Queue { .. }) => true, (ArrayKind::Associative { key: a }, ArrayKind::Associative { key: b }) => { - self.equivalent(a, b) + self.equivalent(*a, *b) } _ => false, }; - kinds && self.equivalent(a_element, b_element) + kinds && self.equivalent(*a_element, *b_element) } _ => false, } @@ -89,7 +89,7 @@ impl TyTable { else { return Err(Mismatch::NotArrays); }; - let assignable = match (&source_kind, &target_kind) { + let assignable = match (source_kind, target_kind) { (ArrayKind::Associative { key: source }, ArrayKind::Associative { key: target }) => { if !self.matches(*source, *target) { return Err(Mismatch::IndexType); @@ -111,7 +111,7 @@ impl TyTable { (_, ArrayKind::Fixed(target)) => Assignable::WhenSized(target.size()), _ => Assignable::Always, }; - if !self.equivalent(source_element, target_element) { + if !self.equivalent(*source_element, *target_element) { return Err(Mismatch::ElementType); } Ok(assignable) diff --git a/crates/celox-sv-analyzer/src/ast/semantic_types/spelling.rs b/crates/celox-sv-analyzer/src/ast/semantic_types/spelling.rs index 90fbbf3dcc9..a5bfa7cee6e 100644 --- a/crates/celox-sv-analyzer/src/ast/semantic_types/spelling.rs +++ b/crates/celox-sv-analyzer/src/ast/semantic_types/spelling.rs @@ -19,12 +19,12 @@ impl TyTable { dims.push_str(&format!("[$:{bound}]")); } ArrayKind::Associative { key } => { - dims.push_str(&format!("[{}]", self.spell(key))); + dims.push_str(&format!("[{}]", self.spell(*key))); } } - id = element; + id = *element; } - let element = self.spell_element(&self.data(id)); + let element = self.spell_element(id); if dims.is_empty() { element } else { @@ -32,8 +32,8 @@ impl TyTable { } } - fn spell_element(&self, data: &TyData) -> String { - match data { + fn spell_element(&self, id: TyId) -> String { + match self.data(id) { TyData::Packed(packed) => match &packed.element { PackedElement::Enum { decl, array } => { let name = format!("enum {}", spell_decl(decl)); @@ -64,7 +64,7 @@ impl TyTable { None => format!("virtual {}", spell_decl(interface)), }, TyData::UnpackedStruct(decl) => format!("struct {}", spell_decl(decl)), - TyData::Array { .. } => self.spell(self.intern(data.clone())), + TyData::Array { .. } => self.spell(id), } } } 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 76ecac80c67..10b220358a7 100644 --- a/crates/celox-sv-analyzer/src/ast/semantic_types/tests.rs +++ b/crates/celox-sv-analyzer/src/ast/semantic_types/tests.rs @@ -3,22 +3,24 @@ use super::{ conversion::of_type, relations::{Assignable, Mismatch}, }; +use crate::ast::Session; use crate::ast::{AnalysisContext, types}; use std::path::Path; /// The semantic types of the typedefs of module `M` in `items`. fn typedefs(items: &str) -> (TyTable, HashMap) { + let session = &mut Session::default(); let source = format!("module M; {items} endmodule"); let tree = crate::source_tree::parse_scope_fixture(&source, Path::new("semantic_types.sv")).unwrap(); let tree = AnalysisContext::unspecialized(&tree); let env = HashMap::default(); - let aliases = types::type_aliases_from_scope_with_env(&tree, &env).unwrap(); - let table = TyTable::default(); + let aliases = types::type_aliases_from_scope_with_env(&tree, session, &env).unwrap(); + let mut table = TyTable::default(); let ids = aliases .iter() .map(|(name, ty)| { - let id = of_type(&table, &tree.functions, ty, &env) + let id = of_type(&mut table, &tree.functions, ty, &env) .unwrap_or_else(|| panic!("`{name}` has no semantic type")); (name.clone(), id) }) @@ -111,7 +113,7 @@ fn named_aggregates_and_enumerations_match_only_their_own_declaration() { #[test] fn interning_a_type_again_returns_its_id() { - let table = TyTable::default(); + let mut table = TyTable::default(); let packed = |keyword| { TyData::Packed(Packed { element: PackedElement::Bits, @@ -126,7 +128,7 @@ fn interning_a_type_again_returns_its_id() { let vector = table.intern(packed(None)); assert_eq!(table.len(), 2); assert_eq!(table.intern(packed(Some("int"))), int); - assert_eq!(table.data(int), packed(Some("int"))); + assert_eq!(*table.data(int), packed(Some("int"))); assert_eq!(table.canonical(int), vector); let queue = |element| TyData::Array { kind: ArrayKind::Queue { bound: None }, @@ -139,6 +141,7 @@ fn interning_a_type_again_returns_its_id() { #[test] fn aggregates_of_each_generate_scope_are_types_of_their_own() { + let session = &mut Session::default(); // IEEE 1800-2023 27.4: a typedef in a generate scope declares a type of // its own in each iteration. let source = "module M; typedef struct packed {int A;} p_t; typedef struct {int A;} u_t; @@ -148,12 +151,19 @@ fn aggregates_of_each_generate_scope_are_types_of_their_own() { let tree = AnalysisContext::unspecialized(&tree); let items = tree.body_membership().unwrap(); let env = HashMap::default(); - let table = TyTable::default(); - let scope = |path| { - 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.functions, &aliases[name], &env).unwrap()) + let mut table = TyTable::default(); + let mut scope = |path| { + let aliases = types::type_aliases_of_generate_scope( + &tree, + session, + &items, + &env, + &HashMap::default(), + path, + ) + .unwrap(); + ["p_t", "u_t"] + .map(|name| of_type(&mut 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/semaphores.rs b/crates/celox-sv-analyzer/src/ast/semaphores.rs index 3e60eec2da4..8dd99b2aed2 100644 --- a/crates/celox-sv-analyzer/src/ast/semaphores.rs +++ b/crates/celox-sv-analyzer/src/ast/semaphores.rs @@ -10,6 +10,7 @@ pub(super) const CLASS: &str = "$builtin::semaphore"; /// The key count of a call, `default` when it is omitted. fn key_count( tree: &AnalysisContext<'_>, + session: &mut Session, arguments: &[Argument], native: &Declarations, dimensions: &PackedDimensions, @@ -30,7 +31,7 @@ fn key_count( .is_none_or(|name| name.spelling == "keyCount") => { match argument.value { - Some(value) => expression_binding::value(value, native, tree, dimensions), + Some(value) => expression_binding::value(value, native, tree, session, dimensions), None => Ok(Expr::Literal(format!("32'sd{default}"))), } } @@ -41,11 +42,12 @@ fn key_count( /// `new(keyCount)` of a semaphore (15.3.1). pub(super) fn new( tree: &AnalysisContext<'_>, + session: &mut Session, arguments: &[Argument], native: &Declarations, dimensions: &PackedDimensions, ) -> Converted { - let keys = key_count(tree, arguments, native, dimensions, "new", 0)?; + let keys = key_count(tree, session, arguments, native, dimensions, "new", 0)?; Ok(events::call(ProcessOp::SemaphoreNew, vec![keys])) } @@ -53,6 +55,7 @@ pub(super) fn new( /// statement or, for `try_get`, as a value. pub(super) fn value( tree: &AnalysisContext<'_>, + session: &mut Session, id: ExprId, native: &Declarations, dimensions: &PackedDimensions, @@ -75,7 +78,8 @@ pub(super) fn value( return Ok(None); }; if separator != "." - || expression_binding::object_native_class(tree, *receiver, native, dimensions).as_deref() + || expression_binding::object_native_class(tree, session, *receiver, native, dimensions) + .as_deref() != Some(CLASS) { return Ok(None); @@ -92,7 +96,7 @@ pub(super) fn value( "semaphore {method}, which returns nothing, used as a value" ))); } - let semaphore = expression_binding::value(*receiver, native, tree, dimensions)?; - let keys = key_count(tree, arguments, native, dimensions, &method, 1)?; + let semaphore = expression_binding::value(*receiver, native, tree, session, dimensions)?; + let keys = key_count(tree, session, arguments, native, dimensions, &method, 1)?; Ok(Some(events::call(op, vec![semaphore, keys]))) } diff --git a/crates/celox-sv-analyzer/src/ast/statements.rs b/crates/celox-sv-analyzer/src/ast/statements.rs index fba4edb72ce..9349028d227 100644 --- a/crates/celox-sv-analyzer/src/ast/statements.rs +++ b/crates/celox-sv-analyzer/src/ast/statements.rs @@ -96,6 +96,7 @@ pub(super) fn lvalue_expr_type( pub(super) fn simplify_condition( tree: &AnalysisContext<'_>, + session: &mut Session, expression: Expr, packed_dimensions: &PackedDimensions, ) -> Expr { @@ -106,7 +107,7 @@ pub(super) fn simplify_condition( op: BinaryOp::LogicOr, right, } = &expression - && two_state_conditions_are_complements(tree, left, right, packed_dimensions) + && two_state_conditions_are_complements(tree, session, left, right, packed_dimensions) { return Expr::Literal("1'b1".to_string()); } @@ -115,6 +116,7 @@ pub(super) fn simplify_condition( pub(super) fn assignment_op_expr( tree: &AnalysisContext<'_>, + session: &mut Session, lhs: &LValue, op: &str, rhs: Expr, @@ -149,6 +151,7 @@ pub(super) fn assignment_op_expr( Ok(expression_binding::remove_real_division_guards( guard_zero_divisions( tree, + session, Expr::Binary { left: Box::new(left), op, diff --git a/crates/celox-sv-analyzer/src/ast/subroutine_owners.rs b/crates/celox-sv-analyzer/src/ast/subroutine_owners.rs index cdfb474c9dd..04e3cb0136a 100644 --- a/crates/celox-sv-analyzer/src/ast/subroutine_owners.rs +++ b/crates/celox-sv-analyzer/src/ast/subroutine_owners.rs @@ -79,6 +79,7 @@ mod tests { #[test] fn trimmed_structural_header_view_uses_selected_native_subroutine_membership() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_scope_fixture("module M(output logic[$bits(g())-1:0]y);function int f();return 1;endfunction function int g();return 2;endfunction assign y=0;endmodule", Path::new("trimmed-subroutine-view.sv")).unwrap(); let tree = tree .with_body_membership(tree.root_unit().unwrap().items[1..].to_vec()) @@ -90,6 +91,7 @@ mod tests { }; let module = Module::from_scope_with_symbols( &AnalysisContext::unspecialized(&tree), + session, "M", &HashMap::default(), &lookup, diff --git a/crates/celox-sv-analyzer/src/ast/timescales.rs b/crates/celox-sv-analyzer/src/ast/timescales.rs index fe2513f9ccd..8bb1e88c330 100644 --- a/crates/celox-sv-analyzer/src/ast/timescales.rs +++ b/crates/celox-sv-analyzer/src/ast/timescales.rs @@ -1148,6 +1148,7 @@ mod tests { "Top", &HashMap::default(), &packages, + &mut packages.design(), ) .unwrap(); let values: Vec<_> = ir.modules()[0] @@ -1178,6 +1179,7 @@ mod tests { "Top", &HashMap::default(), &packages, + &mut packages.design(), ); assert!(result.is_err(), "accepted mixed defaults for {module}"); assert!( @@ -1203,7 +1205,8 @@ mod tests { Path::new("omitted.sv"), "Top", &HashMap::default(), - &packages + &packages, + &mut packages.design() ) .is_err() ); @@ -1230,6 +1233,7 @@ mod tests { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); let values: Vec<_> = ir.modules()[0] @@ -1471,6 +1475,7 @@ mod tests { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); let values: Vec<_> = ir.modules()[0] @@ -1498,7 +1503,8 @@ mod tests { &[], &[], &ModuleInterfaces::default(), - &packages + &packages, + &mut packages.design() ) .is_err(), "accepted {expression}" @@ -1642,6 +1648,7 @@ mod tests { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); let after = COLLECTIONS.with(std::cell::Cell::get); diff --git a/crates/celox-sv-analyzer/src/ast/type_binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding.rs index 99e9f983304..6e24559762b 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding.rs @@ -75,6 +75,7 @@ pub(super) fn port_direction(direction: celox_sv_syntax::Direction) -> PortDirec pub(super) fn port_type( port: &celox_sv_syntax::Port, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Converted> { @@ -82,13 +83,14 @@ pub(super) fn port_type( let Some(id) = port.data_type else { return Ok(None); }; - bind(id, tree, &context) + bind(id, tree, session, &context) } /// Formal/return implicit types use scalar logic rather than an unsized local. pub(super) fn implicit_subroutine_type( id: TypeId, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Converted { @@ -96,18 +98,19 @@ pub(super) fn implicit_subroutine_type( let data = tree.declarations().data_type(id); let mut ty = Type::new(TypeKind::Logic); ty.is_signed = data.signed.unwrap_or(false); - ty.packed_ranges = binding::packed_ranges(&data.packed_dimensions, tree, &context)?; + ty.packed_ranges = binding::packed_ranges(&data.packed_dimensions, tree, session, &context)?; Ok(ty) } pub(super) fn local_signals( declaration: &celox_sv_syntax::VariableDeclaration, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, selected_name: Option<&str>, ) -> Converted> { let context = PackedDimensions::new(HashMap::default(), env, aliases); - let Some(base) = bind(declaration.data_type, tree, &context)? else { + let Some(base) = bind(declaration.data_type, tree, session, &context)? else { return Err(unsupported("unsupported internal data type")); }; let mut signals = Vec::new(); @@ -119,7 +122,13 @@ pub(super) fn local_signals( if selected_name.is_some_and(|selected| selected != name) { continue; } - let ty = containers::with_dimensions(base.clone(), &variable.dimensions, tree, &context)?; + let ty = containers::with_dimensions( + base.clone(), + &variable.dimensions, + tree, + session, + &context, + )?; if declaration.constant && ty.container.is_some() { return Err(unsupported("const dynamic container")); } @@ -135,6 +144,7 @@ pub(super) fn local_signals( pub(super) fn net_signals( declaration: &celox_sv_syntax::NetDeclaration, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, selected_name: Option<&str>, @@ -149,7 +159,7 @@ pub(super) fn net_signals( return Err(unsupported("unsupported net data type")); } let context = PackedDimensions::new(HashMap::default(), env, aliases); - let Some(base) = bind(declaration.data_type, tree, &context)? else { + let Some(base) = bind(declaration.data_type, tree, session, &context)? else { return Err(unsupported("unsupported net data type")); }; let mut signals = Vec::new(); @@ -158,7 +168,13 @@ pub(super) fn net_signals( if selected_name.is_some_and(|selected| selected != name) { continue; } - let ty = containers::with_dimensions(base.clone(), &variable.dimensions, tree, &context)?; + let ty = containers::with_dimensions( + base.clone(), + &variable.dimensions, + tree, + session, + &context, + )?; if ty.container.is_some() { return Err(unsupported("dynamic container net")); } @@ -173,12 +189,13 @@ pub(super) fn net_signals( pub(super) fn argument_type( root: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Converted> { let context = PackedDimensions::new(HashMap::default(), env, aliases); if let celox_sv_syntax::ExprKind::Type(id) = tree.declarations().expression(root).kind { - return bind(id, tree, &context); + return bind(id, tree, session, &context); } let Some((name, dimensions)) = argument_alias(root, tree.declarations()) else { return Ok(None); @@ -186,7 +203,7 @@ pub(super) fn argument_type( let Some(base) = aliases.get(&name) else { return Ok(None); }; - let ranges = binding::packed_ranges(&dimensions, tree, &context)?; + let ranges = binding::packed_ranges(&dimensions, tree, session, &context)?; Ok(Some(types::enclose_aliased_packed_type( base.clone(), ranges, @@ -235,28 +252,31 @@ pub(super) fn procedural_type( id: TypeId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Converted> { let context = PackedDimensions::new(HashMap::default(), env, aliases); - binding::bind_in(id, native, tree, &context) + binding::bind_in(id, native, tree, session, &context) } /// Enum constant bases use the declared native type and bound handles. pub(super) fn enum_constant_base( id: TypeId, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Converted> { let context = PackedDimensions::new(HashMap::default(), env, aliases); - bind(id, tree, &context) + bind(id, tree, session, &context) } pub(super) fn alias_base_type( id: TypeId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, defer_class_defaults: bool, @@ -266,7 +286,7 @@ pub(super) fn alias_base_type( return Ok(None); } let context = PackedDimensions::new(HashMap::default(), env, aliases); - binding::bind_alias_in(id, native, tree, &context, defer_class_defaults) + binding::bind_alias_in(id, native, tree, session, &context, defer_class_defaults) } /// Builtin integral identity/width without syntax or aggregate layout. @@ -317,12 +337,13 @@ pub(super) fn builtin_type(name: &str, signing: Option) -> Option { pub(super) fn alias_signals( declaration: &celox_sv_syntax::VariableDeclaration, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, selected_name: Option<&str>, ) -> Converted> { let context = PackedDimensions::new(HashMap::default(), env, aliases); - let Some(base) = bind(declaration.data_type, tree, &context)? else { + let Some(base) = bind(declaration.data_type, tree, session, &context)? else { return Ok(Vec::new()); }; let mut signals = Vec::new(); @@ -331,7 +352,13 @@ pub(super) fn alias_signals( if selected_name.is_some_and(|selected| selected != name) { continue; } - let ty = containers::with_dimensions(base.clone(), &variable.dimensions, tree, &context)?; + let ty = containers::with_dimensions( + base.clone(), + &variable.dimensions, + tree, + session, + &context, + )?; signals.push(Signal::new(name, ty)); } Ok(signals) 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 c668c4a34b7..b37c4d480bb 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/aggregates.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/aggregates.rs @@ -5,6 +5,7 @@ pub(super) fn bind( root: TypeId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &HashMap, ) -> Converted> { @@ -12,6 +13,7 @@ pub(super) fn bind( root, native, tree, + session, &PackedDimensions::new(HashMap::default(), env, aliases), ) } @@ -21,6 +23,7 @@ mod tests { use super::*; #[test] fn native_field_order_owns_offsets_in_the_shared_layout() { + let session = &mut Session::default(); let tree = crate::source_tree::parse_source( "module M;typedef struct packed {logic[3:0]high;bit[1:0]low;} T;T value;endmodule", Path::new("native-aggregate-order.sv"), @@ -44,6 +47,7 @@ mod tests { root, &native, &tree, + session, &HashMap::default(), &HashMap::default(), ) @@ -94,6 +98,7 @@ mod tests { root, native, &tree, + &mut Session::default(), &HashMap::default(), &HashMap::default(), ); 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 db27ab3ce12..0e01475141e 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/binding.rs @@ -5,18 +5,20 @@ use celox_sv_syntax::{Dimension, DimensionKind, ExprId, ExprKind}; pub(in crate::ast) fn bind( root: TypeId, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted> { - bind_in(root, tree.declarations(), tree, context) + bind_in(root, tree.declarations(), tree, session, context) } pub(in crate::ast) fn bind_in( root: TypeId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted> { - bind_in_mode(root, native, tree, context, BindingMode::Use) + bind_in_mode(root, native, tree, session, context, BindingMode::Use) } /// Typedef discovery precedes enum constant resolution, so dependent aliases @@ -26,6 +28,7 @@ pub(in crate::ast) fn bind_alias_in( root: TypeId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, defer_defaults: bool, ) -> Converted> { @@ -33,6 +36,7 @@ pub(in crate::ast) fn bind_alias_in( root, native, tree, + session, context, BindingMode::Alias { defer_defaults }, ) @@ -48,6 +52,7 @@ impl BindingMode { fn specialize( self, tree: &AnalysisContext<'_>, + session: &mut Session, generic: &str, arguments: &[celox_sv_syntax::Argument], context: &PackedDimensions, @@ -59,11 +64,13 @@ impl BindingMode { } ) { super::super::classes::specializations::specialize_if_ready( - tree, generic, arguments, context, + tree, session, generic, arguments, context, ) } else { - super::super::classes::specializations::specialize(tree, generic, arguments, context) - .map(Some) + super::super::classes::specializations::specialize( + tree, session, generic, arguments, context, + ) + .map(Some) } } } @@ -72,6 +79,7 @@ fn bind_in_mode( root: TypeId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, mode: BindingMode, ) -> Converted> { @@ -99,9 +107,9 @@ fn bind_in_mode( Job::Enter(id) => { let data = native.data_type(id); let ranges = if matches!(data.kind, DataTypeKind::Struct { .. }) { - bind_ranges(&data.packed_dimensions, tree, context)? + bind_ranges(&data.packed_dimensions, tree, session, context)? } else { - packed_ranges(&data.packed_dimensions, tree, context)? + packed_ranges(&data.packed_dimensions, tree, session, context)? }; match &data.kind { DataTypeKind::Implicit => { @@ -121,7 +129,7 @@ fn bind_in_mode( } DataTypeKind::Named(path) => { if let Some(ty) = - super::super::processes::builtin_type(path, tree, context)? + super::super::processes::builtin_type(path, tree, session, context)? { values.push(types::enclose_aliased_packed_type(*ty, ranges)); continue; @@ -133,11 +141,13 @@ fn bind_in_mode( let name = normalize_identifier(&part.name.spelling); if (part.arguments.is_some() || !context.type_aliases.contains_key(&name)) - && let Some(name) = super::super::classes::resolve(tree, &name) - && super::super::classes::is_parameterized(tree, &name) + && let Some(name) = + super::super::classes::resolve(tree, session, &name) + && super::super::classes::is_parameterized(tree, session, &name) { let Some(name) = mode.specialize( tree, + session, &name, part.arguments.as_deref().unwrap_or_default(), context, @@ -156,11 +166,11 @@ fn bind_in_mode( &normalize_identifier(&class.name.spelling), ); if let Some(class) = - class_scope_named(class, tree, context, mode, name)? + class_scope_named(class, tree, session, context, mode, name)? { let member = normalize_identifier(&member.name.spelling); let ty = super::super::classes::specializations::member_type( - tree, &class, &member, + tree, session, &class, &member, ) .ok_or_else(|| { unsupported(format!("type `{member}` of class `{class}`")) @@ -172,11 +182,11 @@ fn bind_in_mode( // A type that a class declares, `C::T` (IEEE 1800-2023 // 8.23, 8.25.1). if let [scope, member] = path.as_slice() - && let Some(class) = class_scope(scope, tree, context, mode)? + && let Some(class) = class_scope(scope, tree, session, context, mode)? { let member = normalize_identifier(&member.name.spelling); let ty = super::super::classes::specializations::member_type( - tree, &class, &member, + tree, session, &class, &member, ) .ok_or_else(|| { unsupported(format!("type `{member}` of class `{class}`")) @@ -202,14 +212,14 @@ fn bind_in_mode( }; if let Some(class) = class .as_ref() - .filter(|class| tree.state.foreign.contains(class)) + .filter(|class| session.foreign.contains(class)) { let arguments = path .last() .and_then(|part| part.arguments.as_deref()) .unwrap_or_default(); let Some(name) = - mode.specialize(tree, class, arguments, context)? + mode.specialize(tree, session, class, arguments, context)? else { return Ok(None); }; @@ -246,14 +256,16 @@ fn bind_in_mode( // package itself, whose classes are declared // under their qualified names. let class = match path.as_slice() { - [_] => super::super::classes::resolve(tree, &name), - _ => super::super::classes::handle_type(tree, &name) + [_] => super::super::classes::resolve(tree, session, &name), + _ => super::super::classes::handle_type(tree, session, &name) .map(|_| name.clone()) - .or_else(|| super::super::classes::resolve(tree, &name)), + .or_else(|| { + super::super::classes::resolve(tree, session, &name) + }), }; - if let Some(class) = class - .and_then(|class| super::super::classes::handle_type(tree, &class)) - { + if let Some(class) = class.and_then(|class| { + super::super::classes::handle_type(tree, session, &class) + }) { values.push(class); continue; } @@ -269,9 +281,11 @@ fn bind_in_mode( let mut ty = builtin_type("int", None).unwrap(); ty.is_enum = true; if matches!(mode, BindingMode::Use) { - validate_enum_initializers(id, native, tree, context, &ty)?; + validate_enum_initializers( + id, native, tree, session, context, &ty, + )?; } - ty.enum_domain = enum_values(id, native, tree, context, &ty); + ty.enum_domain = enum_values(id, native, tree, session, context, &ty); ty.packed_enum = !native.data_type(id).packed_dimensions.is_empty(); ty.packed_ranges = ranges.into_iter().chain(ty.packed_ranges).collect(); values.push(ty); @@ -365,7 +379,7 @@ fn bind_in_mode( modport, } => { values.push(super::super::virtual_interfaces::bind_type( - &tree.state, + session, name, arguments.as_deref(), modport.as_ref(), @@ -379,13 +393,13 @@ fn bind_in_mode( return Err(unsupported("enum base type")); }; if matches!(mode, BindingMode::Use) { - validate_enum_initializers(id, native, tree, context, &ty)?; + validate_enum_initializers(id, native, tree, session, context, &ty)?; } let mut outer = ranges; outer.extend(ty.packed_ranges); ty.packed_ranges = outer; ty.is_enum = true; - ty.enum_domain = enum_values(id, native, tree, context, &ty); + ty.enum_domain = enum_values(id, native, tree, session, context, &ty); ty.packed_enum = !native.data_type(id).packed_dimensions.is_empty(); values.push(ty); } @@ -459,6 +473,7 @@ fn bind_in_mode( pub(in crate::ast) fn packed_ranges( dimensions: &[Dimension], tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted> { if dimensions.is_empty() { @@ -482,12 +497,13 @@ pub(in crate::ast) fn packed_ranges( } all.sort_by_key(|dimension| dimension.tokens.start); all.dedup_by_key(|dimension| dimension.tokens); - bind_ranges(&all, tree, context) + bind_ranges(&all, tree, session, context) } fn bind_ranges( dimensions: &[Dimension], tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted> { let mut result = Vec::new(); @@ -495,8 +511,8 @@ fn bind_ranges( let DimensionKind::Range { left, right } = dimension.kind else { return Err(unsupported("unsized packed dimension")); }; - let left = constant_binding::bind(left, tree, context)?; - let right = constant_binding::bind(right, tree, context)?; + let left = constant_binding::bind(left, tree, session, context)?; + let right = constant_binding::bind(right, tree, session, context)?; if let (Some(left), Some(right)) = (left, right) { result.push(PackedRange::new(left, right)); } @@ -510,12 +526,14 @@ fn bind_ranges( fn class_scope( scope: &celox_sv_syntax::TypeSegment, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, mode: BindingMode, ) -> Converted> { class_scope_named( scope, tree, + session, context, mode, normalize_identifier(&scope.name.spelling), @@ -525,6 +543,7 @@ fn class_scope( fn class_scope_named( scope: &celox_sv_syntax::TypeSegment, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, mode: BindingMode, name: String, @@ -535,7 +554,7 @@ fn class_scope_named( .get(&super::super::classes::specializations::scope_key(&name)) .or_else(|| { // A class of a package is declared under its qualified name. - let class = super::super::classes::resolve(tree, &name)?; + let class = super::super::classes::resolve(tree, session, &name)?; context .type_aliases .get(&super::super::classes::specializations::scope_key(&class)) @@ -545,7 +564,7 @@ fn class_scope_named( { return Ok(Some(class)); } - let Some(class) = super::super::classes::resolve(tree, &name) else { + let Some(class) = super::super::classes::resolve(tree, session, &name) else { return Ok(None); }; // Resolve a user package before std's implicit class fallback for this @@ -556,7 +575,7 @@ fn class_scope_named( return Ok(None); } let name = class; - if !super::super::classes::is_parameterized(tree, &name) { + if !super::super::classes::is_parameterized(tree, session, &name) { if scope .arguments .as_ref() @@ -567,10 +586,12 @@ fn class_scope_named( ))); } // Its members are those of its one specialization. - if super::super::classes::handle_type(tree, &name).is_some() - && super::super::classes::specializations::lookup(tree, &name).is_none() - && super::super::classes::is_declared(tree, &name) - && mode.specialize(tree, &name, &[], context)?.is_none() + if super::super::classes::handle_type(tree, session, &name).is_some() + && super::super::classes::specializations::lookup(session, &name).is_none() + && super::super::classes::is_declared(tree, session, &name) + && mode + .specialize(tree, session, &name, &[], context)? + .is_none() { return Ok(None); } @@ -579,16 +600,17 @@ fn class_scope_named( let Some(arguments) = &scope.arguments else { return Err(AnalyzerError::UnspecializedClassScope { class: name }); }; - mode.specialize(tree, &name, arguments, context) + mode.specialize(tree, session, &name, arguments, context) } pub(in crate::ast) fn expression_type( root: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted> { if let ExprKind::Type(id) = tree.declarations().expression(root).kind { - return Ok(bind(id, tree, context)? + return Ok(bind(id, tree, session, context)? .and_then(|ty| expr_type_from_type(&tree.functions, &ty, &context.const_env))); } if let Some((name, ranges)) = argument_alias(root, tree.declarations()) @@ -600,8 +622,10 @@ pub(in crate::ast) fn expression_type( && !context.parameter_values.contains_key(&name) && let Some(ty) = context.type_aliases.get(&name) { - let ty = - types::enclose_aliased_packed_type(ty.clone(), packed_ranges(&ranges, tree, context)?); + let ty = types::enclose_aliased_packed_type( + ty.clone(), + packed_ranges(&ranges, tree, session, context)?, + ); return Ok(expr_type_from_type( &tree.functions, &ty, @@ -616,7 +640,7 @@ pub(in crate::ast) fn expression_type( ); query.type_query = true; query.functions = Arc::default(); - let value = expression_binding::bind(root, tree, &query)?; + let value = expression_binding::bind(root, tree, session, &query)?; Ok(dimensions::bound_bits_type(tree, &value, &query)) } @@ -626,6 +650,7 @@ pub(in crate::ast) fn validate_enum_initializers( id: TypeId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ty: &Type, ) -> Converted<()> { @@ -677,20 +702,20 @@ pub(in crate::ast) fn validate_enum_initializers( } // During signature discovery some constants are still unresolved. // Leave their resolution to the ordinary constant-binding pass. - let expr = constant_binding::expression(value, native, tree, &env, &context.type_aliases) - .ok() - .flatten() - .and_then(|expr| { - expr_to_const( - &tree.state, - constants::substitute_expr_constants_with_parameter_literals( + let expr = + constant_binding::expression(value, native, tree, session, &env, &context.type_aliases) + .ok() + .flatten() + .and_then(|expr| { + let substituted = constants::substitute_expr_constants_with_parameter_literals( tree, + session, const_expr_to_expr(expr), &env, &unknown_literals, - ), - ) - }); + ); + expr_to_const(session, substituted) + }); let expr = expr.map(|expr| match expr { ConstExpr::Literal(text) => ConstExpr::Literal( resize_unbased_fill_literal_for_cast(&text, shape.width, shape.signed) @@ -755,6 +780,7 @@ fn enum_values( id: TypeId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ty: &Type, ) -> Option> { @@ -778,8 +804,15 @@ fn enum_values( return None; } let value = if let Some(id) = item.value { - let expr = constant_binding::expression(id, native, tree, &env, &context.type_aliases) - .ok()??; + let expr = constant_binding::expression( + id, + native, + tree, + session, + &env, + &context.type_aliases, + ) + .ok()??; // Unbased fills take the enum base's width and signedness, just // as they do when resolving the declared enum constants (5.7.1). let expr = match expr { diff --git a/crates/celox-sv-analyzer/src/ast/type_binding/subroutines.rs b/crates/celox-sv-analyzer/src/ast/type_binding/subroutines.rs index 33cfc6e594b..87871fde359 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding/subroutines.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding/subroutines.rs @@ -5,6 +5,7 @@ use crate::procedural::ParamDirection; pub(in crate::ast) fn subroutine_formals( native: &celox_sv_syntax::Subroutine, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted< Vec<( @@ -37,7 +38,7 @@ pub(in crate::ast) fn subroutine_formals( let mut ty = if port.direction.is_none() && omitted { previous_type.clone().unwrap_or(Type::new(TypeKind::Logic)) } else { - bind(port.data_type, tree, context)?.ok_or_else(|| { + bind(port.data_type, tree, session, context)?.ok_or_else(|| { unsupported(format!( "unsupported {} formal data type", if native.kind == celox_sv_syntax::SubroutineKind::Function { @@ -54,7 +55,7 @@ pub(in crate::ast) fn subroutine_formals( previous_type = Some(ty.clone()); // A container formal that is not a reference holds a copy of the // container (IEEE 1800-2023 13.5.1), as an assignment makes one. - ty = containers::with_dimensions(ty, &port.dimensions, tree, context)?; + ty = containers::with_dimensions(ty, &port.dimensions, tree, session, context)?; result.push(( instances::normalize_identifier(&name.spelling), direction, diff --git a/crates/celox-sv-analyzer/src/ast/type_names.rs b/crates/celox-sv-analyzer/src/ast/type_names.rs index aaf1da7c195..26cc9350612 100644 --- a/crates/celox-sv-analyzer/src/ast/type_names.rs +++ b/crates/celox-sv-analyzer/src/ast/type_names.rs @@ -193,20 +193,22 @@ fn unsupported_operand(what: impl std::fmt::Display) -> AnalyzerError { pub(super) fn query_string( argument: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted { - let context = dimensions::query_context_for_operand(argument, tree, context)?; - let r#type = operand_type(argument, tree, &context)?; - type_name(&r#type, tree, &context.const_env) + let context = dimensions::query_context_for_operand(argument, tree, session, context)?; + let r#type = operand_type(argument, tree, session, &context)?; + type_name(&r#type, tree, session, &context.const_env) } /// The value of a `$typename(argument)` call: the string as a literal. pub(super) fn query_value( argument: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted { - let name = query_string(argument, tree, context)?; + let name = query_string(argument, tree, session, context)?; // A string, as the result of the enumeration method `name` is (6.19.5.6). Ok(expression_binding::string_call( system_functions::StringOp::FromBits, @@ -226,6 +228,7 @@ fn string_literal(text: &str) -> String { fn operand_type( argument: celox_sv_syntax::ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, context: &PackedDimensions, ) -> Converted { let native = tree.declarations(); @@ -249,17 +252,18 @@ fn operand_type( // A type of a package or class, `C::T [3:0]`. None => classes::specializations::scoped_type( tree, + session, selected_base(argument, native), context, )?, } { - let ranges = type_binding::binding::packed_ranges(&dimensions, tree, context)?; + let ranges = type_binding::binding::packed_ranges(&dimensions, tree, session, context)?; return Ok(types::enclose_aliased_packed_type(base, ranges)); } } match &native.expression(argument).kind { - celox_sv_syntax::ExprKind::Type(id) => type_binding::bind(*id, tree, context)? + celox_sv_syntax::ExprKind::Type(id) => type_binding::bind(*id, tree, session, context)? .ok_or_else(|| unsupported_operand("this data type")), celox_sv_syntax::ExprKind::Name(name) => { let name = instances::normalize_identifier(&name.spelling); @@ -273,32 +277,34 @@ fn operand_type( return Err(unsupported_operand(format!("parameter `{name}`"))); } if let Some((property, _)) = - expression_binding::object_property(tree, argument, native, context)? + expression_binding::object_property(tree, session, argument, native, context)? { return Ok(property.r#type.clone()); } if let Some(r#type) = context.type_aliases.get(&name) { return Ok(r#type.clone()); } - if let Some(r#type) = class_operand(tree, &name, context)? { + if let Some(r#type) = class_operand(tree, session, &name, context)? { return Ok(r#type); } Err(unsupported_operand(format!("`{name}`"))) } celox_sv_syntax::ExprKind::Member { .. } => { if let Some((property, _)) = - expression_binding::object_property(tree, argument, native, context)? + expression_binding::object_property(tree, session, argument, native, context)? { return Ok(property.r#type.clone()); } // A static property, `C::v` or `h.v` (8.9). if let Some(property) = expression_binding::object_static_property_declaration( - tree, argument, native, context, + tree, session, argument, native, context, )? { return Ok(property.r#type); } // A type of a package or class, `p::t` or `C::T`. - if let Some(r#type) = classes::specializations::scoped_type(tree, argument, context)? { + if let Some(r#type) = + classes::specializations::scoped_type(tree, session, argument, context)? + { return Ok(r#type); } // A class of a package, `p::C`. @@ -310,22 +316,19 @@ fn operand_type( && separator == "::" && let celox_sv_syntax::ExprKind::Name(package) = &native.expression(*expression).kind - && let Some(r#type) = class_operand( + && let qualified = scope::qualified_name( tree, - &scope::qualified_name( - tree, - &instances::normalize_identifier(&package.spelling), - &instances::normalize_identifier(&name.spelling), - ), - context, - )? + &instances::normalize_identifier(&package.spelling), + &instances::normalize_identifier(&name.spelling), + ) + && let Some(r#type) = class_operand(tree, session, &qualified, context)? { return Ok(r#type); } Err(unsupported_operand("this member or hierarchical name")) } celox_sv_syntax::ExprKind::Parameterized { .. } => { - expression_binding::named_class(tree, argument, native, context)? + expression_binding::named_class(tree, session, argument, native, context)? .map(|class| classes::handle(&class)) .ok_or_else(|| unsupported_operand("this class")) } @@ -338,19 +341,20 @@ fn operand_type( /// The handle type of the class `name` names, if it names one. fn class_operand( tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, context: &PackedDimensions, ) -> Converted> { - let Some(class) = classes::resolve(tree, name) else { + let Some(class) = classes::resolve(tree, session, name) else { return Ok(None); }; // A parameterized class named alone is its default specialization // (8.25). - if classes::is_parameterized(tree, &class) { - let class = classes::specializations::specialize(tree, &class, &[], context)?; + if classes::is_parameterized(tree, session, &class) { + let class = classes::specializations::specialize(tree, session, &class, &[], context)?; return Ok(Some(classes::handle(&class))); } - Ok(classes::handle_type(tree, &class)) + Ok(classes::handle_type(tree, session, &class)) } /// The expression that the selects of native expression `id` apply to. @@ -368,6 +372,7 @@ fn selected_base( pub(super) fn type_name( r#type: &Type, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, ) -> Converted { let range = |left: &ConstExpr, right: &ConstExpr| -> Converted { @@ -388,7 +393,7 @@ pub(super) fn type_name( ContainerKind::Queue { capacity: 0 } => "[$]".to_owned(), ContainerKind::Queue { capacity } => format!("[$:{}]", capacity - 1), ContainerKind::Associative { .. } => match &container.key { - Some(key) => format!("[{}]", type_name(key, tree, env)?), + Some(key) => format!("[{}]", type_name(key, tree, session, env)?), None => "[*]".to_owned(), }, }); @@ -401,7 +406,7 @@ pub(super) fn type_name( { return Err(unsupported_operand("an array of containers")); } - let mut name = element_name(element, tree, env, &range)?; + let mut name = element_name(element, tree, session, env, &range)?; if !dimensions.is_empty() { // `$` stands for the name of the unpacked array (rule d). name.push('$'); @@ -414,12 +419,13 @@ pub(super) fn type_name( fn element_name( r#type: &Type, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, range: &dyn Fn(&ConstExpr, &ConstExpr) -> Converted, ) -> Converted { // An event is a handle of a built-in class that has no class name. if let Some(class) = r#type.class().filter(|_| r#type.kind != TypeKind::Event) { - return class_name(class, tree, env); + return class_name(class, tree, session, env); } match r#type.kind { TypeKind::Event => return Ok("event".to_owned()), @@ -432,13 +438,13 @@ fn element_name( TypeKind::Bit | TypeKind::Logic | TypeKind::Reg | TypeKind::Implicit => {} } if let Some(aggregate) = r#type.unpacked_struct() { - return unpacked_struct_name(r#type, aggregate, tree, env); + return unpacked_struct_name(r#type, aggregate, tree, session, env); } if r#type.is_enum { - return enum_name(r#type, tree, env, range); + return enum_name(r#type, tree, session, env, range); } if !r#type.members.is_empty() { - return aggregate_name(r#type, tree, env, range); + return aggregate_name(r#type, tree, session, env, range); } if r#type.signed_element_depth.is_some() { // No declaration without a typedef has this type (7.4.1). @@ -496,6 +502,7 @@ fn vector_name( fn enum_name( r#type: &Type, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, range: &dyn Fn(&ConstExpr, &ConstExpr) -> Converted, ) -> Converted { @@ -536,6 +543,7 @@ fn enum_name( r#type, "an anonymous enumerated type", tree, + session, env, )?); Ok(name) @@ -545,6 +553,7 @@ fn enum_name( fn aggregate_name( r#type: &Type, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, range: &dyn Fn(&ConstExpr, &ConstExpr) -> Converted, ) -> Converted { @@ -567,7 +576,7 @@ fn aggregate_name( } name.push('{'); for member in &r#type.members { - name.push_str(&type_name(member.r#type(), tree, env)?); + name.push_str(&type_name(member.r#type(), tree, session, env)?); name.push(' '); name.push_str(member.name()); name.push(';'); @@ -577,6 +586,7 @@ fn aggregate_name( r#type, "an anonymous struct or union type", tree, + session, env, )?); for packed in outer { @@ -591,6 +601,7 @@ fn unpacked_struct_name( r#type: &Type, aggregate: &unpacked_structs::UnpackedStruct, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, ) -> Converted { let mut name = "struct{".to_owned(); @@ -601,7 +612,7 @@ fn unpacked_struct_name( "an unpacked structure with an unpacked array member", )); } - name.push_str(&type_name(&member.r#type, tree, env)?); + name.push_str(&type_name(&member.r#type, tree, session, env)?); name.push(' '); name.push_str(&member.name); name.push(';'); @@ -611,6 +622,7 @@ fn unpacked_struct_name( r#type, "an anonymous struct or union type", tree, + session, env, )?); Ok(name) @@ -622,13 +634,15 @@ fn typedef_name( r#type: &Type, anonymous: &str, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, ) -> Converted { match r#type.spelling.name_of() { Some(TypedefName::Scope(name)) => Ok(name.to_string()), - Some(TypedefName::Class { class, name }) => { - Ok(format!("{}::{name}", class_name(class, tree, env)?)) - } + Some(TypedefName::Class { class, name }) => Ok(format!( + "{}::{name}", + class_name(class, tree, session, env)? + )), None => Err(unsupported_operand(anonymous)), } } @@ -638,18 +652,19 @@ fn typedef_name( fn class_name( class: &str, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, ) -> Converted { if class == processes::CLASS { return Ok("std::process".to_owned()); } - let specialization = classes::specializations::lookup(tree, class) - .or_else(|| tree.state.foreign.specialization(class)); + let specialization = classes::specializations::lookup(session, class) + .or_else(|| session.foreign.specialization(class)); let generic = specialization.as_ref().map_or_else( || class.to_owned(), |specialization| specialization.generic.clone(), ); - let declaration = classes::declaration(tree, &generic); + let declaration = classes::declaration(tree, session, &generic); let mut name = match declaration { Some(declaration) => scoped_name( classes::enclosing_unit(tree.declarations(), declaration.tokens), @@ -672,7 +687,7 @@ fn class_name( .arguments .iter() .map(|argument| match argument { - ClassArgument::Type(r#type) => type_name(r#type, tree, env), + ClassArgument::Type(r#type) => type_name(r#type, tree, session, env), ClassArgument::Value(Some(value)) => Ok(value.to_string()), ClassArgument::Value(None) => Err(unsupported_operand(format!( "class `{name}` with a parameter value that is not integral" diff --git a/crates/celox-sv-analyzer/src/ast/types.rs b/crates/celox-sv-analyzer/src/ast/types.rs index 743924cfe45..7ad06e0b9d8 100644 --- a/crates/celox-sv-analyzer/src/ast/types.rs +++ b/crates/celox-sv-analyzer/src/ast/types.rs @@ -4,11 +4,13 @@ use celox_sv_syntax::{BodyItemKind, ParameterKind, TypeAliasTarget}; pub(super) fn type_aliases_from_scope( tree: &AnalysisContext<'_>, + session: &mut Session, ) -> Converted> { // Constants of this scope are not available until parameter collection. // The subsequent pass with an environment requires complete defaults. type_aliases_in_scope( tree, + session, &HashMap::default(), &HashMap::default(), true, @@ -19,10 +21,12 @@ pub(super) fn type_aliases_from_scope( } pub(super) fn type_aliases_from_scope_with_env( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, ) -> Converted> { type_aliases_in_scope( syntax_tree, + session, const_env, &HashMap::default(), true, @@ -35,12 +39,14 @@ pub(super) fn type_aliases_from_scope_with_env( /// Resolve a selected body while retaining its enclosing lexical type bindings. pub(super) fn type_aliases_from_body_with_env( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, items: &[celox_sv_syntax::BodyItemId], const_env: &HashMap, inherited: &HashMap, ) -> Converted> { type_aliases_in_scope( syntax_tree, + session, const_env, inherited, false, @@ -55,6 +61,7 @@ pub(super) fn type_aliases_from_body_with_env( /// in each iteration of a loop (IEEE 1800-2023 27.4). pub(super) fn type_aliases_of_generate_scope( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, items: &[celox_sv_syntax::BodyItemId], const_env: &HashMap, inherited: &HashMap, @@ -62,6 +69,7 @@ pub(super) fn type_aliases_of_generate_scope( ) -> Converted> { type_aliases_in_scope( syntax_tree, + session, const_env, inherited, false, @@ -73,6 +81,7 @@ pub(super) fn type_aliases_of_generate_scope( fn type_aliases_in_scope( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, inherited: &HashMap, include_header: bool, @@ -93,6 +102,7 @@ fn type_aliases_in_scope( parameter, parameter.id, syntax_tree, + session, const_env, &mut aliases, )?; @@ -117,6 +127,7 @@ fn type_aliases_in_scope( parameter, parameter.id, syntax_tree, + session, const_env, &mut aliases, )?; @@ -131,6 +142,7 @@ fn type_aliases_in_scope( id, syntax_tree.declarations(), syntax_tree, + session, const_env, &aliases, defer_class_defaults, @@ -139,8 +151,13 @@ fn type_aliases_in_scope( continue; }; let context = PackedDimensions::new(HashMap::default(), const_env, &aliases); - let mut ty = - containers::with_dimensions(base, &alias.dimensions, syntax_tree, &context)?; + let mut ty = containers::with_dimensions( + base, + &alias.dimensions, + syntax_tree, + session, + &context, + )?; ty.name_declaration(|| declaration_name(syntax_tree, alias, generate_scope)); aliases.insert(instances::normalize_identifier(&alias.name.spelling), ty); } @@ -231,6 +248,7 @@ fn add_type_parameter( parameter: &celox_sv_syntax::Parameter, key: celox_sv_syntax::ParameterId, tree: &AnalysisContext<'_>, + session: &mut Session, env: &HashMap, aliases: &mut HashMap, ) -> Converted<()> { @@ -242,7 +260,7 @@ fn add_type_parameter( aliases.insert(name, bound.clone()); } else if let Some(id) = default { let context = PackedDimensions::new(HashMap::default(), env, aliases); - if let Some(ty) = type_binding::bind(id, tree, &context)? { + if let Some(ty) = type_binding::bind(id, tree, session, &context)? { aliases.insert(name, ty); } } diff --git a/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs b/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs index 865048b72a2..37fc29caaf5 100644 --- a/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs +++ b/crates/celox-sv-analyzer/src/ast/unpacked_structs.rs @@ -245,6 +245,7 @@ pub(in crate::ast) fn native_struct( id: ExprId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted>> { let id = expression_binding::ungroup(id, native); @@ -261,25 +262,27 @@ pub(in crate::ast) fn native_struct( .and_then(|parts| dims.get(&parts[0])?.unpacked_struct.clone()) { Some(aggregate) => Some(aggregate), - None if let Some((ty, _)) = containers::element_member(id, native, tree, dims)? => { + None if let Some((ty, _)) = + containers::element_member(id, native, tree, session, dims)? => + { ty.unpacked_struct().cloned() } // A class property of unpacked structure type. None if let Some((aggregate, _, _)) = - expression_binding::object_aggregate_property(tree, id, native, dims)? => + expression_binding::object_aggregate_property(tree, session, id, native, dims)? => { aggregate.r#type.unpacked_struct().cloned() } // An element popped by `q.pop_front` without parentheses. - None => containers::native_struct_element(id, native, tree, dims)?, + None => containers::native_struct_element(id, native, tree, session, dims)?, }, ExprKind::Conditional { then_expression, else_expression, .. } => { - let then_type = native_struct(*then_expression, native, tree, dims)?; - let else_type = native_struct(*else_expression, native, tree, dims)?; + let then_type = native_struct(*then_expression, native, tree, session, dims)?; + let else_type = native_struct(*else_expression, native, tree, session, dims)?; then_type.filter(|then_type| { else_type .as_ref() @@ -292,13 +295,19 @@ pub(in crate::ast) fn native_struct( } if std::ptr::eq(native, tree.declarations()) => { patterns::typed_shape(id, tree, dims)?.and_then(|shape| shape.unpacked_struct) } - _ if containers::native_struct_element(id, native, tree, dims)?.is_some() => { - containers::native_struct_element(id, native, tree, dims)? + _ if containers::native_struct_element(id, native, tree, session, dims)?.is_some() => { + containers::native_struct_element(id, native, tree, session, dims)? } // A method of the scope class hides a module function of its name, // as call binding resolves it. ExprKind::Call { expression, .. } => { - match expression_binding::object_method_result(tree, *expression, native, dims)? { + match expression_binding::object_method_result( + tree, + session, + *expression, + native, + dims, + )? { Some(ty) => ty.unpacked_struct().cloned(), None => expression_binding::callable_name(tree, *expression, native) .and_then(|name| dims.functions.get(&name)) @@ -357,13 +366,14 @@ pub(in crate::ast) fn check_assignment( name: &str, right: ExprId, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted<()> { let target = dims .get(name) .and_then(|shape| shape.unpacked_struct.clone()) .ok_or_else(|| unsupported("unpacked structure target"))?; - check_value(&target, right, tree.declarations(), tree, dims) + check_value(&target, right, tree.declarations(), tree, session, dims) } /// Check that `value` is an assignment pattern or a value of type `target`. @@ -372,6 +382,7 @@ pub(in crate::ast) fn check_value( value: ExprId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted<()> { let value = expression_binding::ungroup(value, native); @@ -389,10 +400,10 @@ pub(in crate::ast) fn check_value( .. } = &native.expression(value).kind { - check_value(target, *then_expression, native, tree, dims)?; - return check_value(target, *else_expression, native, tree, dims); + check_value(target, *then_expression, native, tree, session, dims)?; + return check_value(target, *else_expression, native, tree, session, dims); } - match native_struct(value, native, tree, dims)? { + match native_struct(value, native, tree, session, dims)? { Some(actual) if actual.same_type(target) => Ok(()), _ => Err(unsupported( "assignment to an unpacked structure of a value that is not of its type", @@ -407,6 +418,7 @@ pub(in crate::ast) fn check_operands( id: ExprId, native: &celox_sv_syntax::Declarations, tree: &AnalysisContext<'_>, + session: &mut Session, dims: &PackedDimensions, ) -> Converted<()> { let operands: Vec = match &native.expression(id).kind { @@ -417,8 +429,8 @@ pub(in crate::ast) fn check_operands( right, } => { if matches!(operator.as_str(), "==" | "!=" | "===" | "!==") { - let left_type = native_struct(*left, native, tree, dims)?; - let right_type = native_struct(*right, native, tree, dims)?; + let left_type = native_struct(*left, native, tree, session, dims)?; + let right_type = native_struct(*right, native, tree, session, dims)?; return match (left_type, right_type) { (None, None) => Ok(()), (Some(left), Some(right)) if left.same_type(&right) => Ok(()), @@ -436,7 +448,7 @@ pub(in crate::ast) fn check_operands( _ => return Ok(()), }; for operand in operands { - if native_struct(operand, native, tree, dims)?.is_some() { + if native_struct(operand, native, tree, session, dims)?.is_some() { return Err(unsupported( "operator, select or cast applied to an unpacked structure", )); diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 55c4f7573f5..ac348ee82b7 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -261,6 +261,7 @@ fn validate_body_items( pub(super) fn reject_silently_ignored_constructs( syntax_tree: &AnalysisContext<'_>, + session: &mut Session, const_env: &HashMap, type_aliases: &HashMap, parameter_dimensions: &ScopedMap, @@ -272,19 +273,19 @@ pub(super) fn reject_silently_ignored_constructs( let mut dimensions = PackedDimensions::new(parameter_dimensions.clone(), const_env, type_aliases); dimensions.parameter_values = parameter_values.clone().into(); - validate_scope(None, syntax_tree, &dimensions)?; + validate_scope(None, syntax_tree, session, &dimensions)?; if syntax_tree .root_unit() .is_ok_and(|unit| unit.kind.is_module_like()) { - let active = generate::items(syntax_tree, const_env, type_aliases)?; + let active = generate::items(syntax_tree, session, const_env, type_aliases)?; let mut views = generate::ScopeViews::new(&dimensions); for item in &active { item.procedure(syntax_tree.declarations())?; item.continuous_assignment(syntax_tree.declarations())?; let syntax_tree = &item.enter(syntax_tree); let syntax_tree = &item.scoped(syntax_tree); - validate_scope(Some(item), syntax_tree, views.dimensions(item))?; + validate_scope(Some(item), syntax_tree, session, views.dimensions(item))?; } } Ok(()) @@ -681,6 +682,7 @@ impl Facts { fn validate_scope( item: Option<&generate::Item>, syntax_tree: &AnalysisContext<'_>, + session: &mut Session, indexed_dimensions: &PackedDimensions, ) -> Converted<()> { use celox_sv_syntax::{BodyItemKind, DataTypeKind, DimensionKind, ExprKind}; @@ -694,7 +696,13 @@ fn validate_scope( .is_ok_and(|unit| unit.kind.is_module_like()); let items = owner.map_or_else(|| syntax_tree.body_membership(), |id| Ok(vec![id]))?; validate_body_items(&items, native, !is_module)?; - parameters::skipped::validate_scope(owner, is_module, syntax_tree, indexed_dimensions)?; + parameters::skipped::validate_scope( + owner, + is_module, + syntax_tree, + session, + indexed_dimensions, + )?; let const_env = &indexed_dimensions.const_env; let type_aliases = &indexed_dimensions.type_aliases; let mut ranges = items @@ -734,6 +742,7 @@ fn validate_scope( &selected, &ranges, syntax_tree, + session, indexed_dimensions, item, )?; @@ -844,7 +853,7 @@ fn validate_scope( continue; } if matches!(data.kind, DataTypeKind::Struct { .. }) - && type_binding::bind(id, syntax_tree, indexed_dimensions)?.is_none() + && type_binding::bind(id, syntax_tree, session, indexed_dimensions)?.is_none() { return Err(unsupported( "unpacked struct, union, or unsupported packed struct member", @@ -873,8 +882,15 @@ fn validate_scope( continue; }; for id in [left, right] { - if constant_binding::expression(id, native, syntax_tree, const_env, type_aliases)? - .is_none() + if constant_binding::expression( + id, + native, + syntax_tree, + session, + const_env, + type_aliases, + )? + .is_none() { return Err(unsupported("unsupported packed range")); } @@ -896,7 +912,7 @@ fn validate_scope( // IEEE 1800-2023 11.5.1 permits a variable base. Its // expression is bound after variable types are available; // only the width requires constant validation here. - check_indexed_width(width, syntax_tree, indexed_dimensions)?; + check_indexed_width(width, syntax_tree, session, indexed_dimensions)?; } } _ => {} @@ -933,6 +949,7 @@ fn validate_scope( operand, native, syntax_tree, + session, indexed_dimensions, )?; } @@ -952,9 +969,9 @@ fn validate_scope( && expression_binding::native_name(syntax_tree, callee, native).as_deref() == Some("$isunbounded") { - expression_binding::bind(root, syntax_tree, indexed_dimensions)?; + expression_binding::bind(root, syntax_tree, session, indexed_dimensions)?; } else { - dimensions::query_value(root, syntax_tree, indexed_dimensions)? + dimensions::query_value(root, syntax_tree, session, indexed_dimensions)? .ok_or_else(|| unsupported("operand of native type query"))?; } } @@ -991,6 +1008,7 @@ fn reject_constant_calls( selected: &impl Fn(celox_sv_syntax::TokenRange) -> bool, ranges: &[celox_sv_syntax::TokenRange], tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, item: Option<&generate::Item>, ) -> Converted<()> { @@ -1107,7 +1125,7 @@ fn reject_constant_calls( if let Some(error) = const_functions::conversion_error(&tree.functions, &name) { return Err(error); } - let context = dimensions::query_context_for_operand(id, tree, dimensions)?; + let context = dimensions::query_context_for_operand(id, tree, session, dimensions)?; // Generate imports can hide an outer constant function with a // package DPI function. Resolve that authored name in the active // item before consulting the qualified package declarations. @@ -1135,6 +1153,7 @@ fn reject_constant_calls( fn check_indexed_width( native: celox_sv_syntax::ExprId, syntax_tree: &AnalysisContext<'_>, + session: &mut Session, dimensions: &PackedDimensions, ) -> Converted<()> { let mut context = dimensions.clone(); @@ -1143,9 +1162,10 @@ fn check_indexed_width( native, syntax_tree.declarations(), syntax_tree, + session, &context, )?; - let width = selects::indexed_expression_value(syntax_tree, value, &context) + let width = selects::indexed_expression_value(syntax_tree, session, value, &context) .ok_or_else(|| unsupported("constant index expression"))?; match eval_ast_const_expr(&syntax_tree.functions, &width, &dimensions.const_env) { Some(width) if width > 0 => Ok(()), @@ -1163,6 +1183,7 @@ mod traversal_tests { #[test] fn validates_native_owners_without_visiting_inactive_generate_bodies() { + let session = &mut Session::default(); for (body, accepted) in [ ( "logic visible; if (0) begin : hidden always_latch visible <= 1; end", @@ -1182,6 +1203,7 @@ mod traversal_tests { .unwrap(); let result = reject_silently_ignored_constructs( &AnalysisContext::unspecialized(&tree), + session, &HashMap::default(), &HashMap::default(), &ScopedMap::default(), diff --git a/crates/celox-sv-analyzer/src/ast/virtual_interfaces.rs b/crates/celox-sv-analyzer/src/ast/virtual_interfaces.rs index 70a5cc29cff..5e59c7651fc 100644 --- a/crates/celox-sv-analyzer/src/ast/virtual_interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/virtual_interfaces.rs @@ -253,13 +253,13 @@ pub(super) fn value_type(interface: VirtualInterface) -> Type { } /// The declarations of the design's virtual interfaces, if it has any. -pub(super) fn declarations(state: &AnalysisState) -> Option<&VirtualInterfaces> { +pub(super) fn declarations(state: &Session) -> Option<&VirtualInterfaces> { state.virtual_interfaces.as_deref() } /// The type `virtual name[.modport]`, checked against the interface. pub(super) fn bind_type( - state: &AnalysisState, + state: &Session, name: &celox_sv_syntax::Name, arguments: Option<&[celox_sv_syntax::Argument]>, modport: Option<&celox_sv_syntax::Name>, @@ -293,7 +293,7 @@ pub(super) fn bind_type( /// The member `member` that a virtual interface of type `ty` reaches, with /// the signals that denote it in each instance the value may denote. pub(super) fn member<'a>( - state: &'a AnalysisState, + state: &'a Session, ty: &VirtualInterface, member: &str, ) -> Converted<(&'a VirtualInterfaceMember, Vec<(u32, String)>)> { @@ -337,7 +337,7 @@ pub(super) fn member<'a>( /// input of its modport, which may not be assigned (IEEE 1800-2023 25.5, /// 23.3.3.4). pub(super) fn check_write( - state: &AnalysisState, + state: &Session, ty: &VirtualInterface, member: &str, ) -> Result<(), AnalyzerError> { @@ -420,6 +420,7 @@ pub(super) fn template(interface: &str, member: &str) -> String { /// `h.m[i]` or `h.m[i][j:k]`, with the access's handle, type and member. pub(super) fn native_selected_member( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::ExprId, native: &celox_sv_syntax::Declarations, dimensions: &PackedDimensions, @@ -431,7 +432,7 @@ pub(super) fn native_selected_member( base = expression_binding::ungroup(*expression, native); } selected - .then(|| native_member(tree, base, native, dimensions)) + .then(|| native_member(tree, session, base, native, dimensions)) .flatten() } @@ -440,14 +441,14 @@ pub(super) fn native_selected_member( /// denotes; an error for `null`. pub(super) fn selected_read( tree: &AnalysisContext<'_>, + session: &mut Session, handle: Expr, ty: &VirtualInterface, member: &str, selected: Expr, dimensions: &PackedDimensions, ) -> Converted { - let state = &*tree.state; - let (_, signals) = self::member(state, ty, member)?; + let (_, signals) = self::member(session, ty, member)?; check_pure(&handle)?; let width = expr_static_width(tree, &selected, dimensions) .ok_or_else(|| unsupported(format!("width of a select of `{member}`")))?; @@ -490,18 +491,20 @@ pub(super) fn rename(expr: Expr, from: &str, to: &str) -> Expr { /// container of virtual interfaces. pub(super) fn native_type( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::ExprId, native: &celox_sv_syntax::Declarations, dimensions: &PackedDimensions, ) -> Option> { - declarations(&tree.state)?; + declarations(session)?; let id = expression_binding::ungroup(id, native); if let celox_sv_syntax::ExprKind::Select { expression, dimension, } = &native.expression(id).kind && matches!(dimension.kind, celox_sv_syntax::DimensionKind::Index(_)) - && let Ok(Some(container)) = containers::native_type(*expression, native, tree, dimensions) + && let Ok(Some(container)) = + containers::native_type(*expression, native, tree, session, dimensions) { return container.element.virtual_interface.clone(); } @@ -548,7 +551,7 @@ pub(super) fn native_type( if indices > 0 { return None; } - let (property, _) = expression_binding::object_property(tree, id, native, dimensions) + let (property, _) = expression_binding::object_property(tree, session, id, native, dimensions) .ok() .flatten()?; property @@ -562,6 +565,7 @@ pub(super) fn native_type( /// virtual interface `h`: the native handle, its type and the member. pub(super) fn native_member( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::ExprId, native: &celox_sv_syntax::Declarations, dimensions: &PackedDimensions, @@ -579,7 +583,7 @@ pub(super) fn native_member( if separator != "." { return None; } - let ty = native_type(tree, *expression, native, dimensions)?; + let ty = native_type(tree, session, *expression, native, dimensions)?; Some(( *expression, ty, @@ -623,15 +627,15 @@ pub(super) fn null_access(handle: &Expr, width: usize, signed: bool) -> Expr { /// member of each instance. pub(super) fn read( tree: &AnalysisContext<'_>, + session: &mut Session, 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)?; + let (found, signals) = self::member(session, ty, member)?; check_pure(&handle)?; let mut arms = Vec::new(); for (id, signal) in signals { @@ -744,13 +748,13 @@ fn visit_const_calls(expr: &ConstExpr, visit: &mut dyn FnMut(&Callee)) { /// `handle` of type `ty` denotes, `signal` naming its member `member`; an /// error for `null`. pub(super) fn dispatch( - state: &AnalysisState, + session: &mut Session, handle: Expr, ty: &VirtualInterface, member: &str, - mut arm: impl FnMut(String) -> Converted>, + mut arm: impl FnMut(&mut Session, String) -> Converted>, ) -> Converted { - let (_, signals) = self::member(state, ty, member)?; + let (_, signals) = self::member(session, ty, member)?; check_pure(&handle)?; let items = signals .into_iter() @@ -759,7 +763,7 @@ pub(super) fn dispatch( labels: vec![crate::procedural::CaseLabel::Value(Expr::Literal(format!( "{WIDTH}'d{id}" )))], - body: arm(signal)?, + body: arm(session, signal)?, }) }) .collect::>>()?; @@ -774,11 +778,7 @@ pub(super) fn dispatch( /// The signal that holds the id of the interface instance that interface /// instance or port `handle` of interface `interface` denotes, if a virtual /// interface may denote it. -pub(super) fn identity_signal( - state: &AnalysisState, - handle: &str, - interface: &str, -) -> Option { +pub(super) fn identity_signal(state: &Session, handle: &str, interface: &str) -> Option { declarations(state)?.interfaces.get(interface)?; Some(Signal { name: VirtualInterfaceSignal::Identity { @@ -801,7 +801,7 @@ pub(super) fn identity_signal( /// interface declares no members: the frontend finds the instance a port /// denotes by the connections of its members. pub(super) fn port_identity_signal( - state: &AnalysisState, + state: &Session, handle: &str, interface: &str, ) -> Option { @@ -820,10 +820,11 @@ pub(super) fn port_identity_signal( /// interface value: the id of the instance it denotes. pub(super) fn identity( tree: &AnalysisContext<'_>, + session: &mut Session, name: &str, dimensions: &PackedDimensions, ) -> Converted> { - if declarations(&tree.state).is_none() || dimensions.get(name).is_some() { + if declarations(session).is_none() || dimensions.get(name).is_some() { return Ok(None); } let signal = VirtualInterfaceSignal::Identity { @@ -846,7 +847,7 @@ pub(super) fn identity( /// The interface instances and ports of a scope with symbols `symbols` and /// ports `ports` that a virtual interface may denote. pub(super) fn handles( - state: &AnalysisState, + state: &Session, symbols: &scope::ScopeSymbols, ports: &[Port], ) -> Vec { @@ -888,18 +889,20 @@ pub(super) fn handles( /// interface value. pub(super) fn native_identity( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::ExprId, dimensions: &PackedDimensions, ) -> Option { - declarations(&tree.state)?; + declarations(session)?; let handle = interface_binding::actual_handle_key( id, tree, + session, &dimensions.const_env, &dimensions.type_aliases, ) .ok()?; - identity(tree, &handle, dimensions).ok().flatten() + identity(tree, session, &handle, dimensions).ok().flatten() } /// What native expression `id` is as a virtual interface value: `None` for @@ -908,6 +911,7 @@ pub(super) fn native_identity( /// else it is. fn native_value_type( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::ExprId, native: &celox_sv_syntax::Declarations, dimensions: &PackedDimensions, @@ -931,17 +935,22 @@ fn native_value_type( "pop_front" | "pop_back" ) && let Ok(Some(container)) = - containers::native_type(*receiver, native, tree, dimensions) + containers::native_type(*receiver, native, tree, session, dimensions) && let Some(element) = &container.element.virtual_interface { return Ok(Some(element.as_ref().clone())); } - let name = - match expression_binding::object_method(tree, *expression, native, dimensions) { - Ok(Some((name, _, _))) => name, - _ => expression_binding::callable_name(tree, *expression, native) - .ok_or_else(|| "the call".to_owned())?, - }; + let name = match expression_binding::object_method( + tree, + session, + *expression, + native, + dimensions, + ) { + Ok(Some((name, _, _))) => name, + _ => expression_binding::callable_name(tree, *expression, native) + .ok_or_else(|| "the call".to_owned())?, + }; return match dimensions.function_return_types.get(&name) { Some(result) => match &result.virtual_interface { Some(ty) => Ok(Some(ty.as_ref().clone())), @@ -952,12 +961,13 @@ fn native_value_type( } _ => {} } - if let Some(ty) = native_type(tree, id, native, dimensions) { + if let Some(ty) = native_type(tree, session, id, native, dimensions) { return Ok(Some(ty.as_ref().clone())); } let handle = interface_binding::actual_handle_key( id, tree, + session, &dimensions.const_env, &dimensions.type_aliases, ) @@ -983,6 +993,7 @@ fn native_value_type( /// of type `target` (IEEE 1800-2023 25.9). pub(super) fn check_assignment( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::ExprId, native: &celox_sv_syntax::Declarations, dimensions: &PackedDimensions, @@ -997,10 +1008,10 @@ pub(super) fn check_assignment( .expression(expression_binding::ungroup(id, native)) .kind { - check_assignment(tree, *then_expression, native, dimensions, target)?; - return check_assignment(tree, *else_expression, native, dimensions, target); + check_assignment(tree, session, *then_expression, native, dimensions, target)?; + return check_assignment(tree, session, *else_expression, native, dimensions, target); } - let actual = match native_value_type(tree, id, native, dimensions) { + let actual = match native_value_type(tree, session, id, native, dimensions) { Ok(None) => return Ok(()), Ok(Some(source)) if target.accepts(&source) => return Ok(()), Ok(Some(source)) => format!("a `{}`", source.spelling()), @@ -1028,12 +1039,13 @@ pub(super) fn arithmetic(op: &str, ty: &VirtualInterface) -> AnalyzerError { /// 25.9). pub(super) fn check_copy_out( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::ExprId, native: &celox_sv_syntax::Declarations, dimensions: &PackedDimensions, formal: &VirtualInterface, ) -> Converted<()> { - let actual = match native_type(tree, id, native, dimensions) { + let actual = match native_type(tree, session, id, native, dimensions) { Some(actual) if actual.accepts(formal) => return Ok(()), Some(actual) => actual.spelling(), None => "the argument".to_owned(), @@ -1092,6 +1104,7 @@ pub(super) fn check_array_assignment( /// conditional counts. fn equality_operand( tree: &AnalysisContext<'_>, + session: &mut Session, id: celox_sv_syntax::ExprId, native: &celox_sv_syntax::Declarations, dimensions: &PackedDimensions, @@ -1105,10 +1118,24 @@ fn equality_operand( .expression(expression_binding::ungroup(id, native)) .kind { - equality_operand(tree, *then_expression, native, dimensions, interface)?; - return equality_operand(tree, *else_expression, native, dimensions, interface); + equality_operand( + tree, + session, + *then_expression, + native, + dimensions, + interface, + )?; + return equality_operand( + tree, + session, + *else_expression, + native, + dimensions, + interface, + ); } - match native_value_type(tree, id, native, dimensions)? { + match native_value_type(tree, session, id, native, dimensions)? { None => Ok(()), Some(source) if source.interface == interface => Ok(()), Some(source) => Err(format!("a `{}`", source.spelling())), @@ -1120,19 +1147,21 @@ fn equality_operand( /// same interface (IEEE 1800-2023 25.9). pub(super) fn check_equality( tree: &AnalysisContext<'_>, + session: &mut Session, left: celox_sv_syntax::ExprId, right: celox_sv_syntax::ExprId, native: &celox_sv_syntax::Declarations, dimensions: &PackedDimensions, ) -> Converted<()> { - if declarations(&tree.state).is_none() { + if declarations(session).is_none() { return Ok(()); } for (one, other) in [(left, right), (right, left)] { - let Some(ty) = native_type(tree, one, native, dimensions) else { + let Some(ty) = native_type(tree, session, one, native, dimensions) else { continue; }; - let Err(actual) = equality_operand(tree, other, native, dimensions, &ty.interface) else { + let Err(actual) = equality_operand(tree, session, other, native, dimensions, &ty.interface) + else { return Ok(()); }; return Err(AnalyzerError::IncompatibleVirtualInterface { @@ -1155,13 +1184,13 @@ pub(super) fn null_check(handle: &Expr) -> Expr { /// zero for `null`. pub(super) fn watched( tree: &AnalysisContext<'_>, + session: &mut Session, handle: Expr, ty: &VirtualInterface, member: &str, ) -> Converted { - let state = &*tree.state; let functions = &tree.functions; - let (found, signals) = self::member(state, ty, member)?; + let (found, signals) = self::member(session, ty, member)?; 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}`")))?; @@ -1181,7 +1210,7 @@ pub(super) fn watched( /// one counts each write of the member, which the settled selection /// ([`watched`]) misses when a process pulses it. pub(super) fn watched_writes( - state: &AnalysisState, + state: &Session, handle: &Expr, ty: &VirtualInterface, member: &str, diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index d6da582fd7b..544bbcd5c38 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -36,7 +36,7 @@ pub use ast::interfaces::{ InterfacePrototype, interface_prototypes, interface_prototypes_for, interface_prototypes_with_options, }; -pub use ast::packages::Packages; +pub use ast::packages::{Design, Packages}; pub use ast::virtual_interfaces::{ VirtualInterface, VirtualInterfaceDeclaration, VirtualInterfaceMember, VirtualInterfaceSignal, VirtualInterfaces, @@ -404,7 +404,7 @@ fn analyze_interface_source( ) -> Result { let source = ParsedSource::parse(code, path)?; let packages = ParsedSource::analyze_packages(&[&source])?; - let plan = &packages.interface_plan; + let plan = packages.interface_plan.clone(); let mut names = source .module_names() .iter() @@ -460,6 +460,7 @@ fn analyze_interface_source( &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), )?; modules.extend(ir.modules().iter().cloned()); warnings.extend(ir.warnings().iter().cloned()); @@ -573,6 +574,7 @@ pub fn analyze_source_module_with_packages( module_name: &str, parameter_overrides: &HashMap, packages: &Packages, + design: &mut Design, ) -> Result { let overrides = parameter_overrides .iter() @@ -596,5 +598,6 @@ pub fn analyze_source_module_with_packages( &[], &ModuleInterfaces::default(), packages, + design, ) } diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index 894e7827c63..ebf2565c35c 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -4,7 +4,7 @@ use std::path::{Path, PathBuf}; use fxhash::FxHashMap as HashMap; -use crate::{AnalyzerError, Ir, ModuleInterfaces, Packages, analyze, ast, ir, source_tree}; +use crate::{AnalyzerError, Design, Ir, ModuleInterfaces, Packages, analyze, ast, ir, source_tree}; /// A parsed source that can analyze many modules or parameter specializations. /// @@ -223,6 +223,7 @@ impl ParsedSource { pattern_overrides: &[(String, ast::BoundPattern)], interfaces: &ModuleInterfaces, packages: &Packages, + design: &mut Design, ) -> Result { self.analyze_module_with_packages( module_name, @@ -232,6 +233,7 @@ impl ParsedSource { interfaces, packages, ModuleAnalysis::Full(&[]), + design, ) } @@ -246,6 +248,7 @@ impl ParsedSource { pattern_overrides: &[(String, ast::BoundPattern)], interfaces: &ModuleInterfaces, packages: &Packages, + design: &mut Design, hierarchical: &[ast::HierarchicalSignal], ) -> Result { self.analyze_module_with_packages( @@ -256,6 +259,7 @@ impl ParsedSource { interfaces, packages, ModuleAnalysis::Full(hierarchical), + design, ) } @@ -270,6 +274,7 @@ impl ParsedSource { pattern_overrides: &[(String, ast::BoundPattern)], interfaces: &ModuleInterfaces, packages: &Packages, + design: &mut Design, ) -> Result { self.analyze_module_with_packages( module_name, @@ -279,6 +284,7 @@ impl ParsedSource { interfaces, packages, ModuleAnalysis::DeclarationsOnly, + design, ) } @@ -358,12 +364,14 @@ impl ParsedSource { module_name: &str, overrides: &HashMap, packages: &Packages, + design: &mut Design, ) -> Result { self.analyze_module_declarations_with_interfaces( module_name, overrides, &ModuleInterfaces::default(), packages, + design, ) } @@ -375,6 +383,7 @@ impl ParsedSource { overrides: &HashMap, interfaces: &ModuleInterfaces, packages: &Packages, + design: &mut Design, ) -> Result { self.validate_module_namespace(module_name, packages)?; let overrides = overrides @@ -395,6 +404,7 @@ impl ParsedSource { }, interfaces, packages, + design, )?; analyze::analyze_source(source) } @@ -416,6 +426,7 @@ impl ParsedSource { interfaces, &packages, ModuleAnalysis::Full(&[]), + &mut packages.design(), ) } @@ -449,12 +460,14 @@ impl ParsedSource { interfaces: &ModuleInterfaces, packages: &Packages, analysis: ModuleAnalysis<'_>, + design: &mut Design, ) -> Result { let overrides = overrides .iter() .map(|(name, value)| (name.clone(), value.clone().into())) .collect(); - let original = packages.authored_module_name(module_name); + let original = packages.authored_module_name(module_name).to_owned(); + let original = original.as_str(); let warnings = self.warnings.get(original).cloned().unwrap_or_default(); let ir = (|| { self.validate_module_namespace(original, packages)?; @@ -475,6 +488,7 @@ impl ParsedSource { }, interfaces, packages, + design, )?; analyze::analyze_source(source) })(); @@ -628,6 +642,7 @@ mod tests { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); let typed = code.replace("logic [3:0]", "logic [7:0]"); @@ -674,6 +689,7 @@ mod tests { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); let module = &ir.modules()[0]; @@ -706,6 +722,7 @@ mod tests { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); assert_eq!( @@ -740,7 +757,8 @@ mod tests { &bindings, &[], &ModuleInterfaces::default(), - &packages + &packages, + &mut packages.design() ) .is_err() ); @@ -753,6 +771,7 @@ mod tests { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); assert_eq!( @@ -863,6 +882,7 @@ mod pattern_override_tests { &[("Q".into(), bound)], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); assert_eq!(ir.modules()[0].initial_processes().len(), 1); @@ -907,6 +927,7 @@ mod pattern_override_tests { &[("Q".into(), pattern.clone())], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); } @@ -1128,6 +1149,7 @@ mod native_interface_tests { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); let instance = &ir.modules()[0].instances()[0]; @@ -1150,6 +1172,7 @@ mod native_interface_tests { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); assert_eq!(child.modules()[0].name(), instance.module_name()); @@ -1228,6 +1251,7 @@ mod native_interface_tests { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); let module = &ir.modules()[0]; @@ -1368,12 +1392,13 @@ mod declaration_tests { &[], &[], &ModuleInterfaces::default(), - &packages + &packages, + &mut packages.design() ) .is_ok() ); let ir = source - .analyze_module_declarations("Top", &overrides, &packages) + .analyze_module_declarations("Top", &overrides, &packages, &mut packages.design()) .unwrap(); let module = &ir.modules()[0]; assert_eq!(module.ports()[0].r#type().resolved_width(), Some(18)); @@ -1411,7 +1436,12 @@ mod declaration_tests { .unwrap(); let packages = ParsedSource::analyze_packages(&[&source]).unwrap(); let ir = source - .analyze_module_declarations("Top", &HashMap::default(), &packages) + .analyze_module_declarations( + "Top", + &HashMap::default(), + &packages, + &mut packages.design(), + ) .unwrap(); let module = &ir.modules()[0]; assert_eq!(module.ports()[0].r#type().resolved_width(), Some(8)); @@ -1492,12 +1522,13 @@ mod shared_namespace_tests { "I", &HashMap::default(), &packages, + &mut packages.design(), ) .unwrap_err(); assert!(matches!(error, AnalyzerError::DuplicateModule { name } if name == "I")); let parsed = ParsedSource::parse(module, Path::new("module.sv")).unwrap(); assert!( - matches!(parsed.analyze_module_declarations("I", &HashMap::default(), &packages), + matches!(parsed.analyze_module_declarations("I", &HashMap::default(), &packages, &mut packages.design()), Err(AnalyzerError::DuplicateModule { name }) if name == "I") ); } @@ -1508,6 +1539,7 @@ mod shared_namespace_tests { "Top", &HashMap::default(), &packages, + &mut packages.design(), ) .unwrap(); } @@ -1528,6 +1560,7 @@ mod shared_namespace_tests { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); } diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/constant_typed_patterns.rs b/crates/celox-sv-analyzer/src/source_tree/tests/constant_typed_patterns.rs index af7e90e2bc3..74a4234b40e 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/constant_typed_patterns.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/constant_typed_patterns.rs @@ -45,6 +45,7 @@ fn initialized(pattern: BoundPattern, declaration: &str) -> Vec { &[("P".into(), pattern)], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); let crate::ir::Stmt::Assign { rhs, .. } = &ir.modules()[0].initial_processes()[0].body()[0] 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 db0cb1c6626..70a681afef7 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 @@ -1,8 +1,10 @@ //! Symbolic declaration consumers must use native execution ownership/values. use super::*; +use crate::ast::Session; use crate::ast::{Callee, ConstExpr, Source}; use celox_sv_syntax::{ExprKind, StatementKind}; fn inline(tree: &SourceTree, input: i128) -> i128 { + let session = &mut Session::default(); let source = Source::from_syntax(tree).unwrap(); let expression = ConstExpr::Function { callee: Callee::Subroutine("f".into()), @@ -12,6 +14,7 @@ fn inline(tree: &SourceTree, input: i128) -> i128 { let syntax = crate::source_tree::SourceTree::empty(); let expression = source.modules()[0].declaration_expr( &crate::ast::AnalysisContext::unspecialized(&syntax), + session, &expression, &HashMap::default(), ); diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/override_patterns.rs b/crates/celox-sv-analyzer/src/source_tree/tests/override_patterns.rs index b1eedebcbca..3fe15717160 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/override_patterns.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/override_patterns.rs @@ -36,6 +36,7 @@ fn leaves(pattern: BoundPattern, dimensions: &str) -> Vec { &[("P".into(), pattern)], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); let statement = &ir.modules()[0].initial_processes()[0].body()[0]; diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index a30b85e205a..052c57d2e5c 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -1409,6 +1409,7 @@ fn resolves_imported_constant_parameter_part_selects() { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap(); assert_eq!(ir.modules()[0].parameters()[0].resolved_value(), Some(11)); @@ -3834,6 +3835,7 @@ fn native_interface_module(source: &str, name: &str) -> ir::Module { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap() .modules()[0] @@ -3881,6 +3883,7 @@ fn native_interface_sources(sources: &[(&str, &Path)]) -> Result &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), )?; modules.extend(ir.modules().iter().cloned()); } @@ -5338,6 +5341,7 @@ fn native_interface_array_ports_reject_incompatible_shapes() { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap_err(); assert_eq!( @@ -5374,6 +5378,7 @@ fn rejects_mismatched_interface_array_connection_widths_and_shapes() { &[], &ModuleInterfaces::default(), &packages, + &mut packages.design(), ) .unwrap_err(); assert!( @@ -7010,6 +7015,7 @@ fn imported_class_member_types_keep_declaration_dimensions() { "Top", &HashMap::default(), &packages, + &mut packages.design(), ) .expect("imported class typedefs must retain their declaration's dimensions"); let top = ir diff --git a/crates/celox-test-suite/src/sv/verification.rs b/crates/celox-test-suite/src/sv/verification.rs index a3d10edcee7..bef8fe0a28f 100644 --- a/crates/celox-test-suite/src/sv/verification.rs +++ b/crates/celox-test-suite/src/sv/verification.rs @@ -76,6 +76,8 @@ fn analyzed_info(design: &Design) -> Option { interfaces.extend(source.module_interfaces().clone()); } let mut modules: Vec = Vec::new(); + // The package class specializations the modules share. + let mut analysis = packages.design(); for source in &sources { for name in source.module_names() { let overrides = if name == &design.top { @@ -98,9 +100,18 @@ fn analyzed_info(design: &Design) -> Option { &overrides, &interfaces, &packages, + &mut analysis, ) } else { - source.analyze_module(name, &overrides, &[], &[], &interfaces, &packages) + source.analyze_module( + name, + &overrides, + &[], + &[], + &interfaces, + &packages, + &mut analysis, + ) }; if let Ok(ir) = result { modules.extend(ir.modules().iter().cloned()); diff --git a/flake.lock b/flake.lock index 7827d017773..5b2fad78799 100644 --- a/flake.lock +++ b/flake.lock @@ -51,34 +51,34 @@ ] }, "locked": { - "lastModified": 1793348683, - "narHash": "sha256-qv+P8z2xS5Xdws5Kigvr/WKJiaJSa6Ke8iH7ozmO53w=", + "lastModified": 1793434469, + "narHash": "sha256-+sgVNI2c67di+XIeMaz5KSei4T65kX68s5Nl0E5Gzbc=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "96a0986b0486341fbc163fa2fabc6d3b44cdcbf1", + "rev": "6ecf534a7c16e7c969f26838fdd8c93597ae93f3", "type": "github" }, "original": { "owner": "oxalica", "repo": "rust-overlay", - "rev": "96a0986b0486341fbc163fa2fabc6d3b44cdcbf1", + "rev": "6ecf534a7c16e7c969f26838fdd8c93597ae93f3", "type": "github" } }, "xezim": { "flake": false, "locked": { - "lastModified": 1793416628, - "narHash": "sha256-2ZeLbw6Mc1RAZY2SJ3/Iv3XV/3+N4CXJFAGv11DNUpA=", + "lastModified": 1793434493, + "narHash": "sha256-Mp0Ij6r4SC54cvfqs+I1/BDWQ1Dek5MXd8KLH0Du+no=", "owner": "aionhw", "repo": "xezim", - "rev": "9fadb2eb4996d5b18100455e82e27f0de573fa4f", + "rev": "441bd475ce5eaaa9137f49710203995e51b7b0c2", "type": "github" }, "original": { "owner": "aionhw", "repo": "xezim", - "rev": "9fadb2eb4996d5b18100455e82e27f0de573fa4f", + "rev": "441bd475ce5eaaa9137f49710203995e51b7b0c2", "type": "github" } } diff --git a/flake.nix b/flake.nix index ac21ab4efbc..03e7a4ad340 100644 --- a/flake.nix +++ b/flake.nix @@ -9,13 +9,13 @@ }; rust-overlay = { # Pin the revision explicitly so Renovate can group overlay and Rust updates. - url = "github:oxalica/rust-overlay/96a0986b0486341fbc163fa2fabc6d3b44cdcbf1"; + url = "github:oxalica/rust-overlay/6ecf534a7c16e7c969f26838fdd8c93597ae93f3"; inputs.nixpkgs.follows = "nixpkgs"; }; # The xezim reference simulator for the shared test suite, pinned by # revision so that Renovate proposes updates. xezim = { - url = "github:aionhw/xezim/9fadb2eb4996d5b18100455e82e27f0de573fa4f"; + url = "github:aionhw/xezim/441bd475ce5eaaa9137f49710203995e51b7b0c2"; flake = false; }; };