From 2e429919ecaedb8570262d827c5482da5e7ad271 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 06:58:10 +0900 Subject: [PATCH 1/5] feat(sv)!: report SystemVerilog compilation warnings The SystemVerilog frontend had no way to report a non-fatal diagnostic: the SV build path returned no compilation warnings, and the `$readmem` word-count mismatch that IEEE 1800-2023 21.4 requires a warning for only went to `tracing`. Lowering now collects `FrontendWarning`s, and the SV and mixed build paths return them as `CompilationWarning::SystemVerilog`, also on error. Repeats from module specializations and retried lowerings are dropped. BREAKING CHANGE: `CompilationWarning` gains a `SystemVerilog` variant with the `systemverilog` feature. Change-Id: I59220d8e108d4bcfc52c5f7b8da7bc0794b09989 --- Cargo.lock | 2 +- crates/celox-frontend-sv/Cargo.toml | 2 +- crates/celox-frontend-sv/src/lib.rs | 2 + crates/celox-frontend-sv/src/lowering.rs | 116 ++++++++++++++++++ .../src/lowering/procedural.rs | 16 ++- crates/celox-frontend-sv/src/warning.rs | 34 +++++ crates/celox/src/lib.rs | 3 + crates/celox/src/parser.rs | 8 ++ crates/celox/src/simulator/builder.rs | 45 +++++-- crates/celox/src/simulator/error.rs | 16 +++ .../tests/frontends/systemverilog/mixed.rs | 29 +++++ .../systemverilog/system_functions.rs | 22 ++++ docs/guide/systemverilog.md | 5 +- docs/ja/guide/systemverilog.md | 5 +- 14 files changed, 286 insertions(+), 19 deletions(-) create mode 100644 crates/celox-frontend-sv/src/warning.rs 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..886c20dbafc 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; 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..d0ebf7d5041 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -116,6 +116,9 @@ pub(crate) struct LoweredSvModule { package_variables: Vec<(SourceVarId, String, String)>, /// The hidden `(copy, signal)` event copies of [`FfEventVars`]. event_copies: Vec<(SourceVarId, SourceVarId)>, + /// Warnings of the module's sequential and initial processes; those of + /// its combinational processes come from [`attach_instance_glue`]. + warnings: Vec, } #[derive(Clone)] @@ -1142,6 +1145,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 +1153,7 @@ pub fn prepare_external_hierarchy( &ExternalHierarchy::default(), &[], four_state, + warnings, ) } @@ -1160,6 +1165,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 +1176,67 @@ 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_unique_warnings(warnings, found); + hierarchy +} + +/// Appends `found` to `warnings` in a stable order, once each: each +/// specialization of a module and each lowering attempt of a process repeats +/// the warnings of the same source. +fn append_unique_warnings( + warnings: &mut Vec, + mut found: Vec, +) { + found.sort(); + found.dedup(); + warnings.extend(found); +} + +/// The warnings of a lowered module, its combinational processes aside. +fn lowered_warnings<'a>( + modules: impl IntoIterator, + warnings: &mut Vec, +) { + for module in modules { + warnings.extend(module.warnings.iter().cloned()); + } +} + +#[allow(clippy::too_many_arguments)] +fn prepare_external_hierarchy_collecting( sources: &[(&str, &Path)], root_names: &HashSet, foreign: &ExternalHierarchy, @@ -1186,6 +1245,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, @@ -1250,6 +1310,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( package_variables: Vec::new(), // The foreign module's own combinational blocks carry its copies. event_copies: Vec::new(), + warnings: Vec::new(), } }; let foreign_modules: HashMap<_, _> = foreign @@ -1426,6 +1487,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( Ok((module_id, specialize_module(base, key, four_state, false)?)) }) .collect::, FrontendError>>()?; + lowered_warnings(lowered_modules.values(), warnings); validate_specialized_instance_net_drivers(&module_ids, &lowered_modules)?; let mut modules = HashMap::default(); for (key, &module_id) in &module_ids { @@ -1450,6 +1512,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( &module_ids, &lowered_modules, four_state, + warnings, )?; modules.insert( module_id, @@ -1564,6 +1627,44 @@ 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_unique_warnings(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])?; let top = top.to_string(); @@ -1628,6 +1729,7 @@ pub fn schedule_sources( Ok((module_id, lowered)) }) .collect::, FrontendError>>()?; + lowered_warnings(lowered_modules.values(), warnings); validate_specialized_instance_net_drivers(&module_ids, &lowered_modules)?; let root = &lowered_modules[&root_id]; if let Some(port) = root @@ -1658,6 +1760,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); @@ -1975,6 +2078,7 @@ fn lower_module_with_overrides( mut runtime_event_sites, mut runtime_errors, mut extern_functions, + mut warnings, ) = { let mut pm = procedural::ProcModule::new( module, @@ -1990,6 +2094,7 @@ fn lower_module_with_overrides( std::mem::take(&mut pm.runtime_event_sites), std::mem::take(&mut pm.runtime_errors), std::mem::take(&mut pm.extern_functions), + std::mem::take(&mut pm.warnings), ) }; mark_ff_event_domains(&event_vars, &mut variables); @@ -2003,6 +2108,7 @@ fn lower_module_with_overrides( &mut runtime_event_sites, &mut runtime_errors, &mut extern_functions, + &mut warnings, )?; initial_memory_values.extend(initial_values); @@ -2113,6 +2219,7 @@ fn lower_module_with_overrides( instances, package_variables, event_copies: event_vars.copies, + warnings, }) } @@ -2371,6 +2478,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(); @@ -2497,6 +2605,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 +2929,7 @@ fn lower_initial_processes( runtime_event_sites: &mut Vec, runtime_errors: &mut HashMap>, extern_functions: &mut Vec, + warnings: &mut Vec, ) -> Result< ( Vec>, @@ -2877,6 +2987,9 @@ fn lower_initial_processes( Err(_) => runtime.push((process, random_seed)), } } + // A process that falls back to a kernel warns again below; the callers + // drop repeated warnings. + warnings.append(&mut pm.warnings); let created = std::mem::take(&mut pm.created); for id in created { if let Some(variable) = variables.remove(&id) { @@ -2961,6 +3074,7 @@ fn lower_initial_processes( *runtime_event_sites = std::mem::take(&mut pm.runtime_event_sites); *runtime_errors = std::mem::take(&mut pm.runtime_errors); *extern_functions = std::mem::take(&mut pm.extern_functions); + warnings.append(&mut pm.warnings); Ok((values, processes?, wait_sites, nba_sites)) } @@ -2974,6 +3088,7 @@ fn lower_comb_processes( four_state: bool, runtime_errors: &mut HashMap>, extern_functions: &mut Vec, + warnings: &mut Vec, ) -> Result< ( Vec>, @@ -3093,6 +3208,7 @@ fn lower_comb_processes( } *runtime_errors = std::mem::take(&mut pm.runtime_errors); *extern_functions = std::mem::take(&mut pm.extern_functions); + warnings.append(&mut pm.warnings); let created = std::mem::take(&mut pm.created); Ok((comb_blocks, arena, created, observers, sites)) } diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 2e7dbec5131..0a1efd4546b 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -44,6 +44,8 @@ pub(super) struct ProcModule<'a> { pub runtime_errors: HashMap>, /// The declared bounds of each unpacked dimension, by variable. unpacked_bounds: HashMap>, + /// Warnings found while lowering, for the caller to report. + pub warnings: Vec, } /// One word a memory file writes: its bits in the destination, value, and @@ -140,6 +142,7 @@ impl<'a> ProcModule<'a> { runtime_event_sites: Vec::new(), runtime_errors: HashMap::default(), unpacked_bounds, + warnings: Vec::new(), } } @@ -333,7 +336,7 @@ 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, @@ -418,9 +421,13 @@ 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::FrontendWarning::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,6 +454,7 @@ impl<'a> ProcModule<'a> { }); } } + self.warnings.extend(warning); Ok((id, words)) } diff --git a/crates/celox-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs new file mode 100644 index 00000000000..3fc86baaf0a --- /dev/null +++ b/crates/celox-frontend-sv/src/warning.rs @@ -0,0 +1,34 @@ +/// A non-fatal diagnostic of the SystemVerilog frontend. The design still +/// compiles; the simulator reports these with its compilation warnings. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, thiserror::Error)] +pub enum FrontendWarning { + /// 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, + }, +} + +impl miette::Diagnostic for FrontendWarning { + fn code<'a>(&'a self) -> Option> { + Some(Box::new(match self { + Self::MemoryFileWordCount { .. } => "memory_file_word_count", + })) + } + + fn severity(&self) -> Option { + Some(miette::Severity::Warning) + } + + fn help<'a>(&'a self) -> Option> { + Some(Box::new(match self { + Self::MemoryFileWordCount { .. } => { + "give one word per address of the range, or place the words with `@address` directives" + } + })) + } +} diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 9850c2b6b88..c4761a1c89c 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -38,6 +38,9 @@ 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; +/// A warning of the SystemVerilog frontend, in [`CompilationWarning::SystemVerilog`]. +#[cfg(feature = "systemverilog")] +pub use celox_frontend_sv::FrontendWarning as SvFrontendWarning; 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..b62857840c0 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(), @@ -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,11 @@ 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 only the last one's warnings + // are kept. + let earlier_warnings = sv_warnings.len(); let external = loop { + sv_warnings.truncate(earlier_warnings); let borrowed_sources = sources .iter() .map(|(source, path)| (source.as_str(), path.as_path())) @@ -819,6 +826,7 @@ pub fn parse_mixed( Some(&mut resolver), sv_top_parameters, &requests, + sv_warnings, ) .map_err(|error| match error { celox_frontend_sv::FrontendError::Lowering(error) => error.into(), diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 35aa936d945..056e2532d14 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -288,6 +288,7 @@ fn analyze( Result, Vec, Vec, + Vec, ) { symbol_table::clear(); attribute_table::clear(); @@ -312,6 +313,7 @@ fn analyze( .into()), Vec::new(), Vec::new(), + Vec::new(), ); } } @@ -349,6 +351,7 @@ fn analyze( Err(SimulatorError::new(SimulatorErrorKind::Syntax(error))), Vec::new(), Vec::new(), + Vec::new(), ); } } @@ -375,7 +378,7 @@ fn analyze( }); 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(), Vec::new()), }; if !contracts.is_empty() { let parsed = match Parser::parse(&contracts, &Path::new("")) { @@ -385,6 +388,7 @@ fn analyze( Err(SimulatorError::new(SimulatorErrorKind::Syntax(error))), errors, Vec::new(), + Vec::new(), ); } }; @@ -417,7 +421,7 @@ 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()); + return (Err(error.into()), errors, Vec::new(), Vec::new()); } errors.append(&mut context.drain_errors()); errors.append(&mut Analyzer::analyze_post_pass2(&ir)); @@ -475,6 +479,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 +561,7 @@ fn analyze( testbench_random_seed, component_libraries, component_file_base, + &mut sv_warnings, ) })() } else { @@ -605,7 +612,14 @@ fn analyze( sir }) .map_err(SimulatorError::from); - (sir, errors, frontend_diagnostics) + #[cfg(feature = "systemverilog")] + let elaboration_warnings = sv_warnings + .into_iter() + .map(CompilationWarning::SystemVerilog) + .collect(); + #[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 +790,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 +824,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 +869,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 +903,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 +997,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 +1014,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 +1103,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 +1137,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( 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..2456c174530 100644 --- a/crates/celox/tests/frontends/systemverilog/mixed.rs +++ b/crates/celox/tests/frontends/systemverilog/mixed.rs @@ -46,6 +46,35 @@ 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:?}"); + assert!( + matches!( + &sim.warnings()[0], + celox::CompilationWarning::SystemVerilog( + celox::SvFrontendWarning::MemoryFileWordCount { .. } + ) + ), + "{warnings:?}" + ); + } + 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; }"; diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index e04f336733b..64d09e799ef 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,26 @@ 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, once per call even though the process is + // lowered more than once. + let mut warned: Vec<_> = sim + .warnings() + .iter() + .map(|warning| match warning { + celox::CompilationWarning::SystemVerilog( + celox::SvFrontendWarning::MemoryFileWordCount { task, file, .. }, + ) => (task.as_str(), file.clone()), + warning => panic!("unexpected warning: {warning}"), + }) + .collect(); + warned.sort(); + let mut expected = vec![ + ("$readmemh", long.display().to_string()), + ("$readmemh", short.display().to_string()), + ]; + expected.sort(); + assert_eq!(warned, expected); } 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"; } diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 56f42b32699..3dbcbe3c26a 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -331,8 +331,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..9d55e31de85 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 構造体)は、 シミュレーション開始時から値を保持する変数です。エラボレーション時の定数が必要な場所では 使えません。 From 0a5aa944e9217226355afd3a51fcdffecf7af166 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 07:28:02 +0900 Subject: [PATCH 2/5] feat(sv)!: locate SystemVerilog warnings at their call A `$readmem` warning did not say which call it came from, and two calls reading the same file into equally sized ranges gave identical warnings that were merged into one. System task statements now keep the span of the call in the source, and a `FrontendWarning` carries its file, line, column and source snippet. Warnings are deduplicated by call site, so repeated lowerings of one call collapse while separate calls stay separate. Lowering writes warnings into one sink passed down from the frontend entry points, so warnings found before a later lowering error are kept. BREAKING CHANGE: `Stmt::SystemTask` of the SV analyzer IR gains a `site` field, and `FrontendWarning` becomes a struct of a `FrontendWarningKind` and an optional `WarningLocation`. Change-Id: Idc622a1e6b7e0f6c7248f502ffeb66b69129246d --- crates/celox-frontend-sv/src/lib.rs | 2 +- crates/celox-frontend-sv/src/lowering.rs | 97 +++++++------- crates/celox-frontend-sv/src/lowering/comb.rs | 10 +- crates/celox-frontend-sv/src/lowering/ff.rs | 11 +- .../src/lowering/procedural.rs | 26 ++-- crates/celox-frontend-sv/src/warning.rs | 100 ++++++++++++++- .../celox-sv-analyzer/src/ast/procedural.rs | 48 ++++++- crates/celox-sv-analyzer/src/ir.rs | 2 +- crates/celox-sv-analyzer/src/procedural.rs | 16 ++- crates/celox/src/lib.rs | 7 +- .../tests/frontends/systemverilog/mixed.rs | 15 +-- .../systemverilog/system_functions.rs | 119 +++++++++++++++--- 12 files changed, 344 insertions(+), 109 deletions(-) diff --git a/crates/celox-frontend-sv/src/lib.rs b/crates/celox-frontend-sv/src/lib.rs index 886c20dbafc..4bbdeeadcad 100644 --- a/crates/celox-frontend-sv/src/lib.rs +++ b/crates/celox-frontend-sv/src/lib.rs @@ -9,7 +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; +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 d0ebf7d5041..ba5b4d63bf8 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -116,9 +116,6 @@ pub(crate) struct LoweredSvModule { package_variables: Vec<(SourceVarId, String, String)>, /// The hidden `(copy, signal)` event copies of [`FfEventVars`]. event_copies: Vec<(SourceVarId, SourceVarId)>, - /// Warnings of the module's sequential and initial processes; those of - /// its combinational processes come from [`attach_instance_glue`]. - warnings: Vec, } #[derive(Clone)] @@ -231,7 +228,8 @@ pub fn interface_signatures_for( prototypes .into_iter() .map(|prototype| { - let lowered = lower_module(&prototype.module, false, true, false)?; + // The probe lowers only the interface; its own lowering warns. + let lowered = lower_module(&prototype.module, false, true, false, &mut Vec::new())?; Ok(InterfaceSignature { name: prototype.name, module: lowered.source, @@ -708,6 +706,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())); @@ -715,7 +714,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()))?, @@ -1209,32 +1208,10 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( requests, &mut found, ); - append_unique_warnings(warnings, found); + crate::warning::append_unique_warnings(sources, warnings, found); hierarchy } -/// Appends `found` to `warnings` in a stable order, once each: each -/// specialization of a module and each lowering attempt of a process repeats -/// the warnings of the same source. -fn append_unique_warnings( - warnings: &mut Vec, - mut found: Vec, -) { - found.sort(); - found.dedup(); - warnings.extend(found); -} - -/// The warnings of a lowered module, its combinational processes aside. -fn lowered_warnings<'a>( - modules: impl IntoIterator, - warnings: &mut Vec, -) { - for module in modules { - warnings.extend(module.warnings.iter().cloned()); - } -} - #[allow(clippy::too_many_arguments)] fn prepare_external_hierarchy_collecting( sources: &[(&str, &Path)], @@ -1245,7 +1222,7 @@ fn prepare_external_hierarchy_collecting( mut resolver: Option<&mut ForeignModuleResolver<'_>>, top_parameters: Option<(&str, &[(String, u64)])>, requests: &[SvModuleRequest], - warnings: &mut Vec, + warnings: &mut Vec, ) -> Result { let (analyzed, bound_names) = analyze_sources_with_requests( sources, @@ -1310,7 +1287,6 @@ fn prepare_external_hierarchy_collecting( package_variables: Vec::new(), // The foreign module's own combinational blocks carry its copies. event_copies: Vec::new(), - warnings: Vec::new(), } }; let foreign_modules: HashMap<_, _> = foreign @@ -1449,7 +1425,7 @@ fn prepare_external_hierarchy_collecting( 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) @@ -1484,10 +1460,12 @@ fn prepare_external_hierarchy_collecting( 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>>()?; - lowered_warnings(lowered_modules.values(), warnings); validate_specialized_instance_net_drivers(&module_ids, &lowered_modules)?; let mut modules = HashMap::default(); for (key, &module_id) in &module_ids { @@ -1545,8 +1523,13 @@ fn prepare_external_hierarchy_collecting( 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 @@ -1642,7 +1625,7 @@ pub fn schedule_sources( trace, &mut found, ); - append_unique_warnings(warnings, found); + crate::warning::append_unique_warnings(sources, warnings, found); scheduled } @@ -1664,7 +1647,7 @@ fn schedule_sources_collecting( parallel: &celox_frontend_core::ParallelScheduleOptions, trace_options: &FrontendTraceOptions, trace: Option<&mut FrontendTrace>, - warnings: &mut Vec, + warnings: &mut Vec, ) -> Result { let analyzed = analyze_sources(sources, &[top])?; let top = top.to_string(); @@ -1697,7 +1680,7 @@ fn schedule_sources_collecting( 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) { @@ -1724,12 +1707,11 @@ fn schedule_sources_collecting( 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)) }) .collect::, FrontendError>>()?; - lowered_warnings(lowered_modules.values(), warnings); validate_specialized_instance_net_drivers(&module_ids, &lowered_modules)?; let root = &lowered_modules[&root_id]; if let Some(port) = root @@ -1771,6 +1753,7 @@ fn schedule_sources_collecting( module_ids.len(), four_state, parallel.enabled(), + warnings, )?; validate_package_variable_drivers([&root_key], &module_ids, &lowered_modules)?; let mut packages = Vec::new(); @@ -1860,6 +1843,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. @@ -1891,6 +1875,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()) @@ -1922,8 +1907,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 @@ -1934,6 +1927,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(); @@ -2078,7 +2072,6 @@ fn lower_module_with_overrides( mut runtime_event_sites, mut runtime_errors, mut extern_functions, - mut warnings, ) = { let mut pm = procedural::ProcModule::new( module, @@ -2087,6 +2080,7 @@ fn lower_module_with_overrides( &constants, ¶meter_types, four_state, + warnings, ); let blocks = lower_ff_processes(module, &mut pm, ff_parts)?; ( @@ -2094,7 +2088,6 @@ fn lower_module_with_overrides( std::mem::take(&mut pm.runtime_event_sites), std::mem::take(&mut pm.runtime_errors), std::mem::take(&mut pm.extern_functions), - std::mem::take(&mut pm.warnings), ) }; mark_ff_event_domains(&event_vars, &mut variables); @@ -2108,7 +2101,7 @@ fn lower_module_with_overrides( &mut runtime_event_sites, &mut runtime_errors, &mut extern_functions, - &mut warnings, + warnings, )?; initial_memory_values.extend(initial_values); @@ -2219,7 +2212,6 @@ fn lower_module_with_overrides( instances, package_variables, event_copies: event_vars.copies, - warnings, }) } @@ -2478,7 +2470,7 @@ pub(crate) fn attach_instance_glue( module_ids: &HashMap, lowered_modules: &HashMap, four_state: bool, - warnings: &mut Vec, + warnings: &mut Vec, ) -> Result<(), ParserError> { let mut signal_names = lowered.signal_names.clone(); let mut parent_variables = lowered.variables.clone(); @@ -2551,6 +2543,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 { @@ -2929,7 +2922,7 @@ fn lower_initial_processes( runtime_event_sites: &mut Vec, runtime_errors: &mut HashMap>, extern_functions: &mut Vec, - warnings: &mut Vec, + warnings: &mut Vec, ) -> Result< ( Vec>, @@ -2951,6 +2944,7 @@ fn lower_initial_processes( constants, parameter_types, four_state, + warnings, ); let mut arena = SLTNodeArena::new(); let mut seed = comb::Store::default(); @@ -2987,9 +2981,6 @@ fn lower_initial_processes( Err(_) => runtime.push((process, random_seed)), } } - // A process that falls back to a kernel warns again below; the callers - // drop repeated warnings. - warnings.append(&mut pm.warnings); let created = std::mem::take(&mut pm.created); for id in created { if let Some(variable) = variables.remove(&id) { @@ -3047,6 +3038,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); @@ -3074,7 +3066,6 @@ fn lower_initial_processes( *runtime_event_sites = std::mem::take(&mut pm.runtime_event_sites); *runtime_errors = std::mem::take(&mut pm.runtime_errors); *extern_functions = std::mem::take(&mut pm.extern_functions); - warnings.append(&mut pm.warnings); Ok((values, processes?, wait_sites, nba_sites)) } @@ -3088,7 +3079,7 @@ fn lower_comb_processes( four_state: bool, runtime_errors: &mut HashMap>, extern_functions: &mut Vec, - warnings: &mut Vec, + warnings: &mut Vec, ) -> Result< ( Vec>, @@ -3110,6 +3101,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); @@ -3208,7 +3200,6 @@ fn lower_comb_processes( } *runtime_errors = std::mem::take(&mut pm.runtime_errors); *extern_functions = std::mem::take(&mut pm.extern_functions); - warnings.append(&mut pm.warnings); let created = std::mem::take(&mut pm.created); Ok((comb_blocks, arena, created, observers, sites)) } diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 9e0c6cdbc9b..8845d28db93 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -1916,8 +1916,9 @@ 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 @@ -1929,7 +1930,7 @@ impl<'p, 'a> Comb<'p, 'a> { 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 +3032,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 +3059,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..098f9122808 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() { diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 0a1efd4546b..1bb727f0cfa 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -44,8 +44,9 @@ pub(super) struct ProcModule<'a> { pub runtime_errors: HashMap>, /// The declared bounds of each unpacked dimension, by variable. unpacked_bounds: HashMap>, - /// Warnings found while lowering, for the caller to report. - pub warnings: Vec, + /// 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 @@ -64,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 @@ -142,7 +144,7 @@ impl<'a> ProcModule<'a> { runtime_event_sites: Vec::new(), runtime_errors: HashMap::default(), unpacked_bounds, - warnings: Vec::new(), + warnings, } } @@ -341,6 +343,7 @@ impl<'a> ProcModule<'a> { 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(); @@ -421,13 +424,16 @@ impl<'a> ProcModule<'a> { finish, ) .map_err(|error| sv::AnalyzerError::MemoryFile(format!("{name}: {}", error.message)))?; - let warning = parsed - .warning - .map(|detail| crate::FrontendWarning::MemoryFileWordCount { - task: name.to_string(), - file: unescape(filename), - detail, - }); + let warning = parsed.warning.map(|detail| { + ( + crate::FrontendWarningKind::MemoryFileWordCount { + task: name.to_string(), + file: unescape(filename), + detail, + }, + site.cloned(), + ) + }); let writes = parsed.writes; let word_mask = (BigUint::from(1u8) << element_width) - BigUint::from(1u8); let mut words = Vec::new(); diff --git a/crates/celox-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs index 3fc86baaf0a..0da3879fae5 100644 --- a/crates/celox-frontend-sv/src/warning.rs +++ b/crates/celox-frontend-sv/src/warning.rs @@ -1,7 +1,22 @@ +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, +} + +/// What a [`FrontendWarning`] reports. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, thiserror::Error)] -pub enum FrontendWarning { +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). @@ -13,10 +28,72 @@ pub enum FrontendWarning { }, } +/// 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); + +/// 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(); + 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 { - Self::MemoryFileWordCount { .. } => "memory_file_word_count", + Some(Box::new(match self.kind { + FrontendWarningKind::MemoryFileWordCount { .. } => "memory_file_word_count", })) } @@ -25,10 +102,23 @@ impl miette::Diagnostic for FrontendWarning { } fn help<'a>(&'a self) -> Option> { - Some(Box::new(match self { - Self::MemoryFileWordCount { .. } => { + Some(Box::new(match self.kind { + FrontendWarningKind::MemoryFileWordCount { .. } => { "give one word per address of the range, or place the words with `@address` directives" } })) } + + 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/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 9590a8d735e..d11df8167ff 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,43 @@ 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. +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/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 053456a0b82..95848b5c151 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -3,7 +3,7 @@ use crate::{ast, symbol::ModuleId, typecheck}; 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, 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/src/lib.rs b/crates/celox/src/lib.rs index c4761a1c89c..dc0064cd13a 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -38,9 +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; -/// A warning of the SystemVerilog frontend, in [`CompilationWarning::SystemVerilog`]. +/// Warnings of the SystemVerilog frontend, in [`CompilationWarning::SystemVerilog`]. #[cfg(feature = "systemverilog")] -pub use celox_frontend_sv::FrontendWarning as SvFrontendWarning; +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/tests/frontends/systemverilog/mixed.rs b/crates/celox/tests/frontends/systemverilog/mixed.rs index 2456c174530..ccc6de4abdf 100644 --- a/crates/celox/tests/frontends/systemverilog/mixed.rs +++ b/crates/celox/tests/frontends/systemverilog/mixed.rs @@ -64,15 +64,12 @@ sv_backends! { 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:?}"); - assert!( - matches!( - &sim.warnings()[0], - celox::CompilationWarning::SystemVerilog( - celox::SvFrontendWarning::MemoryFileWordCount { .. } - ) - ), - "{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) { diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 64d09e799ef..25c4fef0c37 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -979,25 +979,49 @@ sv_backends! { 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, once per call even though the process is - // lowered more than once. - let mut warned: Vec<_> = sim - .warnings() - .iter() - .map(|warning| match warning { - celox::CompilationWarning::SystemVerilog( - celox::SvFrontendWarning::MemoryFileWordCount { task, file, .. }, - ) => (task.as_str(), file.clone()), - warning => panic!("unexpected warning: {warning}"), - }) - .collect(); - warned.sort(); - let mut expected = vec![ - ("$readmemh", long.display().to_string()), - ("$readmemh", short.display().to_string()), - ]; - expected.sort(); - assert_eq!(warned, expected); + // 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"; } @@ -1111,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() @@ -2686,3 +2736,34 @@ 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() + )] + ); +} From e3453059b8b85f56be6161b2287c5ec6287488c1 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 07:34:47 +0900 Subject: [PATCH 3/5] feat(sv): warn at each ignored $exit call IEEE 1800-2023 24.7 ignores `$exit` outside a program block and allows a warning. Celox has no program blocks, so every call is ignored; each now reports an `ExitOutsideProgram` warning at the call. Change-Id: I6237a6ddf9ea602596be02e81e921b44240077c2 --- crates/celox-frontend-sv/src/lowering/comb.rs | 11 ++++++++-- crates/celox-frontend-sv/src/lowering/ff.rs | 5 ++++- .../src/lowering/procedural.rs | 21 ++++++++++++------- crates/celox-frontend-sv/src/warning.rs | 8 +++++++ .../systemverilog/system_functions.rs | 21 +++++++++++++++++++ docs/guide/systemverilog.md | 3 ++- docs/ja/guide/systemverilog.md | 4 +++- 7 files changed, 60 insertions(+), 13 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 8845d28db93..e1fc10b2161 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -1922,11 +1922,18 @@ impl<'p, 'a> Comb<'p, 'a> { 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" ))), diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 098f9122808..bebcdf9317a 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -2090,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 1bb727f0cfa..b931cb20de6 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -424,16 +424,14 @@ impl<'a> ProcModule<'a> { finish, ) .map_err(|error| sv::AnalyzerError::MemoryFile(format!("{name}: {}", error.message)))?; - let warning = parsed.warning.map(|detail| { - ( - crate::FrontendWarningKind::MemoryFileWordCount { + let warning = + parsed + .warning + .map(|detail| crate::FrontendWarningKind::MemoryFileWordCount { task: name.to_string(), file: unescape(filename), detail, - }, - site.cloned(), - ) - }); + }); let writes = parsed.writes; let word_mask = (BigUint::from(1u8) << element_width) - BigUint::from(1u8); let mut words = Vec::new(); @@ -460,10 +458,17 @@ impl<'a> ProcModule<'a> { }); } } - self.warnings.extend(warning); + 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 index 0da3879fae5..a515a5db97f 100644 --- a/crates/celox-frontend-sv/src/warning.rs +++ b/crates/celox-frontend-sv/src/warning.rs @@ -26,6 +26,10 @@ pub enum FrontendWarningKind { 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. @@ -94,6 +98,7 @@ 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", })) } @@ -106,6 +111,9 @@ impl miette::Diagnostic for FrontendWarning { 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" + } })) } diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 25c4fef0c37..2fb0c6ea359 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -1531,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!( diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 3dbcbe3c26a..973e470ac61 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -321,7 +321,8 @@ 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. - **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. diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 9d55e31de85..3770f307344 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -259,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 の From 3d707238869af594130290974921c74eb7c9fb4e Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 19:17:25 +0900 Subject: [PATCH 4/5] fix(sv): keep warnings through failed builds and warn at constant-function $exit A $exit in a constant function warns at its call. Interface probes and earlier mixed-language passes keep their warnings when the build fails before the design lowers again. Change-Id: I57950c1a34f32ff98d495831919bd9df293f8d70 --- crates/celox-frontend-sv/src/lowering.rs | 23 +- crates/celox-frontend-sv/src/warning.rs | 26 ++ crates/celox-sv-analyzer/src/ast.rs | 1 + .../src/ast/const_functions.rs | 11 +- .../celox-sv-analyzer/src/ast/interfaces.rs | 229 ++++++++++-------- crates/celox-sv-analyzer/src/ast/packages.rs | 13 + crates/celox-sv-analyzer/src/ast/warnings.rs | 34 +++ crates/celox-sv-analyzer/src/ir.rs | 18 +- crates/celox-sv-analyzer/src/parsed.rs | 100 ++++---- crates/celox/src/parser.rs | 34 ++- crates/celox/src/simulator/builder.rs | 74 ++++-- .../tests/frontends/systemverilog/mixed.rs | 110 +++++++++ .../systemverilog/system_functions.rs | 116 +++++++++ docs/guide/systemverilog.md | 3 +- docs/ja/guide/systemverilog.md | 3 +- 15 files changed, 605 insertions(+), 190 deletions(-) create mode 100644 crates/celox-sv-analyzer/src/ast/warnings.rs diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index ba5b4d63bf8..425a3e8c702 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -214,12 +214,27 @@ 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); + crate::warning::append_unique_warnings(sources, warnings, found); + signatures +} + +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,8 +243,8 @@ pub fn interface_signatures_for( prototypes .into_iter() .map(|prototype| { - // The probe lowers only the interface; its own lowering warns. - let lowered = lower_module(&prototype.module, false, true, false, &mut Vec::new())?; + 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, @@ -708,6 +723,7 @@ fn lower_package_states( ff_parts: bool, warnings: &mut Vec, ) -> Result, sv::AnalyzerError> { + warnings.extend(crate::warning::analyzer_warnings(packages.warnings())); let mut states = packages.state_modules().collect::>(); states.sort_by(|left, right| left.name().cmp(right.name())); states @@ -1865,6 +1881,7 @@ fn specialize_module( &module.interfaces, &module.packages, )?; + warnings.extend(crate::warning::analyzer_warnings(ir.warnings())); let specialized = ir .modules() .iter() diff --git a/crates/celox-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs index a515a5db97f..d8610c95705 100644 --- a/crates/celox-frontend-sv/src/warning.rs +++ b/crates/celox-frontend-sv/src/warning.rs @@ -14,6 +14,21 @@ pub struct FrontendWarning { pub location: Option, } +/// Warnings are the same when they report the same thing at the same place. +impl PartialEq for FrontendWarning { + fn eq(&self, other: &Self) -> bool { + let place = |warning: &Self| { + warning + .location + .as_ref() + .map(|location| (location.path.clone(), location.line, location.column)) + }; + self.kind == other.kind && place(self) == place(other) + } +} + +impl Eq for FrontendWarning {} + /// What a [`FrontendWarning`] reports. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, thiserror::Error)] pub enum FrontendWarningKind { @@ -62,6 +77,17 @@ impl WarningLocation { /// 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 diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 52c25f15b16..193e67fb71e 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, diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index fe4f56805e1..0fcdec0d2d3 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -1159,7 +1159,16 @@ 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), and is + // reported like the `$exit` of a process. + Stmt::SystemTask { + task: crate::system_functions::SystemTask::Exit, + site, + .. + } => super::warnings::warn(super::warnings::AnalyzerWarning::ExitOutsideProgram { + site: site.clone(), + }), 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..a9b528e2bf3 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( @@ -78,119 +80,134 @@ pub fn interface_prototypes_for( 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 - } + // Analyzing the signature evaluates constant functions, which can + // warn. + let (prototype, warnings) = + super::warnings::analyzing(|| -> 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() + .filter_map(|item| match item { + Item::Process(span) => Some(*span), + Item::Member(index) => interface.members[*index].initializer, + _ => 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 + .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() - .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 + .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 - .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 + .map(|member| member.name.clone()) + .collect(), + has_behavior: interface + .items + .iter() + .any(|item| matches!(item, Item::Process(_))) + || interface + .members .iter() - .map(|item| match item { - ModportItem::Member(direction, name) => { - (name.clone(), direction.keyword().to_string()) - } - ModportItem::Import(name) => { - (name.clone(), "import".to_string()) - } - }) - .collect(), - ) + .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(), }) - .collect(), + }); + prototype.map(|prototype| InterfacePrototype { + warnings, + ..prototype }) }) .collect::, AnalyzerError>>() diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index 3f1332c7a96..746ef813997 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() } 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..b69e478b0cd --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/warnings.rs @@ -0,0 +1,34 @@ +//! The warnings of an analysis. + +use std::cell::RefCell; + +use crate::procedural::SourceSpan; + +/// A warning found while analyzing, before the frontend lowers the design. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AnalyzerWarning { + /// `$exit` outside a program block, here in a constant function, which + /// IEEE 1800-2023 24.7 ignores. + ExitOutsideProgram { site: Option }, +} + +thread_local! { + static WARNINGS: RefCell>> = const { RefCell::new(None) }; +} + +/// Run one analysis and return the warnings it found. +pub(crate) fn analyzing(f: impl FnOnce() -> T) -> (T, Vec) { + let saved = WARNINGS.with(|current| current.replace(Some(Vec::new()))); + let result = f(); + let warnings = WARNINGS.with(|current| current.replace(saved)); + (result, warnings.unwrap_or_default()) +} + +/// Report `warning` with the analysis that is running, if any. +pub(super) fn warn(warning: AnalyzerWarning) { + WARNINGS.with(|current| { + if let Some(warnings) = &mut *current.borrow_mut() { + warnings.push(warning); + } + }); +} diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 95848b5c151..0b12e5fd38a 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -2,6 +2,7 @@ use crate::{ast, symbol::ModuleId, typecheck}; +pub use crate::ast::warnings::AnalyzerWarning; pub use crate::procedural::{ CaseKind, CaseLabel, EventEdge, LoopKind, ParamDirection, SourceSpan, StmtBase, SystemTaskArg, }; @@ -20,16 +21,31 @@ 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(), + } + } + + pub(crate) fn with_warnings(mut self, warnings: Vec) -> Self { + self.warnings = warnings; + self } pub fn modules(&self) -> &[Module] { &self.modules } + + /// What the analysis warned about, such as constructs evaluated while + /// elaborating that no process lowers. + pub fn warnings(&self) -> &[AnalyzerWarning] { + &self.warnings + } } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index 52b1dfd45d4..cb4f97f023d 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -92,37 +92,42 @@ impl ParsedSource { .iter() .map(|source| (source.tree.as_ref(), source.path.as_path())) .collect(); - ast::with_call_sites(|| { - let mut packages = Packages::analyze_with_roots(&trees, roots)?; - for source in sources { - for node in source.tree.as_ref() { - if let sv_parser::RefNode::InterfaceDeclarationAnsi(declaration) = node - && let Some(name) = - ast::component_identifier(&declaration.nodes.0.nodes.3, &source.tree) - && packages - .interface_sources - .insert(name.clone(), (source.tree.clone(), source.path.clone())) - .is_some() - { - return Err(AnalyzerError::DuplicateModule { name }); + let (packages, warnings) = ast::warnings::analyzing(|| { + ast::with_call_sites(|| { + let mut packages = Packages::analyze_with_roots(&trees, roots)?; + for source in sources { + for node in source.tree.as_ref() { + if let sv_parser::RefNode::InterfaceDeclarationAnsi(declaration) = node + && let Some(name) = ast::component_identifier( + &declaration.nodes.0.nodes.3, + &source.tree, + ) + && packages + .interface_sources + .insert(name.clone(), (source.tree.clone(), source.path.clone())) + .is_some() + { + return Err(AnalyzerError::DuplicateModule { name }); + } } } - } - if !packages.interface_sources.is_empty() - && trees.iter().any(|(tree, _)| { - tree.into_iter() - .any(|node| matches!(node, sv_parser::RefNode::InterfacePortHeader(_))) - }) - { - let sources = sources - .iter() - .map(|source| (source.code.as_ref(), source.path.as_path())) - .collect::>(); - packages.interface_plan = - std::sync::Arc::new(ast::interfaces::plan_interfaces(&sources, &[])?); - } - Ok(packages) - }) + if !packages.interface_sources.is_empty() + && trees.iter().any(|(tree, _)| { + tree.into_iter() + .any(|node| matches!(node, sv_parser::RefNode::InterfacePortHeader(_))) + }) + { + let sources = sources + .iter() + .map(|source| (source.code.as_ref(), source.path.as_path())) + .collect::>(); + packages.interface_plan = + std::sync::Arc::new(ast::interfaces::plan_interfaces(&sources, &[])?); + } + Ok(packages) + }) + }); + packages.map(|packages| packages.with_warnings(warnings)) } /// Analyze an instance using its value and caller-resolved type bindings. @@ -202,23 +207,26 @@ impl ParsedSource { .iter() .map(|(name, value)| (name.clone(), value.clone().into())) .collect(); - ast::with_call_sites(|| { - let source = ast::Source::from_indexed_syntax_module( - &self.tree, - &self.path, - &self.index, - module_name, - ast::ModuleParameterBindings { - declarations_only: false, - values: &overrides, - types: type_overrides, - patterns: pattern_overrides, - }, - interfaces, - packages, - )?; - analyze::analyze_source(source) - }) + let (ir, warnings) = ast::warnings::analyzing(|| { + ast::with_call_sites(|| { + let source = ast::Source::from_indexed_syntax_module( + &self.tree, + &self.path, + &self.index, + module_name, + ast::ModuleParameterBindings { + declarations_only: false, + values: &overrides, + types: type_overrides, + patterns: pattern_overrides, + }, + interfaces, + packages, + )?; + analyze::analyze_source(source) + }) + }); + ir.map(|ir| ir.with_warnings(warnings)) } } diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index b62857840c0..4d8e596fa3b 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -729,11 +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 only the last one's warnings - // are kept. - let earlier_warnings = sv_warnings.len(); + // 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 { - sv_warnings.truncate(earlier_warnings); + let mut warnings = Vec::new(); let borrowed_sources = sources .iter() .map(|(source, path)| (source.as_str(), path.as_path())) @@ -826,13 +827,26 @@ pub fn parse_mixed( Some(&mut resolver), sv_top_parameters, &requests, - sv_warnings, - ) - .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 056e2532d14..e33f5484318 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, @@ -358,27 +368,41 @@ fn analyze( } #[cfg(feature = "systemverilog")] let mut sv_interface_signatures = Vec::new(); + // Lowering the design reports the warnings of the interface probes + // again, for its own parameters. These are reported only when the build + // fails before that. + #[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(), 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("")) { @@ -388,7 +412,7 @@ fn analyze( Err(SimulatorError::new(SimulatorErrorKind::Syntax(error))), errors, Vec::new(), - Vec::new(), + sv_compilation_warnings(sv_probe_warnings), ); } }; @@ -421,7 +445,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(), 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)); @@ -613,10 +641,16 @@ fn analyze( }) .map_err(SimulatorError::from); #[cfg(feature = "systemverilog")] - let elaboration_warnings = sv_warnings - .into_iter() - .map(CompilationWarning::SystemVerilog) - .collect(); + let elaboration_warnings = { + if sir.is_err() || errors.iter().any(AnalyzerError::is_error) { + for warning in sv_probe_warnings { + if !sv_warnings.contains(&warning) { + sv_warnings.push(warning); + } + } + } + sv_compilation_warnings(sv_warnings) + }; #[cfg(not(feature = "systemverilog"))] let elaboration_warnings = Vec::new(); (sir, errors, frontend_diagnostics, elaboration_warnings) diff --git a/crates/celox/tests/frontends/systemverilog/mixed.rs b/crates/celox/tests/frontends/systemverilog/mixed.rs index ccc6de4abdf..635712fa3a9 100644 --- a/crates/celox/tests/frontends/systemverilog/mixed.rs +++ b/crates/celox/tests/frontends/systemverilog/mixed.rs @@ -1599,3 +1599,113 @@ 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; endmodule"; + let sim = Simulator::from_sv_sources( + vec![(&bus, Path::new("bus.sv")), (top, Path::new("top.sv"))], + "Top", + ) + .build_cranelift() + .unwrap(); + assert_eq!(located(sim.warnings()), expected); +} diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 2fb0c6ea359..2a272a0f7fc 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -1560,6 +1560,122 @@ 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();") + ] + ); +} + +/// 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 = [ diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 973e470ac61..9fc4f9bda48 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -322,7 +322,8 @@ imports, task imports, exports, packed vector arguments (`svBitVecVal` / - **`$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, with a compilation warning - (`Simulator::warnings()`) at the call. + (`Simulator::warnings()`) at the call. This includes a call in a constant + function. - **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. diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 3770f307344..cdbc45167a9 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -260,8 +260,7 @@ Icarus Verilog などそれを実装するシミュレータと同じ値を返 表示しません。VPI ホストのように対話モードを持たないバッチ実行では `$stop` で終了します。 `$exit` は呼び出した program ブロックの initial 手続きを終了します(24.7)。 Celox は program ブロックを持たず、それ以外からの呼び出しは 24.7 の規定どおり無視し、 -その呼び出し位置でコンパイル警告(`Simulator::warnings()`)を出します。 - +その呼び出し位置でコンパイル警告(`Simulator::warnings()`)を出します。定数関数内の呼び出しも同様です。 `Simulation` は設計全体の時間精度(IEEE 1800-2023 3.14.3)で時刻を数えます。 既定は 1 ps で、`run_until(1000)` は 1 ns まで進めます。時間単位が 1 ns の From 841d49fbec7dad2cb6ccf3d3f73d59f68ec26649 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 18 Oct 2026 21:25:17 +0900 Subject: [PATCH 5/5] fix(sv): own compilation diagnostics explicitly Derive constant-function diagnostics from declarations without a thread-local collector or interpreter side effects. Cache immutable per-component metadata in ParsedSource and publish warnings through IR and AnalyzerError on success and failure. Preserve underlying error classification and source chaining. Diagnose ignored $exit calls in function declarations even when unused; document this policy and test module isolation and failed package/interface analyses. Preserve warnings through interface probing, simulator initialization and test-runner validation errors. Deduplicate by source call and category across parameterized specializations, retaining payload identity for unlocated calls. Keep foreign-codegen builds warning-free. Track interface-probe diagnostic provenance investigation in #1512. AnalyzerError gains WithWarnings with warnings() and into_error() accessors; the unreleased ambient collect_warnings API is removed. Change-Id: I44fd6f2cc3ae57cf1c231bb8fa13bfa264c5d300 --- crates/celox-frontend-sv/src/lowering.rs | 36 ++- crates/celox-frontend-sv/src/warning.rs | 29 +- crates/celox-sv-analyzer/src/analyze.rs | 5 + crates/celox-sv-analyzer/src/ast.rs | 8 + .../src/ast/const_functions.rs | 41 ++- .../celox-sv-analyzer/src/ast/interfaces.rs | 273 ++++++++++-------- crates/celox-sv-analyzer/src/ast/packages.rs | 16 +- .../celox-sv-analyzer/src/ast/procedural.rs | 5 +- crates/celox-sv-analyzer/src/ast/warnings.rs | 112 +++++-- crates/celox-sv-analyzer/src/ir.rs | 11 +- crates/celox-sv-analyzer/src/lib.rs | 84 +++++- crates/celox-sv-analyzer/src/parsed.rs | 116 ++++---- crates/celox-sv-analyzer/src/tests.rs | 153 ++++++++++ crates/celox/src/parser.rs | 4 +- crates/celox/src/simulator/builder.rs | 164 +++++++---- .../tests/frontends/systemverilog/mixed.rs | 138 ++++++++- .../systemverilog/system_functions.rs | 131 +++++++++ crates/celox/tests/sv_dpi.rs | 16 + docs/guide/systemverilog.md | 3 +- docs/ja/guide/systemverilog.md | 1 + 20 files changed, 1057 insertions(+), 289 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 425a3e8c702..2b85f9c4d3c 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -227,10 +227,20 @@ pub fn interface_signatures_for( ) -> 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>, @@ -714,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( @@ -723,7 +746,6 @@ fn lower_package_states( ff_parts: bool, warnings: &mut Vec, ) -> Result, sv::AnalyzerError> { - warnings.extend(crate::warning::analyzer_warnings(packages.warnings())); let mut states = packages.state_modules().collect::>(); states.sort_by(|left, right| left.name().cmp(right.name())); states @@ -1224,6 +1246,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( requests, &mut found, ); + append_error_warnings(&hierarchy, &mut found); crate::warning::append_unique_warnings(sources, warnings, found); hierarchy } @@ -1247,6 +1270,7 @@ fn prepare_external_hierarchy_collecting( 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(""), @@ -1641,6 +1665,7 @@ pub fn schedule_sources( trace, &mut found, ); + append_error_warnings(&scheduled, &mut found); crate::warning::append_unique_warnings(sources, warnings, found); scheduled } @@ -1666,6 +1691,7 @@ fn schedule_sources_collecting( 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(), @@ -1873,14 +1899,18 @@ 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() diff --git a/crates/celox-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs index d8610c95705..bd394ddd465 100644 --- a/crates/celox-frontend-sv/src/warning.rs +++ b/crates/celox-frontend-sv/src/warning.rs @@ -14,16 +14,19 @@ pub struct FrontendWarning { pub location: Option, } -/// Warnings are the same when they report the same thing at the same place. +/// 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 { - let place = |warning: &Self| { - warning - .location - .as_ref() - .map(|location| (location.path.clone(), location.line, location.column)) - }; - self.kind == other.kind && place(self) == place(other) + 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, + } } } @@ -100,7 +103,15 @@ pub(crate) fn append_unique_warnings( found.sort_by(|(left_kind, left), (right_kind, right)| { (left, left_kind).cmp(&(right, right_kind)) }); - found.dedup(); + 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| { 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 193e67fb71e..d18ded4e134 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -423,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 0fcdec0d2d3..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 { @@ -1160,15 +1190,8 @@ impl Frame<'_> { } // Messages have no effect on the value. Unknown and unsupported // system tasks are rejected before elaboration. `$exit` is - // ignored outside a program block (IEEE 1800-2023 24.7), and is - // reported like the `$exit` of a process. - Stmt::SystemTask { - task: crate::system_functions::SystemTask::Exit, - site, - .. - } => super::warnings::warn(super::warnings::AnalyzerWarning::ExitOutsideProgram { - site: site.clone(), - }), + // 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 a9b528e2bf3..2ef6fb40a2b 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -47,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() @@ -70,145 +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| { - // Analyzing the signature evaluates constant functions, which can - // warn. - let (prototype, warnings) = - super::warnings::analyzing(|| -> 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 + 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() + .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() - .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 - } + .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 + }) }) - .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 + }) + .map(|member| member.name.clone()) + .collect(), + has_behavior: interface + .items + .iter() + .any(|item| matches!(item, Item::Process(_))) + || 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 - }) + .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()) + } }) - }) - .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(|prototype| InterfacePrototype { - warnings, - ..prototype - }) + .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 746ef813997..6ba11e3ad9c 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -191,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 { @@ -525,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 d11df8167ff..5c140bff305 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -2326,7 +2326,10 @@ pub(super) fn written_names<'s>(stmts: impl IntoIterator) -> Ha /// The span of `node` in the source text before preprocessing, if all of it /// comes from one file. -fn source_span(node: RefNode<'_>, tree: &SyntaxTree) -> Option { +pub(super) fn source_span( + node: RefNode<'_>, + tree: &SyntaxTree, +) -> Option { let origin = |offset| { tree.get_origin(&Locate { offset, diff --git a/crates/celox-sv-analyzer/src/ast/warnings.rs b/crates/celox-sv-analyzer/src/ast/warnings.rs index b69e478b0cd..5f9f7a80166 100644 --- a/crates/celox-sv-analyzer/src/ast/warnings.rs +++ b/crates/celox-sv-analyzer/src/ast/warnings.rs @@ -1,34 +1,106 @@ -//! The warnings of an analysis. - -use std::cell::RefCell; +//! Diagnostics derived from authored function declarations. +use super::*; use crate::procedural::SourceSpan; -/// A warning found while analyzing, before the frontend lowers the design. +/// A non-fatal source diagnostic, independent of constant evaluation. #[derive(Debug, Clone, PartialEq, Eq)] pub enum AnalyzerWarning { - /// `$exit` outside a program block, here in a constant function, which - /// IEEE 1800-2023 24.7 ignores. + /// An ignored `$exit` in a function outside a program (IEEE 1800-2023 24.7). ExitOutsideProgram { site: Option }, } -thread_local! { - static WARNINGS: RefCell>> = const { RefCell::new(None) }; +pub(crate) fn append( + warnings: &mut Vec, + found: impl IntoIterator, +) { + for warning in found { + if !warnings.contains(&warning) { + warnings.push(warning); + } + } } -/// Run one analysis and return the warnings it found. -pub(crate) fn analyzing(f: impl FnOnce() -> T) -> (T, Vec) { - let saved = WARNINGS.with(|current| current.replace(Some(Vec::new()))); - let result = f(); - let warnings = WARNINGS.with(|current| current.replace(saved)); - (result, warnings.unwrap_or_default()) +/// 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 } -/// Report `warning` with the analysis that is running, if any. -pub(super) fn warn(warning: AnalyzerWarning) { - WARNINGS.with(|current| { - if let Some(warnings) = &mut *current.borrow_mut() { - warnings.push(warning); +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 0b12e5fd38a..996001162ea 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -32,8 +32,13 @@ impl Ir { } } + /// Merge warnings from nested analyses, reporting each source call once. pub(crate) fn with_warnings(mut self, warnings: Vec) -> Self { - self.warnings = warnings; + for warning in warnings { + if !self.warnings.contains(&warning) { + self.warnings.push(warning); + } + } self } @@ -41,8 +46,8 @@ impl Ir { &self.modules } - /// What the analysis warned about, such as constructs evaluated while - /// elaborating that no process lowers. + /// Source diagnostics of the analyzed declarations, including functions + /// whose bodies disappear during constant elaboration. pub fn warnings(&self) -> &[AnalyzerWarning] { &self.warnings } 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 cb4f97f023d..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,42 +97,43 @@ impl ParsedSource { .iter() .map(|source| (source.tree.as_ref(), source.path.as_path())) .collect(); - let (packages, warnings) = ast::warnings::analyzing(|| { - ast::with_call_sites(|| { - let mut packages = Packages::analyze_with_roots(&trees, roots)?; - for source in sources { - for node in source.tree.as_ref() { - if let sv_parser::RefNode::InterfaceDeclarationAnsi(declaration) = node - && let Some(name) = ast::component_identifier( - &declaration.nodes.0.nodes.3, - &source.tree, - ) - && packages - .interface_sources - .insert(name.clone(), (source.tree.clone(), source.path.clone())) - .is_some() - { - return Err(AnalyzerError::DuplicateModule { name }); - } + 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 + && let Some(name) = + ast::component_identifier(&declaration.nodes.0.nodes.3, &source.tree) + && packages + .interface_sources + .insert(name.clone(), (source.tree.clone(), source.path.clone())) + .is_some() + { + return Err(AnalyzerError::DuplicateModule { name }); } } - if !packages.interface_sources.is_empty() - && trees.iter().any(|(tree, _)| { - tree.into_iter() - .any(|node| matches!(node, sv_parser::RefNode::InterfacePortHeader(_))) - }) - { - let sources = sources - .iter() - .map(|source| (source.code.as_ref(), source.path.as_path())) - .collect::>(); - packages.interface_plan = - std::sync::Arc::new(ast::interfaces::plan_interfaces(&sources, &[])?); - } - Ok(packages) - }) + } + if !packages.interface_sources.is_empty() + && trees.iter().any(|(tree, _)| { + tree.into_iter() + .any(|node| matches!(node, sv_parser::RefNode::InterfacePortHeader(_))) + }) + { + let sources = sources + .iter() + .map(|source| (source.code.as_ref(), source.path.as_path())) + .collect::>(); + packages.interface_plan = + std::sync::Arc::new(ast::interfaces::plan_interfaces(&sources, &[])?); + } + Ok(packages) }); - packages.map(|packages| packages.with_warnings(warnings)) + 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. @@ -207,26 +213,30 @@ impl ParsedSource { .iter() .map(|(name, value)| (name.clone(), value.clone().into())) .collect(); - let (ir, warnings) = ast::warnings::analyzing(|| { - ast::with_call_sites(|| { - let source = ast::Source::from_indexed_syntax_module( - &self.tree, - &self.path, - &self.index, - module_name, - ast::ModuleParameterBindings { - declarations_only: false, - values: &overrides, - types: type_overrides, - patterns: pattern_overrides, - }, - interfaces, - packages, - )?; - analyze::analyze_source(source) - }) + 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, + &self.index, + module_name, + ast::ModuleParameterBindings { + declarations_only: false, + values: &overrides, + types: type_overrides, + patterns: pattern_overrides, + }, + interfaces, + packages, + )?; + analyze::analyze_source(source) }); - ir.map(|ir| ir.with_warnings(warnings)) + crate::finish_analysis(ir, warnings) } } 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/parser.rs b/crates/celox/src/parser.rs index 4d8e596fa3b..a6d96f03382 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -635,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", diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index e33f5484318..f59ba796e9b 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -368,9 +368,8 @@ fn analyze( } #[cfg(feature = "systemverilog")] let mut sv_interface_signatures = Vec::new(); - // Lowering the design reports the warnings of the interface probes - // again, for its own parameters. These are reported only when the build - // fails before that. + // 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")] @@ -642,13 +641,23 @@ fn analyze( .map_err(SimulatorError::from); #[cfg(feature = "systemverilog")] let elaboration_warnings = { - if sir.is_err() || errors.iter().any(AnalyzerError::is_error) { - for warning in sv_probe_warnings { - if !sv_warnings.contains(&warning) { - sv_warnings.push(warning); - } + 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"))] @@ -1406,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( @@ -1414,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); @@ -1423,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()); } @@ -1449,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, @@ -2241,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, @@ -2327,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, @@ -2365,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 { @@ -2384,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(); } @@ -2403,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) } @@ -2426,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 { @@ -2436,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); @@ -2449,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) } @@ -2499,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) } @@ -2563,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) } @@ -2580,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, )?; @@ -2591,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()); } @@ -2621,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), @@ -2636,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()); } @@ -2748,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); @@ -2762,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) } @@ -2799,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, @@ -2883,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() { @@ -2905,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); @@ -2926,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) }); @@ -2950,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 { @@ -3103,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( @@ -3122,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/tests/frontends/systemverilog/mixed.rs b/crates/celox/tests/frontends/systemverilog/mixed.rs index 635712fa3a9..ecaff45f62a 100644 --- a/crates/celox/tests/frontends/systemverilog/mixed.rs +++ b/crates/celox/tests/frontends/systemverilog/mixed.rs @@ -1700,12 +1700,148 @@ endinterface .build_cranelift() .unwrap(); assert_eq!(located(sim.warnings()), expected); - let top = "module Top(output logic [7:0] y); Bus bus(); assign y = bus.req; endmodule"; + 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 2a272a0f7fc..515c2e3202f 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -1642,6 +1642,32 @@ fn exit_in_a_constant_function_warns_at_the_call() { ); } +#[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] @@ -2904,3 +2930,108 @@ fn readmem_warnings_survive_a_later_lowering_error() { )] ); } + +#[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 9fc4f9bda48..acf4ad8b874 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -323,7 +323,8 @@ imports, task imports, exports, packed vector arguments (`svBitVecVal` / (24.7). Celox has no program blocks, and a call from anywhere else is ignored, as 24.7 specifies, with a compilation warning (`Simulator::warnings()`) at the call. This includes a call in a constant - function. + 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. diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index cdbc45167a9..cba9fd76e3d 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -261,6 +261,7 @@ Icarus Verilog などそれを実装するシミュレータと同じ値を返 `$exit` は呼び出した program ブロックの initial 手続きを終了します(24.7)。 Celox は program ブロックを持たず、それ以外からの呼び出しは 24.7 の規定どおり無視し、 その呼び出し位置でコンパイル警告(`Simulator::warnings()`)を出します。定数関数内の呼び出しも同様です。 +関数宣言内の呼び出しは、その関数を使わなくても警告します。定数評価が実行したかどうかには依存しません。 `Simulation` は設計全体の時間精度(IEEE 1800-2023 3.14.3)で時刻を数えます。 既定は 1 ps で、`run_until(1000)` は 1 ns まで進めます。時間単位が 1 ns の