diff --git a/crates/celox-frontend-sv/src/lib.rs b/crates/celox-frontend-sv/src/lib.rs index 4bbdeeadcad..ec528a33eac 100644 --- a/crates/celox-frontend-sv/src/lib.rs +++ b/crates/celox-frontend-sv/src/lib.rs @@ -47,3 +47,9 @@ pub use lowering::{ schedule_sources, }; pub use lowering::{InterfaceSignature, interface_signatures, interface_signatures_for}; + +pub use celox_sv_analyzer::AnalysisOptions; +pub use lowering::{ + interface_signatures_for_with_options, + prepare_external_hierarchy_with_foreign_resolver_with_options, schedule_sources_with_options, +}; diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index d7d2f82bbc5..6438f34a334 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -187,6 +187,7 @@ impl LoweredSvModuleKey { fn analyze_sources( sources: &[(&str, &Path)], roots: &[&str], + analysis_options: sv::AnalysisOptions, ) -> Result, sv::AnalyzerError> { analyze_sources_with_requests( sources, @@ -194,6 +195,7 @@ fn analyze_sources( &[], &[], Some(roots), + analysis_options, ) .map(|(modules, _)| modules) } @@ -224,9 +226,19 @@ pub fn interface_signatures_for( sources: &[(&str, &Path)], names: Option<&HashSet>, warnings: &mut Vec, +) -> Result, FrontendError> { + interface_signatures_for_with_options(sources, names, warnings, sv::AnalysisOptions::default()) +} + +/// Probe interface signatures with explicit language compatibility options. +pub fn interface_signatures_for_with_options( + sources: &[(&str, &Path)], + names: Option<&HashSet>, + warnings: &mut Vec, + analysis_options: sv::AnalysisOptions, ) -> Result, FrontendError> { let mut found = Vec::new(); - let signatures = interface_signatures_collecting(sources, names, &mut found); + let signatures = interface_signatures_collecting(sources, names, &mut found, analysis_options); append_error_warnings(&signatures, &mut found); crate::warning::append_unique_warnings(sources, warnings, found); signatures @@ -245,8 +257,9 @@ fn interface_signatures_collecting( sources: &[(&str, &Path)], names: Option<&HashSet>, warnings: &mut Vec, + analysis_options: sv::AnalysisOptions, ) -> Result, FrontendError> { - let prototypes = sv::interface_prototypes_for(sources, names)?; + let prototypes = sv::interface_prototypes_with_options(sources, names, analysis_options)?; if prototypes.is_empty() { return Ok(Vec::new()); } @@ -321,6 +334,7 @@ fn analyze_sources_with_requests( declarations: &[(&str, &Path)], requests: &[SvModuleRequest], roots: Option<&[&str]>, + analysis_options: sv::AnalysisOptions, ) -> Result<(HashMap, HashMap), sv::AnalyzerError> { if !declarations.is_empty() { for (code, path) in sources { @@ -347,7 +361,11 @@ fn analyze_sources_with_requests( .collect::>() }); let time_declarations = if declarations.iter().any(|(code, _)| !code.is_empty()) { - sv::generated_time_declarations(sources, selected_roots.as_deref())? + sv::generated_time_declarations_with_options( + sources, + selected_roots.as_deref(), + analysis_options, + )? } else { String::new() }; @@ -433,9 +451,13 @@ fn analyze_sources_with_requests( .unwrap_or(root) }) .collect::>(); - sv::ParsedSource::analyze_packages_with_roots(&parsed, &roots)? + sv::ParsedSource::analyze_packages_with_options( + &parsed, + Some(&roots), + analysis_options, + )? } - None => sv::ParsedSource::analyze_packages(&parsed)?, + None => sv::ParsedSource::analyze_packages_with_options(&parsed, None, analysis_options)?, }; packages.set_interface_plan(elaboration.clone()); let packages = std::rc::Rc::new(packages); @@ -1233,6 +1255,34 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( top_parameters: Option<(&str, &[(String, u64)])>, requests: &[SvModuleRequest], warnings: &mut Vec, +) -> Result { + prepare_external_hierarchy_with_foreign_resolver_with_options( + sources, + root_names, + foreign, + declarations, + four_state, + resolver, + top_parameters, + requests, + warnings, + sv::AnalysisOptions::default(), + ) +} + +/// Prepare a mixed hierarchy with explicit language compatibility options. +#[allow(clippy::too_many_arguments)] +pub fn prepare_external_hierarchy_with_foreign_resolver_with_options( + 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, + analysis_options: sv::AnalysisOptions, ) -> Result { let mut found = Vec::new(); let hierarchy = prepare_external_hierarchy_collecting( @@ -1245,6 +1295,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( top_parameters, requests, &mut found, + analysis_options, ); append_error_warnings(&hierarchy, &mut found); crate::warning::append_unique_warnings(sources, warnings, found); @@ -1262,6 +1313,7 @@ fn prepare_external_hierarchy_collecting( top_parameters: Option<(&str, &[(String, u64)])>, requests: &[SvModuleRequest], warnings: &mut Vec, + analysis_options: sv::AnalysisOptions, ) -> Result { let (analyzed, bound_names) = analyze_sources_with_requests( sources, @@ -1269,6 +1321,7 @@ fn prepare_external_hierarchy_collecting( declarations, requests, Some(&root_names.iter().map(String::as_str).collect::>()), + analysis_options, )?; package_warnings(&analyzed, warnings); let dummy = sv::ParsedSource::parse( @@ -1651,6 +1704,43 @@ pub fn schedule_sources( trace_options: &FrontendTraceOptions, trace: Option<&mut FrontendTrace>, warnings: &mut Vec, +) -> Result { + schedule_sources_with_options( + sources, + top, + parameter_overrides, + ignored_loops, + true_loops, + four_state, + parallel, + trace_options, + trace, + warnings, + sv::AnalysisOptions::default(), + ) +} + +/// Schedule a design with explicit language compatibility options. +#[allow(clippy::too_many_arguments)] +pub fn schedule_sources_with_options( + 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, + analysis_options: sv::AnalysisOptions, ) -> Result { let mut found = Vec::new(); let scheduled = schedule_sources_collecting( @@ -1664,6 +1754,7 @@ pub fn schedule_sources( trace_options, trace, &mut found, + analysis_options, ); append_error_warnings(&scheduled, &mut found); crate::warning::append_unique_warnings(sources, warnings, found); @@ -1689,8 +1780,9 @@ fn schedule_sources_collecting( trace_options: &FrontendTraceOptions, trace: Option<&mut FrontendTrace>, warnings: &mut Vec, + analysis_options: sv::AnalysisOptions, ) -> Result { - let analyzed = analyze_sources(sources, &[top])?; + let analyzed = analyze_sources(sources, &[top], analysis_options)?; package_warnings(&analyzed, warnings); let top = top.to_string(); let root_key = LoweredSvModuleKey { diff --git a/crates/celox-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs index bd394ddd465..3ae40680a8f 100644 --- a/crates/celox-frontend-sv/src/warning.rs +++ b/crates/celox-frontend-sv/src/warning.rs @@ -35,6 +35,9 @@ impl Eq for FrontendWarning {} /// What a [`FrontendWarning`] reports. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, thiserror::Error)] pub enum FrontendWarningKind { + /// IEEE 1800-2023 3.14.2.3 requires consistent explicit timing declarations. + #[error("mixed explicit and default time units or precisions across design elements")] + MixedTimescale, /// A memory file without address directives holds a different number of /// words than the address range of `$readmemh`/`$readmemb` /// (IEEE 1800-2023 21.4). @@ -85,6 +88,9 @@ pub(crate) fn analyzer_warnings( found: &[celox_sv_analyzer::ir::AnalyzerWarning], ) -> impl Iterator + '_ { found.iter().map(|warning| match warning { + celox_sv_analyzer::ir::AnalyzerWarning::MixedTimescale => { + (FrontendWarningKind::MixedTimescale, None) + } celox_sv_analyzer::ir::AnalyzerWarning::ExitOutsideProgram { site } => { (FrontendWarningKind::ExitOutsideProgram, site.clone()) } @@ -134,6 +140,7 @@ pub(crate) fn append_unique_warnings( impl miette::Diagnostic for FrontendWarning { fn code<'a>(&'a self) -> Option> { Some(Box::new(match self.kind { + FrontendWarningKind::MixedTimescale => "mixed_timescale", FrontendWarningKind::MemoryFileWordCount { .. } => "memory_file_word_count", FrontendWarningKind::ExitOutsideProgram => "exit_outside_program", })) @@ -145,6 +152,9 @@ impl miette::Diagnostic for FrontendWarning { fn help<'a>(&'a self) -> Option> { Some(Box::new(match self.kind { + FrontendWarningKind::MixedTimescale => { + "declare timeunit/timeprecision consistently; undeclared scopes use 1ns/1ps when this check is relaxed" + } FrontendWarningKind::MemoryFileWordCount { .. } => { "give one word per address of the range, or place the words with `@address` directives" } diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index 4db8c62de46..a96640a9df6 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -117,6 +117,7 @@ pub struct NapiOptions { /// Parsed builder options from NapiOptions (common fields available on all targets). #[allow(dead_code)] struct ParsedOptionsCommon { + diagnostic_policy: celox::DiagnosticPolicy, four_state: bool, optimize_options: celox::OptimizeOptions, vcd: Option, @@ -378,6 +379,7 @@ fn parse_options_common(options: &Option) -> Result) -> Result Ok(ParsedOptionsCommon { + diagnostic_policy: Default::default(), four_state: false, optimize_options: celox::OptimizeOptions::all(), vcd: None, @@ -470,6 +473,8 @@ fn append_extra_source(sources: &mut Vec<(String, std::path::PathBuf)>, extra: & #[derive(serde::Deserialize, Default)] #[allow(dead_code)] struct CeloxConfig { + #[serde(default)] + diagnostics: celox::DiagnosticPolicy, /// Glob patterns (relative to project root) for `.veryl` files to exclude /// from compilation and type generation. #[serde(default)] @@ -630,6 +635,7 @@ fn apply_options<'a, T>( mut builder: celox::SimulatorBuilder<'a, T>, opts: &ParsedOptions, ) -> celox::SimulatorBuilder<'a, T> { + builder = builder.diagnostic_policy(opts.diagnostic_policy.clone()); builder = builder.four_state(opts.four_state); builder = builder.optimize_options(opts.optimize_options.clone()); builder = builder.threads(opts.optimize_options.parallel_lanes() as usize); @@ -699,6 +705,7 @@ struct CachedBuild { /// produce identical compiled code. #[derive(Clone, Debug, PartialEq, Eq, Hash)] struct CacheKey { + diagnostic_policy: celox::DiagnosticPolicy, /// (path, content) sorted by path for determinism. sources: Vec<(String, String)>, top: String, @@ -778,6 +785,7 @@ fn build_cache_key( sorted_sources.sort_by(|a, b| a.0.cmp(&b.0)); CacheKey { + diagnostic_policy: opts.diagnostic_policy.clone(), sources: sorted_sources, top: top.to_string(), four_state: opts.four_state, @@ -1374,8 +1382,9 @@ impl NativeSimulatorHandle { top: String, options: Option, ) -> Result { - let opts = parse_options(&options)?; - let (mut sources, metadata, _celox_cfg) = load_project_sources(&project_path)?; + let mut opts = parse_options(&options)?; + let (mut sources, metadata, celox_cfg) = load_project_sources(&project_path)?; + opts.common.diagnostic_policy = celox_cfg.diagnostics.clone(); append_extra_source(&mut sources, &opts.extra_source); let source_refs: Vec<(&str, &std::path::Path)> = sources @@ -1416,8 +1425,9 @@ impl NativeSimulatorHandle { top: String, options: Option, ) -> Result { - let opts = parse_options(&options)?; - let (mut sources, metadata, _celox_cfg) = load_project_sources(&project_path)?; + let mut opts = parse_options(&options)?; + let (mut sources, metadata, celox_cfg) = load_project_sources(&project_path)?; + opts.common.diagnostic_policy = celox_cfg.diagnostics.clone(); append_extra_source(&mut sources, &opts.extra_source); let cache_key = build_cache_key(&sources, &top, &opts, Some(&metadata)); @@ -1915,8 +1925,9 @@ impl NativeSimulationHandle { top: String, options: Option, ) -> Result { - let opts = parse_options(&options)?; + let mut opts = parse_options(&options)?; let (mut sources, metadata, celox_cfg) = load_project_sources(&project_path)?; + opts.common.diagnostic_policy = celox_cfg.diagnostics.clone(); append_extra_source(&mut sources, &opts.extra_source); let source_refs: Vec<(&str, &std::path::Path)> = sources .iter() @@ -2408,8 +2419,9 @@ impl NativeSimulatorHandle { top: String, options: Option, ) -> Result { - let opts = parse_options_common(&options)?; - let (mut sources, metadata, _celox_cfg) = load_project_sources(&project_path)?; + let mut opts = parse_options_common(&options)?; + let (mut sources, metadata, celox_cfg) = load_project_sources(&project_path)?; + opts.diagnostic_policy = celox_cfg.diagnostics.clone(); append_extra_source(&mut sources, &opts.extra_source); let source_refs: Vec<(&str, &std::path::Path)> = sources @@ -2418,7 +2430,7 @@ impl NativeSimulatorHandle { .collect(); let trace_opts = celox::TraceOptions::default(); - let (program, warnings) = celox::compile_to_sir( + let (program, mut warnings) = celox::compile_to_sir( &source_refs, &top, &opts @@ -2440,8 +2452,17 @@ impl NativeSimulatorHandle { &opts.parameters, &opts.optimize_options, ) - .map_err(|e| Error::from_reason(format!("{}", e)))?; + .map_err(|error| { + Error::from_reason( + error + .apply_diagnostic_policy(&opts.diagnostic_policy) + .to_string(), + ) + })?; + opts.diagnostic_policy + .apply(&mut warnings) + .map_err(|error| Error::from_reason(error.to_string()))?; let laid_out = program.into_laid_out(opts.four_state); let layout = laid_out.layout(); @@ -3358,8 +3379,9 @@ pub fn run_test_from_project( options: Option, components: Option>, ) -> Result { - let opts = parse_options(&options)?; - let (mut sources, metadata, _celox_cfg) = load_project_sources(&project_path)?; + let mut opts = parse_options(&options)?; + let (mut sources, metadata, celox_cfg) = load_project_sources(&project_path)?; + opts.common.diagnostic_policy = celox_cfg.diagnostics.clone(); append_extra_source(&mut sources, &opts.extra_source); let source_refs: Vec<(&str, &std::path::Path)> = sources @@ -3765,6 +3787,7 @@ mod tests { fn default_opts() -> ParsedOptions { ParsedOptions { common: ParsedOptionsCommon { + diagnostic_policy: Default::default(), four_state: false, optimize_options: celox::OptimizeOptions::all(), vcd: None, @@ -4131,6 +4154,47 @@ mod tests { } } + #[test] + fn project_diagnostic_policy_changes_invalidate_cached_compilation() { + let project = tempfile::tempdir().unwrap(); + std::fs::create_dir(project.path().join("src")).unwrap(); + std::fs::write( + project.path().join("Veryl.toml"), + "[project]\nname = \"diagnostic_policy\"\nversion = \"0.1.0\"\n", + ) + .unwrap(); + let source = r#"module Top (tmp: output logic<8>, out: output logic) { + function f(a: output logic<8>, b: output logic<8>) -> logic { + a = 1; b = 2; return 1'b1; + } + always_comb { tmp = 0; out = f(b: tmp, a: tmp) & 1'b1; } + }"#; + std::fs::write(project.path().join("src/top.veryl"), source).unwrap(); + let path = project.path().to_str().unwrap().to_string(); + let config = project.path().join("celox.toml"); + for level in ["allow", "warn", "error"] { + std::fs::write( + &config, + format!("[diagnostics]\nunspecified_output_copy_order = '{level}'\n"), + ) + .unwrap(); + let result = NativeSimulatorHandle::from_project(path.clone(), "Top".into(), None); + if level == "error" { + assert!( + result + .err() + .unwrap() + .reason + .contains("unspecified_output_copy_order") + ); + } else { + let handle = result.unwrap(); + let warnings: Vec = serde_json::from_str(&handle.warnings_json()).unwrap(); + assert_eq!(warnings.len(), usize::from(level == "warn")); + } + } + } + #[test] fn normal_project_loading_excludes_example_sources() { let project = tempfile::tempdir().unwrap(); diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index c8b6dfe56d7..7ecddab92a6 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -138,7 +138,7 @@ mod selects; mod shared_map; mod statements; mod subroutine_owners; -mod timescales; +pub(crate) mod timescales; pub(crate) mod type_parameters; mod types; mod validation; @@ -1422,7 +1422,7 @@ pub(crate) fn generated_time_declarations( sources: &[(&str, &std::path::Path)], roots: Option<&[&str]>, ) -> Result { - timescales::generated_source_declarations(sources, roots) + timescales::generated_source_declarations(sources, roots, false) } const MAX_GENERATE_LOOP_EXPANSION: usize = 10_000; diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 4e4abec4ebd..3f9528843b4 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -168,6 +168,12 @@ impl ConstantFunctions { super::warnings::AnalyzerWarning::ExitOutsideProgram { site: left }, super::warnings::AnalyzerWarning::ExitOutsideProgram { site: right }, ) => left.cmp(right), + ( + super::warnings::AnalyzerWarning::MixedTimescale, + super::warnings::AnalyzerWarning::MixedTimescale, + ) => std::cmp::Ordering::Equal, + (super::warnings::AnalyzerWarning::MixedTimescale, _) => std::cmp::Ordering::Less, + (_, super::warnings::AnalyzerWarning::MixedTimescale) => std::cmp::Ordering::Greater, }); warnings } diff --git a/crates/celox-sv-analyzer/src/ast/interfaces.rs b/crates/celox-sv-analyzer/src/ast/interfaces.rs index 21a85db2487..1b2f7aa96c9 100644 --- a/crates/celox-sv-analyzer/src/ast/interfaces.rs +++ b/crates/celox-sv-analyzer/src/ast/interfaces.rs @@ -43,6 +43,15 @@ pub fn interface_prototypes( pub fn interface_prototypes_for( sources: &[(&str, &Path)], selected: Option<&HashSet>, +) -> Result, AnalyzerError> { + interface_prototypes_with_options(sources, selected, crate::AnalysisOptions::default()) +} + +/// Analyze interface prototypes using the selected compatibility policy. +pub fn interface_prototypes_with_options( + sources: &[(&str, &Path)], + selected: Option<&HashSet>, + options: crate::AnalysisOptions, ) -> Result, AnalyzerError> { if selected.is_some_and(HashSet::is_empty) { return Ok(Vec::new()); @@ -74,12 +83,13 @@ pub fn interface_prototypes_for( let timescales = if declarations.is_empty() { None } else { - Some(super::timescales::Timescales::collect( + Some(super::timescales::Timescales::collect_with_options( &files .iter() .zip(sources) .map(|(file, (_, path))| (&file.syntax_tree, *path)) .collect::>(), + options.allow_mixed_timescales, )?) }; let trees = files @@ -87,8 +97,9 @@ pub fn interface_prototypes_for( .zip(sources) .map(|(file, (_, path))| (&file.syntax_tree, *path)) .collect::>(); - let packages = packages::Packages::analyze(&trees) - .map_err(|error| error.with_warnings(source_warnings))?; + let packages = + packages::Packages::analyze_with_options(&trees, None, options.allow_mixed_timescales) + .map_err(|error| error.with_warnings(source_warnings))?; let package_warnings = packages.warnings().to_vec(); let mut used_names = design .modules diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index 93921887be0..397455ff256 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -125,7 +125,7 @@ impl Packages { } pub(crate) fn with_warnings(mut self, warnings: Vec) -> Self { - self.warnings = warnings; + super::warnings::append(&mut self.warnings, warnings); self } @@ -193,12 +193,20 @@ impl Packages { pub(crate) fn analyze_with_roots( trees: &[(&SyntaxTree, &Path)], roots: Option<&[&str]>, + ) -> Result { + Self::analyze_with_options(trees, roots, false) + } + + pub(crate) fn analyze_with_options( + trees: &[(&SyntaxTree, &Path)], + roots: Option<&[&str]>, + allow_mixed_timescales: bool, ) -> 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) { + match Self::analyze_with_roots_impl(trees, roots, allow_mixed_timescales) { Ok(packages) => Ok(packages.with_warnings(warnings)), Err(error) => Err(error.with_warnings(warnings)), } @@ -207,14 +215,22 @@ impl Packages { fn analyze_with_roots_impl( trees: &[(&SyntaxTree, &Path)], roots: Option<&[&str]>, + allow_mixed_timescales: bool, ) -> Result { - let mut timescales = timescales::Timescales::collect(trees)?; + let mut timescales = + timescales::Timescales::collect_with_options(trees, allow_mixed_timescales)?; if let Some(roots) = roots { timescales.select_roots(roots); } + let mixed_timescales = timescales.has_mixed_timescales(); let timescales = Arc::new(timescales); let state = std::rc::Rc::new(AnalysisState::default()); let mut packages = Self::analyze_packages(trees, timescales, &state)?; + if mixed_timescales { + packages + .warnings + .push(super::warnings::AnalyzerWarning::MixedTimescale); + } packages.call_sites = state.next_call_site.clone(); let units: Vec<_> = trees .iter() diff --git a/crates/celox-sv-analyzer/src/ast/timescales.rs b/crates/celox-sv-analyzer/src/ast/timescales.rs index 4674ff9d630..405e542190a 100644 --- a/crates/celox-sv-analyzer/src/ast/timescales.rs +++ b/crates/celox-sv-analyzer/src/ast/timescales.rs @@ -107,6 +107,7 @@ pub(super) struct Timescales { instantiated: HashSet, roots: Option>, specified: [u8; 2], + allow_mixed_timescales: bool, } /// Time-query state owned by one analysis, shared explicitly by nested scopes. @@ -360,16 +361,18 @@ fn time_declarations(unit: Option, precision: Option) -> String { pub(crate) fn generated_source_declarations( sources: &[(&str, &Path)], roots: Option<&[&str]>, + allow_mixed_timescales: bool, ) -> Converted { let trees = sources .iter() .map(|(code, path)| crate::source_tree::parse_source(code, path).map(|tree| (tree, *path))) .collect::>>()?; - let mut scales = Timescales::collect( + let mut scales = Timescales::collect_with_options( &trees .iter() .map(|(tree, path)| (tree, *path)) .collect::>(), + allow_mixed_timescales, )?; if let Some(roots) = roots { scales.select_roots(roots); @@ -497,6 +500,10 @@ fn design_path( } impl Timescales { + pub(super) fn has_mixed_timescales(&self) -> bool { + self.specified.contains(&3) + } + pub(super) fn scope_scale(&self, name: &str) -> Option<(i32, i32)> { let scope = self .definitions @@ -509,12 +516,13 @@ impl Timescales { self.precision.unwrap_or(DEFAULT.precision) } fn including_tree(&self, tree: &SyntaxTree) -> Converted { - let local = Self::collect(&[(tree, Path::new(""))])?; + let local = + Self::collect_with_options(&[(tree, Path::new(""))], self.allow_mixed_timescales)?; let specified = [ self.specified[0] | local.specified[0], self.specified[1] | local.specified[1], ]; - if specified.contains(&3) { + if specified.contains(&3) && !self.allow_mixed_timescales { return Err(unsupported( "mixed explicit and default time units or precisions across design elements", )); @@ -567,10 +575,21 @@ impl Timescales { )) } + #[cfg(test)] pub(super) fn collect(trees: &[(&SyntaxTree, &Path)]) -> Converted { + Self::collect_with_options(trees, false) + } + + pub(super) fn collect_with_options( + trees: &[(&SyntaxTree, &Path)], + allow_mixed_timescales: bool, + ) -> Converted { #[cfg(test)] COLLECTIONS.with(|count| count.set(count.get() + 1)); - let mut design = Self::default(); + let mut design = Self { + allow_mixed_timescales, + ..Self::default() + }; // Each bit records whether a design element uses a default (1) or an // explicit/inherited setting (2), independently for unit and precision. let mut specified = [0u8; 2]; @@ -698,6 +717,11 @@ impl Timescales { unit: declarations[i].0.unwrap_or(inherited.unit), precision: declarations[i].1.unwrap_or(inherited.precision), }; + // Relaxed designs may mix explicit precision with the default. + // Both contribute to the global simulation precision. + let precision = scopes[i].scale.precision; + design.precision = + Some(design.precision.map_or(precision, |old| old.min(precision))); if scopes[i].scale.precision > scopes[i].scale.unit { return Err(unsupported("timeprecision coarser than timeunit")); } @@ -716,7 +740,7 @@ impl Timescales { }), ); } - if specified.contains(&3) { + if specified.contains(&3) && !allow_mixed_timescales { return Err(unsupported( "mixed explicit and default time units or precisions across design elements", )); diff --git a/crates/celox-sv-analyzer/src/ast/warnings.rs b/crates/celox-sv-analyzer/src/ast/warnings.rs index 4e37c04f63c..20761ddfaef 100644 --- a/crates/celox-sv-analyzer/src/ast/warnings.rs +++ b/crates/celox-sv-analyzer/src/ast/warnings.rs @@ -6,6 +6,8 @@ use crate::procedural::SourceSpan; /// A non-fatal source diagnostic, independent of constant evaluation. #[derive(Debug, Clone, PartialEq, Eq)] pub enum AnalyzerWarning { + /// Explicit and implementation-default time scales occur in one design. + MixedTimescale, /// An ignored `$exit` in a function outside a program (IEEE 1800-2023 24.7). ExitOutsideProgram { site: Option }, } diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 3297d4397cd..3eb556a805e 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -27,7 +27,10 @@ pub mod syntax; pub mod system_functions; pub mod typecheck; -pub use ast::interfaces::{InterfacePrototype, interface_prototypes, interface_prototypes_for}; +pub use ast::interfaces::{ + InterfacePrototype, interface_prototypes, interface_prototypes_for, + interface_prototypes_with_options, +}; pub use ast::interfaces::{NativeInterfacePlan, plan_interfaces}; pub use ast::packages::Packages; pub use ast::{ModuleInterface, ModuleInterfaces}; @@ -38,6 +41,12 @@ pub use parsed::ParsedSource; /// simulator's two-state/four-state mode is known. pub const DIV_ZERO_UNKNOWN_LITERAL: &str = "$celox_div_zero_unknown"; +/// Options for recoverable language compatibility checks. +#[derive(Debug, Clone, Copy, Default)] +pub struct AnalysisOptions { + pub allow_mixed_timescales: bool, +} + /// Errors reported by the SystemVerilog analyzer. #[derive(Debug, Clone, PartialEq, Eq, Error)] pub enum AnalyzerError { @@ -228,6 +237,15 @@ pub fn generated_time_declarations( ast::generated_time_declarations(sources, roots) } +/// Generate timing declarations using the selected compatibility policy. +pub fn generated_time_declarations_with_options( + sources: &[(&str, &Path)], + roots: Option<&[&str]>, + options: AnalysisOptions, +) -> Result { + ast::timescales::generated_source_declarations(sources, roots, options.allow_mixed_timescales) +} + /// Parse and analyze a SystemVerilog source string. pub fn analyze_source(code: &str, path: &Path) -> Result { let syntax_tree = source_tree::parse_source(code, path)?; diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index d0e3cc56d0b..890a7f99f95 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -80,7 +80,7 @@ impl ParsedSource { /// Analyze the packages declared in `sources`, each once, after the /// packages it depends on. pub fn analyze_packages(sources: &[&ParsedSource]) -> Result { - Self::analyze_packages_impl(sources, None) + Self::analyze_packages_with_options(sources, None, crate::AnalysisOptions::default()) } /// Analyze packages and time queries using the roots selected by the @@ -89,12 +89,14 @@ impl ParsedSource { sources: &[&ParsedSource], roots: &[&str], ) -> Result { - Self::analyze_packages_impl(sources, Some(roots)) + Self::analyze_packages_with_options(sources, Some(roots), crate::AnalysisOptions::default()) } - fn analyze_packages_impl( + /// Analyze a design with an explicit timescale compatibility policy. + pub fn analyze_packages_with_options( sources: &[&ParsedSource], roots: Option<&[&str]>, + options: crate::AnalysisOptions, ) -> Result { let trees: Vec<_> = sources .iter() @@ -102,7 +104,8 @@ impl ParsedSource { .collect(); let mut warnings = Vec::new(); let packages = (|| { - let mut packages = Packages::analyze_with_roots(&trees, roots)?; + let mut packages = + Packages::analyze_with_options(&trees, roots, options.allow_mixed_timescales)?; ast::warnings::append(&mut warnings, packages.warnings().iter().cloned()); for source in sources { for handle in source.tree.root_scopes()? { diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 39fcd943d70..79e26769689 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -168,13 +168,15 @@ fn run_testbench(arguments: RunArgs) -> Result<(), String> { &arguments.design.top, ) .four_state(true) - .opt_level(arguments.opt_level); + .opt_level(arguments.opt_level) + .diagnostic_policy(arguments.design.diagnostics.clone()); if let Some(metadata) = metadata { builder = builder.with_metadata(metadata); } let mut simulator = builder .build() .map_err(|error| format!("compilation failed:\n{error}"))?; + report_warnings(simulator.warnings())?; let program = celox::testbench::compile_initial_testbench(&simulator).ok_or_else(|| { "selected module has no native testbench; select a #[test] module with --top".to_string() })?; @@ -205,8 +207,10 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { let simulation = celox::Simulation::from_sv_sources(source_refs, &arguments.design.top) .four_state(true) .opt_level(arguments.opt_level) + .diagnostic_policy(arguments.design.diagnostics.clone()) .build() .map_err(|error| format!("compilation failed:\n{error}"))?; + report_warnings(simulation.warnings())?; simulate_sv( simulation, arguments.max_steps, @@ -433,10 +437,12 @@ fn compile_native_design(design: &Design) -> Result .collect(); let simulator = celox::Simulator::from_sv_sources(refs, &design.top) .four_state(true) + .diagnostic_policy(design.diagnostics.clone()) .native_force_support(true) .opt_level(celox::OptLevel::O0) .build() .map_err(|error| format!("compilation failed:\n{error}"))?; + report_warnings(simulator.warnings())?; return Ok(simulator.shared_code().program_image().clone()); } #[cfg(not(feature = "systemverilog"))] @@ -452,7 +458,22 @@ fn compile_native_design(design: &Design) -> Result { return Err("pass .sv/.v sources, or one .veryl project entry file".to_string()); } - celox_vpi::driver::compile_native_image(&design.sources[0], &design.top) + let (image, warnings) = celox_vpi::driver::compile_native_image_with_diagnostics( + &design.sources[0], + &design.top, + design.diagnostics.clone(), + )?; + report_warnings(&warnings)?; + Ok(image) +} + +fn report_warnings(warnings: &[celox::CompilationWarning]) -> Result<(), String> { + let mut output = std::io::stderr().lock(); + for warning in warnings { + writeln!(output, "{}", celox::render_diagnostic(warning)) + .map_err(|error| format!("failed to write diagnostics: {error}"))?; + } + Ok(()) } fn environment_path(name: &str) -> Option { diff --git a/crates/celox-vpi/src/bin/celox/project.rs b/crates/celox-vpi/src/bin/celox/project.rs index 15822f80617..c017ca30528 100644 --- a/crates/celox-vpi/src/bin/celox/project.rs +++ b/crates/celox-vpi/src/bin/celox/project.rs @@ -12,6 +12,9 @@ use serde::Deserialize; pub(super) struct DesignArgs { /// Ordered SV sources, or one Veryl project entry file. pub sources: Vec, + /// Override a compilation diagnostic: CODE=allow|warn|error (repeatable). + #[arg(long = "diagnostic", value_name = "CODE=LEVEL")] + diagnostics: Vec, /// Project manifest (otherwise discover celox.toml when no inputs are given). #[arg(long, value_name = "FILE")] project: Option, @@ -42,6 +45,7 @@ enum Input { #[derive(Default, Deserialize)] #[serde(default, deny_unknown_fields)] struct Manifest { + diagnostics: celox::DiagnosticPolicy, sources: Vec, filelists: Vec, include_dirs: Vec, @@ -56,6 +60,7 @@ struct Manifest { #[derive(Default, Deserialize)] #[serde(default, deny_unknown_fields)] struct Target { + diagnostics: celox::DiagnosticPolicy, sources: Vec, filelists: Vec, include_dirs: Vec, @@ -67,6 +72,7 @@ struct Target { #[derive(Default)] pub(super) struct Design { + pub diagnostics: celox::DiagnosticPolicy, pub sources: Vec, pub include_dirs: Vec, pub defines: BTreeMap, @@ -160,10 +166,12 @@ impl DesignArgs { &config.include_dirs, &config.defines, )?; + design.diagnostics = config.diagnostics.clone(); design.top = config.top.clone().unwrap_or_default(); let mut opt_level = config.opt_level.as_deref(); design.max_steps = config.max_steps; if let Some(target) = selected { + design.diagnostics.0.extend(target.diagnostics.0.clone()); design.extend( base, &target.sources, @@ -204,6 +212,9 @@ impl DesignArgs { } } } + for diagnostic in &self.diagnostics { + design.diagnostics.set_override(diagnostic)?; + } design.include_dirs.extend(self.include_dirs); for define in &self.defines { design.define(define)?; diff --git a/crates/celox-vpi/src/driver.rs b/crates/celox-vpi/src/driver.rs index ba812e4321a..2f00c6cfac7 100644 --- a/crates/celox-vpi/src/driver.rs +++ b/crates/celox-vpi/src/driver.rs @@ -2,7 +2,9 @@ use std::path::Path; -use celox::{NativeProgramImage, NativeProgramInstance, Simulator}; +use celox::{ + CompilationWarning, DiagnosticPolicy, NativeProgramImage, NativeProgramInstance, Simulator, +}; use libloading::{Library, Symbol}; use veryl_metadata::Metadata; @@ -20,7 +22,7 @@ pub fn compile_native_sources(sources: &[&Path], top: &str) -> Result 1 && !all_sv { return Err("multiple source paths require only .sv files; pass one Veryl project entry file for Veryl designs".to_string()); } - let simulator = if all_sv { + if all_sv { let contents = sources .iter() .map(|path| { @@ -38,7 +40,21 @@ pub fn compile_native_sources(sources: &[&Path], top: &str) -> Result Result<(NativeProgramImage, Vec), String> { + let simulator = if let Ok(metadata_path) = Metadata::search_from(source) { let mut metadata = Metadata::load(&metadata_path) .map_err(|error| format!("failed to load {}: {error}", metadata_path.display()))?; let paths = metadata @@ -58,6 +74,7 @@ pub fn compile_native_sources(sources: &[&Path], top: &str) -> Result>(); Simulator::from_sources(source_refs, top) .with_metadata(metadata) + .diagnostic_policy(policy.clone()) .four_state(true) .native_force_support(true) .opt_level(celox::OptLevel::O0) @@ -66,13 +83,15 @@ pub fn compile_native_sources(sources: &[&Path], top: &str) -> Result); + +impl DiagnosticPolicy { + /// Set a per-code override. Later assignments replace earlier ones. + pub fn set(&mut self, code: impl Into, level: DiagnosticLevel) { + self.0.insert(code.into(), level); + } + + /// Parse the CLI spelling `CODE=allow|warn|error`. + pub fn set_override(&mut self, value: &str) -> Result<(), String> { + let (code, level) = value + .split_once('=') + .ok_or_else(|| "diagnostic override must be CODE=allow|warn|error".to_string())?; + if code.is_empty() + || !code + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') + { + return Err(format!("invalid diagnostic code `{code}`")); + } + let level = match level { + "allow" => DiagnosticLevel::Allow, + "warn" => DiagnosticLevel::Warn, + "error" => DiagnosticLevel::Error, + _ => { + return Err(format!( + "invalid diagnostic level `{level}`; use allow, warn, or error" + )); + } + }; + self.set(code, level); + Ok(()) + } + + /// Read the diagnostics table of a celox.toml, ignoring other configuration. + pub fn from_file(path: &Path) -> Result { + #[derive(serde::Deserialize, Default)] + struct Config { + #[serde(default)] + diagnostics: DiagnosticPolicy, + } + let text = std::fs::read_to_string(path) + .map_err(|error| format!("failed to read {}: {error}", path.display()))?; + toml::from_str::(&text) + .map(|config| config.diagnostics) + .map_err(|error| format!("failed to parse {}: {error}", path.display())) + } + + pub(crate) fn level(&self, code: &str) -> DiagnosticLevel { + self.0 + .get(code) + .copied() + .unwrap_or(if code == "mixed_timescale" { + DiagnosticLevel::Error + } else { + DiagnosticLevel::Warn + }) + } + + #[cfg(feature = "systemverilog")] + pub(crate) fn sv_options(&self) -> celox_frontend_sv::AnalysisOptions { + celox_frontend_sv::AnalysisOptions { + allow_mixed_timescales: self.level("mixed_timescale") != DiagnosticLevel::Error, + } + } + + /// Suppress diagnostics or reject those configured as errors. + pub fn apply(&self, warnings: &mut Vec) -> Result<(), SimulatorError> { + let mut retained = Vec::new(); + let mut errors = Vec::new(); + for warning in warnings.drain(..) { + let code = warning + .code() + .map(|code| code.to_string()) + .unwrap_or_default(); + match self.level(&code) { + DiagnosticLevel::Allow => (), + DiagnosticLevel::Warn => retained.push(warning), + DiagnosticLevel::Error => errors.push(warning), + } + } + *warnings = retained; + if errors.is_empty() { + Ok(()) + } else { + Err( + SimulatorError::new(SimulatorErrorKind::DiagnosticPolicy(errors)) + .with_warnings(std::mem::take(warnings)), + ) + } + } +} diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 892bc41a031..b53e0dc7298 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -220,3 +220,6 @@ pub use simulator::{ #[cfg(test)] mod flatting_tests; + +mod diagnostic_policy; +pub use diagnostic_policy::{DiagnosticLevel, DiagnosticPolicy}; diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index a6d96f03382..0a5b63d56eb 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -589,6 +589,7 @@ pub fn parse_sv( mut trace: Option<&mut crate::debug::CompilationTrace>, optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, + diagnostic_policy: &crate::DiagnosticPolicy, preserve_element_storage_layout: bool, testbench_random_seed: Option, component_libraries: Vec, @@ -597,7 +598,7 @@ pub fn parse_sv( ) -> Result { let frontend_trace_options = trace_opts.frontend(diagnostics); let mut frontend_trace = celox_frontend_core::FrontendTrace::default(); - let scheduled = celox_frontend_sv::schedule_sources( + let scheduled = celox_frontend_sv::schedule_sources_with_options( sources, top, parameter_overrides, @@ -608,6 +609,7 @@ pub fn parse_sv( &frontend_trace_options, trace.is_some().then_some(&mut frontend_trace), warnings, + diagnostic_policy.sv_options(), ) .map_err(|error| match error { celox_frontend_sv::FrontendError::Lowering(error) => error.into(), @@ -680,6 +682,7 @@ pub fn parse_mixed( trace: Option<&mut crate::debug::CompilationTrace>, optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, + diagnostic_policy: &crate::DiagnosticPolicy, preserve_element_storage_layout: bool, testbench_random_seed: Option, component_libraries: Vec, @@ -818,17 +821,19 @@ pub fn parse_mixed( signatures.insert(key, signature.clone()); Ok(signature) }; - let external = celox_frontend_sv::prepare_external_hierarchy_with_foreign_resolver( - &borrowed_sources, - &external_roots, - &foreign, - foreign_declarations, - four_state, - Some(&mut resolver), - sv_top_parameters, - &requests, - &mut warnings, - ); + let external = + celox_frontend_sv::prepare_external_hierarchy_with_foreign_resolver_with_options( + &borrowed_sources, + &external_roots, + &foreign, + foreign_declarations, + four_state, + Some(&mut resolver), + sv_top_parameters, + &requests, + &mut warnings, + diagnostic_policy.sv_options(), + ); let external = match external { Ok(external) => external, Err(error) => { diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index ff202ec6e88..e13deea5aa7 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1096,6 +1096,11 @@ mod host { &self.warnings } + /// Consume the simulator and return its compilation diagnostics. + pub fn into_warnings(self) -> Vec { + self.warnings + } + /// Captures the current state of all signals and writes them to the VCD file. /// /// # Panics diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 5beee6554d9..b5dcb099d37 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -290,6 +290,7 @@ fn analyze( param_overrides: &[(String, u64)], optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, + diagnostic_policy: &crate::DiagnosticPolicy, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], preserve_element_storage_layout: bool, recover_comb_loops: bool, @@ -301,6 +302,8 @@ fn analyze( Vec, Vec, ) { + #[cfg(not(feature = "systemverilog"))] + let _ = diagnostic_policy; symbol_table::clear(); attribute_table::clear(); @@ -378,10 +381,11 @@ fn analyze( let references = super::mixed::referenced_sv_components( authored_parsers.iter().map(|parser| &parser.veryl), ); - let contracts = celox_frontend_sv::interface_signatures_for( + let contracts = celox_frontend_sv::interface_signatures_for_with_options( sv_sources, Some(&references), &mut sv_probe_warnings, + diagnostic_policy.sv_options(), ) .map_err(|error| match error { celox_frontend_sv::FrontendError::Analyzer(error) => parser::sv_analysis_error(error), @@ -586,6 +590,7 @@ fn analyze( trace_out, optimize_options, diagnostics, + diagnostic_policy, preserve_element_storage_layout, testbench_random_seed, component_libraries, @@ -751,6 +756,7 @@ pub fn compile_to_sir_with_file_dependencies( param_overrides, optimize_options, &crate::RuntimeDiagnostics::default(), + &crate::DiagnosticPolicy::default(), &[], crate::backend::memory_layout::MemoryLayoutMode::Packed, true, @@ -866,6 +872,7 @@ fn compile_frontend_testbench_to_sir_with_layout_mode( reset_type: Option, optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, + diagnostic_policy: &crate::DiagnosticPolicy, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -898,6 +905,7 @@ fn compile_frontend_testbench_to_sir_with_layout_mode( &[], optimize_options, diagnostics, + diagnostic_policy, injected_manifests, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, @@ -957,6 +965,7 @@ fn compile_to_sir_with_layout_mode( param_overrides: &[(String, u64)], optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, + diagnostic_policy: &crate::DiagnosticPolicy, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -979,6 +988,7 @@ fn compile_to_sir_with_layout_mode( param_overrides, optimize_options, diagnostics, + diagnostic_policy, injected_manifests, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, @@ -1054,6 +1064,7 @@ pub fn compile_sv_to_sir( param_overrides, optimize_options, &crate::RuntimeDiagnostics::default(), + &crate::DiagnosticPolicy::default(), crate::backend::memory_layout::MemoryLayoutMode::Packed, ) } @@ -1081,6 +1092,7 @@ fn compile_sv_to_sir_with_layout_mode( param_overrides: &[(String, u64)], optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, + diagnostic_policy: &crate::DiagnosticPolicy, layout_mode: crate::backend::memory_layout::MemoryLayoutMode, ) -> Result<(OptimizedSir, Vec), SimulatorError> { let metadata = metadata.unwrap_or_else(|| Metadata::create_default("prj").unwrap()); @@ -1105,6 +1117,7 @@ fn compile_sv_to_sir_with_layout_mode( trace_out, optimize_options, diagnostics, + diagnostic_policy, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, metadata.test.seed, component_libraries, @@ -1210,6 +1223,7 @@ pub fn compile_mixed_to_sir_with_file_dependencies( param_overrides, optimize_options, &crate::RuntimeDiagnostics::default(), + &crate::DiagnosticPolicy::default(), &[], crate::backend::memory_layout::MemoryLayoutMode::Packed, true, @@ -1242,6 +1256,7 @@ fn compile_mixed_to_sir_with_layout_mode( param_overrides: &[(String, u64)], optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, + diagnostic_policy: &crate::DiagnosticPolicy, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -1264,6 +1279,7 @@ fn compile_mixed_to_sir_with_layout_mode( param_overrides, optimize_options, diagnostics, + diagnostic_policy, injected_manifests, layout_mode == crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, recover_comb_loops, @@ -1326,6 +1342,7 @@ fn compile_hdl_to_sir_with_layout_mode( param_overrides: &[(String, u64)], optimize_options: &crate::optimizer::OptimizeOptions, diagnostics: &crate::RuntimeDiagnostics, + diagnostic_policy: &crate::DiagnosticPolicy, injected_manifests: &[(String, veryl_metadata::ComponentManifest)], layout_mode: crate::backend::memory_layout::MemoryLayoutMode, recover_comb_loops: bool, @@ -1349,6 +1366,7 @@ fn compile_hdl_to_sir_with_layout_mode( param_overrides, optimize_options, diagnostics, + diagnostic_policy, injected_manifests, layout_mode, recover_comb_loops, @@ -1372,6 +1390,7 @@ fn compile_hdl_to_sir_with_layout_mode( param_overrides, optimize_options, diagnostics, + diagnostic_policy, injected_manifests, layout_mode, recover_comb_loops, @@ -1392,6 +1411,7 @@ fn compile_hdl_to_sir_with_layout_mode( param_overrides, optimize_options, diagnostics, + diagnostic_policy, layout_mode, ), (false, false) => compile_mixed_to_sir_with_layout_mode( @@ -1409,6 +1429,7 @@ fn compile_hdl_to_sir_with_layout_mode( param_overrides, optimize_options, diagnostics, + diagnostic_policy, injected_manifests, layout_mode, recover_comb_loops, @@ -1461,6 +1482,7 @@ mod host { pub x86_options: crate::backend::X86BackendOptions, pub trace: crate::debug::TraceOptions, pub diagnostics: crate::RuntimeDiagnostics, + pub diagnostic_policy: crate::DiagnosticPolicy, /// When true, JIT-compiled functions emit trigger detection code for /// edge-based event discovery. Only needed by [`crate::Simulation`]. pub emit_triggers: bool, @@ -1661,6 +1683,7 @@ mod host { x86_options: crate::backend::X86BackendOptions::default(), trace: Default::default(), diagnostics: Default::default(), + diagnostic_policy: Default::default(), emit_triggers: false, native_force_support: false, dead_store_policy: DeadStorePolicy::Off, @@ -2053,7 +2076,13 @@ mod host { self } - /// Configure diagnostics explicitly for this build. + /// Override recoverable compilation diagnostic severities. + pub fn diagnostic_policy(mut self, policy: crate::DiagnosticPolicy) -> Self { + self.options.diagnostic_policy = policy; + self + } + + /// Configure runtime and optimizer diagnostics explicitly for this build. pub fn diagnostics(mut self, diagnostics: crate::DiagnosticsOptions) -> Self { self.options.diagnostics = diagnostics.runtime; self.options.optimize_options.diagnostics = diagnostics.sir; @@ -2376,7 +2405,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, mut warnings) = if let Some(artifact) = &self.frontend_artifact { + let compiled = if let Some(artifact) = &self.frontend_artifact { if self.sources.is_empty() { compile_frontend_to_sir_with_layout_mode( artifact, @@ -2388,7 +2417,7 @@ mod host { &self.options.optimize_options, &self.options.diagnostics, layout_mode, - )? + ) } else { compile_frontend_testbench_to_sir_with_layout_mode( artifact, @@ -2404,12 +2433,13 @@ mod host { self.reset_type, &self.options.optimize_options, &self.options.diagnostics, + &self.options.diagnostic_policy, &injected_manifests, layout_mode, !self.options.native_force_support, self.options.allow_always_ff_function_effects, &self.file_dependencies, - )? + ) } } else { compile_hdl_to_sir_with_layout_mode( @@ -2427,13 +2457,17 @@ mod host { &self.param_overrides, &self.options.optimize_options, &self.options.diagnostics, + &self.options.diagnostic_policy, &injected_manifests, layout_mode, !self.options.native_force_support, self.options.allow_always_ff_function_effects, &self.file_dependencies, - )? + ) }; + let (program, mut warnings) = compiled + .map_err(|error| error.apply_diagnostic_policy(&self.options.diagnostic_policy))?; + self.options.diagnostic_policy.apply(&mut warnings)?; if let Some(start) = compile_start { tracing::debug!("[phase-timing] compile_to_sir: {:?}", start.elapsed()); } @@ -3025,6 +3059,7 @@ mod host { self.reset_type, &self.options.optimize_options, &self.options.diagnostics, + &self.options.diagnostic_policy, &injected_manifests, layout_mode, !self.options.native_force_support, @@ -3048,6 +3083,7 @@ mod host { &self.param_overrides, &self.options.optimize_options, &self.options.diagnostics, + &self.options.diagnostic_policy, &injected_manifests, layout_mode, !self.options.native_force_support, @@ -3056,7 +3092,10 @@ mod host { ) }; + let program_res = program_res + .map_err(|error| error.apply_diagnostic_policy(&self.options.diagnostic_policy)); let sim_res = program_res.and_then(|(program, mut warnings)| { + self.options.diagnostic_policy.apply(&mut warnings)?; let mut laid_out = program.into_laid_out_with_mode(self.options.four_state, layout_mode); if self.vcd_path.is_some() { diff --git a/crates/celox/src/simulator/error.rs b/crates/celox/src/simulator/error.rs index f5ae0dbb407..fa9e69fa1db 100644 --- a/crates/celox/src/simulator/error.rs +++ b/crates/celox/src/simulator/error.rs @@ -115,9 +115,39 @@ impl miette::Diagnostic for CompilationWarning { } } +/// Keep the original code, source span and help when promoting a warning. +#[derive(Debug)] +struct PromotedDiagnostic<'a>(&'a CompilationWarning); + +impl fmt::Display for PromotedDiagnostic<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.fmt(f) + } +} +impl std::error::Error for PromotedDiagnostic<'_> {} +impl miette::Diagnostic for PromotedDiagnostic<'_> { + fn code<'a>(&'a self) -> Option> { + miette::Diagnostic::code(self.0) + } + fn severity(&self) -> Option { + Some(miette::Severity::Error) + } + fn source_code(&self) -> Option<&dyn miette::SourceCode> { + miette::Diagnostic::source_code(self.0) + } + fn labels(&self) -> Option + '_>> { + miette::Diagnostic::labels(self.0) + } + fn help<'a>(&'a self) -> Option> { + miette::Diagnostic::help(self.0) + } +} + /// The specific kind of simulator error. #[derive(Debug)] pub enum SimulatorErrorKind { + /// Recoverable diagnostics promoted to errors by the caller. + DiagnosticPolicy(Vec), FrontendArtifact(crate::FrontendArtifactError), SIRParser(crate::ParserError), /// The Veryl source could not be parsed. @@ -247,6 +277,20 @@ impl SimulatorError { self } + /// Suppress configured warnings accompanying an existing failure. + /// The original fatal diagnostic remains authoritative. + pub fn apply_diagnostic_policy(mut self, policy: &crate::DiagnosticPolicy) -> Self { + use miette::Diagnostic; + self.warnings.retain(|warning| { + let code = warning + .code() + .map(|code| code.to_string()) + .unwrap_or_default(); + policy.level(&code) != crate::DiagnosticLevel::Allow + }); + self + } + /// Returns a reference to the error kind. pub fn kind(&self) -> &SimulatorErrorKind { &self.kind @@ -261,6 +305,11 @@ impl SimulatorError { impl fmt::Display for SimulatorError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.kind.as_ref() { + SimulatorErrorKind::DiagnosticPolicy(errors) => { + for error in errors { + f.write_str(&render_diagnostic(&PromotedDiagnostic(error)))?; + } + } SimulatorErrorKind::FrontendArtifact(error) => write!(f, "{error}")?, SimulatorErrorKind::SIRParser(e) => f.write_str(&render_diagnostic(e))?, SimulatorErrorKind::Syntax(e) => f.write_str(&render_diagnostic(e))?, diff --git a/crates/celox/tests/diagnostic_policy.rs b/crates/celox/tests/diagnostic_policy.rs new file mode 100644 index 00000000000..f50e0db70f8 --- /dev/null +++ b/crates/celox/tests/diagnostic_policy.rs @@ -0,0 +1,178 @@ +use celox::{DiagnosticLevel, DiagnosticPolicy, Simulator, SimulatorErrorKind}; + +fn policy(code: &str, level: DiagnosticLevel) -> DiagnosticPolicy { + let mut policy = DiagnosticPolicy::default(); + policy.set(code, level); + policy +} + +const VERYL_WARNING: &str = r#" +module Top (tmp: output logic<8>, out: output logic) { + function write_outputs(first: output logic<8>, second: output logic<8>) -> logic { + first = 8'd1; + second = 8'd2; + return 1'b1; + } + always_comb { + tmp = 0; + out = write_outputs(second: tmp, first: tmp) & 1'b1; + } +} +"#; + +#[test] +fn existing_warnings_can_be_suppressed_or_promoted() { + let code = "unspecified_output_copy_order"; + let sim = Simulator::builder(VERYL_WARNING, "Top").build().unwrap(); + assert_eq!(sim.warnings().len(), 1); + let sim = Simulator::builder(VERYL_WARNING, "Top") + .diagnostic_policy(policy(code, DiagnosticLevel::Allow)) + .build() + .unwrap(); + assert!(sim.warnings().is_empty()); + let error = Simulator::builder(VERYL_WARNING, "Top") + .diagnostic_policy(policy(code, DiagnosticLevel::Error)) + .build() + .err() + .unwrap(); + assert!(matches!( + error.kind(), + SimulatorErrorKind::DiagnosticPolicy(_) + )); + assert!(error.to_string().contains(code)); +} + +#[test] +fn invalid_overrides_and_config_levels_fail() { + for value in [ + "mixed_timescale", + "=warn", + "mixed_timescale=quiet", + "foo-bar=allow", + ] { + assert!( + DiagnosticPolicy::default().set_override(value).is_err(), + "{value}" + ); + } + let directory = tempfile::tempdir().unwrap(); + let config = directory.path().join("celox.toml"); + std::fs::write(&config, "[diagnostics]\nmixed_timescale = 'quiet'\n").unwrap(); + assert!( + DiagnosticPolicy::from_file(&config) + .unwrap_err() + .contains("quiet") + ); +} + +#[cfg(feature = "systemverilog")] +mod sv { + use super::*; + use std::path::Path; + + const PLAIN: &str = "module Plain(output logic ok); assign ok = $timeunit() == -9 && $timeprecision() == -12; endmodule"; + const EXPLICIT: &str = "module Top(output logic ok); timeunit 10ns / 1ns; wire child_ok; Plain child(child_ok); assign ok = child_ok && $timeunit() == -8 && $timeprecision() == -9 && $timeprecision($root) == -12; endmodule"; + + fn builder() -> celox::SimulatorBuilder<'static> { + Simulator::from_sv_sources( + vec![ + (PLAIN, Path::new("plain.sv")), + (EXPLICIT, Path::new("top.sv")), + ], + "Top", + ) + } + + #[test] + fn mixed_timescales_remain_an_error_by_default() { + let error = builder().build().err().unwrap().to_string(); + assert!(error.contains("mixed explicit and default"), "{error}"); + } + + macro_rules! relaxed_backend { + ($name:ident, $method:ident) => { + #[test] + fn $name() { + for level in [DiagnosticLevel::Warn, DiagnosticLevel::Allow] { + let mut sim = builder() + .diagnostic_policy(policy("mixed_timescale", level)) + .$method() + .unwrap(); + assert_eq!( + sim.warnings().len(), + usize::from(level == DiagnosticLevel::Warn) + ); + if let Some(warning) = sim.warnings().first() { + assert!(celox::render_diagnostic(warning).contains("mixed_timescale")); + } + sim.eval_comb().unwrap(); + assert_eq!(sim.get(sim.signal("ok")), 1u8.into()); + } + } + }; + } + relaxed_backend!(native_retains_timing_semantics, build_native); + relaxed_backend!(cranelift_retains_timing_semantics, build_cranelift); + relaxed_backend!(interpreter_retains_timing_semantics, build_interpreter); + relaxed_backend!(wasm_retains_timing_semantics, build_wasm); + + #[test] + fn suppressing_an_sv_warning_does_not_hide_a_different_error() { + let source = "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("top.sv"))], "Top") + .diagnostic_policy(policy("exit_outside_program", DiagnosticLevel::Allow)) + .build() + .err() + .unwrap(); + assert!( + error.to_string().contains("user constant function call"), + "{error}" + ); + assert!(error.warnings().is_empty(), "{error}"); + } + + #[test] + fn mixed_language_interface_probes_use_the_same_policy() { + let veryl = "module Top(a: input logic<8>, y: output logic<8>) { inst bus: $sv::Bus; assign bus.req = a; assign y = bus.rsp; }"; + let explicit = "module Unused; timeunit 1ns / 1ps; endmodule"; + let bus = "interface Bus; logic [7:0] req, rsp; assign rsp = req + 1; endinterface"; + let mut sim = Simulator::from_mixed_sources( + vec![(veryl, Path::new("top.veryl"))], + vec![ + (bus, Path::new("bus.sv")), + (explicit, Path::new("explicit.sv")), + ], + "Top", + ) + .diagnostic_policy(policy("mixed_timescale", DiagnosticLevel::Warn)) + .build() + .unwrap(); + assert_eq!( + sim.warnings() + .iter() + .filter(|warning| matches!( + warning, + celox::CompilationWarning::SystemVerilog(celox::SvFrontendWarning { + kind: celox::SvFrontendWarningKind::MixedTimescale, + .. + }) + )) + .count(), + 1 + ); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 8u8)).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 9u8.into()); + } + + #[test] + fn relaxed_timescales_still_reject_invalid_precision() { + let source = "module Top; timeunit 1ps / 1ns; endmodule"; + assert!( + Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .diagnostic_policy(policy("mixed_timescale", DiagnosticLevel::Allow)) + .build() + .is_err() + ); + } +} diff --git a/docs/guide/celox-toml.md b/docs/guide/celox-toml.md index fe1a4d40cbb..be6da5de840 100644 --- a/docs/guide/celox-toml.md +++ b/docs/guide/celox-toml.md @@ -128,3 +128,58 @@ The Vite plugin picks up `test_veryl/` automatically and generates type definiti - All test source directories are merged with the project sources at simulation time. Modules from both are available in the same namespace. - The Vite plugin regenerates types for test sources on hot reload, just like for production sources. - `[simulation]` settings apply to every `Simulation.fromProject` / `Simulation.create` call within the project. A per-call `{ maxSteps }` option always takes precedence over the `celox.toml` value. + +### `[diagnostics]` + +Override individual compilation diagnostics by their displayed code: + +```toml +[diagnostics] +mixed_timescale = "warn" +exit_outside_program = "allow" +memory_file_word_count = "error" +``` + +`allow` suppresses the diagnostic, `warn` retains it without failing compilation, +and `error` rejects the design. Unlisted codes keep their default severity. +Existing Veryl and SystemVerilog warnings can be suppressed or promoted this way. +Use the exact code printed in the diagnostic; entries for codes not encountered +by a compilation have no effect. + +Recoverable errors support relaxation only when the compiler defines a fallback. +Currently `mixed_timescale` is the supported error: IEEE 1800-2023 §3.14.2.3 requires +consistent explicit time units and precisions. Its default is `error`. With `warn` +or `allow`, undeclared settings use Celox's defaults (1ns unit, 1ps precision), +explicit settings remain effective, and the global precision includes default +scopes. Syntax errors, unsupported constructs and invalid precision declarations +remain errors. + +Project simulator constructors load this table alongside `Veryl.toml`. Native +compilation also supports standalone SystemVerilog projects: + +```sh +celox run bus.sv top.sv --top Top --diagnostic mixed_timescale=warn +celox vpi build --project ./celox.toml --target compat --diagnostic exit_outside_program=allow +``` + +Both commands use the project discovery and path rules in the +[CLI guide](./cocotb.md). With explicit sources, use `--project FILE` to load +configuration. With no inputs, or with `--target NAME`, they discover `celox.toml` +from the current directory and its ancestors. A selected target can override +individual codes without replacing the entire policy: + +```toml +sources = ["bus.sv", "top.sv"] +top = "Top" + +[diagnostics] +mixed_timescale = "error" + +[targets.compat.diagnostics] +mixed_timescale = "warn" +``` + +The order is common diagnostics → selected target → CLI overrides. Repeat +`--diagnostic CODE=LEVEL` to override multiple codes; the last assignment to a +code wins. `celox run` and `celox vpi build` print retained compilation warnings. +Diagnostic severity does not change optimizer settings or runtime error handling. diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index dba2f166a5b..a6946a7e75d 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -72,6 +72,9 @@ default_target = "smoke" [defines] SIMULATION = "1" +[diagnostics] +mixed_timescale = "warn" + [targets.smoke] sources = ["test/Tb.sv"] top = "Tb" @@ -111,6 +114,12 @@ otherwise the sole target. Multiple targets without a default require `--target`. A project may also name a single `.veryl` entry file; its Veryl project discovery still uses `Veryl.toml`. +Compilation diagnostic levels can be set in `[diagnostics]`, overridden in +`[targets.NAME.diagnostics]`, and overridden again with repeatable +`--diagnostic CODE=allow|warn|error` options on either command. See +[diagnostic configuration](./celox-toml.md#diagnostics) for supported recovery +behavior and examples. + ### Use a file list directly ```sh diff --git a/docs/ja/guide/celox-toml.md b/docs/ja/guide/celox-toml.md index 057346f1173..66a1a19400c 100644 --- a/docs/ja/guide/celox-toml.md +++ b/docs/ja/guide/celox-toml.md @@ -116,3 +116,40 @@ Vite プラグインは `test_veryl/` を自動的に検出し、そこで宣言 - すべてのテストソースディレクトリはシミュレーション時にプロジェクトソースと統合されます。両方のモジュールが同じ名前空間で利用できます。 - Vite プラグインは本番ソースと同様に、ホットリロード時にテストソースの型も再生成します。 - `[simulation]` の設定は、プロジェクト内の `Simulation.fromProject` / `Simulation.create` 呼び出しすべてに適用されます。呼び出し時に `{ maxSteps }` を指定すると、常に `celox.toml` の値より優先されます。 + +### `[diagnostics]` + +診断に表示されるコードを使って、コンパイル時の診断レベルを個別に変更できます。 + +```toml +[diagnostics] +mixed_timescale = "warn" +exit_outside_program = "allow" +memory_file_word_count = "error" +``` + +`allow` は診断を抑制し、`warn` は警告を残してコンパイルを続行し、`error` はコンパイルを失敗させます。指定しない診断は既定のレベルを維持します。既存の Veryl・SystemVerilog の警告にも適用できます。診断に表示されたコードをそのまま指定してください。そのコンパイルで発生しないコードの設定は影響しません。 + +エラーの緩和は、コンパイラが継続時の動作を定義している診断に対応します。現在の対象は `mixed_timescale` です。IEEE 1800-2023 §3.14.2.3 が求める時間単位・精度の明示指定の一貫性を検査し、既定では `error` になります。`warn` または `allow` を選ぶと、未指定部分には Celox の既定値(単位 1ns、精度 1ps)を適用します。明示した値は維持し、全体の精度には既定値を使うスコープも含めます。構文エラー、未対応の構文、不正な精度指定は引き続きエラーになります。 + +プロジェクトのシミュレータ生成時は `Veryl.toml` と同じ場所の設定を読み込みます。CLI は単独の SystemVerilog プロジェクトにも対応します。 + +```sh +celox run bus.sv top.sv --top Top --diagnostic mixed_timescale=warn +celox vpi build --project ./celox.toml --target compat --diagnostic exit_outside_program=allow +``` + +両コマンドは [CLI ガイド](./cocotb.md) のプロジェクト探索・パス解決の規則を使います。ソースを明示した場合は `--project FILE` で設定を読み込みます。入力の指定がない場合、または `--target NAME` を指定した場合は、カレントディレクトリから親へ `celox.toml` を探索します。ターゲットごとに一部の診断だけ上書きすることもできます。 + +```toml +sources = ["bus.sv", "top.sv"] +top = "Top" + +[diagnostics] +mixed_timescale = "error" + +[targets.compat.diagnostics] +mixed_timescale = "warn" +``` + +共通設定→選択したターゲット→CLI の順に優先されます。`--diagnostic CODE=LEVEL` は繰り返し指定でき、同じコードを複数回指定した場合は最後の指定が有効です。`celox run` と `celox vpi build` は抑制していない警告を表示します。診断レベルを変更しても、最適化設定や実行時エラーの扱いは変わりません。 diff --git a/docs/ja/guide/cocotb.md b/docs/ja/guide/cocotb.md index 248e22a2ad7..f29a09e3a43 100644 --- a/docs/ja/guide/cocotb.md +++ b/docs/ja/guide/cocotb.md @@ -66,6 +66,9 @@ default_target = "smoke" [defines] SIMULATION = "1" +[diagnostics] +mixed_timescale = "warn" + [targets.smoke] sources = ["test/Tb.sv"] top = "Tb" @@ -103,6 +106,8 @@ includeディレクトリも同じ階層順で追加します。マクロは実 単独の`.veryl`エントリーファイルをプロジェクトに指定することもでき、 Veryl側のソース探索には引き続き`Veryl.toml`を使います。 +コンパイル時の診断レベルは `[diagnostics]` で設定でき、`[targets.NAME.diagnostics]`、両コマンドの `--diagnostic CODE=allow|warn|error` の順に上書きできます。CLI オプションは繰り返し指定できます。緩和時の動作と使用例は [診断設定](./celox-toml.md#diagnostics) を参照してください。 + ### ファイル一覧を直接使う ```sh