diff --git a/Cargo.lock b/Cargo.lock index dbbf7d2f625..66be2a01be7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -629,10 +629,10 @@ dependencies = [ "celox-slt", "celox-sv-analyzer", "fxhash", + "miette", "num-bigint", "num-traits", "thiserror 2.0.21", - "tracing", ] [[package]] diff --git a/crates/celox-frontend-sv/Cargo.toml b/crates/celox-frontend-sv/Cargo.toml index dcca9794a7b..4597d98a0db 100644 --- a/crates/celox-frontend-sv/Cargo.toml +++ b/crates/celox-frontend-sv/Cargo.toml @@ -16,10 +16,10 @@ celox-sir = { workspace = true } celox-slt = { workspace = true } celox-sv-analyzer = { workspace = true } fxhash = { workspace = true } +miette = { workspace = true } num-bigint = { workspace = true } num-traits = { workspace = true } thiserror = { workspace = true } -tracing = { workspace = true } [features] # Accept DPI-C imports. Calls link to C functions when a simulator is built. diff --git a/crates/celox-frontend-sv/src/lib.rs b/crates/celox-frontend-sv/src/lib.rs index 8dec97e5667..4bbdeeadcad 100644 --- a/crates/celox-frontend-sv/src/lib.rs +++ b/crates/celox-frontend-sv/src/lib.rs @@ -1,6 +1,7 @@ //! SystemVerilog frontend adapter for Celox. mod lowering; +mod warning; pub use celox_sv_analyzer::AnalyzerError; pub use celox_sv_analyzer::ModuleInterfaces; @@ -8,6 +9,7 @@ pub use celox_sv_analyzer::ir as analyzer_ir; pub use celox_sv_analyzer::typecheck as analyzer_typecheck; pub use lowering::{ForeignModuleResolver, prepare_external_hierarchy_with_foreign_resolver}; pub use lowering::{SvModuleRequest, SvParameterValue}; +pub use warning::{FrontendWarning, FrontendWarningKind, WarningLocation}; pub fn module_interfaces( sources: &[(&str, &std::path::Path)], diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 89dfa1ae1a1..2b85f9c4d3c 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -214,12 +214,37 @@ pub struct InterfaceSignature { pub fn interface_signatures( sources: &[(&str, &Path)], ) -> Result, FrontendError> { - interface_signatures_for(sources, None) + interface_signatures_for(sources, None, &mut Vec::new()) } +/// The signatures of the interfaces in `names`, or of every interface. +/// Lowering an interface for its signature reports its warnings in +/// `warnings`; lowering the design reports them again. pub fn interface_signatures_for( sources: &[(&str, &Path)], names: Option<&HashSet>, + warnings: &mut Vec, +) -> Result, FrontendError> { + let mut found = Vec::new(); + let signatures = interface_signatures_collecting(sources, names, &mut found); + append_error_warnings(&signatures, &mut found); + crate::warning::append_unique_warnings(sources, warnings, found); + signatures +} + +fn append_error_warnings( + result: &Result, + warnings: &mut Vec, +) { + if let Err(FrontendError::Analyzer(error)) = result { + warnings.extend(crate::warning::analyzer_warnings(error.warnings())); + } +} + +fn interface_signatures_collecting( + sources: &[(&str, &Path)], + names: Option<&HashSet>, + warnings: &mut Vec, ) -> Result, FrontendError> { let prototypes = sv::interface_prototypes_for(sources, names)?; if prototypes.is_empty() { @@ -228,7 +253,8 @@ pub fn interface_signatures_for( prototypes .into_iter() .map(|prototype| { - let lowered = lower_module(&prototype.module, false, true, false)?; + warnings.extend(crate::warning::analyzer_warnings(&prototype.warnings)); + let lowered = lower_module(&prototype.module, false, true, false, warnings)?; Ok(InterfaceSignature { name: prototype.name, module: lowered.source, @@ -698,6 +724,19 @@ fn validate_net_driver_ranges( Ok(()) } +/// Report the warnings of analyzing the packages the modules share, before +/// lowering a module can fail. +fn package_warnings( + analyzed: &HashMap, + warnings: &mut Vec, +) { + if let Some(module) = analyzed.values().next() { + warnings.extend(crate::warning::analyzer_warnings( + module.packages.warnings(), + )); + } +} + /// The packages that declare variables, lowered as the modules of their one /// instance each, numbered from `first`. fn lower_package_states( @@ -705,6 +744,7 @@ fn lower_package_states( first: usize, four_state: bool, ff_parts: bool, + warnings: &mut Vec, ) -> Result, sv::AnalyzerError> { let mut states = packages.state_modules().collect::>(); states.sort_by(|left, right| left.name().cmp(right.name())); @@ -712,7 +752,7 @@ fn lower_package_states( .into_iter() .enumerate() .map(|(index, module)| { - let mut lowered = lower_module(module, four_state, true, ff_parts)?; + let mut lowered = lower_module(module, four_state, true, ff_parts, warnings)?; lowered.sim_module.time_precision = Some( celox_design::TimePrecision::try_from(packages.global_time_precision()) .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?, @@ -1142,6 +1182,7 @@ pub fn prepare_external_hierarchy( sources: &[(&str, &Path)], root_names: &HashSet, four_state: bool, + warnings: &mut Vec, ) -> Result { prepare_external_hierarchy_with_foreign( sources, @@ -1149,6 +1190,7 @@ pub fn prepare_external_hierarchy( &ExternalHierarchy::default(), &[], four_state, + warnings, ) } @@ -1160,6 +1202,7 @@ pub fn prepare_external_hierarchy_with_foreign( foreign: &ExternalHierarchy, declarations: &[(&str, &Path)], four_state: bool, + warnings: &mut Vec, ) -> Result { prepare_external_hierarchy_with_foreign_resolver( sources, @@ -1170,14 +1213,46 @@ pub fn prepare_external_hierarchy_with_foreign( None, None, &[], + warnings, ) } pub type ForeignModuleResolver<'a> = dyn FnMut(&str, &[(String, SvParameterValue)]) -> Result + 'a; +/// Appends the warnings of the lowered modules to `warnings`, also when +/// lowering fails after them. #[allow(clippy::too_many_arguments)] pub fn prepare_external_hierarchy_with_foreign_resolver( + sources: &[(&str, &Path)], + root_names: &HashSet, + foreign: &ExternalHierarchy, + declarations: &[(&str, &Path)], + four_state: bool, + resolver: Option<&mut ForeignModuleResolver<'_>>, + top_parameters: Option<(&str, &[(String, u64)])>, + requests: &[SvModuleRequest], + warnings: &mut Vec, +) -> Result { + let mut found = Vec::new(); + let hierarchy = prepare_external_hierarchy_collecting( + sources, + root_names, + foreign, + declarations, + four_state, + resolver, + top_parameters, + requests, + &mut found, + ); + append_error_warnings(&hierarchy, &mut found); + crate::warning::append_unique_warnings(sources, warnings, found); + hierarchy +} + +#[allow(clippy::too_many_arguments)] +fn prepare_external_hierarchy_collecting( sources: &[(&str, &Path)], root_names: &HashSet, foreign: &ExternalHierarchy, @@ -1186,6 +1261,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( mut resolver: Option<&mut ForeignModuleResolver<'_>>, top_parameters: Option<(&str, &[(String, u64)])>, requests: &[SvModuleRequest], + warnings: &mut Vec, ) -> Result { let (analyzed, bound_names) = analyze_sources_with_requests( sources, @@ -1194,6 +1270,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( requests, Some(&root_names.iter().map(String::as_str).collect::>()), )?; + package_warnings(&analyzed, warnings); let dummy = sv::ParsedSource::parse( "module __celox_foreign(); endmodule", Path::new(""), @@ -1388,7 +1465,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( let base = analyzed .get(&key.name) .ok_or_else(|| unsupported_sv_instance(key.name.clone()))?; - let lowered = specialize_module(base, &key, four_state, false)?; + let lowered = specialize_module(base, &key, four_state, false, warnings)?; for instance in &lowered.instances { let child_key = LoweredSvModuleKey::instance_key(instance); if !analyzed.contains_key(&child_key.name) @@ -1423,7 +1500,10 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( let base = analyzed .get(&key.name) .ok_or_else(|| unsupported_sv_instance(key.name.clone()))?; - Ok((module_id, specialize_module(base, key, four_state, false)?)) + Ok(( + module_id, + specialize_module(base, key, four_state, false, warnings)?, + )) }) .collect::, FrontendError>>()?; validate_specialized_instance_net_drivers(&module_ids, &lowered_modules)?; @@ -1450,6 +1530,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( &module_ids, &lowered_modules, four_state, + warnings, )?; modules.insert( module_id, @@ -1482,8 +1563,13 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( packages: Vec::new(), }); }; - let package_states = - lower_package_states(&any_module.packages, module_ids.len(), four_state, false)?; + let package_states = lower_package_states( + &any_module.packages, + module_ids.len(), + four_state, + false, + warnings, + )?; // How often the design instantiates these modules is not known here; // assembly checks the drivers of package variables across instances. let mut sim_modules: HashMap = modules @@ -1564,8 +1650,48 @@ pub fn schedule_sources( parallel: &celox_frontend_core::ParallelScheduleOptions, trace_options: &FrontendTraceOptions, trace: Option<&mut FrontendTrace>, + warnings: &mut Vec, +) -> Result { + let mut found = Vec::new(); + let scheduled = schedule_sources_collecting( + sources, + top, + parameter_overrides, + ignored_loops, + true_loops, + four_state, + parallel, + trace_options, + trace, + &mut found, + ); + append_error_warnings(&scheduled, &mut found); + crate::warning::append_unique_warnings(sources, warnings, found); + scheduled +} + +#[allow(clippy::too_many_arguments)] +fn schedule_sources_collecting( + sources: &[(&str, &Path)], + top: &str, + parameter_overrides: &[(String, u64)], + ignored_loops: &[( + (Vec<(String, usize)>, Vec), + (Vec<(String, usize)>, Vec), + )], + true_loops: &[( + (Vec<(String, usize)>, Vec), + (Vec<(String, usize)>, Vec), + usize, + )], + four_state: bool, + parallel: &celox_frontend_core::ParallelScheduleOptions, + trace_options: &FrontendTraceOptions, + trace: Option<&mut FrontendTrace>, + warnings: &mut Vec, ) -> Result { let analyzed = analyze_sources(sources, &[top])?; + package_warnings(&analyzed, warnings); let top = top.to_string(); let root_key = LoweredSvModuleKey { name: top.clone(), @@ -1596,7 +1722,7 @@ pub fn schedule_sources( let base = analyzed .get(&key.name) .ok_or_else(|| unsupported_sv_instance(key.name.clone()))?; - let lowered = specialize_module(base, &key, four_state, false)?; + let lowered = specialize_module(base, &key, four_state, false, warnings)?; for instance in &lowered.instances { let child_key = LoweredSvModuleKey::instance_key(instance); if !analyzed.contains_key(&child_key.name) { @@ -1623,7 +1749,7 @@ pub fn schedule_sources( let base = analyzed .get(&key.name) .ok_or_else(|| unsupported_sv_instance(key.name.clone()))?; - let lowered = specialize_module(base, key, four_state, parallel.enabled()) + let lowered = specialize_module(base, key, four_state, parallel.enabled(), warnings) .map_err(FrontendError::from)?; Ok((module_id, lowered)) }) @@ -1658,6 +1784,7 @@ pub fn schedule_sources( &module_ids, &lowered_modules, four_state, + warnings, )?; module_names.insert(module_id, key.name.clone()); modules.insert(module_id, sim_module); @@ -1668,6 +1795,7 @@ pub fn schedule_sources( module_ids.len(), four_state, parallel.enabled(), + warnings, )?; validate_package_variable_drivers([&root_key], &module_ids, &lowered_modules)?; let mut packages = Vec::new(); @@ -1757,6 +1885,7 @@ fn specialize_module( key: &LoweredSvModuleKey, four_state: bool, ff_parts: bool, + warnings: &mut Vec, ) -> Result { let overrides = evaluated_parameter_overrides(&key.parameter_overrides)?; // Type bindings are already resolved in the caller scope. @@ -1770,14 +1899,19 @@ fn specialize_module( .iter() .filter_map(|parameter| Some((parameter.name.clone(), parameter.bound_pattern.clone()?))) .collect(); - let ir = module.source.analyze_module( + let analyzed = module.source.analyze_module( &module.name, &overrides, &type_overrides, &pattern_overrides, &module.interfaces, &module.packages, - )?; + ); + if let Err(error) = &analyzed { + warnings.extend(crate::warning::analyzer_warnings(error.warnings())); + } + let ir = analyzed?; + warnings.extend(crate::warning::analyzer_warnings(ir.warnings())); let specialized = ir .modules() .iter() @@ -1788,6 +1922,7 @@ fn specialize_module( four_state, module.implicit_nets_allowed, ff_parts, + warnings, )?; lowered.sim_module.time_precision = Some( celox_design::TimePrecision::try_from(module.packages.global_time_precision()) @@ -1819,8 +1954,16 @@ fn lower_module( four_state: bool, implicit_nets_allowed: bool, ff_parts: bool, + warnings: &mut Vec, ) -> Result { - lower_module_with_overrides(module, &[], four_state, implicit_nets_allowed, ff_parts) + lower_module_with_overrides( + module, + &[], + four_state, + implicit_nets_allowed, + ff_parts, + warnings, + ) } /// `ff_parts` additionally keeps every `always_ff` process as an @@ -1831,6 +1974,7 @@ fn lower_module_with_overrides( four_state: bool, implicit_nets_allowed: bool, ff_parts: bool, + warnings: &mut Vec, ) -> Result { let mut package_variables = Vec::new(); let name = module.name().to_string(); @@ -1983,6 +2127,7 @@ fn lower_module_with_overrides( &constants, ¶meter_types, four_state, + warnings, ); let blocks = lower_ff_processes(module, &mut pm, ff_parts)?; ( @@ -2003,6 +2148,7 @@ fn lower_module_with_overrides( &mut runtime_event_sites, &mut runtime_errors, &mut extern_functions, + warnings, )?; initial_memory_values.extend(initial_values); @@ -2371,6 +2517,7 @@ pub(crate) fn attach_instance_glue( module_ids: &HashMap, lowered_modules: &HashMap, four_state: bool, + warnings: &mut Vec, ) -> Result<(), ParserError> { let mut signal_names = lowered.signal_names.clone(); let mut parent_variables = lowered.variables.clone(); @@ -2443,6 +2590,7 @@ pub(crate) fn attach_instance_glue( &lowered.constants, &lowered.parameter_types, four_state, + warnings, ); for (_, _, child, connections) in &mut resolved_instances { for connection in connections { @@ -2497,6 +2645,7 @@ pub(crate) fn attach_instance_glue( four_state, &mut module.runtime_errors, &mut module.extern_functions, + warnings, ) .map_err(|error| match error { sv::AnalyzerError::MemoryFile(detail) => ParserError::MemoryFile { @@ -2820,6 +2969,7 @@ fn lower_initial_processes( runtime_event_sites: &mut Vec, runtime_errors: &mut HashMap>, extern_functions: &mut Vec, + warnings: &mut Vec, ) -> Result< ( Vec>, @@ -2841,6 +2991,7 @@ fn lower_initial_processes( constants, parameter_types, four_state, + warnings, ); let mut arena = SLTNodeArena::new(); let mut seed = comb::Store::default(); @@ -2934,6 +3085,7 @@ fn lower_initial_processes( constants, parameter_types, four_state, + warnings, ); pm.runtime_event_sites = std::mem::take(runtime_event_sites); pm.runtime_errors = std::mem::take(runtime_errors); @@ -2974,6 +3126,7 @@ fn lower_comb_processes( four_state: bool, runtime_errors: &mut HashMap>, extern_functions: &mut Vec, + warnings: &mut Vec, ) -> Result< ( Vec>, @@ -2995,6 +3148,7 @@ fn lower_comb_processes( constants, parameter_types, four_state, + warnings, ); pm.runtime_errors = std::mem::take(runtime_errors); pm.extern_functions = std::mem::take(extern_functions); diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 9e0c6cdbc9b..e1fc10b2161 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -1916,20 +1916,28 @@ impl<'p, 'a> Comb<'p, 'a> { sv::ir::Stmt::SystemTask { task: sv::ir::SystemTask::Readmem(format), args, + site, } => { - self.readmem(&mut store, frames, *format, args)?; + self.readmem(&mut store, frames, *format, args, site.as_ref())?; Ok(store) } // IEEE 1800-2023 24.7: `$exit` outside a program block is - // ignored. + // ignored, with a warning. sv::ir::Stmt::SystemTask { task: sv::ir::SystemTask::Exit, + site, .. - } => Ok(store), + } => { + self.m.warn( + crate::FrontendWarningKind::ExitOutsideProgram, + site.as_ref(), + ); + Ok(store) + } sv::ir::Stmt::SystemTask { task, .. } if self.initial => Err(unsupported(format!( "system task `{task}` inside an initial block" ))), - sv::ir::Stmt::SystemTask { task, args } => { + sv::ir::Stmt::SystemTask { task, args, .. } => { self.system_task(&mut store, frames, *task, args)?; Ok(store) } @@ -3031,6 +3039,7 @@ impl<'p, 'a> Comb<'p, 'a> { frames: &[Frame], format: sv::ir::MemoryFormat, args: &[sv::ir::SystemTaskArg], + site: Option<&sv::ir::SourceSpan>, ) -> Result<(), sv::AnalyzerError> { let name = sv::ir::SystemTask::Readmem(format); let mut addresses = [None, None]; @@ -3057,7 +3066,9 @@ impl<'p, 'a> Comb<'p, 'a> { if self.path_condition()?.is_some() { return Err(unsupported(format!("`{name}` under a run-time condition"))); } - let (id, words) = self.m.readmem(format, args, addresses[0], addresses[1])?; + let (id, words) = self + .m + .readmem(format, args, addresses[0], addresses[1], site)?; for word in words { let width = word.access.msb - word.access.lsb + 1; let node = self.alloc(SLTNode::Constant(word.value, word.mask, width, false))?; diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index a8601ee0c68..bebcdf9317a 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -213,7 +213,7 @@ impl<'p, 'a> Ff<'p, 'a> { writes.extend(parts.iter().map(|part| (part.clone(), !nonblocking))); } // `$readmemh` writes its destination immediately. - sv::ir::Stmt::SystemTask { task, args } => { + sv::ir::Stmt::SystemTask { task, args, .. } => { if let Some(destination) = readmem_destination(*task, args) { writes.push((sv::ir::LValue::Ident(destination.to_string()), true)); } @@ -2035,7 +2035,9 @@ impl<'p, 'a> Ff<'p, 'a> { self.eval(expr, None)?; Ok(true) } - sv::ir::Stmt::SystemTask { task, args } => self.system_task(*task, args), + sv::ir::Stmt::SystemTask { task, args, site } => { + self.system_task(*task, args, site.as_ref()) + } } } @@ -2045,6 +2047,7 @@ impl<'p, 'a> Ff<'p, 'a> { &mut self, task: sv::ir::SystemTask, args: &[sv::ir::SystemTaskArg], + site: Option<&sv::ir::SourceSpan>, ) -> Result { if let sv::ir::SystemTask::Readmem(format) = task { let mut addresses = [None, None]; @@ -2068,7 +2071,9 @@ impl<'p, 'a> Ff<'p, 'a> { .ok_or_else(|| unsupported(format!("`{task}` address")))?, ); } - let (id, words) = self.m.readmem(format, args, addresses[0], addresses[1])?; + let (id, words) = self + .m + .readmem(format, args, addresses[0], addresses[1], site)?; for word in words { let width = word.access.msb - word.access.lsb + 1; let reg = if word.mask.is_zero() { @@ -2085,8 +2090,11 @@ impl<'p, 'a> Ff<'p, 'a> { } return Ok(true); } - // IEEE 1800-2023 24.7: `$exit` outside a program block is ignored. + // IEEE 1800-2023 24.7: `$exit` outside a program block is ignored, + // with a warning. if task == sv::ir::SystemTask::Exit { + self.m + .warn(crate::FrontendWarningKind::ExitOutsideProgram, site); return Ok(true); } let kind = diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 2e7dbec5131..b931cb20de6 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -44,6 +44,9 @@ pub(super) struct ProcModule<'a> { pub runtime_errors: HashMap>, /// The declared bounds of each unpacked dimension, by variable. unpacked_bounds: HashMap>, + /// Where the warnings found while lowering go. A process lowered more + /// than once repeats its warnings; the frontend reports each once. + warnings: &'a mut Vec, } /// One word a memory file writes: its bits in the destination, value, and @@ -62,6 +65,7 @@ impl<'a> ProcModule<'a> { constants: &'a HashMap, parameter_types: &'a HashMap, four_state: bool, + warnings: &'a mut Vec, ) -> Self { let next_id = SourceVarId( variables @@ -140,6 +144,7 @@ impl<'a> ProcModule<'a> { runtime_event_sites: Vec::new(), runtime_errors: HashMap::default(), unpacked_bounds, + warnings, } } @@ -333,11 +338,12 @@ impl<'a> ProcModule<'a> { /// the values of its optional start and finish addresses: the file is /// read when the design is compiled. pub fn readmem( - &self, + &mut self, format: sv::ir::MemoryFormat, args: &[sv::ir::SystemTaskArg], start: Option, finish: Option, + site: Option<&sv::ir::SourceSpan>, ) -> Result<(SourceVarId, Vec), sv::AnalyzerError> { let name = sv::ir::SystemTask::Readmem(format).name(); let radix = format.base(); @@ -418,9 +424,14 @@ impl<'a> ProcModule<'a> { finish, ) .map_err(|error| sv::AnalyzerError::MemoryFile(format!("{name}: {}", error.message)))?; - if let Some(warning) = parsed.warning { - tracing::warn!(task = name, file = filename, "{warning}"); - } + let warning = + parsed + .warning + .map(|detail| crate::FrontendWarningKind::MemoryFileWordCount { + task: name.to_string(), + file: unescape(filename), + detail, + }); let writes = parsed.writes; let word_mask = (BigUint::from(1u8) << element_width) - BigUint::from(1u8); let mut words = Vec::new(); @@ -447,9 +458,17 @@ impl<'a> ProcModule<'a> { }); } } + if let Some(warning) = warning { + self.warn(warning, site); + } Ok((id, words)) } + /// Report a warning of the statement at `site`. + pub fn warn(&mut self, kind: crate::FrontendWarningKind, site: Option<&sv::ir::SourceSpan>) { + self.warnings.push((kind, site.cloned())); + } + /// Register a runtime event site and return its local number. pub fn event_site(&mut self, site: RuntimeEventSite) -> u32 { self.runtime_event_sites.push(site); diff --git a/crates/celox-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs new file mode 100644 index 00000000000..bd394ddd465 --- /dev/null +++ b/crates/celox-frontend-sv/src/warning.rs @@ -0,0 +1,169 @@ +use std::path::Path; +use std::sync::Arc; + +use celox_sv_analyzer::ir::SourceSpan; + +/// A non-fatal diagnostic of the SystemVerilog frontend. The design still +/// compiles; the simulator reports these with its compilation warnings. +#[derive(Debug, Clone, thiserror::Error)] +#[error("{kind}")] +pub struct FrontendWarning { + pub kind: FrontendWarningKind, + /// The construct that warns, unless the analyzer created it or its file + /// cannot be read. + pub location: Option, +} + +/// Located warnings identify the warning category and source call, independent +/// of the parameter-dependent payload produced by an individual specialization. +impl PartialEq for FrontendWarning { + fn eq(&self, other: &Self) -> bool { + match (&self.location, &other.location) { + (Some(left), Some(right)) => { + std::mem::discriminant(&self.kind) == std::mem::discriminant(&other.kind) + && (&left.path, left.line, left.column) + == (&right.path, right.line, right.column) + } + (None, None) => self.kind == other.kind, + _ => false, + } + } +} + +impl Eq for FrontendWarning {} + +/// What a [`FrontendWarning`] reports. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, thiserror::Error)] +pub enum FrontendWarningKind { + /// A memory file without address directives holds a different number of + /// words than the address range of `$readmemh`/`$readmemb` + /// (IEEE 1800-2023 21.4). + #[error("`{task}` reading {file}: {detail}")] + MemoryFileWordCount { + task: String, + file: String, + detail: String, + }, + /// `$exit` outside a program block, which IEEE 1800-2023 24.7 ignores. + /// Celox has no program blocks, so every call is ignored. + #[error("`$exit` outside a program block is ignored")] + ExitOutsideProgram, +} + +/// Where a warning is in the source. +#[derive(Debug, Clone)] +pub struct WarningLocation { + pub path: String, + /// The 1-based line of the start of the construct. + pub line: usize, + /// The 1-based column, in characters, of the start of the construct. + pub column: usize, + source: miette::NamedSource>, + span: miette::SourceSpan, +} + +impl WarningLocation { + fn new(path: String, text: Arc, span: &SourceSpan) -> Option { + let before = text.get(..span.start)?; + text.get(span.start..span.end)?; + let line_start = before.rfind('\n').map_or(0, |newline| newline + 1); + Some(Self { + line: before.matches('\n').count() + 1, + column: before[line_start..].chars().count() + 1, + source: miette::NamedSource::new(&path, text), + span: (span.start..span.end).into(), + path, + }) + } +} + +/// A warning found while lowering, with the span of its construct. +pub(crate) type PendingWarning = (FrontendWarningKind, Option); + +/// The warnings of an analysis, as warnings of the frontend. +pub(crate) fn analyzer_warnings( + found: &[celox_sv_analyzer::ir::AnalyzerWarning], +) -> impl Iterator + '_ { + found.iter().map(|warning| match warning { + celox_sv_analyzer::ir::AnalyzerWarning::ExitOutsideProgram { site } => { + (FrontendWarningKind::ExitOutsideProgram, site.clone()) + } + }) +} + +/// Appends `found` to `warnings` in source order, once for each construct: +/// each specialization of a module and each lowering attempt of a process +/// repeats the warnings of the same source. Spans are resolved against +/// `sources`, or else the file at their path. +pub(crate) fn append_unique_warnings( + sources: &[(&str, &Path)], + warnings: &mut Vec, + mut found: Vec, +) { + found.sort_by(|(left_kind, left), (right_kind, right)| { + (left, left_kind).cmp(&(right, right_kind)) + }); + found.dedup_by(|(left_kind, left), (right_kind, right)| { + match (left.as_ref(), right.as_ref()) { + (Some(left), Some(right)) => { + left == right + && std::mem::discriminant(left_kind) == std::mem::discriminant(right_kind) + } + _ => left == right && left_kind == right_kind, + } + }); + let mut texts = fxhash::FxHashMap::>>::default(); + for (kind, span) in found { + let location = span.and_then(|span| { + let text = texts + .entry(span.path.clone()) + .or_insert_with(|| { + sources + .iter() + .find(|(_, path)| *path == span.path) + .map(|(code, _)| Arc::from(*code)) + .or_else(|| std::fs::read_to_string(&span.path).ok().map(Arc::from)) + }) + .clone(); + WarningLocation::new(span.path.display().to_string(), text?, &span) + }); + warnings.push(FrontendWarning { kind, location }); + } +} + +impl miette::Diagnostic for FrontendWarning { + fn code<'a>(&'a self) -> Option> { + Some(Box::new(match self.kind { + FrontendWarningKind::MemoryFileWordCount { .. } => "memory_file_word_count", + FrontendWarningKind::ExitOutsideProgram => "exit_outside_program", + })) + } + + fn severity(&self) -> Option { + Some(miette::Severity::Warning) + } + + fn help<'a>(&'a self) -> Option> { + Some(Box::new(match self.kind { + FrontendWarningKind::MemoryFileWordCount { .. } => { + "give one word per address of the range, or place the words with `@address` directives" + } + FrontendWarningKind::ExitOutsideProgram => { + "end the simulation with `$finish`, or remove the call" + } + })) + } + + fn source_code(&self) -> Option<&dyn miette::SourceCode> { + self.location + .as_ref() + .map(|location| &location.source as &dyn miette::SourceCode) + } + + fn labels(&self) -> Option + '_>> { + let location = self.location.as_ref()?; + Some(Box::new(std::iter::once( + miette::LabeledSpan::new_with_span(Some("called here".to_string()), location.span), + ))) + } +} diff --git a/crates/celox-sv-analyzer/src/analyze.rs b/crates/celox-sv-analyzer/src/analyze.rs index 4cebe51c5e7..c96899c7e06 100644 --- a/crates/celox-sv-analyzer/src/analyze.rs +++ b/crates/celox-sv-analyzer/src/analyze.rs @@ -8,6 +8,11 @@ use crate::{ }; pub fn analyze_source(source: ast::Source) -> Result { + let warnings = source.warnings(); + crate::finish_analysis(analyze_source_impl(source), warnings) +} + +fn analyze_source_impl(source: ast::Source) -> Result { let mut module_table = ModuleTable::default(); let mut modules = Vec::new(); for module in source.modules() { diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 52c25f15b16..d18ded4e134 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -64,6 +64,7 @@ mod timescales; pub(crate) mod type_parameters; mod types; mod validation; +pub(crate) mod warnings; use array_compatibility::{ check_unpacked_array_assignment, net_lvalue_unpacked_shape, selected_unpacked_shape, @@ -422,6 +423,14 @@ impl Source { pub fn modules(&self) -> &[Module] { &self.modules } + + pub(crate) fn warnings(&self) -> Vec { + let mut warnings = Vec::new(); + for module in &self.modules { + warnings::append(&mut warnings, module.constant_functions.warnings()); + } + warnings + } } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index fe4f56805e1..3bdf00e1c7d 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -125,6 +125,36 @@ pub(super) fn is_constant_function(name: &str) -> bool { /// their bodies cannot be converted, there are none, and the reason is kept /// for the calls of them. impl ConstantFunctions { + pub(crate) fn warnings(&self) -> Vec { + let mut warnings = Vec::new(); + for function in self.functions.values() { + for statement in &function.body { + statement.walk(&mut |statement| { + if let Stmt::SystemTask { + task: crate::system_functions::SystemTask::Exit, + site, + .. + } = statement + { + super::warnings::append( + &mut warnings, + [super::warnings::AnalyzerWarning::ExitOutsideProgram { + site: site.clone(), + }], + ); + } + }); + } + } + warnings.sort_by(|left, right| match (left, right) { + ( + super::warnings::AnalyzerWarning::ExitOutsideProgram { site: left }, + super::warnings::AnalyzerWarning::ExitOutsideProgram { site: right }, + ) => left.cmp(right), + }); + warnings + } + fn unconverted(error: AnalyzerError) -> Self { Self { errors: Arc::new(FunctionErrors { @@ -1159,7 +1189,9 @@ impl Frame<'_> { self.eval(expr)?; } // Messages have no effect on the value. Unknown and unsupported - // system tasks are rejected before elaboration. + // system tasks are rejected before elaboration. `$exit` is + // ignored outside a program block (IEEE 1800-2023 24.7). Its + // diagnostic belongs to the declaration, not to evaluation. Stmt::SystemTask { .. } => {} // A function has no timing controls (IEEE 1800-2023 13.4). Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::Wait(_) => return None, diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index b74f01df307..2ef6fb40a2b 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -26,6 +26,8 @@ pub struct InterfacePrototype { /// A declaration cast whose target depends on an overridable header. /// Native IR currently retains only its resolved target width. pub header_dependent_cast: bool, + /// What analyzing the signature warned about. + pub warnings: Vec, } pub fn interface_prototypes( @@ -45,7 +47,20 @@ pub fn interface_prototypes_for( .iter() .map(|(code, path)| File::new(code, path)) .collect::, _>>()?; - let design = Design::collect_selected(&files, selected)?; + let declaration_warnings: Vec<_> = files + .iter() + .map(|file| super::warnings::components(&file.syntax_tree)) + .collect(); + let mut source_warnings = Vec::new(); + for declarations in &declaration_warnings { + for (name, warnings) in declarations { + if selected.is_none_or(|names| names.contains(name)) { + super::warnings::append(&mut source_warnings, warnings.iter().cloned()); + } + } + } + let design = Design::collect_selected(&files, selected) + .map_err(|error| error.with_warnings(source_warnings.clone()))?; let mut declarations = design .interfaces .values() @@ -68,130 +83,153 @@ pub fn interface_prototypes_for( .zip(sources) .map(|(file, (_, path))| (&file.syntax_tree, *path)) .collect::>(); - let packages = packages::Packages::analyze(&trees)?; + let packages = packages::Packages::analyze(&trees) + .map_err(|error| error.with_warnings(source_warnings))?; + let package_warnings = packages.warnings().to_vec(); let mut used_names = design .modules .keys() .chain(design.interfaces.keys()) .cloned() .collect::>(); + let mut found = package_warnings.clone(); declarations .into_iter() .map(|interface| { - let prefix = format!("__celox_interface_{}", interface.name); - let mut probe_name = prefix.clone(); - let mut index = 0; - while !used_names.insert(probe_name.clone()) { - probe_name = format!("{prefix}_{index}"); - index += 1; - } - let time_declarations = timescales - .as_ref() - .unwrap() - .declaration_statements(&interface.name)?; - let behavior_functions = interface - .items - .iter() - .filter_map(|item| match item { - Item::Process(span) => Some(*span), - Item::Member(index) => interface.members[*index].initializer, - _ => None, - }) - .flat_map(|span| interface.referenced(span)) - .filter(|name| interface.function(name).is_some()) - .map(str::to_string) - .collect::>(); - let behavior_captures = - interface.captured_members(&interface.function_closure(&behavior_functions)); - Ok(InterfacePrototype { - name: interface.name.clone(), - header_dependent_cast: interface.header_dependent_cast(&files[interface.file])?, - module: { - let file = &files[interface.file]; - let declaration = file - .syntax_tree - .into_iter() - .find_map(|node| { - if let RefNode::InterfaceDeclarationAnsi(declaration) = node - && name( - RefNode::InterfaceIdentifier(&declaration.nodes.0.nodes.3), - &file.syntax_tree, - ) - .ok() - .as_ref() - == Some(&interface.name) - { - Some(declaration) - } else { - None - } - }) - .ok_or_else(|| unsupported("non-ANSI interface signature"))?; - interface_ast::signature( - declaration, - &file.syntax_tree, - sources[interface.file].1, - &packages, - probe_name.clone(), - &interface - .members - .iter() - .map(|m| m.name.clone()) - .collect::>(), - &interface.names, - )? - }, - time_declarations, - parameters: interface - .parameters - .iter() - .map(|parameter| parameter.name.clone()) - .collect(), - driven: interface - .members - .iter() - .filter(|member| { - member.initializer.is_some() - || behavior_captures.get(&member.name) == Some(&Direction::Output) - || interface.references.iter().any(|(span, name)| { - name == &member.name - && interface.lvalues.contains(&span.0) - && !interface.functions.iter().any(|function| { - function.span.0 <= span.0 && span.1 <= function.span.1 - }) - }) - }) - .map(|member| member.name.clone()) - .collect(), - has_behavior: interface + let warnings = declaration_warnings[interface.file] + .get(&interface.name) + .cloned() + .unwrap_or_default(); + super::warnings::append(&mut found, warnings.iter().cloned()); + let prototype = (|| -> Result { + let prefix = format!("__celox_interface_{}", interface.name); + let mut probe_name = prefix.clone(); + let mut index = 0; + while !used_names.insert(probe_name.clone()) { + probe_name = format!("{prefix}_{index}"); + index += 1; + } + let time_declarations = timescales + .as_ref() + .unwrap() + .declaration_statements(&interface.name)?; + let behavior_functions = interface .items .iter() - .any(|item| matches!(item, Item::Process(_))) - || interface + .filter_map(|item| match item { + Item::Process(span) => Some(*span), + Item::Member(index) => interface.members[*index].initializer, + _ => None, + }) + .flat_map(|span| interface.referenced(span)) + .filter(|name| interface.function(name).is_some()) + .map(str::to_string) + .collect::>(); + let behavior_captures = + interface.captured_members(&interface.function_closure(&behavior_functions)); + Ok(InterfacePrototype { + name: interface.name.clone(), + warnings: Vec::new(), + header_dependent_cast: interface + .header_dependent_cast(&files[interface.file])?, + module: { + let file = &files[interface.file]; + let declaration = file + .syntax_tree + .into_iter() + .find_map(|node| { + if let RefNode::InterfaceDeclarationAnsi(declaration) = node + && name( + RefNode::InterfaceIdentifier(&declaration.nodes.0.nodes.3), + &file.syntax_tree, + ) + .ok() + .as_ref() + == Some(&interface.name) + { + Some(declaration) + } else { + None + } + }) + .ok_or_else(|| unsupported("non-ANSI interface signature"))?; + interface_ast::signature( + declaration, + &file.syntax_tree, + sources[interface.file].1, + &packages, + probe_name.clone(), + &interface + .members + .iter() + .map(|m| m.name.clone()) + .collect::>(), + &interface.names, + )? + }, + time_declarations, + parameters: interface + .parameters + .iter() + .map(|parameter| parameter.name.clone()) + .collect(), + driven: interface .members .iter() - .any(|member| member.initializer.is_some()), - modports: interface - .modports - .iter() - .map(|(name, items)| { - ( - name.clone(), - items - .iter() - .map(|item| match item { - ModportItem::Member(direction, name) => { - (name.clone(), direction.keyword().to_string()) - } - ModportItem::Import(name) => { - (name.clone(), "import".to_string()) - } + .filter(|member| { + member.initializer.is_some() + || behavior_captures.get(&member.name) == Some(&Direction::Output) + || interface.references.iter().any(|(span, name)| { + name == &member.name + && interface.lvalues.contains(&span.0) + && !interface.functions.iter().any(|function| { + function.span.0 <= span.0 && span.1 <= function.span.1 + }) }) - .collect(), - ) - }) - .collect(), - }) + }) + .map(|member| member.name.clone()) + .collect(), + has_behavior: interface + .items + .iter() + .any(|item| matches!(item, Item::Process(_))) + || interface + .members + .iter() + .any(|member| member.initializer.is_some()), + modports: interface + .modports + .iter() + .map(|(name, items)| { + ( + name.clone(), + items + .iter() + .map(|item| match item { + ModportItem::Member(direction, name) => { + (name.clone(), direction.keyword().to_string()) + } + ModportItem::Import(name) => { + (name.clone(), "import".to_string()) + } + }) + .collect(), + ) + }) + .collect(), + }) + })(); + prototype + .map(|mut prototype| { + prototype.warnings = package_warnings.clone(); + for warning in warnings { + if !prototype.warnings.contains(&warning) { + prototype.warnings.push(warning); + } + } + prototype + }) + .map_err(|error| error.with_warnings(found.clone())) }) .collect::, AnalyzerError>>() } diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index 3f1332c7a96..6ba11e3ad9c 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -29,6 +29,8 @@ pub struct Packages { /// The compilation unit of each source file that declares items outside /// its modules and packages. units: HashMap>, + /// What analyzing the packages warned about. + warnings: Vec, } /// The compilation-unit scope of a source file. @@ -120,6 +122,17 @@ impl Packages { self.interface_plan = Arc::new(plan); } + pub(crate) fn with_warnings(mut self, warnings: Vec) -> Self { + self.warnings = warnings; + self + } + + /// What analyzing the packages warned about, such as constant functions + /// that call `$exit`. + pub fn warnings(&self) -> &[super::warnings::AnalyzerWarning] { + &self.warnings + } + pub fn is_empty(&self) -> bool { self.packages.is_empty() } @@ -178,6 +191,20 @@ impl Packages { pub(crate) fn analyze_with_roots( trees: &[(&SyntaxTree, &Path)], roots: Option<&[&str]>, + ) -> Result { + let mut warnings = Vec::new(); + for (tree, _) in trees { + super::warnings::append(&mut warnings, super::warnings::packages(tree)); + } + match Self::analyze_with_roots_impl(trees, roots) { + Ok(packages) => Ok(packages.with_warnings(warnings)), + Err(error) => Err(error.with_warnings(warnings)), + } + } + + fn analyze_with_roots_impl( + trees: &[(&SyntaxTree, &Path)], + roots: Option<&[&str]>, ) -> Result { let mut timescales = timescales::Timescales::collect(trees)?; if let Some(roots) = roots { @@ -512,7 +539,7 @@ fn analyze_package_scope( /// The compilation-unit scope of `tree` as a package declaration: the items /// of the file outside its design elements, which are package items too. /// A compilation unit has no keyword of its own, so its keywords are empty. -fn unit_declaration(tree: &SyntaxTree) -> Option { +pub(super) fn unit_declaration(tree: &SyntaxTree) -> Option { let items: Vec<_> = tree .into_iter() .filter_map(|node| match node { diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 9590a8d735e..5c140bff305 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -944,6 +944,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { self.tree, system_functions::CallSite::Statement(self.body), )?)], + site: source_span(RefNode::SystemTfCall(system_call), self.tree), }]); } system_functions::SystemCall::Task(task) => task, @@ -972,7 +973,11 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { }; // 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 { task, args }]) + Ok(vec![Stmt::SystemTask { + task, + args, + site: source_span(RefNode::SystemTfCall(system_call), self.tree), + }]) } _ => Err(unsupported("method or randomize call")), } @@ -1487,6 +1492,7 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { vec![Stmt::SystemTask { task: SystemTask::Severity(system_functions::Severity::Error), args: vec![SystemTaskArg::Str(format!("{keyword} failed"))], + site: None, }] }); Ok(vec![Stmt::If { @@ -2317,3 +2323,46 @@ pub(super) fn written_names<'s>(stmts: impl IntoIterator) -> Ha } names } + +/// The span of `node` in the source text before preprocessing, if all of it +/// comes from one file. +pub(super) fn source_span( + node: RefNode<'_>, + tree: &SyntaxTree, +) -> Option { + let origin = |offset| { + tree.get_origin(&Locate { + offset, + line: 0, + len: 1, + }) + }; + let mut span: Option = None; + for child in node { + let RefNode::Locate(locate) = child else { + continue; + }; + if locate.len == 0 { + continue; + } + let (path, start) = origin(locate.offset)?; + let (last_path, last) = origin(locate.offset + locate.len - 1)?; + if last_path != path || span.as_ref().is_some_and(|span| span.path != *path) { + return None; + } + let end = last + 1; + span = Some(match span { + None => crate::procedural::SourceSpan { + path: path.clone(), + start, + end, + }, + Some(span) => crate::procedural::SourceSpan { + start: span.start.min(start), + end: span.end.max(end), + ..span + }, + }); + } + span +} diff --git a/crates/celox-sv-analyzer/src/ast/warnings.rs b/crates/celox-sv-analyzer/src/ast/warnings.rs new file mode 100644 index 00000000000..5f9f7a80166 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/warnings.rs @@ -0,0 +1,106 @@ +//! Diagnostics derived from authored function declarations. + +use super::*; +use crate::procedural::SourceSpan; + +/// A non-fatal source diagnostic, independent of constant evaluation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AnalyzerWarning { + /// An ignored `$exit` in a function outside a program (IEEE 1800-2023 24.7). + ExitOutsideProgram { site: Option }, +} + +pub(crate) fn append( + warnings: &mut Vec, + found: impl IntoIterator, +) { + for warning in found { + if !warnings.contains(&warning) { + warnings.push(warning); + } + } +} + +/// Function diagnostics belong to the declaration, including functions whose +/// bodies disappear during constant evaluation. This pass has no side effects. +pub(crate) fn functions<'a>( + nodes: impl IntoIterator>, + tree: &SyntaxTree, +) -> Vec { + let mut warnings = Vec::new(); + let mut functions = Vec::new(); + let mut programs = Vec::new(); + for node in nodes { + if matches!(node, RefNode::ProgramDeclaration(_)) { + if let Some(span) = super::procedural::source_span(node, tree) { + programs.push(span); + } + } else if matches!(node, RefNode::FunctionDeclaration(_)) { + functions.push(node); + } + } + for function in functions { + for node in function { + if let RefNode::SystemTfCall(call) = node + && super::system_tf_call_parts(call, tree).is_some_and(|(name, _)| name == "$exit") + { + let site = super::procedural::source_span(RefNode::SystemTfCall(call), tree); + if site.as_ref().is_some_and(|site| { + programs.iter().any(|program| { + program.path == site.path + && program.start <= site.start + && site.end <= program.end + }) + }) { + continue; + } + append( + &mut warnings, + [AnalyzerWarning::ExitOutsideProgram { site }], + ); + } + } + } + warnings +} + +pub(crate) fn components(tree: &SyntaxTree) -> HashMap> { + let mut warnings = HashMap::default(); + for node in tree { + let identifier = match &node { + RefNode::ModuleDeclarationAnsi(_) => { + super::module_name_from_node(node.clone(), tree).ok() + } + RefNode::ModuleDeclarationNonansi(_) => { + super::module_name_from_node(node.clone(), tree).ok() + } + RefNode::InterfaceDeclarationAnsi(interface) => { + super::component_identifier(&interface.nodes.0.nodes.3, tree) + } + RefNode::InterfaceDeclarationNonansi(interface) => { + super::component_identifier(&interface.nodes.0.nodes.3, tree) + } + _ => None, + }; + if let Some(name) = identifier { + append(warnings.entry(name).or_default(), functions(node, tree)); + } + } + warnings +} + +pub(crate) fn packages(tree: &SyntaxTree) -> Vec { + let mut warnings = Vec::new(); + for node in tree { + if matches!(node, RefNode::PackageDeclaration(_)) { + append(&mut warnings, functions(node, tree)); + } + } + if let Some(unit) = super::packages::unit_declaration(tree) { + append( + &mut warnings, + functions(RefNode::PackageDeclaration(&unit), tree), + ); + } + warnings +} diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 053456a0b82..996001162ea 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -2,8 +2,9 @@ use crate::{ast, symbol::ModuleId, typecheck}; +pub use crate::ast::warnings::AnalyzerWarning; pub use crate::procedural::{ - CaseKind, CaseLabel, EventEdge, LoopKind, ParamDirection, StmtBase, SystemTaskArg, + CaseKind, CaseLabel, EventEdge, LoopKind, ParamDirection, SourceSpan, StmtBase, SystemTaskArg, }; pub use crate::system_functions::{ ArrayQuery, Callee, MemoryFormat, Radix, Severity, SystemFunction, SystemTask, @@ -20,16 +21,36 @@ pub type SubroutineParam = crate::procedural::SubroutineParamBase; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Ir { modules: Vec, + warnings: Vec, } impl Ir { pub(crate) fn new(modules: Vec) -> Self { - Self { modules } + Self { + modules, + warnings: Vec::new(), + } + } + + /// Merge warnings from nested analyses, reporting each source call once. + pub(crate) fn with_warnings(mut self, warnings: Vec) -> Self { + for warning in warnings { + if !self.warnings.contains(&warning) { + self.warnings.push(warning); + } + } + self } pub fn modules(&self) -> &[Module] { &self.modules } + + /// Source diagnostics of the analyzed declarations, including functions + /// whose bodies disappear during constant elaboration. + pub fn warnings(&self) -> &[AnalyzerWarning] { + &self.warnings + } } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 9150260bf5e..35b0e79dedf 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -36,6 +36,13 @@ pub const DIV_ZERO_UNKNOWN_LITERAL: &str = "$celox_div_zero_unknown"; /// Errors reported by the SystemVerilog analyzer. #[derive(Debug, Clone, PartialEq, Eq, Error)] pub enum AnalyzerError { + /// Diagnostics discovered before a later analysis failure. + #[error("{error}")] + WithWarnings { + #[source] + error: Box, + warnings: Vec, + }, #[error("SystemVerilog parse error: {0}")] Parse(String), #[error("Unsupported SystemVerilog construct: {0}")] @@ -158,8 +165,46 @@ const UNSUPPORTED_CONSTRUCT_ISSUES: &[(&str, u32)] = &[ ]; impl AnalyzerError { + pub(crate) fn with_warnings(self, found: Vec) -> Self { + if found.is_empty() { + return self; + } + match self { + Self::WithWarnings { + error, + mut warnings, + } => { + ast::warnings::append(&mut warnings, found); + Self::WithWarnings { error, warnings } + } + error => Self::WithWarnings { + error: Box::new(error), + warnings: found, + }, + } + } + + /// Diagnostics retained when semantic analysis failed. + pub fn warnings(&self) -> &[ir::AnalyzerWarning] { + match self { + Self::WithWarnings { warnings, .. } => warnings, + _ => &[], + } + } + + /// The underlying source error, without its separately reported diagnostics. + pub fn into_error(self) -> Self { + match self { + Self::WithWarnings { error, .. } => error.into_error(), + error => error, + } + } + /// GitHub issue that tracks support for the construct this error rejects. pub fn tracking_issue(&self) -> u32 { + if let Self::WithWarnings { error, .. } = self { + return error.tracking_issue(); + } let Self::Unsupported(construct) = self else { return SV_FRONTEND_TRACKING_ISSUE; }; @@ -181,8 +226,9 @@ pub fn generated_time_declarations( /// Parse and analyze a SystemVerilog source string. pub fn analyze_source(code: &str, path: &Path) -> Result { - ast::with_call_sites(|| { - let syntax_tree = syntax::parse_source(code, path)?; + let syntax_tree = syntax::parse_source(code, path)?; + let warnings = ast::warnings::functions(&syntax_tree, &syntax_tree); + collecting_warnings(warnings, || { if syntax_tree .into_iter() .any(|node| matches!(node, sv_parser::RefNode::InterfaceDeclarationAnsi(_))) @@ -202,8 +248,9 @@ pub fn analyze_source_with_module_parameter_overrides( module_name: &str, parameter_overrides: &HashMap, ) -> Result { - ast::with_call_sites(|| { - let syntax_tree = syntax::parse_source(code, path)?; + let syntax_tree = syntax::parse_source(code, path)?; + let warnings = ast::warnings::functions(&syntax_tree, &syntax_tree); + collecting_warnings(warnings, || { if syntax_tree .into_iter() .any(|node| matches!(node, sv_parser::RefNode::InterfaceDeclarationAnsi(_))) @@ -247,6 +294,7 @@ fn analyze_interface_source( .cloned(), ); let mut modules = Vec::new(); + let mut warnings = packages.warnings().to_vec(); for name in names { let values = if name == override_module || plan @@ -284,8 +332,27 @@ fn analyze_interface_source( &packages, )?; modules.extend(ir.modules().iter().cloned()); + warnings.extend(ir.warnings().iter().cloned()); + } + Ok(Ir::new(modules).with_warnings(warnings)) +} + +/// Publish diagnostics as owned result data, on either exit path. +fn collecting_warnings( + warnings: Vec, + analysis: impl FnOnce() -> Result, +) -> Result { + finish_analysis(ast::with_call_sites(analysis), warnings) +} + +pub(crate) fn finish_analysis( + result: Result, + warnings: Vec, +) -> Result { + match result { + Ok(ir) => Ok(ir.with_warnings(warnings)), + Err(error) => Err(error.with_warnings(warnings)), } - Ok(Ir::new(modules)) } /// Return the module names declared in a SystemVerilog source without @@ -312,8 +379,11 @@ pub fn analyze_source_module_with_parameter_overrides( module_name: &str, parameter_overrides: &HashMap, ) -> Result { - ast::with_call_sites(|| { - let syntax_tree = syntax::parse_source(code, path)?; + let syntax_tree = syntax::parse_source(code, path)?; + let warnings = ast::warnings::components(&syntax_tree) + .remove(module_name) + .unwrap_or_default(); + collecting_warnings(warnings, || { let source = ast::Source::from_syntax_module_with_parameter_overrides( &syntax_tree, module_name, diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index 52b1dfd45d4..f9264733322 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -18,17 +18,22 @@ pub struct ParsedSource { path: PathBuf, tree: std::rc::Rc, index: ast::module_index::ModuleIndex, + /// Immutable declaration diagnostics, indexed once alongside module syntax. + warnings: HashMap>, } impl ParsedSource { pub fn parse(code: &str, path: &Path) -> Result { let tree = syntax::parse_source(code, path)?; - let index = ast::with_call_sites(|| ast::module_index::ModuleIndex::new(&tree))?; + let warnings = ast::warnings::components(&tree); + let index = ast::with_call_sites(|| ast::module_index::ModuleIndex::new(&tree)) + .map_err(|error| error.with_warnings(ast::warnings::functions(&tree, &tree)))?; Ok(Self { code: code.into(), path: path.to_path_buf(), tree: std::rc::Rc::new(tree), index, + warnings, }) } @@ -92,8 +97,10 @@ impl ParsedSource { .iter() .map(|source| (source.tree.as_ref(), source.path.as_path())) .collect(); - ast::with_call_sites(|| { + let mut warnings = Vec::new(); + let packages = ast::with_call_sites(|| { let mut packages = Packages::analyze_with_roots(&trees, roots)?; + ast::warnings::append(&mut warnings, packages.warnings().iter().cloned()); for source in sources { for node in source.tree.as_ref() { if let sv_parser::RefNode::InterfaceDeclarationAnsi(declaration) = node @@ -122,7 +129,11 @@ impl ParsedSource { std::sync::Arc::new(ast::interfaces::plan_interfaces(&sources, &[])?); } Ok(packages) - }) + }); + match packages { + Ok(packages) => Ok(packages.with_warnings(warnings)), + Err(error) => Err(error.with_warnings(warnings)), + } } /// Analyze an instance using its value and caller-resolved type bindings. @@ -202,7 +213,13 @@ impl ParsedSource { .iter() .map(|(name, value)| (name.clone(), value.clone().into())) .collect(); - ast::with_call_sites(|| { + let original = packages + .interface_plan + .modules + .get(module_name) + .map_or(module_name, |plan| plan.original.as_str()); + let warnings = self.warnings.get(original).cloned().unwrap_or_default(); + let ir = ast::with_call_sites(|| { let source = ast::Source::from_indexed_syntax_module( &self.tree, &self.path, @@ -218,7 +235,8 @@ impl ParsedSource { packages, )?; analyze::analyze_source(source) - }) + }); + crate::finish_analysis(ir, warnings) } } diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index 516d0ffcb52..1741eaafa30 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -9,6 +9,15 @@ use crate::system_functions::SystemTask; +/// Where a construct is written: its file and byte range in the source text +/// before preprocessing. +#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct SourceSpan { + pub path: std::path::PathBuf, + pub start: usize, + pub end: usize, +} + /// One procedural statement. #[derive(Debug, Clone, PartialEq, Eq)] pub enum StmtBase { @@ -59,10 +68,12 @@ pub enum StmtBase { /// the expression is evaluated like any other operand and its value is /// discarded. Eval(E), - /// A system task call statement such as `$display`. + /// A system task call statement such as `$display`. `site` is the call, + /// unless the analyzer created the statement. SystemTask { task: SystemTask, args: Vec>, + site: Option, }, /// The declaration point of a local variable: it is (re)initialized here, /// to `init` or to the default value of its type. @@ -274,8 +285,9 @@ impl StmtBase { args: args.into_iter().map(|arg| arg.map(&mut *fe)).collect(), }, StmtBase::Eval(expr) => StmtBase::Eval(fe(expr)), - StmtBase::SystemTask { task, args } => StmtBase::SystemTask { + StmtBase::SystemTask { task, args, site } => StmtBase::SystemTask { task, + site, args: args .into_iter() .map(|arg| match arg { diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index c4d7e1f0560..848910ff26e 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -5319,3 +5319,156 @@ fn native_interface_bindings_reject_enum_constant_collisions() { "{error}" ); } + +#[test] +fn public_analyses_report_constant_function_exit_warnings() { + let exit_sites = |ir: &Ir| { + ir.warnings() + .iter() + .map(|warning| match warning { + ir::AnalyzerWarning::ExitOutsideProgram { site } => { + let site = site.as_ref().unwrap(); + (site.path.clone(), site.start) + } + }) + .collect::>() + }; + let module = "module Top(output int y); + function automatic int f(); $exit; return 1; endfunction + localparam int N = f(); + assign y = N; + endmodule"; + let path = Path::new("exit.sv"); + let expected = vec![(path.to_path_buf(), module.find("$exit").unwrap())]; + let overrides = HashMap::default(); + assert_eq!(exit_sites(&analyze_source(module, path).unwrap()), expected); + assert_eq!( + exit_sites( + &analyze_source_with_module_parameter_overrides(module, path, "Top", &overrides) + .unwrap() + ), + expected + ); + assert_eq!( + exit_sites( + &analyze_source_module_with_parameter_overrides(module, path, "Top", &overrides) + .unwrap() + ), + expected + ); + // A source with an interface is analyzed module by module. + let with_interface = format!("interface Bus; logic x; endinterface\n{module}"); + assert_eq!( + exit_sites(&analyze_source(&with_interface, path).unwrap()), + vec![(path.to_path_buf(), with_interface.find("$exit").unwrap())] + ); +} + +#[test] +fn interface_prototypes_include_package_warnings() { + let source = r#"package P; + function automatic int width(); $exit; return 8; endfunction + localparam int W = width(); + endpackage + interface Bus; + logic [P::W-1:0] req; + endinterface"#; + let prototypes = crate::interface_prototypes(&[(source, Path::new("bus.sv"))]).unwrap(); + assert_eq!(prototypes.len(), 1); + let [ir::AnalyzerWarning::ExitOutsideProgram { site: Some(site) }] = + prototypes[0].warnings.as_slice() + else { + panic!("unexpected warnings: {:?}", prototypes[0].warnings); + }; + assert_eq!(site.path, Path::new("bus.sv")); + assert_eq!(site.start, source.find("$exit").unwrap()); +} + +#[test] +fn declaration_warnings_are_owned_by_failed_analyses() { + let source = r#"module Top(output int y); + function automatic int f(); $exit; return 2; endfunction + localparam int N = f(); + always_comb y <= N; + endmodule"#; + let error = analyze_source(source, Path::new("failed.sv")).unwrap_err(); + assert_eq!(error.warnings().len(), 1); + let clean = analyze_source("module Clean; endmodule", Path::new("clean.sv")).unwrap(); + assert!(clean.warnings().is_empty()); + let [ir::AnalyzerWarning::ExitOutsideProgram { site: Some(site) }] = error.warnings() else { + panic!("{error:?}"); + }; + assert_eq!(site.path, Path::new("failed.sv")); + assert_eq!(site.start, source.find("$exit").unwrap()); + assert_eq!(error.tracking_issue(), 453); + assert!(matches!(error.into_error(), AnalyzerError::Unsupported(_))); +} + +#[test] +fn declaration_warnings_are_scoped_to_the_analyzed_module() { + let source = r#"module Warn; + function automatic int unused(); $exit; return 1; endfunction + endmodule + module Clean; endmodule"#; + let parsed = ParsedSource::parse(source, Path::new("modules.sv")).unwrap(); + let packages = ParsedSource::analyze_packages(&[&parsed]).unwrap(); + let analyze = |name| { + parsed + .analyze_module( + name, + &HashMap::default(), + &[], + &[], + &ModuleInterfaces::default(), + &packages, + ) + .unwrap() + }; + assert_eq!(analyze("Warn").warnings().len(), 1); + assert!(analyze("Clean").warnings().is_empty()); + assert_eq!(analyze("Warn").warnings().len(), 1); +} + +#[test] +fn program_functions_do_not_report_outside_program_warnings() { + let source = "program P; function automatic int f(); $exit; return 1; endfunction endprogram"; + let result = analyze_source(source, Path::new("program.sv")); + match result { + Ok(ir) => assert!(ir.warnings().is_empty()), + Err(error) => assert!(error.warnings().is_empty()), + } +} + +#[test] +fn package_errors_own_their_declaration_warnings() { + let source = r#"package P; + function automatic int f(); $exit; return 1; endfunction + localparam int N = f(); + localparam int BAD = missing(); + endpackage"#; + let path = Path::new("failed-package.sv"); + let tree = crate::syntax::parse_source(source, path).unwrap(); + let error = Packages::analyze(&[(&tree, path)]).unwrap_err(); + let [ir::AnalyzerWarning::ExitOutsideProgram { site: Some(site) }] = error.warnings() else { + panic!("{error:?}"); + }; + assert_eq!(site.path, path); + assert_eq!(site.start, source.find("$exit").unwrap()); + assert!(std::error::Error::source(&error).is_some()); + assert!(matches!(error.into_error(), AnalyzerError::Unsupported(_))); +} + +#[test] +fn interface_shape_errors_keep_owned_function_warnings() { + let source = r#"interface Bus; + function automatic int unused(); $exit; return 1; endfunction + logic req; + logic req; + endinterface"#; + let error = interface_prototypes(&[(source, Path::new("duplicate.sv"))]).unwrap_err(); + assert_eq!(error.warnings().len(), 1); + assert!(matches!( + error.into_error(), + AnalyzerError::DuplicateInterfaceItem { .. } + )); +} diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 9850c2b6b88..dc0064cd13a 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -38,6 +38,12 @@ pub use celox_design::{DomainKind, ElaboratedDesign, EventTopology, RuntimeSchem pub use celox_frontend_core::FrontendArtifactError; pub use celox_frontend_sdk as frontend_sdk; pub use celox_frontend_sdk::FrontendArtifact; +/// Warnings of the SystemVerilog frontend, in [`CompilationWarning::SystemVerilog`]. +#[cfg(feature = "systemverilog")] +pub use celox_frontend_sv::{ + FrontendWarning as SvFrontendWarning, FrontendWarningKind as SvFrontendWarningKind, + WarningLocation as SvWarningLocation, +}; pub use celox_frontend_veryl::{FrontendDiagnostic, LoweringPhase, ParserError}; pub use celox_runtime::{ BaselineRecord, DesignReflection, NbaRecord, ProcessRecord, ReflectionScope, ReflectionScopeId, diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index 0cbcdc47d64..a6d96f03382 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -593,6 +593,7 @@ pub fn parse_sv( testbench_random_seed: Option, component_libraries: Vec, component_file_base: Option, + warnings: &mut Vec, ) -> Result { let frontend_trace_options = trace_opts.frontend(diagnostics); let mut frontend_trace = celox_frontend_core::FrontendTrace::default(); @@ -606,6 +607,7 @@ pub fn parse_sv( &crate::optimizer::parallel_schedule_options(optimize_options), &frontend_trace_options, trace.is_some().then_some(&mut frontend_trace), + warnings, ) .map_err(|error| match error { celox_frontend_sv::FrontendError::Lowering(error) => error.into(), @@ -633,8 +635,8 @@ pub fn parse_sv( /// support stays unsupported, and anything else is an error in the source. #[cfg(feature = "systemverilog")] pub(crate) fn sv_analysis_error(error: celox_frontend_sv::AnalyzerError) -> ParserError { - match error { - celox_frontend_sv::AnalyzerError::Unsupported(_) => ParserError::unsupported( + match error.into_error() { + error @ celox_frontend_sv::AnalyzerError::Unsupported(_) => ParserError::unsupported( error.tracking_issue(), celox_frontend_veryl::LoweringPhase::SimulatorParser, "systemverilog analysis", @@ -682,6 +684,7 @@ pub fn parse_mixed( testbench_random_seed: Option, component_libraries: Vec, component_file_base: Option, + sv_warnings: &mut Vec, ) -> Result< ( crate::ir::OptimizedSir, @@ -726,7 +729,12 @@ pub fn parse_mixed( // A native specialization can introduce further SV specializations and // interface behavior. Analyze the expanded requests until every alternating // language boundary has been prepared; cache native elaboration by key. + // Each pass lowers every SV module again, so a successful pass replaces + // the warnings of the previous one. A failing pass may stop before the + // modules that warned, so its warnings join the previous pass's. + let mut pass_warnings = Vec::new(); let external = loop { + let mut warnings = Vec::new(); let borrowed_sources = sources .iter() .map(|(source, path)| (source.as_str(), path.as_path())) @@ -819,12 +827,26 @@ pub fn parse_mixed( Some(&mut resolver), sv_top_parameters, &requests, - ) - .map_err(|error| match error { - celox_frontend_sv::FrontendError::Lowering(error) => error.into(), - celox_frontend_sv::FrontendError::Analyzer(error) => sv_analysis_error(error), - })?; + &mut warnings, + ); + let external = match external { + Ok(external) => external, + Err(error) => { + for warning in warnings { + if !pass_warnings.contains(&warning) { + pass_warnings.push(warning); + } + } + sv_warnings.extend(pass_warnings); + return Err(match error { + celox_frontend_sv::FrontendError::Lowering(error) => error.into(), + celox_frontend_sv::FrontendError::Analyzer(error) => sv_analysis_error(error), + }); + } + }; + pass_warnings = warnings; if pending_sources.is_empty() && pending_requests.is_empty() { + sv_warnings.extend(pass_warnings); break external; } external_roots.extend(pending_roots); diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 35aa936d945..f59ba796e9b 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -12,6 +12,16 @@ use veryl_parser::Parser; use veryl_parser::resource_table; use crate::parser::BuildConfig; + +#[cfg(feature = "systemverilog")] +fn sv_compilation_warnings( + warnings: Vec, +) -> Vec { + warnings + .into_iter() + .map(CompilationWarning::SystemVerilog) + .collect() +} use crate::{ CompilationWarning, FrontendDiagnostic, HashMap, ParserError, SimulatorError, SimulatorErrorKind, ir::OptimizedSir, parser, @@ -288,6 +298,7 @@ fn analyze( Result, Vec, Vec, + Vec, ) { symbol_table::clear(); attribute_table::clear(); @@ -312,6 +323,7 @@ fn analyze( .into()), Vec::new(), Vec::new(), + Vec::new(), ); } } @@ -349,33 +361,47 @@ fn analyze( Err(SimulatorError::new(SimulatorErrorKind::Syntax(error))), Vec::new(), Vec::new(), + Vec::new(), ); } } } #[cfg(feature = "systemverilog")] let mut sv_interface_signatures = Vec::new(); + // Behaviorless interfaces may never be lowered again. Retain their probe + // warnings too, deduplicating calls also encountered during design lowering. + #[cfg(feature = "systemverilog")] + let mut sv_probe_warnings = Vec::new(); #[cfg(feature = "systemverilog")] if let Some(sv_sources) = sv_sources { let references = super::mixed::referenced_sv_components( authored_parsers.iter().map(|parser| &parser.veryl), ); - let contracts = celox_frontend_sv::interface_signatures_for(sv_sources, Some(&references)) - .map_err(|error| match error { - celox_frontend_sv::FrontendError::Analyzer(error) => { - parser::sv_analysis_error(error) - } - celox_frontend_sv::FrontendError::Lowering(error) => error.into(), - }) - .and_then(|mut signatures| { - signatures.retain(|signature| references.contains(&signature.name)); - let source = super::mixed::veryl_interface_contracts(&signatures)?; - sv_interface_signatures = signatures; - Ok(source) - }); + let contracts = celox_frontend_sv::interface_signatures_for( + sv_sources, + Some(&references), + &mut sv_probe_warnings, + ) + .map_err(|error| match error { + celox_frontend_sv::FrontendError::Analyzer(error) => parser::sv_analysis_error(error), + celox_frontend_sv::FrontendError::Lowering(error) => error.into(), + }) + .and_then(|mut signatures| { + signatures.retain(|signature| references.contains(&signature.name)); + let source = super::mixed::veryl_interface_contracts(&signatures)?; + sv_interface_signatures = signatures; + Ok(source) + }); let contracts = match contracts { Ok(contracts) => contracts, - Err(error) => return (Err(error.into()), errors, Vec::new()), + Err(error) => { + return ( + Err(error.into()), + errors, + Vec::new(), + sv_compilation_warnings(sv_probe_warnings), + ); + } }; if !contracts.is_empty() { let parsed = match Parser::parse(&contracts, &Path::new("")) { @@ -385,6 +411,7 @@ fn analyze( Err(SimulatorError::new(SimulatorErrorKind::Syntax(error))), errors, Vec::new(), + sv_compilation_warnings(sv_probe_warnings), ); } }; @@ -417,7 +444,11 @@ fn analyze( && let Err(error) = elaborate_parameterized_top(&mut ir, &mut context, top, param_overrides) { errors.append(&mut context.drain_errors()); - return (Err(error.into()), errors, Vec::new()); + #[cfg(feature = "systemverilog")] + let warnings = sv_compilation_warnings(sv_probe_warnings); + #[cfg(not(feature = "systemverilog"))] + let warnings = Vec::new(); + return (Err(error.into()), errors, Vec::new(), warnings); } errors.append(&mut context.drain_errors()); errors.append(&mut Analyzer::analyze_post_pass2(&ir)); @@ -475,6 +506,8 @@ fn analyze( build_config.reset_type = rt; } build_config.parallel_lanes = optimize_options.parallel_lanes(); + #[cfg(feature = "systemverilog")] + let mut sv_warnings = Vec::new(); let sir = if let Some(external) = external_frontend { parser::parse_with_external_hierarchy( &top, @@ -555,6 +588,7 @@ fn analyze( testbench_random_seed, component_libraries, component_file_base, + &mut sv_warnings, ) })() } else { @@ -605,7 +639,30 @@ fn analyze( sir }) .map_err(SimulatorError::from); - (sir, errors, frontend_diagnostics) + #[cfg(feature = "systemverilog")] + let elaboration_warnings = { + for warning in sv_probe_warnings { + if !sv_warnings.contains(&warning) { + sv_warnings.push(warning); + } + } + sv_warnings.sort_by(|left, right| { + left.location + .as_ref() + .map(|location| (&location.path, location.line, location.column)) + .cmp( + &right + .location + .as_ref() + .map(|location| (&location.path, location.line, location.column)), + ) + .then(left.kind.cmp(&right.kind)) + }); + sv_compilation_warnings(sv_warnings) + }; + #[cfg(not(feature = "systemverilog"))] + let elaboration_warnings = Vec::new(); + (sir, errors, frontend_diagnostics, elaboration_warnings) } /// Compile Veryl source code to the SIR (Simulation IR) representation. @@ -776,7 +833,7 @@ fn compile_frontend_testbench_to_sir_with_layout_mode( ); } let lowered = celox_frontend_core::lower_frontend_artifact(artifact)?; - let (sir, errors, frontend_diagnostics) = analyze( + let (sir, errors, frontend_diagnostics, elaboration_warnings) = analyze( sources, None, Some(&lowered.external), @@ -810,6 +867,7 @@ fn compile_frontend_testbench_to_sir_with_layout_mode( .into_iter() .map(CompilationWarning::Frontend), ) + .chain(elaboration_warnings) .collect::>(); if !real_errors.is_empty() { return Err( @@ -854,7 +912,7 @@ fn compile_to_sir_with_layout_mode( recover_comb_loops: bool, allow_always_ff_function_effects: bool, ) -> Result<(OptimizedSir, Vec), SimulatorError> { - let (sir, errors, frontend_diagnostics) = analyze( + let (sir, errors, frontend_diagnostics, elaboration_warnings) = analyze( sources, None, None, @@ -888,6 +946,7 @@ fn compile_to_sir_with_layout_mode( .into_iter() .map(CompilationWarning::Frontend), ) + .chain(elaboration_warnings) .collect::>(); if !real_errors.is_empty() { return Err( @@ -981,7 +1040,8 @@ fn compile_sv_to_sir_with_layout_mode( build_config.reset_type = reset_type; } let (component_libraries, component_file_base) = component_runtime_config(&metadata); - parser::parse_sv( + let mut sv_warnings = Vec::new(); + let sir = parser::parse_sv( sources, top, param_overrides, @@ -997,9 +1057,16 @@ fn compile_sv_to_sir_with_layout_mode( metadata.test.seed, component_libraries, component_file_base, - ) - .map(|program| (program, Vec::new())) - .map_err(SimulatorError::from) + &mut sv_warnings, + ); + let warnings = sv_warnings + .into_iter() + .map(CompilationWarning::SystemVerilog) + .collect(); + match sir { + Ok(program) => Ok((program, warnings)), + Err(error) => Err(SimulatorError::from(error).with_warnings(warnings)), + } } /// Compile a mixed Veryl/SystemVerilog hierarchy to optimized SIR. @@ -1079,7 +1146,7 @@ fn compile_mixed_to_sir_with_layout_mode( recover_comb_loops: bool, allow_always_ff_function_effects: bool, ) -> Result<(OptimizedSir, Vec), SimulatorError> { - let (sir, errors, frontend_diagnostics) = analyze( + let (sir, errors, frontend_diagnostics, elaboration_warnings) = analyze( sources, Some(sv_sources), None, @@ -1113,6 +1180,7 @@ fn compile_mixed_to_sir_with_layout_mode( .into_iter() .map(CompilationWarning::Frontend), ) + .chain(elaboration_warnings) .collect::>(); if !real_errors.is_empty() { return Err( @@ -1347,7 +1415,8 @@ mod host { }) { return Err(SimulatorError::from(crate::CodegenError::message( "VCD requires packed array storage; compile this native image with VCD enabled", - ))); + )) + .with_warnings(std::mem::take(&mut sim.warnings))); } let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -1355,7 +1424,10 @@ mod host { &descs, sim.program.design.time_precision, ) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + .map_err(|_| { + SimulatorError::from(crate::RuntimeErrorCode::InternalError) + .with_warnings(std::mem::take(&mut sim.warnings)) + })?; sim.vcd_writer = Some(vcd_writer); } let apply_initial_start = options.diagnostics.phase_timing.then(crate::timing::now); @@ -1364,7 +1436,9 @@ mod host { tracing::debug!("[phase-timing] apply_initial_values: {:?}", start.elapsed()); } let settle_start = options.diagnostics.phase_timing.then(crate::timing::now); - sim.modify(|_| {}).map_err(SimulatorError::from)?; + sim.modify(|_| {}).map_err(|error| { + SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) + })?; if let Some(start) = settle_start { tracing::debug!("[phase-timing] initial_settle: {:?}", start.elapsed()); } @@ -1390,21 +1464,18 @@ mod host { all(feature = "x86_64-codegen", not(target_arch = "x86_64")) ))] { - let _ = ( - image, - program, - warnings, - options, - vcd_path, - injected_components, - ); - return Err(SimulatorError::from(crate::RuntimeErrorCode::InternalError)); + let _ = (image, program, options, vcd_path, injected_components); + return Err(SimulatorError::from(crate::RuntimeErrorCode::InternalError) + .with_warnings(warnings)); } // Safety: callers either produced the image in this process or loaded // it from an explicitly trusted native-image artifact. - let backend = unsafe { - crate::backend::native::NativeBackend::from_image_with_dpi(image, &options.dpi)? + let backend = match unsafe { + crate::backend::native::NativeBackend::from_image_with_dpi(image, &options.dpi) + } { + Ok(backend) => backend, + Err(error) => return Err(error.with_warnings(warnings)), }; initialize_native_backend( backend, @@ -2182,7 +2253,7 @@ mod host { let phase_timing = self.options.diagnostics.phase_timing; let compile_start = phase_timing.then(crate::timing::now); let injected_manifests = self.injected_components.manifests(); - let (program, warnings) = if let Some(artifact) = &self.frontend_artifact { + let (program, mut warnings) = if let Some(artifact) = &self.frontend_artifact { if self.sources.is_empty() { compile_frontend_to_sir_with_layout_mode( artifact, @@ -2268,7 +2339,10 @@ mod host { // function fails the build early; the backends reuse the result. self.options .dpi - .resolve_ahead(&laid_out.runtime().runtime_schema.extern_functions)?; + .resolve_ahead(&laid_out.runtime().runtime_schema.extern_functions) + .map_err(|error| { + SimulatorError::from(error).with_warnings(std::mem::take(&mut warnings)) + })?; Ok(( laid_out, @@ -2306,7 +2380,7 @@ mod host { let phase_timing = self.options.diagnostics.phase_timing; let phase_start = phase_timing.then(crate::timing::now); - let (laid_out, warnings, options, vcd_path, injected_components) = self + let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; if let Some(s) = phase_start { @@ -2325,7 +2399,8 @@ mod host { &laid_out, &options, wants_codegen_trace.then_some(&mut trace), - )?; + ) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; if options.trace.output_to_stdout { trace.print(); } @@ -2344,11 +2419,16 @@ mod host { &descs, sim.program.design.time_precision, ) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + .map_err(|_| { + SimulatorError::from(crate::RuntimeErrorCode::InternalError) + .with_warnings(std::mem::take(&mut sim.warnings)) + })?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); - sim.modify(|_| {}).map_err(SimulatorError::from)?; + sim.modify(|_| {}).map_err(|error| { + SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) + })?; Ok(sim) } @@ -2367,7 +2447,7 @@ mod host { let phase_timing = self.options.diagnostics.phase_timing; let phase_start = phase_timing.then(crate::timing::now); - let (laid_out, warnings, options, vcd_path, injected_components) = self + let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; if let Some(s) = phase_start { @@ -2377,7 +2457,8 @@ mod host { ); } - let backend = crate::backend::InterpBackend::new(&laid_out, &options)?; + let backend = crate::backend::InterpBackend::new(&laid_out, &options) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; let mut sim = Simulator::with_backend_and_program(backend, laid_out.into_runtime(), warnings); @@ -2390,11 +2471,16 @@ mod host { &descs, sim.program.design.time_precision, ) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + .map_err(|_| { + SimulatorError::from(crate::RuntimeErrorCode::InternalError) + .with_warnings(std::mem::take(&mut sim.warnings)) + })?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); - sim.modify(|_| {}).map_err(SimulatorError::from)?; + sim.modify(|_| {}).map_err(|error| { + SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) + })?; Ok(sim) } @@ -2440,11 +2526,16 @@ mod host { &descs, sim.program.design.time_precision, ) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + .map_err(|_| { + SimulatorError::from(crate::RuntimeErrorCode::InternalError) + .with_warnings(std::mem::take(&mut sim.warnings)) + })?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); - sim.modify(|_| {}).map_err(SimulatorError::from)?; + sim.modify(|_| {}).map_err(|error| { + SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) + })?; Ok(sim) } @@ -2504,11 +2595,16 @@ mod host { &descs, sim.program.design.time_precision, ) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + .map_err(|_| { + SimulatorError::from(crate::RuntimeErrorCode::InternalError) + .with_warnings(std::mem::take(&mut sim.warnings)) + })?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); - sim.modify(|_| {}).map_err(SimulatorError::from)?; + sim.modify(|_| {}).map_err(|error| { + SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) + })?; Ok(sim) } @@ -2521,7 +2617,7 @@ mod host { pub fn compile_native(self) -> Result { let phase_timing = self.options.diagnostics.phase_timing; let sir_start = phase_timing.then(crate::timing::now); - let (laid_out, warnings, options, vcd_path, injected_components) = self + let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program( crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, )?; @@ -2532,7 +2628,8 @@ mod host { ); } let backend_start = phase_timing.then(crate::timing::now); - let image = crate::backend::native::NativeBackend::compile_image(&laid_out, &options)?; + let image = crate::backend::native::NativeBackend::compile_image(&laid_out, &options) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; if let Some(start) = backend_start { tracing::debug!("[phase-timing] native_codegen: {:?}", start.elapsed()); } @@ -2562,7 +2659,7 @@ mod host { let phase_timing = self.options.diagnostics.phase_timing; let sir_start = phase_timing.then(crate::timing::now); let mut trace = crate::debug::CompilationTrace::default(); - let (laid_out, warnings, options, vcd_path, injected_components) = self + let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program_with_trace( crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, Some(&mut trace), @@ -2577,7 +2674,8 @@ mod host { let (image, native_trace) = crate::backend::native::NativeBackend::compile_image_with_codegen_trace( &laid_out, &options, - )?; + ) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; if let Some(start) = backend_start { tracing::debug!("[phase-timing] native_codegen: {:?}", start.elapsed()); } @@ -2689,9 +2787,10 @@ mod host { pub fn build_wasm( self, ) -> Result, SimulatorError> { - let (laid_out, warnings, options, vcd_path, injected_components) = self + let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; - let backend = crate::backend::wasm_runtime::WasmBackend::new(&laid_out, &options)?; + let backend = crate::backend::wasm_runtime::WasmBackend::new(&laid_out, &options) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; let mut sim = Simulator::with_backend_and_program(backend, laid_out.into_runtime(), warnings); sim.components.set_injected(injected_components); @@ -2703,11 +2802,16 @@ mod host { &descs, sim.program.design.time_precision, ) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + .map_err(|_| { + SimulatorError::from(crate::RuntimeErrorCode::InternalError) + .with_warnings(std::mem::take(&mut sim.warnings)) + })?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); - sim.modify(|_| {}).map_err(SimulatorError::from)?; + sim.modify(|_| {}).map_err(|error| { + SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) + })?; Ok(sim) } @@ -2740,6 +2844,7 @@ mod host { SimulatorError::new(SimulatorErrorKind::Codegen(crate::CodegenError::message( "no initial block found — this module is not a native testbench", ))) + .with_warnings(std::mem::take(&mut sim.warnings)) })?; Ok(crate::testbench::run_testbench_detailed( &mut sim, &testbench, @@ -2824,7 +2929,7 @@ mod host { ) }; - let sim_res = program_res.and_then(|(program, warnings)| { + let sim_res = program_res.and_then(|(program, mut warnings)| { let mut laid_out = program.into_laid_out_with_mode(self.options.four_state, layout_mode); if self.vcd_path.is_some() { @@ -2846,20 +2951,23 @@ mod host { crate::backend::native::NativeBackend::new_with_codegen_trace( &laid_out, &self.options, - )?; + ) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; trace.native_optimized_sir = Some(native_trace.optimized_sir); trace.mir = Some(native_trace.mir); trace.reactive_event_graph = Some(native_trace.reactive_graph); trace.native_state_layout = Some(native_trace.state_layout); backend } else { - crate::backend::native::NativeBackend::new(&laid_out, &self.options)? + crate::backend::native::NativeBackend::new(&laid_out, &self.options) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))? }; #[cfg(not(any( all(target_arch = "x86_64", not(feature = "arm64-codegen")), all(target_arch = "aarch64", not(feature = "x86_64-codegen")) )))] - let backend = JitBackend::new(&laid_out, &self.options, None)?; + let backend = JitBackend::new(&laid_out, &self.options, None) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; let mut sim = Simulator::with_backend_and_program(backend, laid_out.into_runtime(), warnings); @@ -2867,7 +2975,9 @@ mod host { .set_injected(self.injected_components.clone()); sim.diagnostics = self.options.diagnostics.clone(); sim.apply_initial_values(); - sim.modify(|_| {}).map_err(SimulatorError::from)?; + sim.modify(|_| {}).map_err(|error| { + SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) + })?; Ok(sim) }); @@ -2891,6 +3001,7 @@ mod host { SimulatorError::new(SimulatorErrorKind::Codegen(crate::CodegenError::message( "no initial block found — this module is not a native testbench", ))) + .with_warnings(std::mem::take(&mut sim.warnings)) })?; let result = crate::testbench::run_testbench(&mut sim, &testbench); if let Some(start) = testbench_start { @@ -3044,9 +3155,10 @@ mod host { ) -> Result, ) -> Result, SimulatorError> { self.options.emit_triggers = true; - let (laid_out, warnings, options, vcd_path, injected_components) = + let (laid_out, mut warnings, options, vcd_path, injected_components) = self.into_laid_out_program(layout_mode)?; - let backend = compile(&laid_out, &options)?; + let backend = compile(&laid_out, &options) + .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; // Initial kernels must keep their time-zero gates until the timed // scheduler starts them; ordinary Simulator builders release them. let mut sim = Simulator::with_backend_and_program_for_simulation( @@ -3063,11 +3175,16 @@ mod host { &descs, sim.program.design.time_precision, ) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + .map_err(|_| { + SimulatorError::from(crate::RuntimeErrorCode::InternalError) + .with_warnings(std::mem::take(&mut sim.warnings)) + })?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); - sim.modify(|_| {}).map_err(SimulatorError::from)?; + sim.modify(|_| {}).map_err(|error| { + SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) + })?; Ok(crate::Simulation::new(sim)) } } diff --git a/crates/celox/src/simulator/error.rs b/crates/celox/src/simulator/error.rs index 1b6438b2dd1..f5ae0dbb407 100644 --- a/crates/celox/src/simulator/error.rs +++ b/crates/celox/src/simulator/error.rs @@ -42,6 +42,8 @@ fn render_analyzer_error(error: &veryl_analyzer::AnalyzerError) -> String { pub enum CompilationWarning { Analyzer(veryl_analyzer::AnalyzerError), Frontend(celox_frontend_veryl::FrontendDiagnostic), + #[cfg(feature = "systemverilog")] + SystemVerilog(celox_frontend_sv::FrontendWarning), } impl fmt::Display for CompilationWarning { @@ -49,6 +51,8 @@ impl fmt::Display for CompilationWarning { match self { Self::Analyzer(diagnostic) => diagnostic.fmt(f), Self::Frontend(diagnostic) => diagnostic.fmt(f), + #[cfg(feature = "systemverilog")] + Self::SystemVerilog(diagnostic) => diagnostic.fmt(f), } } } @@ -60,6 +64,8 @@ impl miette::Diagnostic for CompilationWarning { match self { Self::Analyzer(diagnostic) => miette::Diagnostic::code(diagnostic), Self::Frontend(diagnostic) => miette::Diagnostic::code(diagnostic), + #[cfg(feature = "systemverilog")] + Self::SystemVerilog(diagnostic) => miette::Diagnostic::code(diagnostic), } } @@ -67,6 +73,8 @@ impl miette::Diagnostic for CompilationWarning { match self { Self::Analyzer(diagnostic) => miette::Diagnostic::severity(diagnostic), Self::Frontend(diagnostic) => miette::Diagnostic::severity(diagnostic), + #[cfg(feature = "systemverilog")] + Self::SystemVerilog(diagnostic) => miette::Diagnostic::severity(diagnostic), } } @@ -74,6 +82,8 @@ impl miette::Diagnostic for CompilationWarning { match self { Self::Analyzer(diagnostic) => miette::Diagnostic::help(diagnostic), Self::Frontend(diagnostic) => miette::Diagnostic::help(diagnostic), + #[cfg(feature = "systemverilog")] + Self::SystemVerilog(diagnostic) => miette::Diagnostic::help(diagnostic), } } @@ -81,6 +91,8 @@ impl miette::Diagnostic for CompilationWarning { match self { Self::Analyzer(diagnostic) => miette::Diagnostic::url(diagnostic), Self::Frontend(diagnostic) => miette::Diagnostic::url(diagnostic), + #[cfg(feature = "systemverilog")] + Self::SystemVerilog(diagnostic) => miette::Diagnostic::url(diagnostic), } } @@ -88,6 +100,8 @@ impl miette::Diagnostic for CompilationWarning { match self { Self::Analyzer(diagnostic) => miette::Diagnostic::source_code(diagnostic), Self::Frontend(diagnostic) => miette::Diagnostic::source_code(diagnostic), + #[cfg(feature = "systemverilog")] + Self::SystemVerilog(diagnostic) => miette::Diagnostic::source_code(diagnostic), } } @@ -95,6 +109,8 @@ impl miette::Diagnostic for CompilationWarning { match self { Self::Analyzer(diagnostic) => miette::Diagnostic::labels(diagnostic), Self::Frontend(diagnostic) => miette::Diagnostic::labels(diagnostic), + #[cfg(feature = "systemverilog")] + Self::SystemVerilog(diagnostic) => miette::Diagnostic::labels(diagnostic), } } } diff --git a/crates/celox/tests/frontends/systemverilog/mixed.rs b/crates/celox/tests/frontends/systemverilog/mixed.rs index 7feb18cf301..ecaff45f62a 100644 --- a/crates/celox/tests/frontends/systemverilog/mixed.rs +++ b/crates/celox/tests/frontends/systemverilog/mixed.rs @@ -46,6 +46,32 @@ sv_backends! { assert_eq!(sim.get(sim.signal("y")), 5u8.into()); } + fn reports_sv_warnings_of_a_veryl_top(sim) { + @setup { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("short.hex"); + std::fs::write(&file, "aa").unwrap(); + let veryl = "module Top(y: output logic<8>) { inst child: $sv::Child(y); }"; + let sv = format!(r#" + module Child(output logic [7:0] y); + logic [7:0] mem [0:1]; + initial $readmemh("{}", mem); + assign y = mem[0]; + endmodule + "#, file.display()); + } + @build Simulator::from_mixed_sources(vec![(veryl, Path::new("top.veryl"))], vec![(&sv, Path::new("child.sv"))], "Top"); + assert_eq!(sim.get(sim.signal("y")), 0xaau8.into()); + let warnings: Vec<_> = sim.warnings().iter().map(ToString::to_string).collect(); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + let celox::CompilationWarning::SystemVerilog(warning) = &sim.warnings()[0] else { + panic!("{warnings:?}"); + }; + assert!(matches!(warning.kind, celox::SvFrontendWarningKind::MemoryFileWordCount { .. })); + let location = warning.location.as_ref().unwrap(); + assert_eq!((location.path.as_str(), location.line), ("child.sv", 4)); + } + fn resolves_veryl_interface_parameter_types_after_prior_overrides(sim) { @setup { let veryl = "interface Bus #(param W: u32 = 8, param V: logic = 4) { var req: logic; var rsp: logic; modport slave { req: input, rsp: output, } } module Child(bus: modport Bus::slave) { assign bus.rsp = bus.req; }"; @@ -1573,3 +1599,249 @@ mod pending_interface_functions { } } } + +/// The probe analyzes the interface for its signature; the signature then +/// fails the build before the design analyzes it again. +#[test] +fn keeps_sv_interface_warnings_when_its_signature_fails() { + let veryl = "module Top(y: output logic<8>) { inst bus: $sv::Bus; assign y = bus.req; }"; + let sv = r#"interface Bus; + function automatic int width(); + $exit; + return 8; + endfunction + localparam int W = width(); + logic [W-1:0] req; + assign req = 1; + function automatic logic [W-1:0] get(); + return req; + endfunction + modport reader(input req, import get); +endinterface +"#; + let error = Simulator::from_mixed_sources( + vec![(veryl, Path::new("top.veryl"))], + vec![(sv, Path::new("bus.sv"))], + "Top", + ) + .build_cranelift() + .unwrap_err(); + assert!(error.to_string().contains("imported function"), "{error}"); + let warned: Vec<_> = error + .warnings() + .iter() + .filter_map(|warning| match warning { + celox::CompilationWarning::SystemVerilog(warning) => Some(&warning.kind), + _ => None, + }) + .collect(); + assert_eq!( + warned, + vec![&celox::SvFrontendWarningKind::ExitOutsideProgram] + ); +} + +/// Warnings in an SV interface point at their call in the interface's file, +/// under an SV top and under a Veryl top alike. +#[test] +fn locates_sv_interface_warnings_at_their_call() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("short.hex"); + std::fs::write(&file, "aa").unwrap(); + let bus = format!( + r#"interface Bus; + function automatic int width(); + $exit; + return 8; + endfunction + localparam int W = width(); + logic [W-1:0] mem [0:1]; + logic [W-1:0] req; + initial begin + $readmemh("{}", mem); + $exit(); + end + assign req = mem[0]; +endinterface +"#, + file.display() + ); + let located = |warnings: &[celox::CompilationWarning]| { + warnings + .iter() + .filter_map(|warning| match warning { + celox::CompilationWarning::SystemVerilog(warning) => { + let location = warning.location.as_ref().unwrap(); + Some(( + matches!( + warning.kind, + celox::SvFrontendWarningKind::ExitOutsideProgram + ), + location.path.clone(), + location.line, + location.column, + )) + } + _ => None, + }) + .collect::>() + }; + let expected = vec![ + (true, "bus.sv".to_string(), 3, 9), + (false, "bus.sv".to_string(), 10, 9), + (true, "bus.sv".to_string(), 11, 9), + ]; + let veryl = "module Top(y: output logic<8>) { inst bus: $sv::Bus; assign y = bus.req; }"; + let sim = Simulator::from_mixed_sources( + vec![(veryl, Path::new("top.veryl"))], + vec![(&bus, Path::new("bus.sv"))], + "Top", + ) + .build_cranelift() + .unwrap(); + assert_eq!(located(sim.warnings()), expected); + let top = + "module Top(output logic [7:0] y); Bus bus(); assign y = bus.req; initial $exit; endmodule"; + let sim = Simulator::from_sv_sources( + vec![(&bus, Path::new("bus.sv")), (top, Path::new("top.sv"))], + "Top", + ) + .build_cranelift() + .unwrap(); + let mut expected = expected; + expected.push(( + true, + "top.sv".to_string(), + 1, + top.find("$exit").unwrap() + 1, + )); + assert_eq!(located(sim.warnings()), expected); +} + +#[test] +fn retains_behaviorless_interface_probe_warnings() { + let veryl = "module Top(y: output logic<8>) { inst bus: $sv::Bus; assign y = bus.req; }"; + let sv = r#"interface Bus; + function automatic int width(); $exit; return 8; endfunction + localparam int W = width(); + logic [W-1:0] req; + endinterface"#; + let sim = Simulator::from_mixed_sources( + vec![(veryl, Path::new("top.veryl"))], + vec![(sv, Path::new("bus.sv"))], + "Top", + ) + .build_cranelift() + .unwrap(); + let warnings: Vec<_> = sim + .warnings() + .iter() + .filter_map(|warning| match warning { + celox::CompilationWarning::SystemVerilog(warning) => Some(warning), + _ => None, + }) + .collect(); + assert_eq!(warnings.len(), 1); + assert_eq!( + warnings[0].kind, + celox::SvFrontendWarningKind::ExitOutsideProgram + ); + let location = warnings[0].location.as_ref().unwrap(); + assert_eq!((location.path.as_str(), location.line), ("bus.sv", 2)); +} + +#[test] +fn keeps_warnings_when_interface_analysis_fails() { + let veryl = "module Top(y: output logic<8>) { inst bus: $sv::Bus; assign y = bus.req; }"; + for sv in [ + r#"interface Bus; + function automatic int width(); $exit; return 8; endfunction + localparam int W = width(); + logic [W-1:0] req; + localparam int BAD = missing(); + endinterface"#, + r#"package P; + function automatic int width(); $exit; return 8; endfunction + localparam int W = width(); + endpackage + interface Bus; + logic [P::W-1:0] req; + localparam int BAD = missing(); + endinterface"#, + ] { + let error = Simulator::from_mixed_sources( + vec![(veryl, Path::new("top.veryl"))], + vec![(sv, Path::new("bus.sv"))], + "Top", + ) + .build_cranelift() + .unwrap_err(); + assert!(error.to_string().contains("constant function"), "{error}"); + let warnings: Vec<_> = error + .warnings() + .iter() + .filter_map(|warning| match warning { + celox::CompilationWarning::SystemVerilog(warning) => Some(warning), + _ => None, + }) + .collect(); + assert_eq!(warnings.len(), 1, "{error}"); + assert_eq!( + warnings[0].kind, + celox::SvFrontendWarningKind::ExitOutsideProgram + ); + let location = warnings[0].location.as_ref().unwrap(); + assert_eq!((location.path.as_str(), location.line), ("bus.sv", 2)); + } +} + +#[test] +fn review_warnings_follow_instantiated_interface_parameters() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("short.hex"); + std::fs::write(&file, "aa").unwrap(); + let sv = format!( + r#"interface Bus #(parameter N = 2); + logic [7:0] mem [0:N-1]; + logic [7:0] req; + initial $readmemh("{}", mem); + assign req = mem[0]; + endinterface + interface Passive; + function automatic int width(); $exit; return 8; endfunction + localparam int W = width(); + logic [W-1:0] req; + endinterface"#, + file.display() + ); + for n in [1, 2] { + let veryl = format!( + "module Top(y: output logic<8>) {{ inst bus: $sv::Bus #(N: {n}); inst passive: $sv::Passive; assign y = bus.req ^ passive.req; }}" + ); + let sim = Simulator::from_mixed_sources( + vec![(&veryl, Path::new("top.veryl"))], + vec![(&sv, Path::new("bus.sv"))], + "Top", + ) + .build_cranelift() + .unwrap(); + let warnings: Vec<_> = sim + .warnings() + .iter() + .filter_map(|warning| match warning { + celox::CompilationWarning::SystemVerilog(warning) => Some(warning), + _ => None, + }) + .collect(); + let lines: Vec<_> = warnings + .iter() + .map(|warning| warning.location.as_ref().unwrap().line) + .collect(); + assert_eq!( + lines, + if n == 1 { vec![8] } else { vec![4, 8] }, + "N={n}: {:?}", + sim.warnings() + ); + } +} diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index e04f336733b..515c2e3202f 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -945,6 +945,8 @@ sv_backends! { assert_eq!(sim.get(initial_words), 0xaabbcc00u32.into()); sim.tick(clk).unwrap(); assert_eq!(sim.get(registered), 0x0a0b0c00u32.into()); + // Address directives, or a word for each address, warn nothing. + assert!(sim.warnings().is_empty(), "{:?}", sim.warnings()); } fn readmem_count_mismatch_preserves_unwritten_words(sim) { @@ -976,6 +978,50 @@ sv_backends! { let short_y = sim.signal("short_y"); assert_eq!(sim.get(y), 0xbbcc3344u32.into()); assert_eq!(sim.get(short_y), 0x112233aau32.into()); + // IEEE 1800-2023 21.4: a count mismatch without address directives + // issues a warning, at each call. + let warned = readmem_warnings(sim.warnings()); + assert_eq!(warned, vec![ + ("readmem.sv".to_string(), source_line(&source, "short_mem, 3, 2"), short.display().to_string()), + ("readmem.sv".to_string(), source_line(&source, "mem, -1, 0"), long.display().to_string()), + ]); + } + + fn readmem_count_mismatch_warns_once_per_call(sim) { + @setup { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("short.hex"); + std::fs::write(&file, "aa").unwrap(); + let source = format!(r#" + module Child #(parameter int P = 0) (output logic [7:0] y); + logic [7:0] mem [0:1]; + initial $readmemh("{file}", mem); + assign y = mem[0] + P; + endmodule + module Top(output logic [31:0] y); + logic [7:0] a [0:1]; + logic [7:0] b [0:1]; + initial $readmemh("{file}", a); + initial $readmemh("{file}", b); + Child #(.P(0)) c0(y[23:16]); + Child #(.P(1)) c1(y[31:24]); + assign y[15:0] = {{a[0], b[0]}}; + endmodule + "#, file = file.display()); + } + @build Simulator::from_sv_sources(vec![(&source, Path::new("calls.sv"))], "Top"); + assert_eq!(sim.get(sim.signal("y")), 0xabaaaaaau32.into()); + // Calls that read the same file into equal ranges warn separately; + // a call in a module specialized twice warns once. + let file = file.display().to_string(); + assert_eq!(readmem_warnings(sim.warnings()), vec![ + ("calls.sv".to_string(), source_line(&source, "\", mem);"), file.clone()), + ("calls.sv".to_string(), source_line(&source, "\", a);"), file.clone()), + ("calls.sv".to_string(), source_line(&source, "\", b);"), file), + ]); + let rendered = celox::render_diagnostic(&sim.warnings()[1]); + let line = source_line(&source, "\", a);"); + assert!(rendered.contains(&format!("[calls.sv:{line}:29]")), "{rendered}"); } fn signed_casts_in_parameters(sim) { @case "system_functions::signed_casts_in_parameters"; } fn array_queries_preserve_bounds_and_dimensions(sim) { @case "system_functions::array_queries_preserve_bounds_and_dimensions"; } @@ -1089,6 +1135,32 @@ fn rejects_bit_vector_functions_with_missing_or_extra_arguments() { } } +/// The file, line and memory file of each `$readmem` word-count warning. +fn readmem_warnings(warnings: &[celox::CompilationWarning]) -> Vec<(String, usize, String)> { + warnings + .iter() + .map(|warning| match warning { + celox::CompilationWarning::SystemVerilog(celox::SvFrontendWarning { + kind: celox::SvFrontendWarningKind::MemoryFileWordCount { task, file, .. }, + location: Some(location), + }) => { + assert_eq!(task, "$readmemh"); + (location.path.clone(), location.line, file.clone()) + } + warning => panic!("unexpected warning: {warning}"), + }) + .collect() +} + +/// The 1-based line of the first line of `source` containing `needle`. +fn source_line(source: &str, needle: &str) -> usize { + source + .lines() + .position(|line| line.contains(needle)) + .unwrap() + + 1 +} + fn build_error(source: &str) -> String { match Simulator::from_sv_sources(vec![(source, Path::new("system_functions.sv"))], "Top") .build_cranelift() @@ -1459,6 +1531,27 @@ fn exit_outside_a_program_block_is_ignored() { assert!(!sim.is_stopped()); assert_eq!(sim.get(sim.signal("a")), 3u8.into()); assert_eq!(sim.drain_runtime_events(), Vec::new()); + // Each call warns once, at its line. + let warned: Vec<_> = sim + .warnings() + .iter() + .map(|warning| match warning { + celox::CompilationWarning::SystemVerilog(celox::SvFrontendWarning { + kind: celox::SvFrontendWarningKind::ExitOutsideProgram, + location: Some(location), + }) => location.line, + warning => panic!("unexpected warning: {warning}"), + }) + .collect(); + assert_eq!( + warned, + source + .lines() + .enumerate() + .filter(|(_, line)| line.contains("$exit")) + .map(|(index, _)| index + 1) + .collect::>() + ); let error = build_error("module Top(output logic y); initial $exit(1); assign y = 0; endmodule"); assert!( @@ -1467,6 +1560,148 @@ fn exit_outside_a_program_block_is_ignored() { ); } +/// The location of each `$exit` warning, which must be all of them. +fn exit_warning_locations(warnings: &[celox::CompilationWarning]) -> Vec<(usize, usize)> { + warnings + .iter() + .map(|warning| match warning { + celox::CompilationWarning::SystemVerilog(celox::SvFrontendWarning { + kind: celox::SvFrontendWarningKind::ExitOutsideProgram, + location: Some(location), + }) => (location.line, location.column), + warning => panic!("unexpected warning: {warning}"), + }) + .collect() +} + +/// The 1-based line and column of the first `needle` in `source`. +fn source_position(source: &str, needle: &str) -> (usize, usize) { + let line = source_line(source, needle); + let column = source.lines().nth(line - 1).unwrap().find(needle).unwrap() + 1; + (line, column) +} + +#[test] +fn exit_in_a_timed_process_warns_at_the_call() { + let source = r#" + module Top(input logic clk, output int a); + timeunit 1ps; + timeprecision 1ps; + initial begin + #1 $exit; + a = 1; + end + always @(posedge clk) begin + #1; + $exit(); + end + endmodule + "#; + let mut sim = initial_simulation(source); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("a")), 1u8.into()); + assert_eq!( + exit_warning_locations(sim.warnings()), + vec![ + source_position(source, "$exit;"), + source_position(source, "$exit();") + ] + ); +} + +#[test] +fn exit_in_a_constant_function_warns_at_the_call() { + let source = r#" + package P; + function automatic int g(); + $exit; + return 2; + endfunction + localparam int Q = g(); + endpackage + module Top(output int y); + function automatic int f(); + $exit(); + return 4; + endfunction + localparam int N = f(); + assign y = N + P::Q; + endmodule + "#; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("constant.sv"))], "Top") + .build_cranelift() + .unwrap(); + sim.eval_comb().unwrap(); + assert_eq!(sim.get(sim.signal("y")), 6u8.into()); + assert_eq!( + exit_warning_locations(sim.warnings()), + vec![ + source_position(source, "$exit;"), + source_position(source, "$exit();") + ] + ); +} + +#[test] +fn package_warnings_survive_a_failing_module() { + // Analyzing the top fails the build before the package states lower. + let source = r#" + package P; + function automatic int g(); + $exit; + return 2; + endfunction + localparam int Q = g(); + endpackage + module Top(output int y); + always_comb y <= P::Q; + endmodule + "#; + let Err(error) = Simulator::from_sv_sources(vec![(source, Path::new("package.sv"))], "Top") + .build_cranelift() + else { + panic!("design unexpectedly compiled"); + }; + assert_eq!( + exit_warning_locations(error.warnings()), + vec![source_position(source, "$exit;")] + ); +} + +/// Type and assignment-pattern parameters are bound by rewriting the module +/// source; the warnings still point at the call in the file. +#[test] +fn warnings_of_rewritten_specializations_point_at_their_call() { + let source = r#" + module Child #(parameter type T = logic, parameter int P [2] = '{1, 2}) + (output int y); + T v; + initial begin + $exit; + end + assign y = P[0]; + endmodule + module Top(output int a, b, c); + Child #(.T(logic [63:0])) c0(.y(a)); + Child #(.P('{100000, 200000})) c1(.y(b)); + Child c2(.y(c)); + endmodule + "#; + let sim = Simulator::from_sv_sources(vec![(source, Path::new("rewritten.sv"))], "Top") + .build_cranelift() + .unwrap(); + // The three specializations share the call. + assert_eq!( + exit_warning_locations(sim.warnings()), + vec![source_position(source, "$exit;")] + ); + let rendered = celox::render_diagnostic(&sim.warnings()[0]); + assert!( + rendered.contains("$exit;") && !rendered.contains("logic [63:0]"), + "{rendered}" + ); +} + #[test] fn rejects_unknown_system_functions_in_every_context() { let cases = [ @@ -2664,3 +2899,139 @@ fn time_is_zero_in_a_simulator_without_time() { sim.tick(clk).unwrap(); assert_eq!(sim.drain_runtime_events(), displays(&["0 0"])); } + +#[test] +fn readmem_warnings_survive_a_later_lowering_error() { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("short.hex"); + std::fs::write(&file, "aa").unwrap(); + // The top's inout port fails the build after its processes lowered. + let source = format!( + r#" + module Top(inout wire x, output logic [7:0] y); + logic [7:0] mem [0:1]; + initial $readmemh("{}", mem); + assign y = mem[0]; + endmodule + "#, + file.display() + ); + let Err(error) = + Simulator::from_sv_sources(vec![(&source, Path::new("inout.sv"))], "Top").build_cranelift() + else { + panic!("design unexpectedly compiled"); + }; + assert_eq!( + readmem_warnings(error.warnings()), + vec![( + "inout.sv".to_string(), + source_line(&source, "$readmemh"), + file.display().to_string() + )] + ); +} + +#[test] +fn exit_warnings_survive_analyzer_errors() { + for source in [ + r#"module Top(output int y); + function automatic int f(); $exit; return 2; endfunction + localparam int N = f(); + always_comb y <= N; + endmodule"#, + r#"package P; + function automatic int f(); $exit; return 2; endfunction + localparam int N = f(); + localparam int BAD = missing(); + endpackage + module Top(output int y); assign y = P::N; endmodule"#, + ] { + let error = Simulator::from_sv_sources(vec![(source, Path::new("error.sv"))], "Top") + .build_cranelift() + .unwrap_err(); + assert_eq!( + exit_warning_locations(error.warnings()), + vec![source_position(source, "$exit;")], + "{error}" + ); + } +} + +#[test] +fn exit_warnings_survive_simulator_initialization_errors() { + let source = "module Top(output int y); initial $exit; assign y = 1; endmodule"; + let dir = tempfile::tempdir().unwrap(); + // A directory cannot be opened as a VCD file, after compilation succeeded. + let builder = + || Simulator::from_sv_sources(vec![(source, Path::new("init.sv"))], "Top").vcd(dir.path()); + let mut errors = vec![ + builder().build_cranelift().unwrap_err(), + builder().build_interpreter().unwrap_err(), + builder().build_tiered().unwrap_err(), + builder().build_wasm().unwrap_err(), + celox::Simulation::from_sv_sources(vec![(source, Path::new("init.sv"))], "Top") + .vcd(dir.path()) + .build_cranelift() + .unwrap_err(), + ]; + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + errors.push(builder().build_native().unwrap_err()); + for error in errors { + assert_eq!( + exit_warning_locations(error.warnings()), + vec![source_position(source, "$exit;")] + ); + } +} + +#[test] +fn review_warnings_survive_test_runner_errors() { + let source = r#"module Top(output int y); + function automatic int value(); $exit; return 1; endfunction + localparam int N = value(); + assign y = N; + endmodule"#; + let builder = || Simulator::from_sv_sources(vec![(source, Path::new("testbench.sv"))], "Top"); + let mut errors = vec![ + builder().run_test().unwrap_err(), + builder().run_test_cranelift().unwrap_err(), + builder().run_test_detailed().unwrap_err(), + ]; + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + errors.push(builder().run_test_native().unwrap_err()); + for error in errors { + assert!( + error.to_string().contains("no initial block found"), + "{error}" + ); + assert_eq!( + exit_warning_locations(error.warnings()), + vec![source_position(source, "$exit;")] + ); + } +} + +sv_backends! { + fn review_warnings_deduplicate_parameterized_readmem_calls(sim) { + @setup { + let dir = tempfile::tempdir().unwrap(); + let file = dir.path().join("short.hex"); + std::fs::write(&file, "aa").unwrap(); + let source = format!(r#"module Child #(parameter N = 2)(output logic [7:0] y); + logic [7:0] mem [0:N-1]; + initial $readmemh("{}", mem); + assign y = mem[0]; + endmodule + module Top(output logic [7:0] a, b, c); + Child #(.N(2)) one(a); + Child #(.N(3)) two(b); + Child #(.N(4)) three(c); + endmodule"#, file.display()); + } + @build Simulator::from_sv_sources(vec![(&source, Path::new("specialized.sv"))], "Top"); + let warnings = readmem_warnings(sim.warnings()); + assert_eq!(warnings.len(), 1, "{:?}", sim.warnings()); + assert_eq!(warnings[0].0, "specialized.sv"); + assert_eq!(warnings[0].1, source_line(&source, "$readmemh")); + } +} diff --git a/crates/celox/tests/sv_dpi.rs b/crates/celox/tests/sv_dpi.rs index f8c5bb8baf4..c29213b3495 100644 --- a/crates/celox/tests/sv_dpi.rs +++ b/crates/celox/tests/sv_dpi.rs @@ -517,6 +517,7 @@ fn registering_a_name_again_replaces_the_function() { fn unresolved_function_is_a_build_error() { let source = r#" module Top(input logic clk, input int a, output int y); + initial $exit; import "DPI-C" function int missing_dpi_function(input int x); always_ff @(posedge clk) y <= missing_dpi_function(a); endmodule @@ -533,6 +534,21 @@ fn unresolved_function_is_a_build_error() { error.to_string().contains("missing_dpi_function"), "{error}" ); + let warnings: Vec<_> = error + .warnings() + .iter() + .filter_map(|warning| match warning { + celox::CompilationWarning::SystemVerilog(warning) => Some(warning), + _ => None, + }) + .collect(); + assert_eq!(warnings.len(), 1); + assert_eq!( + warnings[0].kind, + celox::SvFrontendWarningKind::ExitOutsideProgram + ); + let location = warnings[0].location.as_ref().unwrap(); + assert_eq!((location.path.as_str(), location.line), ("dpi.sv", 3)); } extern "C" fn dpi_twice(x: i32) -> i32 { diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 56f42b32699..acf4ad8b874 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -321,7 +321,10 @@ imports, task imports, exports, packed vector arguments (`svBitVecVal` / interactive mode, such as the VPI host, end the run at `$stop`. - **`$exit`** ends the initial procedures of the program block that calls it (24.7). Celox has no program blocks, and a call from anywhere else is - ignored, as 24.7 specifies. + ignored, as 24.7 specifies, with a compilation warning + (`Simulator::warnings()`) at the call. This includes a call in a constant + function. Calls in function declarations are diagnosed even when the function + is unused; the diagnostic does not depend on constant evaluation executing it. - **Immediate cover** executes its pass statement when the condition is true. Coverage counters and reports are not exposed. Deferred cover (`#0` / `final`) is rejected because its scheduling is not modeled. @@ -331,8 +334,9 @@ imports, task imports, exports, packed vector arguments (`svBitVecVal` / words are written on every activation; in `initial` they are part of the initial state. Explicit ranges load in either direction, and `@` file addresses are absolute array indices. An address directive outside the requested range - is an error. Without directives, a word-count mismatch emits a warning: - excess words are ignored, and missing words leave memory unchanged. + is an error. Without directives, a word-count mismatch is a compilation + warning (`Simulator::warnings()`): excess words are ignored, and missing words + leave memory unchanged. - **Constant parameters of aggregate type** (unpacked arrays, packed structs given by a pattern) are variables that hold their value from the start of the simulation; they cannot be used where an elaboration-time constant is diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 7a518a1fa7e..cba9fd76e3d 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -185,7 +185,10 @@ package・interface の手続きは宣言元の時間単位と精度を保持し - **定数関数**は、呼び出す表示タスクと重大度タスクを無視します。 - **`$readmemh` / `$readmemb`** は、デザインのコンパイル時にファイルを読みます。ファイルが ないか不正な場合は `MemoryFile` エラーです。`always_ff` では起動のたびにファイルの各ワードを - 書き込み、`initial` では初期状態の一部になります。 + 書き込み、`initial` では初期状態の一部になります。明示した範囲はどちらの向きにも読み込み、 + ファイル中の `@` アドレスは配列の絶対インデックスです。要求範囲外のアドレス指定はエラーです。 + アドレス指定がなくワード数が範囲と合わない場合はコンパイル警告(`Simulator::warnings()`)に + なり、余ったワードは無視され、足りない分のメモリは変わりません。 - **集約型の定数パラメータ**(unpacked 配列や、パターンで与える packed 構造体)は、 シミュレーション開始時から値を保持する変数です。エラボレーション時の定数が必要な場所では 使えません。 @@ -256,7 +259,9 @@ Icarus Verilog などそれを実装するシミュレータと同じ値を返 なるのと同様に `RuntimeEvent::Stop` として報告します。診断レベルの引数では何も 表示しません。VPI ホストのように対話モードを持たないバッチ実行では `$stop` で終了します。 `$exit` は呼び出した program ブロックの initial 手続きを終了します(24.7)。 -Celox は program ブロックを持たず、それ以外からの呼び出しは 24.7 の規定どおり無視します。 +Celox は program ブロックを持たず、それ以外からの呼び出しは 24.7 の規定どおり無視し、 +その呼び出し位置でコンパイル警告(`Simulator::warnings()`)を出します。定数関数内の呼び出しも同様です。 +関数宣言内の呼び出しは、その関数を使わなくても警告します。定数評価が実行したかどうかには依存しません。 `Simulation` は設計全体の時間精度(IEEE 1800-2023 3.14.3)で時刻を数えます。 既定は 1 ps で、`run_until(1000)` は 1 ns まで進めます。時間単位が 1 ns の