diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7f46105596e..a7eba619c0d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -293,8 +293,8 @@ jobs: case "$feature" in celox/*) args+=(--features "$feature");; esac done CELOX_COCOTB_PYTHON="$(command -v python)" \ - cargo test --locked -p celox-vpi "${args[@]}" --test cocotb_e2e \ - cocotb_drives_an_attached_native_flip_flop -- --exact --ignored + cargo test --locked -p celox-vpi --features systemverilog "${args[@]}" --test cocotb_e2e \ + cocotb_ -- --ignored external-suites: name: External suite (${{ matrix.suite }}, ${{ matrix.tool }}) @@ -385,6 +385,49 @@ jobs: if-no-files-found: error retention-days: 14 + common-cells: + name: Upstream SystemVerilog testbench + if: ${{ !cancelled() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') }} + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v7 + + - uses: ./.github/actions/setup-rust + + - uses: Swatinem/rust-cache@v2 + with: + save-if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} + + - uses: actions/setup-node@v7 + with: + node-version: 24 + + - name: Fetch pinned common_cells + run: | + revision="$(cat conformance/common-cells/revision)" + git init -q "$RUNNER_TEMP/common-cells" + git -C "$RUNNER_TEMP/common-cells" fetch -q --depth 1 \ + https://github.com/pulp-platform/common_cells.git "$revision" + git -C "$RUNNER_TEMP/common-cells" checkout -q FETCH_HEAD + + - name: Build the SystemVerilog CLI + run: cargo build --locked -p celox-vpi --features systemverilog --bin celox + + - name: Run upstream TB and assertion negative control + run: >- + node scripts/run-common-cells.mjs "$RUNNER_TEMP/common-cells" + target/debug/celox "$RUNNER_TEMP/common-cells-results" + + - name: Retain testbench logs + if: always() + uses: actions/upload-artifact@v7 + with: + name: common-cells-results + path: ${{ runner.temp }}/common-cells-results + if-no-files-found: ignore + retention-days: 14 + sv-tests: name: sv-tests conformance needs: changes @@ -879,6 +922,7 @@ jobs: rust-tests, sv-tests, external-suites, + common-cells, napi-linux, napi-wasm, rust, diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d8b2cbce565..ab1b238ad16 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -289,6 +289,7 @@ Local validation uses the behavior-based matrix above. | Daily at 01:47 UTC (10:47 JST) | `bench.yml` measures Rust, Verilator, and TypeScript on one host and publishes master history. Manual dispatch supports branch measurements. | | Daily at 02:17 UTC (11:17 JST) | `codspeed.yml` measures compile time on the default branch using CPU simulation. Execution failures and CodSpeed performance-check failures open or update a branch issue; the next healthy run closes it. Manual dispatch supports branch measurements. PRs, merge groups, and pushes do not run CodSpeed. | | Daily at 02:37 UTC (11:37 JST) | `heliodor-bench.yml` runs the complete master Linux suite on x86-64 and AArch64. Explicit manual selections retain focused suite runs and ARM64 profiling. PRs do not run this workflow; its tooling tests run in `Lint & Format` with the other script tests. | +| Every daily/manual full CI run | Run the pinned upstream `common_cells` Gray code SV TB through `celox run --project`, plus an assertion negative control. Logs are retained for 14 days and failures feed the Full CI issue. See [the reproduction instructions](conformance/common-cells/README.md). | | Every full CI run | Run every shared Veryl and SystemVerilog case against both Verilator and Icarus, with locked Nix tools. Run the live adapter tests normally marked ignored because they need external tools. Preserve reports and per-case diagnostics as artifacts for 14 days, including on failure; matrix failures do not cancel the other comparisons. | | Affected pull requests and merge groups; daily at 03:41 UTC (12:41 JST); on demand | `lydite-checks.yml` owns Lydite Rust tests, proof, conformance, editor, and mutation gates. Unrelated changes skip these jobs, and Celox changes skip the bridge. Daily and manual runs enable all lanes and report failures in an issue. | | On demand | Dispatch `ci.yml` on the desired branch to run full CI and external comparisons, regardless of its diff. | diff --git a/Cargo.lock b/Cargo.lock index ac95a37e5bc..6179911501e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -827,10 +827,13 @@ version = "0.11.0" dependencies = [ "celox", "celox-design", + "celox-sv-analyzer", "clap", "fxhash", "libloading", + "serde", "tempfile", + "toml", "veryl-metadata", ] diff --git a/conformance/common-cells/README.md b/conformance/common-cells/README.md new file mode 100644 index 00000000000..e4105d2da11 --- /dev/null +++ b/conformance/common-cells/README.md @@ -0,0 +1,38 @@ +# Upstream SystemVerilog testbench smoke test + +Daily full CI runs the unmodified `cc_graycode_tb` from +[PULP common_cells](https://github.com/pulp-platform/common_cells), pinned by +[`revision`](revision). The same job runs on manual `ci.yml` dispatches and on +develop's nightly full CI. It exercises the `celox run --project` CLI with the +SystemVerilog frontend and native timed simulation. + +The default 9-bit TB applies 1,536 inputs using loops, `#1` delays, an untimed +task, and immediate assertions. It checks binary/Gray round trips and changes +in the Gray code population count. This is a small combinational design smoke +test, not coverage of all common_cells modules or clocked testbenches. + +The gate first requires the original RTL/TB to exit successfully. It then forces +the Gray encoder output to zero in a separate RTL copy and requires exit code 1 +with an assertion diagnostic. Compilation errors, crashes and timeouts do not +satisfy this negative control. Upstream files are never edited. Each execution +has a two-minute wall timeout and the CLI's default scheduler step limit. + +To reproduce from the repository root: + +```sh +revision="$(cat conformance/common-cells/revision)" +git init work/common-cells +git -C work/common-cells fetch --depth 1 https://github.com/pulp-platform/common_cells.git "$revision" +git -C work/common-cells checkout FETCH_HEAD +cargo build --locked -p celox-vpi --features systemverilog --bin celox +node scripts/run-common-cells.mjs work/common-cells target/debug/celox work/common-cells-results +``` + +The output directory contains the generated `celox.toml`, negative-control +sources, both logs, and a `result.json` written only after both checks pass. +Use a fresh output directory for each run. CI retains this directory for 14 days, +including on failure; failures feed the existing Full CI issue reporter. + +Update the pin deliberately after reviewing and running the upstream TB. The +negative-control assignment is checked explicitly so an upstream rewrite cannot +silently remove that check. diff --git a/conformance/common-cells/revision b/conformance/common-cells/revision new file mode 100644 index 00000000000..8f27dce2c8c --- /dev/null +++ b/conformance/common-cells/revision @@ -0,0 +1 @@ +e73baaec2ca665cd80c3c384e9258e35242b829c diff --git a/crates/celox-frontend-sv/src/lib.rs b/crates/celox-frontend-sv/src/lib.rs index 4bbdeeadcad..bc6ad7f6c91 100644 --- a/crates/celox-frontend-sv/src/lib.rs +++ b/crates/celox-frontend-sv/src/lib.rs @@ -47,3 +47,11 @@ 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, +}; + +pub use lowering::schedule_sources_with_force_signals; diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index d7d2f82bbc5..2d33bb4fec5 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -55,6 +55,11 @@ pub enum FrontendError { Lowering(#[from] ParserError), } +// These names cannot be authored as unescaped SV identifiers and are hidden +// from the source-facing hierarchy. The runtime image records their addresses. +const FORCE_ENABLE: &str = "@force-enable:"; +const FORCE_VALUE: &str = "@force-value:"; + #[derive(Clone)] struct SvVariable { path: Vec, @@ -69,6 +74,8 @@ struct SvVariable { source: Option, /// A procedural local or a lowering temporary: not addressable by name. hidden: bool, + /// Compiler-generated external override slot: (target, is_enable). + force_control: Option<(SourceVarId, bool)>, } impl SvVariable { @@ -97,7 +104,7 @@ impl SvVariable { /// A hidden variable other than the time slot, whose value the lowered /// code computes. The time slot is state the scheduler writes. fn is_scratch(&self) -> bool { - self.hidden && self.path != [TIME_SLOT] + self.hidden && self.path != [TIME_SLOT] && self.force_control.is_none() } } @@ -121,7 +128,7 @@ pub(crate) struct LoweredSvModule { #[derive(Clone)] struct AnalyzedSvModule { name: String, - interface_ports: HashSet, + interface_member_paths: HashMap>, source: std::rc::Rc, implicit_nets_allowed: bool, /// The positional interface of every module in all sources, used to bind @@ -135,6 +142,7 @@ struct AnalyzedSvModule { pub(crate) struct LoweredSvInstance { pub module_name: String, pub instance_name: String, + pub force_signals: Vec, pub parameter_overrides: Vec, pub port_connections: Vec, /// For an element of an instance array: its position in declaration order @@ -163,6 +171,7 @@ pub(crate) struct LoweredSvPortConnection { #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub(crate) struct LoweredSvModuleKey { pub name: String, + pub force_signals: Vec, pub parameter_overrides: Vec, } @@ -170,6 +179,7 @@ impl LoweredSvModuleKey { pub fn base(name: String) -> Self { Self { name, + force_signals: Vec::new(), parameter_overrides: Vec::new(), } } @@ -179,6 +189,7 @@ impl LoweredSvModuleKey { parameter_overrides.sort_by(|left, right| left.name.cmp(&right.name)); Self { name: instance.module_name.clone(), + force_signals: instance.force_signals.clone(), parameter_overrides, } } @@ -187,6 +198,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 +206,7 @@ fn analyze_sources( &[], &[], Some(roots), + analysis_options, ) .map(|(modules, _)| modules) } @@ -224,9 +237,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 +268,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()); } @@ -254,7 +278,7 @@ fn interface_signatures_collecting( .into_iter() .map(|prototype| { warnings.extend(crate::warning::analyzer_warnings(&prototype.warnings)); - let lowered = lower_module(&prototype.module, false, true, false, warnings)?; + let lowered = lower_module(&prototype.module, false, true, false, warnings, &[])?; Ok(InterfaceSignature { name: prototype.name, module: lowered.source, @@ -321,6 +345,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 +372,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() }; @@ -372,7 +401,8 @@ fn analyze_sources_with_requests( ) }) .collect::>(); - let elaboration = sv::plan_interfaces(sources, &bindings)?; + let (elaboration, interface_member_paths) = + sv::plan_interfaces_with_member_paths(sources, &bindings)?; let root_names = elaboration.root_names.clone(); let mut modules = HashMap::default(); let sources: Vec<_> = sources @@ -433,9 +463,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); @@ -465,10 +499,9 @@ fn analyze_sources_with_requests( modules.insert( name, AnalyzedSvModule { - interface_ports: elaboration - .modules + interface_member_paths: interface_member_paths .get(&module_name) - .map(|plan| plan.ports.iter().map(|port| port.name.clone()).collect()) + .cloned() .unwrap_or_default(), implicit_nets_allowed: implicit_net_permissions .get( @@ -752,7 +785,7 @@ fn lower_package_states( .into_iter() .enumerate() .map(|(index, module)| { - let mut lowered = lower_module(module, four_state, true, ff_parts, warnings)?; + 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()))?, @@ -1233,6 +1266,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 +1306,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 +1324,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 +1332,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( @@ -1307,6 +1371,7 @@ fn prepare_external_hierarchy_collecting( type_kind: variable.metadata.type_kind, source: variable.source.clone(), hidden: !variable.module_affiliated, + force_control: None, }, ) }) @@ -1603,25 +1668,9 @@ fn prepare_external_hierarchy_collecting( } } } - // Structured paths carry the original interface port identity to foreign - // consumers. Ordinary identifiers containing '$' remain a single segment. for (key, id) in &module_ids { - let Some(base) = analyzed.get(&key.name) else { - continue; - }; - for port in &lowered_modules[id].port_order { - let variable = modules - .get_mut(id) - .unwrap() - .sim_module - .variables - .get_mut(port) - .unwrap(); - if let Some((root, member)) = variable.path[0].split_once('$') - && base.interface_ports.contains(root) - { - variable.path = vec![root.to_string(), member.to_string()]; - } + if let Some(base) = analyzed.get(&key.name) { + restore_interface_member_paths(&mut modules.get_mut(id).unwrap().sim_module, base); } } Ok(ExternalHierarchy { @@ -1651,6 +1700,83 @@ 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 { + schedule_sources_with_force_signals( + sources, + top, + parameter_overrides, + ignored_loops, + true_loops, + four_state, + parallel, + trace_options, + trace, + warnings, + analysis_options, + &[], + ) +} + +/// Schedule with explicitly forceable signal names. Only these objects receive +/// external override inputs; unrelated logic retains its normal optimization. +#[allow(clippy::too_many_arguments)] +pub fn schedule_sources_with_force_signals( + 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, + force_signals: &[String], ) -> Result { let mut found = Vec::new(); let scheduled = schedule_sources_collecting( @@ -1664,6 +1790,8 @@ pub fn schedule_sources( trace_options, trace, &mut found, + analysis_options, + force_signals, ); append_error_warnings(&scheduled, &mut found); crate::warning::append_unique_warnings(sources, warnings, found); @@ -1689,12 +1817,19 @@ fn schedule_sources_collecting( trace_options: &FrontendTraceOptions, trace: Option<&mut FrontendTrace>, warnings: &mut Vec, + analysis_options: sv::AnalysisOptions, + force_signals: &[String], ) -> 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 { name: top.clone(), + force_signals: force_signals + .iter() + .filter_map(|path| path.strip_prefix(&format!("{top}."))) + .map(str::to_string) + .collect(), parameter_overrides: parameter_overrides .iter() .map(|(name, value)| LoweredSvParameterOverride { @@ -1811,6 +1946,9 @@ fn schedule_sources_collecting( .map(|(&module_id, lowered)| (module_id, lowered)), &package_states, )?; + for (key, id) in &module_ids { + restore_interface_member_paths(modules.get_mut(id).unwrap(), &analyzed[&key.name]); + } let symbolic = SymbolicRtl { modules, module_names, @@ -1830,6 +1968,24 @@ fn schedule_sources_collecting( .map_err(FrontendError::from) } +// Use elaboration provenance rather than treating every '$' as a separator: +// legal authored identifiers may themselves contain '$'. +fn restore_interface_member_paths(module: &mut SimModule, source: &AnalyzedSvModule) { + for variable in module.variables.values_mut() { + variable.path = variable + .path + .iter() + .flat_map(|segment| { + source + .interface_member_paths + .get(segment) + .cloned() + .unwrap_or_else(|| vec![segment.clone()]) + }) + .collect(); + } +} + fn sv_specialization_limit_error(name: String) -> ParserError { ParserError::unsupported( sv::SV_FRONTEND_TRACKING_ISSUE, @@ -1917,13 +2073,42 @@ fn specialize_module( .iter() .find(|candidate| candidate.name() == module.name) .ok_or_else(|| sv::AnalyzerError::Unsupported(format!("module `{}`", module.name)))?; + let local_forces = key + .force_signals + .iter() + .map(|path| { + module + .interface_member_paths + .iter() + .find(|(_, segments)| segments.join(".") == *path) + .map_or_else(|| path.clone(), |(flat, _)| flat.clone()) + }) + .collect::>(); let mut lowered = lower_module( specialized, four_state, module.implicit_nets_allowed, ff_parts, warnings, + &local_forces, )?; + for instance in &mut lowered.instances { + let name = if let Some((index, _)) = instance.array_element { + format!( + "{}[{}]", + instance.instance_name, + instance.array_index_base + index + ) + } else { + instance.instance_name.clone() + }; + let prefix = format!("{name}."); + instance.force_signals = key + .force_signals + .iter() + .filter_map(|path| path.strip_prefix(&prefix).map(str::to_string)) + .collect(); + } lowered.sim_module.time_precision = Some( celox_design::TimePrecision::try_from(module.packages.global_time_precision()) .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?, @@ -1955,6 +2140,7 @@ fn lower_module( implicit_nets_allowed: bool, ff_parts: bool, warnings: &mut Vec, + force_signals: &[String], ) -> Result { lower_module_with_overrides( module, @@ -1963,6 +2149,7 @@ fn lower_module( implicit_nets_allowed, ff_parts, warnings, + force_signals, ) } @@ -1975,6 +2162,7 @@ fn lower_module_with_overrides( implicit_nets_allowed: bool, ff_parts: bool, warnings: &mut Vec, + force_signals: &[String], ) -> Result { let mut package_variables = Vec::new(); let name = module.name().to_string(); @@ -2023,6 +2211,7 @@ fn lower_module_with_overrides( type_kind: type_info.type_kind, source: None, hidden: false, + force_control: None, }; name_to_id.insert(port.name().to_string(), id); port_order.push(id); @@ -2071,6 +2260,7 @@ fn lower_module_with_overrides( type_kind: type_info.type_kind, source: None, hidden: false, + force_control: None, }; name_to_id.insert(signal.name().to_string(), id); // The package's object has its own default value. @@ -2093,6 +2283,50 @@ fn lower_module_with_overrides( variables.insert(id, variable); } + let forceable = variables + .iter() + .filter_map(|(&id, var)| { + let name = &var.path[0]; + force_signals.iter().any(|path| name == path).then_some(id) + }) + .collect::>(); + for id in forceable { + let target = variables[&id].clone(); + // Whole packed variables only. Array elements require a separately + // specified addressing contract rather than a guessed flat offset. + if !target.array_dims.is_empty() { + continue; + } + for (prefix, width, is_4state) in [ + (FORCE_ENABLE, 1, false), + (FORCE_VALUE, target.width, target.is_4state), + ] { + let control_name = format!("{prefix}{}", target.path[0]); + if name_to_id.contains_key(&control_name) { + return Err(sv::AnalyzerError::Unsupported(format!( + "signal `{control_name}` conflicts with a compiler force control" + ))); + } + let mut control = target.clone(); + control.force_control = Some((id, prefix == FORCE_ENABLE)); + control.path = vec![control_name.clone()]; + control.width = width; + control.signed = false; + control.is_4state = is_4state; + control.kind = VariableKind::Variable; + control.hidden = true; + control.packed_ranges = vec![(width as i128 - 1, 0)]; + control.type_kind = if is_4state { + PortTypeKind::Logic + } else { + PortTypeKind::Bit + }; + let control_id = next_var_id(&mut next_id); + variables.insert(control_id, control); + name_to_id.insert(control_name, control_id); + } + } + if !cfg!(feature = "dpi") && !module.dpi_imports().is_empty() { return Err(sv::AnalyzerError::Unsupported( "DPI-C import (enable the `sv-dpi` feature of `celox`)".to_string(), @@ -2198,6 +2432,7 @@ fn lower_module_with_overrides( instances.push(LoweredSvInstance { module_name: instance.module_name().to_string(), instance_name: instance.name().to_string(), + force_signals: Vec::new(), parameter_overrides: lower_parameter_overrides( instance, &constants, @@ -3069,6 +3304,7 @@ fn lower_initial_processes( source: None, // Control slots are not signals of the design. hidden: true, + force_control: None, }, ); id @@ -3400,6 +3636,7 @@ fn ensure_parent_output_signals( type_kind: PortTypeKind::Logic, source: None, hidden: false, + force_control: None, }; parent .variables diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index e1fc10b2161..633ef544b4a 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -136,6 +136,43 @@ impl<'p, 'a> Comb<'p, 'a> { store: &Store, id: SourceVarId, access: BitAccess, + ) -> Result { + let mut value = self.read_unforced(store, id, access)?; + // Initial-state folding runs before a foreign caller can apply force. + // Runtime initial processes are lowered separately through Ff. + if !self.initial + && let Some((enabled, forced)) = self.m.force_controls(id) + { + let cond = self.alloc(SLTNode::Input { + variable: enabled, + signed: false, + index: vec![], + access: full(1), + })?; + let replacement = self.alloc(SLTNode::Input { + variable: forced, + signed: false, + index: vec![], + access, + })?; + value.0 = self.alloc(SLTNode::Mux { + cond, + then_expr: replacement, + else_expr: value.0, + })?; + value.1.insert(VarAtomBase::new(enabled, 0, 0)); + value + .1 + .insert(VarAtomBase::new(forced, access.lsb, access.msb)); + } + Ok(value) + } + + fn read_unforced( + &mut self, + store: &Store, + id: SourceVarId, + access: BitAccess, ) -> Result { let signed = self.m.var(id).signed && access.lsb == 0 && access.msb + 1 == self.m.var(id).width; @@ -189,6 +226,34 @@ impl<'p, 'a> Comb<'p, 'a> { value: Value, ) -> Result<(), sv::AnalyzerError> { let width = self.m.var(id).width; + let mut value = value; + // Initial-state folding runs before a foreign caller can apply force. + // Runtime initial processes are lowered separately through Ff. + if !self.initial + && let Some((enabled, forced)) = self.m.force_controls(id) + { + let condition = self.alloc(SLTNode::Input { + variable: enabled, + signed: false, + index: vec![], + access: full(1), + })?; + let replacement = self.alloc(SLTNode::Input { + variable: forced, + signed: false, + index: vec![], + access, + })?; + value.0 = self.alloc(SLTNode::Mux { + cond: condition, + then_expr: replacement, + else_expr: value.0, + })?; + value.1.insert(VarAtomBase::new(enabled, 0, 0)); + value + .1 + .insert(VarAtomBase::new(forced, access.lsb, access.msb)); + } debug_assert_eq!(self.width(value.0), access.msb - access.lsb + 1); store .entry(id) @@ -563,11 +628,13 @@ impl<'p, 'a> Comb<'p, 'a> { access, } => { if index.is_empty() { - if store.get(&variable).is_some_and(|range| { - range - .get_parts_ref(access) - .is_ok_and(|parts| parts.iter().any(|(value, _)| value.is_some())) - }) { + if self.m.force_controls(variable).is_some() + || store.get(&variable).is_some_and(|range| { + range + .get_parts_ref(access) + .is_ok_and(|parts| parts.iter().any(|(value, _)| value.is_some())) + }) + { let (value, sources) = self.read(store, variable, access)?; let _ = signed; (value, sources) @@ -592,9 +659,10 @@ impl<'p, 'a> Comb<'p, 'a> { }); } let var_width = self.m.var(variable).width; - let written = store.get(&variable).is_some_and(|range| { - range.ranges.values().any(|(value, _, _)| value.is_some()) - }); + let written = self.m.force_controls(variable).is_some() + || store.get(&variable).is_some_and(|range| { + range.ranges.values().any(|(value, _, _)| value.is_some()) + }); if written { // Read the selected bits out of the current value. let (whole, whole_sources) = self.read(store, variable, full(var_width))?; diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index bebcdf9317a..10ebf538941 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -344,7 +344,7 @@ impl<'p, 'a> Ff<'p, 'a> { } else { expr }; - let expr = self.propagate(&expr); + let expr = force_reads(&self.propagate(&expr), self.m); if let (sv::ir::Expr::Literal(literal), Some((width, _))) = (&expr, context) && let Some(fill) = unbased_fill_literal(literal) { @@ -1391,6 +1391,28 @@ impl<'p, 'a> Ff<'p, 'a> { } fn store(&mut self, id: SourceVarId, offset: SIROffset, width: usize, value: RegisterId) { + let value = if let Some((enabled, forced)) = self.m.force_controls(id) { + let condition = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Load( + condition, + stable(enabled), + SIROffset::Static(0), + 1, + )); + let replacement = self.b.alloc_reg(self.b.register(&value).clone()); + self.b.emit(SIRInstruction::Load( + replacement, + stable(forced), + offset.clone(), + width, + )); + let selected = self.b.alloc_reg(self.b.register(&value).clone()); + self.b + .emit(SIRInstruction::Mux(selected, condition, replacement, value)); + selected + } else { + value + }; let target = self.target(id); self.b.emit(SIRInstruction::Store( target, @@ -3908,3 +3930,90 @@ fn substitute_overlay( }, } } + +fn force_reads(expr: &sv::ir::Expr, m: &ProcModule<'_>) -> sv::ir::Expr { + if m.forceable.is_empty() { + return expr.clone(); + } + use sv::ir::Expr; + let go = |expr: &Expr| force_reads(expr, m); + match expr { + Expr::Ident(name) => { + if let Some(id) = m.id(name) + && let Some((enabled, forced)) = m.force_controls(id) + { + Expr::Resize { + width: m.var(id).width, + signed: m.var(id).signed, + expr: Box::new(Expr::Mux { + condition: Box::new(Expr::Ident(m.var(enabled).path[0].clone())), + then_expr: Box::new(Expr::Ident(m.var(forced).path[0].clone())), + else_expr: Box::new(expr.clone()), + }), + } + } else { + expr.clone() + } + } + Expr::Literal(_) => expr.clone(), + Expr::Select { + expr, + msb, + lsb, + signed, + } => Expr::Select { + expr: Box::new(go(expr)), + msb: msb.clone(), + lsb: lsb.clone(), + signed: *signed, + }, + Expr::Concat(parts) => Expr::Concat(parts.iter().map(go).collect()), + Expr::RepeatConcat { count, parts } => Expr::RepeatConcat { + count: count.clone(), + parts: parts.iter().map(go).collect(), + }, + Expr::Resize { + expr, + width, + signed, + } => Expr::Resize { + expr: Box::new(go(expr)), + width: *width, + signed: *signed, + }, + Expr::Unary { op, expr } => Expr::Unary { + op: *op, + expr: Box::new(go(expr)), + }, + Expr::Binary { left, op, right } => Expr::Binary { + left: Box::new(go(left)), + op: *op, + right: Box::new(go(right)), + }, + Expr::Mux { + condition, + then_expr, + else_expr, + } => Expr::Mux { + condition: Box::new(go(condition)), + then_expr: Box::new(go(then_expr)), + else_expr: Box::new(go(else_expr)), + }, + Expr::Call { + callee, + args, + arg_order, + } => Expr::Call { + arg_order: arg_order.clone(), + callee: callee.clone(), + args: args.iter().map(|arg| arg.as_ref().map(go)).collect(), + }, + Expr::Inside { expr, items } => Expr::Inside { + expr: Box::new(go(expr)), + items: items + .iter() + .map(|item| item.map(&mut |operand| go(operand))) + .collect(), + }, + } +} diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index b931cb20de6..56ef6cc6520 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -33,6 +33,7 @@ pub(super) struct ProcModule<'a> { /// Number of extern calls lowered so far. pub extern_calls: usize, pub four_state: bool, + pub forceable: HashMap, /// Hidden variables created while lowering, for the caller to publish. pub created: Vec, temp_counter: usize, @@ -127,7 +128,20 @@ impl<'a> ProcModule<'a> { unpacked_bounds.insert(id, bounds); } } + let forceable = variables + .iter() + .filter_map(|(&enabled, var)| { + let (target, true) = var.force_control? else { + return None; + }; + let value = variables.iter().find_map(|(&id, var)| { + (var.force_control == Some((target, false))).then_some(id) + })?; + Some((target, (enabled, value))) + }) + .collect(); Self { + forceable, variables, name_to_id, next_id, @@ -498,6 +512,10 @@ impl<'a> ProcModule<'a> { self.name_to_id.get(name).copied() } + pub fn force_controls(&self, id: SourceVarId) -> Option<(SourceVarId, SourceVarId)> { + self.forceable.get(&id).copied() + } + pub fn var(&self, id: SourceVarId) -> &SvVariable { &self.variables[&id] } @@ -552,6 +570,7 @@ impl<'a> ProcModule<'a> { }, source: None, hidden: true, + force_control: None, }, ); self.name_to_id.insert(name, id); @@ -613,6 +632,7 @@ impl<'a> ProcModule<'a> { type_kind: source.type_kind, source: None, hidden: true, + force_control: None, }; let id = next_var_id(&mut self.next_id); self.variables.insert(id, variable); @@ -1007,6 +1027,7 @@ pub(super) fn register_locals( type_kind: type_info.type_kind, source: None, hidden: true, + force_control: None, }, ); name_to_id.insert(local.name.clone(), id); 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..945f9e1528d 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 @@ -3058,14 +3069,26 @@ pub fn plan_interfaces( sources: &[(&str, &Path)], bindings: &[(String, String, Vec<(String, String)>)], ) -> Converted { + plan_interfaces_with_member_paths(sources, bindings).map(|(plan, _)| plan) +} + +/// Original paths of flattened interface fields, indexed by bound module name. +pub type InterfaceMemberPaths = HashMap>>; + +/// Build the interface plan and retain source member paths for reflection. +pub fn plan_interfaces_with_member_paths( + sources: &[(&str, &Path)], + bindings: &[(String, String, Vec<(String, String)>)], +) -> Converted<(NativeInterfacePlan, InterfaceMemberPaths)> { let files = sources .iter() .map(|(code, path)| File::new(code, path)) .collect::>>()?; let design = Design::collect(&files)?; let mut result = NativeInterfacePlan::default(); + let mut reflected_paths = HashMap::default(); if design.interfaces.is_empty() { - return Ok(result); + return Ok((result, reflected_paths)); } let mut queue = design .modules @@ -3391,6 +3414,18 @@ pub fn plan_interfaces( queue.push((child_name.clone(), generic)); } } + let mut member_paths = HashMap::default(); + for (handle_name, declarations) in &handles.by_name { + for (_, handle) in declarations { + for member in &design.interfaces[&handle.interface].members { + member_paths.insert( + format!("{handle_name}{SEPARATOR}{}", member.name), + vec![handle_name.clone(), member.name.clone()], + ); + } + } + } + reflected_paths.insert(bound_name.clone(), member_paths); result.modules.insert( bound_name, NativeModulePlan { @@ -3400,5 +3435,5 @@ pub fn plan_interfaces( }, ); } - Ok(result) + Ok((result, reflected_paths)) } 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..4f8fa0b85bb 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -27,8 +27,13 @@ pub mod syntax; pub mod system_functions; pub mod typecheck; -pub use ast::interfaces::{InterfacePrototype, interface_prototypes, interface_prototypes_for}; -pub use ast::interfaces::{NativeInterfacePlan, plan_interfaces}; +pub use ast::interfaces::{ + InterfaceMemberPaths, NativeInterfacePlan, plan_interfaces, plan_interfaces_with_member_paths, +}; +pub use ast::interfaces::{ + InterfacePrototype, interface_prototypes, interface_prototypes_for, + interface_prototypes_with_options, +}; pub use ast::packages::Packages; pub use ast::{ModuleInterface, ModuleInterfaces}; pub use ir::Ir; @@ -38,6 +43,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 +239,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/Cargo.toml b/crates/celox-vpi/Cargo.toml index 09346002387..2fbdfa3cc2f 100644 --- a/crates/celox-vpi/Cargo.toml +++ b/crates/celox-vpi/Cargo.toml @@ -9,7 +9,8 @@ description.workspace = true edition.workspace = true [features] -systemverilog = ["celox/systemverilog"] +default = ["systemverilog"] +systemverilog = ["celox/systemverilog", "dep:celox-sv-analyzer"] [lib] crate-type = ["rlib", "cdylib"] @@ -36,9 +37,12 @@ celox = { path = "../celox", features = ["systemverilog"] } [dependencies] celox-design.workspace = true +celox-sv-analyzer = { workspace = true, optional = true } clap.workspace = true fxhash.workspace = true libloading = "0.9" +serde.workspace = true +toml.workspace = true veryl-metadata.workspace = true [dev-dependencies] diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index e535c94da1e..89dde289003 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -12,7 +12,11 @@ use celox::{ NativeProgramImage, NativeProgramInstance, StateDifference, StateFile, StateObject, StateRole, format_state_value, }; -use clap::{Args, Parser, Subcommand}; +use clap::{Args, CommandFactory, FromArgMatches, Parser, Subcommand}; + +#[path = "celox/project.rs"] +mod project; +use project::{Design, DesignArgs}; #[derive(Parser)] #[command( @@ -37,34 +41,71 @@ enum CliCommand { #[derive(Args)] struct RunArgs { - /// SystemVerilog sources in compilation order, or one Veryl project entry file. - #[arg(required = true)] - sources: Vec, + #[command(flatten)] + design: DesignArgs, - /// Top-level testbench module name. - #[arg(long)] - top: String, + /// Maximum SV scheduler steps or Veryl ticks (default: project setting or 1000000). + /// Does not bound compilation or work within a single step/tick. + #[arg(long, value_parser = clap::value_parser!(u64).range(1..))] + max_steps: Option, +} - /// Compiler optimization level: O0, O1, O2. - #[arg(short = 'O', long, default_value = "O2", value_parser = parse_opt_level)] +struct RunConfig { + design: Design, opt_level: celox::OptLevel, - - /// Maximum SV scheduler steps or Veryl testbench ticks before failing. - /// Does not bound compilation or work within a single step/tick. - #[arg(long, default_value_t = 1_000_000, value_parser = clap::value_parser!(u64).range(1..))] max_steps: u64, } +fn resolve_design(arguments: DesignArgs) -> Design { + arguments.resolve().unwrap_or_else(|message| { + Cli::command() + .error(clap::error::ErrorKind::InvalidValue, message) + .exit() + }) +} + +fn cli_from_matches(matches: &clap::ArgMatches) -> Result { + let mut cli = Cli::from_arg_matches(matches)?; + match &mut cli.command { + CliCommand::Run(arguments) => arguments.design.capture_input_order( + matches + .subcommand_matches("run") + .expect("parsed run command"), + ), + CliCommand::Vpi(VpiArgs { + command: VpiCommand::Build(arguments), + }) => { + arguments.design.capture_input_order( + matches + .subcommand_matches("vpi") + .and_then(|matches| matches.subcommand_matches("build")) + .expect("parsed vpi build command"), + ); + } + CliCommand::State(_) => {} + } + Ok(cli) +} + fn parse_opt_level(value: &str) -> Result { celox::OptLevel::parse(value).ok_or_else(|| "expected O0, O1, or O2".to_string()) } +fn resolve_run_config(arguments: RunArgs) -> RunConfig { + let design = resolve_design(arguments.design); + RunConfig { + opt_level: design.opt_level.unwrap_or(celox::OptLevel::O2), + max_steps: arguments + .max_steps + .or(design.max_steps) + .unwrap_or(1_000_000), + design, + } +} + fn run_testbench(arguments: RunArgs) -> Result<(), String> { - let all_sv = arguments.sources.iter().all(|path| { - path.extension() - .is_some_and(|extension| extension == "sv" || extension == "v") - }); - if all_sv { + let arguments = resolve_run_config(arguments); + if arguments.design.is_sv() { #[cfg(feature = "systemverilog")] return run_sv(arguments); #[cfg(not(feature = "systemverilog"))] @@ -73,14 +114,14 @@ fn run_testbench(arguments: RunArgs) -> Result<(), String> { .to_string(), ); } - if arguments.sources.len() != 1 - || !arguments.sources[0] + if arguments.design.sources.len() != 1 + || !arguments.design.sources[0] .extension() .is_some_and(|extension| extension == "veryl") { return Err("pass .sv/.v sources, or one .veryl project entry file".to_string()); } - let source = &arguments.sources[0]; + let source = &arguments.design.sources[0]; let mut metadata = veryl_metadata::Metadata::search_from(source) .ok() .map(|path| { @@ -117,16 +158,20 @@ fn run_testbench(arguments: RunArgs) -> Result<(), String> { .iter() .map(|(text, path)| (text.as_str(), *path)) .collect(), - &arguments.top, + &arguments.design.top, ) .four_state(true) - .opt_level(arguments.opt_level); + .opt_level(arguments.opt_level) + .diagnostic_policy(arguments.design.diagnostics.clone()) + .signal_access(arguments.design.signal_access.clone()); + builder = arguments.design.apply_parameters(builder); 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() })?; @@ -148,25 +193,23 @@ fn run_testbench(arguments: RunArgs) -> Result<(), String> { } #[cfg(feature = "systemverilog")] -fn run_sv(arguments: RunArgs) -> Result<(), String> { - let contents = arguments - .sources - .iter() - .map(|path| { - std::fs::read_to_string(path) - .map_err(|error| format!("failed to read {}: {error}", path.display())) - }) - .collect::, _>>()?; - let sources = contents +fn run_sv(arguments: RunConfig) -> Result<(), String> { + let sources = arguments.design.sv_sources()?; + let source_refs = sources .iter() - .zip(&arguments.sources) .map(|(text, path)| (text.as_str(), path.as_path())) .collect(); - let simulation = celox::Simulation::from_sv_sources(sources, &arguments.top) + let builder = celox::Simulation::from_sv_sources(source_refs, &arguments.design.top) .four_state(true) .opt_level(arguments.opt_level) + .diagnostic_policy(arguments.design.diagnostics.clone()) + .signal_access(arguments.design.signal_access.clone()); + let simulation = arguments + .design + .apply_parameters(builder) .build() .map_err(|error| format!("compilation failed:\n{error}"))?; + report_warnings(simulation.warnings())?; simulate_sv( simulation, arguments.max_steps, @@ -311,13 +354,8 @@ enum VpiCommand { #[derive(Args)] struct BuildArgs { - /// One Veryl project entry file, or one or more SystemVerilog (.sv) files. - #[arg(required = true)] - sources: Vec, - - /// Top-level module name. - #[arg(long)] - top: String, + #[command(flatten)] + design: DesignArgs, /// Native simulation executable to create. #[arg(short, long, default_value = "celox.out")] @@ -356,6 +394,7 @@ struct SimulationArgs { } fn build(arguments: BuildArgs) -> Result<(), String> { + let design = resolve_design(arguments.design); let runtime = env::current_exe() .map_err(|error| format!("failed to locate the celox executable: {error}"))?; if arguments.output.exists() @@ -379,18 +418,68 @@ fn build(arguments: BuildArgs) -> Result<(), String> { })?; } - let sources = arguments - .sources - .iter() - .map(PathBuf::as_path) - .collect::>(); - celox_vpi::driver::compile_native_sources(&sources, &arguments.top)? + compile_native_design(&design)? .write_attached_runtime(runtime, &arguments.output) .map_err(|error| format!("failed to write {}: {error}", arguments.output.display()))?; println!("Created {}", arguments.output.display()); Ok(()) } +fn compile_native_design(design: &Design) -> Result { + if design.is_sv() { + #[cfg(feature = "systemverilog")] + { + let sources = design.sv_sources()?; + let refs = sources + .iter() + .map(|(text, path)| (text.as_str(), path.as_path())) + .collect(); + let builder = celox::Simulator::from_sv_sources(refs, &design.top) + .four_state(true) + .diagnostic_policy(design.diagnostics.clone()) + .signal_access(design.signal_access.clone()) + .opt_level(design.opt_level.unwrap_or(celox::OptLevel::O1)); + let simulator = design + .apply_parameters(builder) + .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"))] + return Err( + "SystemVerilog support requires building celox-vpi with --features systemverilog" + .to_string(), + ); + } + if design.sources.len() != 1 + || !design.sources[0] + .extension() + .is_some_and(|extension| extension == "veryl") + { + return Err("pass .sv/.v sources, or one .veryl project entry file".to_string()); + } + let (image, warnings) = celox_vpi::driver::compile_native_image_with_parameters( + &design.sources[0], + &design.top, + design.diagnostics.clone(), + design.opt_level.unwrap_or(celox::OptLevel::O1), + design.signal_access.clone(), + &design.parameters, + )?; + 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 { env::var_os(name).map(PathBuf::from) } @@ -731,7 +820,10 @@ fn run() -> Result { Some(attached) => { run_simulation(attached.image, SimulationArgs::parse()).map(|()| ExitCode::SUCCESS) } - None => match Cli::parse().command { + None => match cli_from_matches(&Cli::command().get_matches()) + .unwrap_or_else(|error| error.exit()) + .command + { CliCommand::Run(arguments) => run_testbench(arguments).map(|()| ExitCode::SUCCESS), CliCommand::Vpi(arguments) => match arguments.command { VpiCommand::Build(arguments) => build(arguments).map(|()| ExitCode::SUCCESS), @@ -757,31 +849,76 @@ mod tests { #[test] fn run_defaults_to_o2_for_both_languages_and_allows_overrides() { - for (source, default) in [ - ("top.sv", celox::OptLevel::O2), - ("top.v", celox::OptLevel::O2), - ("top.veryl", celox::OptLevel::O2), - ] { - for (extra, expected) in [ - (Vec::new(), default), - (vec!["-O", "O0"], celox::OptLevel::O0), - (vec!["-O", "O1"], celox::OptLevel::O1), - (vec!["--opt-level", "O2"], celox::OptLevel::O2), - ] { - let cli = Cli::try_parse_from( - ["celox", "run", source, "--top", "Top"] - .into_iter() - .chain(extra), - ) - .unwrap(); - let CliCommand::Run(arguments) = cli.command else { - panic!("expected the run command"); - }; - assert_eq!(arguments.opt_level, expected, "{source}"); + let temporary = tempfile::tempdir().unwrap(); + for project_level in [None, Some("O0"), Some("O1"), Some("O2")] { + let project = temporary.path().join("celox.toml"); + if let Some(level) = project_level { + std::fs::write(&project, format!("opt_level = '{level}'\n")).unwrap(); + } + for source in ["top.sv", "top.v", "top.veryl"] { + for extra in [ + vec![], + vec!["-O", "O0"], + vec!["-O", "O1"], + vec!["--opt-level", "O2"], + ] { + let mut argv = vec!["celox", "run", source, "--top", "Top"]; + if project_level.is_some() { + argv.extend(["--project", project.to_str().unwrap()]); + } + argv.extend(extra.iter().copied()); + let cli = Cli::try_parse_from(argv).unwrap(); + let CliCommand::Run(arguments) = cli.command else { + panic!("expected the run command"); + }; + let expected = + parse_opt_level(extra.last().copied().or(project_level).unwrap_or("O2")) + .unwrap(); + assert_eq!( + resolve_run_config(arguments).opt_level, + expected, + "{source}: {project_level:?} {extra:?}" + ); + } } } } + #[test] + fn source_and_filelist_arguments_keep_their_command_line_order() { + let temporary = tempfile::tempdir().unwrap(); + let list = temporary.path().join("sources.f"); + std::fs::write(&list, "middle.sv\n").unwrap(); + for command in [vec!["celox", "run"], vec!["celox", "vpi", "build"]] { + let matches = Cli::command() + .try_get_matches_from(command.into_iter().chain([ + "first.sv", + "-f", + list.to_str().unwrap(), + "last.sv", + "--top", + "Top", + ])) + .unwrap(); + let cli = cli_from_matches(&matches).unwrap(); + let design = match cli.command { + CliCommand::Run(args) => args.design.resolve().unwrap(), + CliCommand::Vpi(VpiArgs { + command: VpiCommand::Build(args), + }) => args.design.resolve().unwrap(), + _ => panic!("expected a compilation command"), + }; + assert_eq!( + design.sources, + [ + PathBuf::from("first.sv"), + temporary.path().join("middle.sv"), + PathBuf::from("last.sv") + ] + ); + } + } + #[cfg(feature = "systemverilog")] #[test] fn sv_scheduler_limit_fails_and_preserves_scheduled_output() { diff --git a/crates/celox-vpi/src/bin/celox/project.rs b/crates/celox-vpi/src/bin/celox/project.rs new file mode 100644 index 00000000000..a3d8e4fa9a2 --- /dev/null +++ b/crates/celox-vpi/src/bin/celox/project.rs @@ -0,0 +1,596 @@ +//! Project and file-list resolution shared by `run` and `vpi build`. + +use std::{ + collections::BTreeMap, + path::{Path, PathBuf}, +}; + +use clap::Args; +use serde::Deserialize; + +#[derive(Args, Default)] +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, + /// Optimization level: O0, O1, O2 (default: project setting or O2 for run, O1 for vpi build). + #[arg(short = 'O', long, value_parser = super::parse_opt_level)] + opt_level: Option, + /// Preserve a hierarchical signal for observation (repeatable; replaces project list). + #[arg( + long = "live-signal", + value_name = "PATH", + conflicts_with = "no_live_signals" + )] + live_signals: Vec, + /// Permit force/release on a packed SV signal (repeatable; replaces project list). + #[arg( + long = "force-signal", + value_name = "PATH", + conflicts_with = "no_force_signals" + )] + force_signals: Vec, + /// Clear the project's live_signals list. + #[arg(long)] + no_live_signals: bool, + /// Clear the project's force_signals list. + #[arg(long)] + no_force_signals: bool, + /// Project manifest (otherwise discover celox.toml when no inputs are given). + #[arg(long, value_name = "FILE")] + project: Option, + /// Named target in celox.toml. + #[arg(long, value_name = "NAME")] + target: Option, + /// Ordered SV file list; relative entries resolve from the list's directory. + #[arg(short = 'f', long = "filelist", value_name = "FILE")] + filelists: Vec, + /// SystemVerilog include search directory (repeatable). + #[arg(short = 'I', long = "include-dir", value_name = "DIR")] + include_dirs: Vec, + /// SystemVerilog macro, NAME or NAME=VALUE (repeatable; last value wins). + #[arg(short = 'D', long = "define", value_name = "NAME[=VALUE]")] + defines: Vec, + /// Override a numeric top parameter (repeatable; last value wins). + #[arg( + short = 'G', + long = "parameter", + visible_alias = "param", + value_name = "NAME=VALUE" + )] + parameters: Vec, + /// Top-level module; overrides the selected target. + #[arg(long)] + top: Option, + #[arg(skip)] + input_order: Vec, +} + +enum Input { + Source(usize), + Filelist(usize), +} + +#[derive(Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +struct Manifest { + // Existing NAPI project settings can share this manifest. Their consumers + // remain in celox-napi; keep these types aligned with CeloxConfig there. + #[serde(rename = "exclude")] + _exclude: Vec, + #[serde(rename = "test")] + _test: VerylTestConfig, + #[serde(rename = "simulation")] + _simulation: VerylSimulationConfig, + diagnostics: celox::DiagnosticPolicy, + sources: Vec, + filelists: Vec, + include_dirs: Vec, + defines: BTreeMap, + parameters: BTreeMap, + top: Option, + opt_level: Option, + live_signals: Option>, + force_signals: Option>, + max_steps: Option, + default_target: Option, + targets: BTreeMap, +} + +#[derive(Default, Deserialize)] +#[serde(default)] +struct VerylTestConfig { + #[serde(rename = "sources")] + _sources: Vec, +} + +#[derive(Default, Deserialize)] +#[serde(default)] +struct VerylSimulationConfig { + #[serde(rename = "max_steps")] + _max_steps: Option, +} + +#[derive(Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +struct Target { + diagnostics: celox::DiagnosticPolicy, + sources: Vec, + filelists: Vec, + include_dirs: Vec, + defines: BTreeMap, + parameters: BTreeMap, + top: Option, + opt_level: Option, + live_signals: Option>, + force_signals: Option>, + max_steps: Option, +} + +#[derive(Default)] +pub(super) struct Design { + pub diagnostics: celox::DiagnosticPolicy, + pub sources: Vec, + pub include_dirs: Vec, + pub defines: BTreeMap, + pub parameters: BTreeMap, + pub top: String, + pub opt_level: Option, + pub signal_access: celox::SignalAccessOptions, + pub max_steps: Option, +} + +impl DesignArgs { + pub fn capture_input_order(&mut self, matches: &clap::ArgMatches) { + let mut inputs = Vec::new(); + for (id, is_list) in [("sources", false), ("filelists", true)] { + if let Some(indices) = matches.indices_of(id) { + inputs.extend(indices.enumerate().map(|(offset, position)| { + ( + position, + if is_list { + Input::Filelist(offset) + } else { + Input::Source(offset) + }, + ) + })); + } + } + inputs.sort_by_key(|(position, _)| *position); + self.input_order = inputs.into_iter().map(|(_, input)| input).collect(); + } + + pub fn resolve(self) -> Result { + let manifest_path = match self.project { + Some(path) => Some(path), + None if self.target.is_some() + || (self.sources.is_empty() && self.filelists.is_empty()) => + { + let cwd = std::env::current_dir() + .map_err(|error| format!("failed to locate current directory: {error}"))?; + cwd.ancestors() + .map(|path| path.join("celox.toml")) + .find(|path| path.is_file()) + } + None => None, + }; + if self.target.is_some() && manifest_path.is_none() { + return Err( + "--target requires --project FILE or a discoverable celox.toml".to_string(), + ); + } + let mut design = Design::default(); + if let Some(path) = manifest_path { + let path = path + .canonicalize() + .map_err(|error| format!("failed to open project {}: {error}", path.display()))?; + let text = std::fs::read_to_string(&path) + .map_err(|error| format!("failed to read project {}: {error}", path.display()))?; + let config: Manifest = toml::from_str(&text) + .map_err(|error| format!("invalid project {}: {error}", path.display()))?; + let base = path.parent().expect("canonical project has a parent"); + let target_name = self.target.as_ref().or(config.default_target.as_ref()); + let selected = match target_name { + Some(name) => Some(config.targets.get(name).ok_or_else(|| { + format!( + "unknown target `{name}` in {}; available targets: {}", + path.display(), + config + .targets + .keys() + .cloned() + .collect::>() + .join(", ") + ) + })?), + None if config.top.is_some() || config.targets.is_empty() => None, + None if config.targets.len() == 1 => config.targets.values().next(), + None => { + return Err(format!( + "select --target NAME; available targets: {}", + config + .targets + .keys() + .cloned() + .collect::>() + .join(", ") + )); + } + }; + design.extend( + base, + &config.sources, + &config.filelists, + &config.include_dirs, + &config.defines, + )?; + design.extend_parameters(&config.parameters)?; + design.diagnostics = config.diagnostics.clone(); + design.top = config.top.clone().unwrap_or_default(); + let mut opt_level = config.opt_level.as_deref(); + design.signal_access.live_signals = config.live_signals.clone().unwrap_or_default(); + design.signal_access.force_signals = config.force_signals.clone().unwrap_or_default(); + design.max_steps = config.max_steps; + if let Some(target) = selected { + design.extend_parameters(&target.parameters)?; + design.diagnostics.0.extend(target.diagnostics.0.clone()); + design.extend( + base, + &target.sources, + &target.filelists, + &target.include_dirs, + &target.defines, + )?; + if let Some(top) = &target.top { + design.top.clone_from(top); + } + opt_level = target.opt_level.as_deref().or(opt_level); + if let Some(paths) = &target.live_signals { + design.signal_access.live_signals.clone_from(paths); + } + if let Some(paths) = &target.force_signals { + design.signal_access.force_signals.clone_from(paths); + } + design.max_steps = target.max_steps.or(design.max_steps); + } + design.opt_level = opt_level + .map(|value| { + celox::OptLevel::parse(value).ok_or_else(|| { + format!("invalid opt_level `{value}`: expected O0, O1, or O2") + }) + }) + .transpose()?; + if design.max_steps == Some(0) { + return Err("max_steps must be positive".to_string()); + } + } + design.opt_level = self.opt_level.or(design.opt_level); + if self.no_live_signals { + design.signal_access.live_signals.clear(); + } else if !self.live_signals.is_empty() { + design.signal_access.live_signals = self.live_signals; + } + if self.no_force_signals { + design.signal_access.force_signals.clear(); + } else if !self.force_signals.is_empty() { + design.signal_access.force_signals = self.force_signals; + } + let inputs = if self.input_order.is_empty() { + (0..self.sources.len()) + .map(Input::Source) + .chain((0..self.filelists.len()).map(Input::Filelist)) + .collect() + } else { + self.input_order + }; + for input in inputs { + match input { + Input::Source(index) => design.sources.push(self.sources[index].clone()), + Input::Filelist(index) => { + design.read_filelist(&self.filelists[index], &mut Vec::new())? + } + } + } + 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)?; + } + for parameter in self.parameters { + let (name, value) = parameter + .split_once('=') + .ok_or_else(|| format!("invalid parameter `{parameter}`: expected NAME=VALUE"))?; + design.set_parameter(name, parse_parameter_value(value)?)?; + } + if let Some(top) = self.top { + design.top = top; + } + if design.sources.is_empty() { + return Err( + "provide sources, -f FILE, or a celox.toml project with sources".to_string(), + ); + } + if design.top.trim().is_empty() { + return Err("provide --top MODULE or set top in celox.toml".to_string()); + } + if !design.is_sv() && (!design.include_dirs.is_empty() || !design.defines.is_empty()) { + return Err( + "include directories and defines require SystemVerilog sources".to_string(), + ); + } + Ok(design) + } +} + +/// TOML integers cover ordinary values; strings also permit radix prefixes +/// and the full unsigned 64-bit range supported by SimulatorBuilder::param. +#[derive(Deserialize)] +#[serde(untagged)] +enum ParameterValue { + Integer(u64), + String(String), +} + +fn parse_parameter_value(value: &str) -> Result { + let (radix, digits) = if let Some(digits) = value.strip_prefix("0x") { + (16, digits) + } else if let Some(digits) = value.strip_prefix("0b") { + (2, digits) + } else if let Some(digits) = value.strip_prefix("0o") { + (8, digits) + } else { + (10, value) + }; + let invalid = || { + format!( + "invalid parameter value `{value}`: expected an unsigned 64-bit integer (decimal, 0x, 0o, or 0b)" + ) + }; + if digits.is_empty() + || digits.starts_with('_') + || digits.ends_with('_') + || digits.contains("__") + || digits.starts_with('+') + { + return Err(invalid()); + } + u64::from_str_radix(&digits.replace('_', ""), radix).map_err(|_| invalid()) +} + +impl Design { + pub fn apply_parameters<'a, T>( + &self, + mut builder: celox::SimulatorBuilder<'a, T>, + ) -> celox::SimulatorBuilder<'a, T> { + for (name, value) in &self.parameters { + builder = builder.param(name, *value); + } + builder + } + + fn extend_parameters( + &mut self, + parameters: &BTreeMap, + ) -> Result<(), String> { + for (name, value) in parameters { + let value = match value { + ParameterValue::Integer(value) => *value, + ParameterValue::String(value) => parse_parameter_value(value)?, + }; + self.set_parameter(name, value)?; + } + Ok(()) + } + + fn set_parameter(&mut self, name: &str, value: u64) -> Result<(), String> { + if name.is_empty() + || !name.bytes().enumerate().all(|(index, byte)| { + byte == b'_' + || byte.is_ascii_alphabetic() + || (index != 0 && (byte.is_ascii_digit() || byte == b'$')) + }) + { + return Err(format!("invalid top parameter name `{name}`")); + } + self.parameters.insert(name.to_string(), value); + Ok(()) + } + + pub fn is_sv(&self) -> bool { + self.sources.iter().all(|path| { + path.extension() + .is_some_and(|extension| extension == "sv" || extension == "v") + }) + } + + fn extend( + &mut self, + base: &Path, + sources: &[PathBuf], + lists: &[PathBuf], + includes: &[PathBuf], + defines: &BTreeMap, + ) -> Result<(), String> { + self.sources + .extend(sources.iter().map(|path| base.join(path))); + self.include_dirs + .extend(includes.iter().map(|path| base.join(path))); + for (name, value) in defines { + self.define(&format!("{name}={value}"))?; + } + for list in lists { + self.read_filelist(&base.join(list), &mut Vec::new())?; + } + Ok(()) + } + + fn define(&mut self, definition: &str) -> Result<(), String> { + let (name, value) = definition.split_once('=').unwrap_or((definition, "1")); + if name.is_empty() + || !name.bytes().enumerate().all(|(index, byte)| { + byte == b'_' + || byte.is_ascii_alphabetic() + || (index != 0 && (byte.is_ascii_digit() || byte == b'$')) + }) + || value.contains(['\n', '\r']) + { + return Err(format!("invalid macro definition `{definition}`")); + } + self.defines.insert(name.to_string(), value.to_string()); + Ok(()) + } + + fn read_filelist(&mut self, path: &Path, active: &mut Vec) -> Result<(), String> { + let path = path + .canonicalize() + .map_err(|error| format!("failed to open file list {}: {error}", path.display()))?; + if active.contains(&path) { + return Err(format!("recursive file list: {}", path.display())); + } + if active.len() >= 64 { + return Err("file-list nesting exceeds 64 levels".to_string()); + } + let text = std::fs::read_to_string(&path) + .map_err(|error| format!("failed to read file list {}: {error}", path.display()))?; + let tokens = tokenize(&text).map_err(|error| format!("{}: {error}", path.display()))?; + let base = path.parent().expect("canonical file list has a parent"); + active.push(path.clone()); + let mut tokens = tokens.iter(); + while let Some(token) = tokens.next() { + match token.as_str() { + "-f" | "-I" | "-D" => { + let value = tokens + .next() + .ok_or_else(|| format!("{}: {token} requires a value", path.display()))?; + match token.as_str() { + "-f" => self.read_filelist(&base.join(value), active)?, + "-I" => self.include_dirs.push(base.join(value)), + _ => self.define(value)?, + } + } + _ if token.starts_with("+incdir+") => { + for value in token[8..].split('+') { + if value.is_empty() { + return Err(format!("{}: empty +incdir+ path", path.display())); + } + self.include_dirs.push(base.join(value)); + } + } + _ if token.starts_with("+define+") => { + for value in token[8..].split('+') { + self.define(value)?; + } + } + _ if token.starts_with("-I") && token.len() > 2 => { + self.include_dirs.push(base.join(&token[2..])) + } + _ if token.starts_with("-D") && token.len() > 2 => self.define(&token[2..])?, + _ if token.starts_with('-') || token.starts_with('+') => { + return Err(format!( + "{}: unsupported file-list option `{token}`", + path.display() + )); + } + _ => self.sources.push(base.join(token)), + } + } + active.pop(); + Ok(()) + } + + #[cfg(feature = "systemverilog")] + pub fn sv_sources(&self) -> Result, String> { + let macros = self + .defines + .iter() + .map(|(name, value)| (name.clone(), Some(value.clone()))) + .collect::>(); + let includes = self + .include_dirs + .iter() + .map(PathBuf::as_path) + .collect::>(); + self.sources + .iter() + .map(|path| { + let text = std::fs::read_to_string(path) + .map_err(|error| format!("failed to read {}: {error}", path.display()))?; + let text = if macros.is_empty() && includes.is_empty() { + text + } else { + celox_sv_analyzer::syntax::preprocess_source(&text, path, ¯os, &includes) + .map_err(|error| { + format!("preprocessing {} failed: {error}", path.display()) + })? + }; + Ok((text, path.clone())) + }) + .collect() + } +} + +/// Whitespace-separated paths/options, quoted paths, backslash escapes and +/// #, // and /* */ comments. No shell expansion or execution is performed. +fn tokenize(text: &str) -> Result, String> { + let mut chars = text.chars().peekable(); + let mut tokens = Vec::new(); + let mut token = String::new(); + let mut quote = None; + while let Some(c) = chars.next() { + if let Some(delimiter) = quote { + if c == delimiter { + quote = None; + } else if c == '\\' && delimiter == '"' { + token.push(chars.next().ok_or("trailing escape in quoted path")?); + } else { + token.push(c); + } + } else if c == '"' || c == '\'' { + quote = Some(c); + } else if c == '\\' { + token.push(chars.next().ok_or("trailing escape in file list")?); + } else if (c == '#' && token.is_empty()) + || (c == '/' && chars.peek() == Some(&'/') && token.is_empty()) + { + for c in chars.by_ref() { + if c == '\n' { + break; + } + } + } else if c == '/' && chars.peek() == Some(&'*') { + chars.next(); + let mut closed = false; + while let Some(c) = chars.next() { + if c == '*' && chars.peek() == Some(&'/') { + chars.next(); + closed = true; + break; + } + } + if !closed { + return Err("unterminated file-list comment".to_string()); + } + if !token.is_empty() { + tokens.push(std::mem::take(&mut token)); + } + } else if c.is_whitespace() { + if !token.is_empty() { + tokens.push(std::mem::take(&mut token)); + } + } else { + token.push(c); + } + } + if quote.is_some() { + return Err("unterminated quoted path in file list".to_string()); + } + if !token.is_empty() { + tokens.push(token); + } + Ok(tokens) +} diff --git a/crates/celox-vpi/src/driver.rs b/crates/celox-vpi/src/driver.rs index ba812e4321a..9c7f09adb60 100644 --- a/crates/celox-vpi/src/driver.rs +++ b/crates/celox-vpi/src/driver.rs @@ -1,8 +1,10 @@ //! Shared compiler and cocotb runtime entry points used by the command-line tools. -use std::path::Path; +use std::{collections::BTreeMap, 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,64 @@ pub fn compile_native_sources(sources: &[&Path], top: &str) -> Result Result<(NativeProgramImage, Vec), String> { + compile_native_image_configured( + source, + top, + policy, + celox::OptLevel::O0, + celox::SignalAccessOptions::default(), + true, + &BTreeMap::new(), + ) +} + +/// Compile with an explicit observation/force contract, retaining optimization. +pub fn compile_native_image_with_options( + source: &Path, + top: &str, + policy: DiagnosticPolicy, + level: celox::OptLevel, + access: celox::SignalAccessOptions, +) -> Result<(NativeProgramImage, Vec), String> { + compile_native_image_with_parameters(source, top, policy, level, access, &BTreeMap::new()) +} + +/// Compile with numeric top parameter overrides, leaving project source files intact. +pub fn compile_native_image_with_parameters( + source: &Path, + top: &str, + policy: DiagnosticPolicy, + level: celox::OptLevel, + access: celox::SignalAccessOptions, + parameters: &BTreeMap, +) -> Result<(NativeProgramImage, Vec), String> { + compile_native_image_configured(source, top, policy, level, access, false, parameters) +} + +fn compile_native_image_configured( + source: &Path, + top: &str, + policy: DiagnosticPolicy, + level: celox::OptLevel, + access: celox::SignalAccessOptions, + legacy_force: bool, + parameters: &BTreeMap, +) -> 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 @@ -56,23 +115,38 @@ pub fn compile_native_sources(sources: &[&Path], top: &str) -> Result>(); - Simulator::from_sources(source_refs, top) + let builder = 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) + .native_force_support(legacy_force) + .signal_access(access.clone()) + .opt_level(level); + parameters + .iter() + .fold(builder, |builder, (name, value)| { + builder.param(name, *value) + }) .build() } else { let contents = std::fs::read_to_string(source) .map_err(|error| format!("failed to read {}: {error}", source.display()))?; - Simulator::from_sources(vec![(contents.as_str(), source)], top) + let builder = Simulator::from_sources(vec![(contents.as_str(), source)], top) + .diagnostic_policy(policy.clone()) .four_state(true) - .native_force_support(true) - .opt_level(celox::OptLevel::O0) + .native_force_support(legacy_force) + .signal_access(access.clone()) + .opt_level(level); + parameters + .iter() + .fold(builder, |builder, (name, value)| { + builder.param(name, *value) + }) .build() } - .map_err(|error| format!("compilation failed: {error:?}"))?; - Ok(simulator.shared_code().program_image().clone()) + .map_err(|error| format!("compilation failed: {error}"))?; + let image = simulator.shared_code().program_image().clone(); + Ok((image, simulator.into_warnings())) } /// Run cocotb's VPI bootstrap against a compiled native program instance. diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index e1d8a32eb27..4fa69954160 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -2804,3 +2804,118 @@ fn callback_teardown_keeps_its_host_selected_until_dispatch_returns() { assert!(info.argv.is_null()); } } + +#[cfg(feature = "systemverilog")] +#[test] +fn interface_members_are_navigable_after_native_image_round_trip() { + let _serial = lock_vpi(); + let source = r#" + interface Axis; + logic [7:0] data, cost$usd; + logic valid, ready; + modport sink(input data, valid, output ready); + endinterface + module Child(Axis.sink s_axis, output logic [7:0] y); + assign s_axis.ready = 1; + assign y = s_axis.valid ? s_axis.data + 1 : 0; + endmodule + module Top(output logic [7:0] y); + Axis s_axis(), s$axis(); + logic [7:0] cash$flow; + assign cash$flow = 3; + Child uut(s_axis, y); + endmodule + "#; + let simulator = + Simulator::from_sv_sources(vec![(source, std::path::Path::new("axis.sv"))], "Top") + .native_force_support(true) + .four_state(true) + .build_native() + .unwrap(); + let container = simulator + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let runtime = unsafe { NativeProgramInstance::from_attached_bytes(&container) }.unwrap(); + drop(simulator); + let _session = install_runtime(runtime).unwrap(); + unsafe { + let top = vpi_handle_by_name(c"Top".as_ptr(), ptr::null_mut()); + let bus = vpi_handle_by_name(c"s_axis".as_ptr(), top); + assert!(!bus.is_null(), "the declared interface must have a scope"); + let data = vpi_handle_by_name(c"data".as_ptr(), bus); + let valid = vpi_handle_by_name(c"valid".as_ptr(), bus); + let ready = vpi_handle_by_name(c"ready".as_ptr(), bus); + assert!(!data.is_null() && !valid.is_null() && !ready.is_null()); + assert_eq!(CStr::from_ptr(vpi_get_str(VPI_NAME, data)), c"data"); + assert_eq!( + CStr::from_ptr(vpi_get_str(VPI_FULL_NAME, data)), + c"Top.s_axis.data" + ); + assert_eq!(vpi_get(VPI_SIZE, data), 8); + let parent = vpi_handle(VPI_SCOPE, data); + assert_eq!( + CStr::from_ptr(vpi_get_str(VPI_FULL_NAME, parent)), + c"Top.s_axis" + ); + let child_data = vpi_handle_by_name(c"Top.uut.s_axis.data".as_ptr(), ptr::null_mut()); + assert!( + !child_data.is_null(), + "interface ports must retain their paths too" + ); + put_int(data, 41); + put_int(valid, 1); + let y = vpi_handle_by_name(c"y".as_ptr(), top); + let mut value = VpiValue { + format: VPI_INT_VAL, + value: VpiValueData { integer: 0 }, + }; + vpi_get_value(y, &mut value); + assert_eq!(value.value.integer, 42); + vpi_get_value(child_data, &mut value); + assert_eq!( + value.value.integer, 41, + "child member alias must see the deposited value" + ); + let members = vpi_iterate(VPI_REG, bus); + let mut names = Vec::new(); + loop { + let member = vpi_scan(members); + if member.is_null() { + break; + } + names.push( + CStr::from_ptr(vpi_get_str(VPI_NAME, member)) + .to_str() + .unwrap() + .to_owned(), + ); + vpi_free_object(member); + } + names.sort(); + assert_eq!(names, ["cost$usd", "data", "ready", "valid"]); + let dollar_member = vpi_handle_by_name(c"cost$usd".as_ptr(), bus); + let dollar_interface = vpi_handle_by_name(c"Top.s$axis.data".as_ptr(), ptr::null_mut()); + let dollar_signal = vpi_handle_by_name(c"Top.cash$flow".as_ptr(), ptr::null_mut()); + assert!( + !dollar_member.is_null() && !dollar_interface.is_null() && !dollar_signal.is_null() + ); + assert!(vpi_handle_by_name(c"Top.cash".as_ptr(), ptr::null_mut()).is_null()); + for handle in [ + top, + bus, + data, + valid, + ready, + parent, + child_data, + y, + dollar_member, + dollar_interface, + dollar_signal, + ] { + vpi_free_object(handle); + } + } +} diff --git a/crates/celox-vpi/tests/cocotb_e2e.rs b/crates/celox-vpi/tests/cocotb_e2e.rs index 0163ad031b8..3b4b66860d9 100644 --- a/crates/celox-vpi/tests/cocotb_e2e.rs +++ b/crates/celox-vpi/tests/cocotb_e2e.rs @@ -489,3 +489,44 @@ fn compile_reports_a_missing_additional_source() { "{error}" ); } + +#[cfg(feature = "systemverilog")] +#[test] +#[ignore = "requires a cocotb installation"] +fn cocotb_uses_declared_force_targets_in_an_optimized_native_image() { + let python = env::var("CELOX_COCOTB_PYTHON").expect("set CELOX_COCOTB_PYTHON"); + let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cocotb"); + let temporary = tempfile::tempdir().unwrap(); + let executable = temporary.path().join("force-sim"); + let results = temporary.path().join("results.xml"); + let compile = Command::new(env!("CARGO_BIN_EXE_celox")) + .args(["vpi", "build"]) + .arg(fixture.join("force_profile.sv")) + .args(["--top", "Top", "-O", "O2", "--force-signal", "Top.x", "-o"]) + .arg(&executable) + .output() + .unwrap(); + assert!(compile.status.success(), "{compile:?}"); + let site = python_output( + &python, + &["-c", "import site; print(':'.join(site.getsitepackages()))"], + ); + let runtime = Command::new(&executable) + .args([ + "--test-module", + "test_force_profile", + "--python", + &python, + "--results-file", + ]) + .arg(&results) + .current_dir(&fixture) + .env("PYTHONPATH", format!("{}:{site}", fixture.display())) + .output() + .unwrap(); + assert!(runtime.status.success(), "cocotb force failed: {runtime:?}"); + let xml = fs::read_to_string(results).unwrap(); + assert_eq!(xml.matches(" Output { + Command::new(env!("CARGO_BIN_EXE_celox")) + .current_dir(cwd) + .args(args) + .output() + .unwrap() +} + +fn success(output: &Output) { + assert!( + output.status.success(), + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); +} + +fn rejected(output: &Output, message: &str) { + assert_eq!(output.status.code(), Some(2), "{output:?}"); + assert!( + String::from_utf8_lossy(&output.stderr).contains(message), + "{output:?}" + ); +} + +#[test] +fn veryl_projects_select_targets_and_cli_overrides_run_limits() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.veryl"), + "#[test(Top)] module Top { inst clk: $tb::clock_gen; initial { clk.next(3); $finish(); } }", + ) + .unwrap(); + fs::write( + root.path().join("celox.toml"), + r#" + sources = ["top.veryl"] + default_target = "smoke" + opt_level = "O0" + [targets.smoke] + top = "Top" + opt_level = "O2" + max_steps = 1 + [targets.other] + top = "Missing" + "#, + ) + .unwrap(); + let nested = root.path().join("nested/work"); + fs::create_dir_all(&nested).unwrap(); + let output = invoke(&nested, &["run"]); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("testbench ticks before completion")); + success(&invoke(&nested, &["run", "--max-steps", "10", "-O", "O1"])); + success(&invoke( + &nested, + &[ + "run", + "--target", + "other", + "--top", + "Top", + "--max-steps", + "10", + ], + )); + rejected( + &invoke(&nested, &["run", "--target", "missing"]), + "unknown target `missing`", + ); +} + +#[test] +fn explicit_project_paths_do_not_depend_on_working_directory() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.veryl"), + "#[test(Top)] module Top { initial { $finish(); } }", + ) + .unwrap(); + fs::write( + root.path().join("celox.toml"), + "sources = ['top.veryl']\n[targets.only]\ntop = 'Top'\n", + ) + .unwrap(); + let elsewhere = tempfile::tempdir().unwrap(); + let manifest = root.path().join("celox.toml"); + success(&invoke( + elsewhere.path(), + &["run", "--project", manifest.to_str().unwrap()], + )); + fs::write( + &manifest, + "[targets.only]\nsources = ['top.veryl']\ntop = 'Missing'\n", + ) + .unwrap(); + success(&invoke( + elsewhere.path(), + &[ + "run", + "--project", + manifest.to_str().unwrap(), + "--top", + "Top", + ], + )); +} + +#[test] +fn explicit_veryl_sources_accept_existing_project_settings() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("top.veryl"), + "#[test(Top)] module Top { initial { $finish(); } }", + ) + .unwrap(); + for settings in [ + "exclude = ['src/legacy/**']", + "[test]\nsources = ['test_veryl']", + "[simulation]\nmax_steps = 1000", + "exclude = ['src/legacy/**']\n[test]\nsources = ['test_veryl']\n[simulation]\nmax_steps = 1000", + ] { + fs::write(root.path().join("celox.toml"), settings).unwrap(); + for command in [vec!["run"], vec!["vpi", "build"]] { + let args = command + .into_iter() + .chain(["top.veryl", "--top", "Top", "--project", "celox.toml"]) + .collect::>(); + success(&invoke(root.path(), &args)); + } + assert!(root.path().join("celox.out").is_file()); + } +} + +#[test] +fn project_errors_are_actionable() { + let root = tempfile::tempdir().unwrap(); + let manifest = root.path().join("celox.toml"); + for (text, expected) in [ + ("sources = [", "invalid project"), + ("soruces = []", "unknown field"), + ("exclude = 1", "invalid project"), + ("[test]\nsources = 1", "invalid project"), + ("[simulation]\nmax_steps = -1", "invalid project"), + ( + "sources = ['top.sv']\ntop = 'Top'\nopt_level = 'O3'", + "invalid opt_level", + ), + ( + "sources = ['top.sv']\ntop = 'Top'\nmax_steps = 0", + "max_steps must be positive", + ), + ( + "sources = ['top.sv']\n[targets.a]\ntop = 'A'\n[targets.b]\ntop = 'B'", + "select --target NAME", + ), + ( + "sources = ['top.sv']\ndefault_target = 'missing'", + "unknown target `missing`", + ), + ( + "sources = ['top.sv']\ntop = 'Top'\n[targets.a]\nsource = []", + "unknown field", + ), + ("sources = ['top.sv']", "provide --top MODULE"), + ("top = 'Top'", "provide sources"), + ( + "sources = ['top.veryl']\ntop = 'Top'\ninclude_dirs = ['include']", + "require SystemVerilog sources", + ), + ( + "sources = ['top.sv']\ntop = 'Top'\n[defines]\n'not-valid' = '1'", + "invalid macro definition", + ), + ] { + fs::write(&manifest, text).unwrap(); + rejected(&invoke(root.path(), &["run"]), expected); + } +} + +#[test] +fn filelist_errors_do_not_silently_skip_inputs_or_options() { + let root = tempfile::tempdir().unwrap(); + for (text, expected) in [ + ("-f files.f", "recursive file list"), + ("-f missing.f", "failed to open file list"), + ("-f", "-f requires a value"), + ("+incdir+", "empty +incdir+ path"), + ("+define+", "invalid macro definition"), + ("+define+123bad", "invalid macro definition"), + ("-unsupported option", "unsupported file-list option"), + ("\"missing quote", "unterminated quoted path"), + ("/* missing comment end", "unterminated file-list comment"), + ] { + fs::write(root.path().join("files.f"), text).unwrap(); + rejected( + &invoke(root.path(), &["run", "-f", "files.f", "--top", "Top"]), + expected, + ); + } +} + +#[cfg(feature = "systemverilog")] +fn sv_project(root: &Path) { + for dir in ["rtl/space dir", "lists/nested", "include", "work"] { + fs::create_dir_all(root.join(dir)).unwrap(); + } + fs::write( + root.join("rtl/prelude.sv"), + "package prelude; parameter int BASE = 1; endpackage", + ) + .unwrap(); + fs::write( + root.join("rtl/space dir/types.sv"), + "package values; parameter int BASE = prelude::BASE; endpackage", + ) + .unwrap(); + fs::write(root.join("rtl/dut.sv"), "module Dut(output logic [7:0] q);\n`include \"value.svh\"\nassign q = values::BASE + VALUE; endmodule").unwrap(); + fs::write( + root.join("include/value.svh"), + "localparam int VALUE = `RESULT;\n", + ) + .unwrap(); + fs::write(root.join("tb.sv"), "module Tb; wire [7:0] q; Dut dut(q); initial begin #1; $display(\"q=%0d\", q); $finish; end endmodule").unwrap(); + fs::write( + root.join("lists/common.f"), + "# comment\n\"../rtl/space dir/types.sv\"\n/* block comment */ -f nested/dut.f\n", + ) + .unwrap(); + fs::write( + root.join("lists/nested/dut.f"), + "+incdir+../../include\n+define+RESULT=20\n../../rtl/dut.sv // line comment\n", + ) + .unwrap(); + fs::write( + root.join("celox.toml"), + r#" + sources = ["rtl/prelude.sv"] + filelists = ["lists/common.f"] + default_target = "smoke" + [defines] + RESULT = "10" + [targets.smoke] + sources = ["tb.sv"] + top = "Tb" + opt_level = "O2" + max_steps = 20 + [targets.smoke.defines] + RESULT = "41" + [targets.dut] + top = "Dut" + "#, + ) + .unwrap(); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn sv_projects_resolve_ordered_lists_includes_defines_and_targets() { + let root = tempfile::tempdir().unwrap(); + sv_project(root.path()); + let output = invoke(&root.path().join("work"), &["run"]); + success(&output); + assert_eq!(output.stdout, b"q=42\n"); + let output = invoke( + root.path(), + &["run", "--target", "smoke", "-D", "RESULT=99"], + ); + success(&output); + assert_eq!(output.stdout, b"q=100\n"); + + let output = invoke( + root.path(), + &["vpi", "build", "--target", "dut", "-o", "dut-sim"], + ); + success(&output); + let bytes = fs::read(root.path().join("dut-sim")).unwrap(); + let attached = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap(); + assert!( + attached + .image + .reflection() + .scopes() + .iter() + .any(|scope| scope.full_name == "Dut") + ); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn standalone_filelists_and_cli_preprocessing_options_work_for_both_commands() { + let root = tempfile::tempdir().unwrap(); + sv_project(root.path()); + fs::write( + root.path().join("all.f"), + "rtl/prelude.sv\n-f lists/common.f\n-Iinclude\n-DRESULT=41\n+define+UNUSED+OTHER=2\ntb.sv\n", + ) + .unwrap(); + let output = invoke( + root.path(), + &["run", "-f", "all.f", "--top", "Tb", "-DRESULT=41"], + ); + success(&output); + assert_eq!(output.stdout, b"q=42\n"); + let output = invoke( + root.path(), + &[ + "vpi", "build", "-f", "all.f", "--top", "Dut", "-o", "raw-sim", + ], + ); + success(&output); + + let output = invoke( + root.path(), + &[ + "run", + "rtl/prelude.sv", + "rtl/space dir/types.sv", + "rtl/dut.sv", + "tb.sv", + "--top", + "Tb", + "-I", + "include", + "-D", + "RESULT=41", + ], + ); + success(&output); + assert_eq!(output.stdout, b"q=42\n"); +} + +#[cfg(not(feature = "systemverilog"))] +#[test] +fn sv_project_without_feature_reports_the_required_build_option() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("celox.toml"), + "sources = ['top.sv']\ntop = 'Top'\n", + ) + .unwrap(); + for args in [&["run"][..], &["vpi", "build"]] { + let output = invoke(root.path(), args); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("--features systemverilog")); + } +} + +#[cfg(feature = "systemverilog")] +#[test] +fn native_build_applies_target_and_cli_signal_access_contracts() { + use celox::{BigUint, NativeProgramInstance, SimBackend}; + let root = tempfile::tempdir().unwrap(); + fs::write(root.path().join("top.sv"), "module Top(input logic [7:0] a, output logic [7:0] y); logic [7:0] hidden; assign hidden=a+7; assign y=a+1; endmodule").unwrap(); + fs::write( + root.path().join("celox.toml"), + r#" + sources = ["top.sv"] + top = "Top" + opt_level = "O0" + live_signals = ["Top.bad_common"] + force_signals = ["Top.bad_common"] + [targets.selected] + opt_level = "O2" + live_signals = ["Top.hidden"] + force_signals = ["Top.hidden"] + [targets.empty] + live_signals = [] + force_signals = [] + "#, + ) + .unwrap(); + for arguments in [ + vec!["--target", "selected"], + vec![ + "-O", + "O2", + "--live-signal", + "Top.hidden", + "--force-signal", + "Top.hidden", + ], + ] { + let output = invoke( + root.path(), + &[vec!["vpi", "build", "-o", "sim"], arguments].concat(), + ); + success(&output); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: this CLI invocation compiled the trusted test design. + let mut sim = unsafe { NativeProgramInstance::from_image(image) }.unwrap(); + let lookup = |sim: &NativeProgramInstance, path: &str| { + celox::ReflectionSignalId( + sim.reflection() + .signals() + .iter() + .position(|signal| signal.full_name == path) + .unwrap() as u32, + ) + }; + let a = lookup(&sim, "Top.a"); + let hidden = lookup(&sim, "Top.hidden"); + let signal = sim.reflection().signal(a).unwrap().signal; + sim.backend_mut().set(signal, 11u8); + sim.eval_comb().unwrap(); + let signal = sim.reflection().signal(hidden).unwrap().signal; + assert_eq!( + sim.backend().get_four_state(signal), + (BigUint::from(18u8), BigUint::from(0u8)) + ); + assert!(!sim.force_signal(a, 1u8.into(), 0u8.into())); + assert!(sim.force_signal(hidden, 40u8.into(), 0u8.into())); + } + success(&invoke( + root.path(), + &["vpi", "build", "--target", "empty", "-o", "empty"], + )); + success(&invoke( + root.path(), + &[ + "vpi", + "build", + "--no-live-signals", + "--no-force-signals", + "-o", + "cleared", + ], + )); + let output = invoke( + root.path(), + &[ + "vpi", + "build", + "--target", + "selected", + "--force-signal", + "Top.typo", + ], + ); + assert!(!output.status.success()); + assert!(String::from_utf8_lossy(&output.stderr).contains("Top.typo")); +} + +#[cfg(feature = "systemverilog")] +#[test] +fn top_parameters_merge_common_target_and_cli_without_editing_sv() { + let root = tempfile::tempdir().unwrap(); + let source = "module Top #(parameter W=8, parameter V=1, parameter NEXT=V+1) (output logic [W-1:0] y); assign y=NEXT; initial begin #1; $display(\"v=%0d w=%0d\", y, $bits(y)); $finish; end endmodule"; + fs::write(root.path().join("top.sv"), source).unwrap(); + fs::write( + root.path().join("celox.toml"), + r#" + sources = ["top.sv"] + top = "Top" + [parameters] + W = 8 + V = 2 + [targets.wide.parameters] + W = 16 + V = "0x1233" + "#, + ) + .unwrap(); + let output = invoke(root.path(), &["run", "--target", "wide"]); + success(&output); + assert_eq!(output.stdout, b"v=4660 w=16\n"); + let output = invoke( + root.path(), + &[ + "run", + "--target", + "wide", + "-GV=0b11", + "--parameter", + "V=0o10", + ], + ); + success(&output); + assert_eq!(output.stdout, b"v=9 w=16\n"); + success(&invoke( + root.path(), + &[ + "vpi", + "build", + "--target", + "wide", + "--param", + "V=18446744073709551615", + "-o", + "sim", + ], + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: the CLI just compiled this test's source. + let sim = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + let signal = sim.signal_ref("Top.y").unwrap(); + assert_eq!(signal.width, 16); + assert_eq!(celox::SimBackend::get_as::(sim.backend(), signal), 0); + assert_eq!( + fs::read_to_string(root.path().join("top.sv")).unwrap(), + source + ); + let output = invoke(root.path(), &["run", "--target", "wide", "-GMISSING=1"]); + assert!(!output.status.success()); + assert!( + String::from_utf8_lossy(&output.stderr).contains("unknown top-level parameter override") + ); +} + +#[test] +fn top_parameters_reach_veryl_run_and_native_build() { + let root = tempfile::tempdir().unwrap(); + fs::write( + root.path().join("tb.veryl"), + "#[test(Top)] module Top #(param V: u32 = 1) { initial { $assert(V == 7); $finish(); } }", + ) + .unwrap(); + success(&invoke( + root.path(), + &["run", "tb.veryl", "--top", "Top", "-G", "V=7"], + )); + fs::write( + root.path().join("dut.veryl"), + "module Top #(param W: u32 = 8, param V: u32 = 1) (y: output logic) { assign y=V; }", + ) + .unwrap(); + success(&invoke( + root.path(), + &[ + "vpi", + "build", + "dut.veryl", + "--top", + "Top", + "-GW=16", + "-GV=0x1234", + "-o", + "sim", + ], + )); + let bytes = fs::read(root.path().join("sim")).unwrap(); + let image = celox::NativeProgramImage::discover_appended(&bytes) + .unwrap() + .unwrap() + .image; + // Safety: the CLI just compiled this test's source. + let sim = unsafe { celox::NativeProgramInstance::from_image(image) }.unwrap(); + let signal = sim.signal_ref("Top.y").unwrap(); + assert_eq!(signal.width, 16); + assert_eq!( + celox::SimBackend::get_as::(sim.backend(), signal), + 0x1234 + ); + let output = invoke( + root.path(), + &["vpi", "build", "dut.veryl", "--top", "Top", "-GWIDHT=16"], + ); + assert!(!output.status.success()); + assert!( + String::from_utf8_lossy(&output.stderr).contains("unknown top-level parameter override") + ); +} + +#[test] +fn invalid_parameter_assignments_are_rejected() { + let root = tempfile::tempdir().unwrap(); + for value in [ + "V", + "=1", + "x.y=1", + "V=", + "V=-1", + "V=1+2", + "V=18446744073709551616", + "V=0x", + "V=0b2", + "V=_1", + ] { + let output = invoke(root.path(), &["run", "dut.sv", "--top", "Top", "-G", value]); + rejected(&output, "parameter"); + } +} diff --git a/crates/celox-vpi/tests/signal_access.rs b/crates/celox-vpi/tests/signal_access.rs new file mode 100644 index 00000000000..3df8011e0ab --- /dev/null +++ b/crates/celox-vpi/tests/signal_access.rs @@ -0,0 +1,377 @@ +//! Explicit signal access is a native-image API/optimization contract. +#![cfg(feature = "systemverilog")] +use celox::BigUint; +use celox::{NativeProgramInstance, OptLevel, SignalAccessOptions, SimBackend, Simulator}; + +fn instance(source: &str, level: OptLevel, access: SignalAccessOptions) -> NativeProgramInstance { + let simulator = + Simulator::from_sv_sources(vec![(source, std::path::Path::new("force.sv"))], "Top") + .four_state(true) + .opt_level(level) + .signal_access(access) + .build() + .unwrap(); + let bytes = simulator + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + // Safety: execute only the compiler artifact created by this test. + unsafe { NativeProgramInstance::from_attached_bytes(&bytes) }.unwrap() +} +fn id(sim: &NativeProgramInstance, name: &str) -> celox::ReflectionSignalId { + sim.reflection() + .signals() + .iter() + .position(|signal| signal.full_name == name) + .map(|index| celox::ReflectionSignalId(index as u32)) + .unwrap() +} +fn read(sim: &NativeProgramInstance, name: &str) -> (BigUint, BigUint) { + sim.backend() + .get_four_state(sim.reflection().signal(id(sim, name)).unwrap().signal) +} +fn deposit(sim: &mut NativeProgramInstance, name: &str, value: u8) { + let signal = sim.reflection().signal(id(sim, name)).unwrap().signal; + sim.backend_mut().set(signal, value); +} +#[test] +fn explicit_force_preserves_blocking_loop_semantics_at_every_opt_level() { + let source = r#"module Top(input logic [7:0] a, output logic [7:0] x, total); + always_comb begin total=a; for (int i=0; i<4; i++) begin x=1; total+=x; end end + endmodule"#; + for level in [OptLevel::O0, OptLevel::O1, OptLevel::O2] { + let mut sim = instance( + source, + level, + SignalAccessOptions { + force_signals: vec!["Top.x".into()], + ..Default::default() + }, + ); + let x = id(&sim, "Top.x"); + assert!(sim.force_signal(x, 3u8.into(), 0u8.into())); + assert!(!sim.force_signal(id(&sim, "Top.a"), 8u8.into(), 0u8.into())); + deposit(&mut sim, "Top.a", 1); + sim.eval_comb().unwrap(); + assert_eq!( + read(&sim, "Top.total"), + (13u8.into(), 0u8.into()), + "{level:?}" + ); + assert_eq!(read(&sim, "Top.x").0, 3u8.into()); + sim.release_signal(x); + sim.eval_comb().unwrap(); + assert_eq!(read(&sim, "Top.total").0, 5u8.into(), "release {level:?}"); + assert_eq!(read(&sim, "Top.x").0, 1u8.into()); + } +} +#[test] +fn explicit_live_root_keeps_internal_computation_at_o2() { + let source = "module Top(input logic [7:0] a, output logic [7:0] y); logic [7:0] hidden; assign hidden=a+7; assign y=a+1; endmodule"; + let mut sim = instance( + source, + OptLevel::O2, + SignalAccessOptions { + live_signals: vec!["Top.hidden".into()], + ..Default::default() + }, + ); + deposit(&mut sim, "Top.a", 11); + sim.eval_comb().unwrap(); + assert_eq!(read(&sim, "Top.hidden"), (18u8.into(), 0u8.into())); +} +#[test] +fn misspelled_access_paths_fail_even_without_dse() { + for force in [false, true] { + let mut access = SignalAccessOptions::default(); + if force { + access.force_signals.push("Top.missing".into()); + } else { + access.live_signals.push("Top.missing".into()); + } + let result = Simulator::from_sv_sources( + vec![( + "module Top; logic a; endmodule", + std::path::Path::new("missing.sv"), + )], + "Top", + ) + .opt_level(OptLevel::O1) + .signal_access(access) + .build(); + assert!(result.err().unwrap().to_string().contains("Top.missing")); + } +} + +#[test] +fn force_contract_is_per_instance_and_keeps_internal_o2_targets_live() { + let source = r#" + module Child(input logic [7:0] a, output logic [7:0] y); + logic [7:0] hidden; + always_comb begin hidden=a+7; y=hidden+1; end + endmodule + module Top(input logic [7:0] a, output logic [7:0] y, z); + Child left(a,y), right(a,z); + endmodule"#; + let mut sim = instance( + source, + OptLevel::O2, + SignalAccessOptions { + force_signals: vec!["Top.left.hidden".into()], + ..Default::default() + }, + ); + assert!( + !sim.reflection() + .signals() + .iter() + .any(|signal| signal.name.contains("@force")) + ); + assert!(sim.force_signal(id(&sim, "Top.left.hidden"), 30u8.into(), 0u8.into())); + assert!(!sim.force_signal(id(&sim, "Top.right.hidden"), 50u8.into(), 0u8.into())); + deposit(&mut sim, "Top.a", 11); + sim.eval_comb().unwrap(); + assert_eq!(read(&sim, "Top.y").0, 31u8.into()); + assert_eq!(read(&sim, "Top.z").0, 19u8.into()); + assert_eq!(read(&sim, "Top.left.hidden").0, 30u8.into()); +} + +#[test] +fn force_unknown_value_and_replacement_survive_optimized_partial_writes() { + let source = "module Top(input logic [7:0] a, output logic [7:0] x, y); always_comb begin x[3:0]=a[3:0]; x[7:4]=a[7:4]; y=x; end endmodule"; + let mut sim = instance( + source, + OptLevel::O2, + SignalAccessOptions { + force_signals: vec!["Top.x".into()], + ..Default::default() + }, + ); + let x = id(&sim, "Top.x"); + assert!(sim.force_signal(x, 0xa5u8.into(), 0x18u8.into())); + deposit(&mut sim, "Top.a", 11); + sim.eval_comb().unwrap(); + assert_eq!(read(&sim, "Top.y"), (0xa5u8.into(), 0x18u8.into())); + assert!(sim.force_signal(x, 7u8.into(), 0u8.into())); + sim.eval_comb().unwrap(); + assert_eq!(read(&sim, "Top.y"), (7u8.into(), 0u8.into())); +} + +#[test] +fn force_on_owned_interface_member_propagates_through_port_glue() { + let source = r#" + interface Bus; logic [7:0] data; modport sink(input data); endinterface + module Child(Bus.sink s_axis, output logic [7:0] y); assign y=s_axis.data+1; endmodule + module Top(output logic [7:0] y); Bus s_axis(); assign s_axis.data=11; Child uut(s_axis,y); endmodule + "#; + let mut sim = instance( + source, + OptLevel::O2, + SignalAccessOptions { + force_signals: vec!["Top.s_axis.data".into()], + ..Default::default() + }, + ); + assert!(sim.force_signal(id(&sim, "Top.s_axis.data"), 30u8.into(), 0u8.into())); + sim.eval_comb().unwrap(); + assert_eq!(read(&sim, "Top.y").0, 31u8.into()); +} + +#[test] +fn force_profile_does_not_disable_o2_dead_store_elimination() { + let source = "module Top(input logic [7:0] a, output logic [7:0] y); logic [7:0] preserved, discarded; assign preserved=a+7; assign discarded=a+8; assign y=a+1; endmodule"; + let mut sim = instance( + source, + OptLevel::O2, + SignalAccessOptions { + force_signals: vec!["Top.preserved".into()], + ..Default::default() + }, + ); + deposit(&mut sim, "Top.a", 11); + sim.eval_comb().unwrap(); + assert_eq!(read(&sim, "Top.preserved"), (18u8.into(), 0u8.into())); + assert_eq!(read(&sim, "Top.discarded").1, 255u8.into()); +} + +#[test] +fn optimized_sequential_blocking_assignments_observe_force_and_release() { + let source = "module Top(input logic clk, output logic [7:0] q, y); always @(posedge clk) begin q=1; y=q+1; end endmodule"; + let mut sim = instance( + source, + OptLevel::O2, + SignalAccessOptions { + force_signals: vec!["Top.q".into()], + ..Default::default() + }, + ); + let q = id(&sim, "Top.q"); + let clock = sim + .reflection() + .signal(id(&sim, "Top.clk")) + .unwrap() + .state_address; + assert!(sim.force_signal(q, 3u8.into(), 0u8.into())); + deposit(&mut sim, "Top.clk", 1); + sim.settle_active_edges(&[clock]).unwrap(); + assert_eq!(read(&sim, "Top.q").0, 3u8.into()); + assert_eq!(read(&sim, "Top.y").0, 4u8.into()); + sim.release_signal(q); + sim.eval_comb().unwrap(); + assert_eq!(read(&sim, "Top.q").0, 3u8.into()); + deposit(&mut sim, "Top.clk", 0); + sim.eval_comb().unwrap(); + deposit(&mut sim, "Top.clk", 1); + sim.settle_active_edges(&[clock]).unwrap(); + assert_eq!(read(&sim, "Top.q").0, 1u8.into()); + assert_eq!(read(&sim, "Top.y").0, 2u8.into()); +} + +#[test] +fn wide_force_controls_keep_value_and_unknown_planes() { + let source = "module Top(output logic [128:0] x, y); assign x=129'd1; assign y=x; endmodule"; + let mut sim = instance( + source, + OptLevel::O2, + SignalAccessOptions { + force_signals: vec!["Top.x".into()], + ..Default::default() + }, + ); + let value = (BigUint::from(1u8) << 128usize) + BigUint::from(5u8); + assert!(sim.force_signal(id(&sim, "Top.x"), value.clone(), 2u8.into())); + sim.eval_comb().unwrap(); + assert_eq!(read(&sim, "Top.y"), (value, 2u8.into())); +} + +#[test] +fn unsupported_force_targets_fail_explicitly() { + for (source, target, expected) in [ + ( + "module Top; logic [7:0] mem[4]; endmodule", + "Top.mem", + "packed non-clock", + ), + ( + "module Top(input logic clk, output logic q); always @(posedge clk) q<=1; endmodule", + "Top.clk", + "packed non-clock", + ), + ( + "interface Bus; logic data; modport sink(input data); endinterface module Child(Bus.sink bus, output logic y); assign y=bus.data; endmodule module Top(output logic y); Bus bus(); Child uut(bus,y); endmodule", + "Top.uut.bus.data", + "owning interface variable", + ), + ] { + let error = Simulator::from_sv_sources( + vec![(source, std::path::Path::new("unsupported.sv"))], + "Top", + ) + .signal_access(SignalAccessOptions { + force_signals: vec![target.into()], + ..Default::default() + }) + .build() + .err() + .unwrap() + .to_string(); + assert!(error.contains(expected), "{error}"); + } +} + +#[test] +fn explicit_force_runs_with_parallel_optimized_kernels() { + let source = "module Top(input logic [7:0] a, b, output logic [7:0] x, y, z); always_comb begin x=a+1; y=x+1; end assign z=b+2; endmodule"; + let simulator = + Simulator::from_sv_sources(vec![(source, std::path::Path::new("parallel.sv"))], "Top") + .four_state(true) + .opt_level(OptLevel::O2) + .threads(4) + .parallel_partition(celox::ParallelPartition::Always) + .signal_access(SignalAccessOptions { + force_signals: vec!["Top.x".into()], + ..Default::default() + }) + .build() + .unwrap(); + // Safety: this test just compiled the image being executed. + let mut sim = unsafe { + NativeProgramInstance::from_image(simulator.shared_code().program_image().clone()) + } + .unwrap(); + assert!(sim.force_signal(id(&sim, "Top.x"), 99u8.into(), 0u8.into())); + deposit(&mut sim, "Top.a", 11); + deposit(&mut sim, "Top.b", 20); + sim.eval_comb().unwrap(); + assert_eq!(read(&sim, "Top.y").0, 100u8.into()); + assert_eq!(read(&sim, "Top.z").0, 22u8.into()); +} + +#[test] +fn forced_signed_values_keep_sign_extension_division_and_comparison() { + let source = "module Top(output logic signed [7:0] x, quotient, output logic signed [15:0] wide, output logic negative); always_comb begin x=1; wide=x; quotient=x/8'sd2; negative=x<8'sd0; end endmodule"; + let mut sim = instance( + source, + OptLevel::O2, + SignalAccessOptions { + force_signals: vec!["Top.x".into()], + ..Default::default() + }, + ); + assert!(sim.force_signal(id(&sim, "Top.x"), 250u8.into(), 0u8.into())); + sim.eval_comb().unwrap(); + assert_eq!(read(&sim, "Top.wide").0, 65530u32.into()); + assert_eq!(read(&sim, "Top.quotient").0, 253u8.into()); + assert_eq!(read(&sim, "Top.negative").0, 1u8.into()); +} + +#[test] +fn veryl_observation_roots_work_and_unsupported_force_is_rejected() { + let source = "module Top(a: input logic<8>, y: output logic<8>) { var hidden: logic<8>; assign hidden=a+7; assign y=a+1; }"; + let simulator = Simulator::builder(source, "Top") + .four_state(true) + .opt_level(OptLevel::O2) + .signal_access(SignalAccessOptions { + live_signals: vec!["Top.hidden".into()], + ..Default::default() + }) + .build() + .unwrap(); + // Safety: this test just compiled the image being executed. + let mut sim = unsafe { + NativeProgramInstance::from_image(simulator.shared_code().program_image().clone()) + } + .unwrap(); + deposit(&mut sim, "Top.a", 11); + sim.eval_comb().unwrap(); + assert_eq!(read(&sim, "Top.hidden"), (18u8.into(), 0u8.into())); + let error = Simulator::builder(source, "Top") + .signal_access(SignalAccessOptions { + force_signals: vec!["Top.hidden".into()], + ..Default::default() + }) + .build() + .err() + .unwrap() + .to_string(); + assert!(error.contains("pure SystemVerilog"), "{error}"); +} + +#[test] +fn force_permissions_preserve_declaration_initial_values() { + let source = "module Top(output logic [7:0] y); logic [7:0] x=4; assign y=x+1; endmodule"; + let mut sim = instance( + source, + OptLevel::O2, + SignalAccessOptions { + force_signals: vec!["Top.x".into()], + ..Default::default() + }, + ); + assert_eq!(read(&sim, "Top.x"), (4u8.into(), 0u8.into())); + assert_eq!(read(&sim, "Top.y"), (5u8.into(), 0u8.into())); + assert!(sim.force_signal(id(&sim, "Top.x"), 8u8.into(), 0u8.into())); + sim.eval_comb().unwrap(); + assert_eq!(read(&sim, "Top.y").0, 9u8.into()); +} diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index ee25e93a203..568a1ca1c40 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -377,8 +377,16 @@ struct NativeRuntimeOptions { kernel_selection: celox_runtime::parallel::KernelSelection, } +#[derive(Clone, Debug, Serialize, Deserialize)] +pub(super) struct NativeForceBinding { + pub signal: celox_runtime::ReflectionSignalId, + pub enabled: SignalRef, + pub value: SignalRef, +} + #[derive(Clone, Debug, Serialize, Deserialize)] pub(crate) struct NativeRuntimeSchema { + pub(super) force_bindings: Vec, pub(crate) runtime_errors: HashMap>, pub(crate) runtime_event_sites: Vec, /// Extern functions the code calls, resolved when the image is attached. @@ -520,6 +528,35 @@ impl NativeProgramImage { self.reflection .validate() .map_err(|error| format!("invalid design reflection: {error}"))?; + for binding in &self.runtime_schema.force_bindings { + let target = self + .reflection + .signal(binding.signal) + .ok_or("force target is not a reflected signal")?; + if binding.enabled.width != 1 + || binding.enabled.is_4state + || binding.value.width != target.signal.width + { + return Err("invalid force control shape".into()); + } + for control in [binding.enabled, binding.value] { + if control.array_layout.is_some() { + return Err("force controls must be packed".into()); + } + let size = control + .width + .div_ceil(8) + .checked_mul(if control.is_4state { 2 } else { 1 }) + .ok_or("force control size overflows")?; + if control + .offset + .checked_add(size) + .is_none_or(|end| end > self.native_memory_size) + { + return Err("force control exceeds native memory".into()); + } + } + } if self.code.is_empty() { return Err("code image is empty".into()); } @@ -637,6 +674,85 @@ impl NativeProgramImage { // Compilation // ──────────────────────────────────────────────────────────────── +fn build_force_bindings( + program: &crate::ir::RuntimeProgram, + layout: &crate::backend::MemoryLayout, + paths: &[String], +) -> Result, SimulatorError> { + if paths.is_empty() { + return Ok(Vec::new()); + } + let reflection = program.build_design_reflection(layout); + let signal_ref = |addr: &AbsoluteAddr| SignalRef { + offset: layout.offsets[addr], + width: layout.widths[addr], + is_4state: layout.is_4states[addr], + array_layout: None, + }; + let mut result = Vec::new(); + for path in paths { + let (index, target) = reflection + .signals() + .iter() + .enumerate() + .find(|(_, signal)| signal.full_name == *path) + .ok_or_else(|| { + codegen_err(CodegenError::message(format!( + "unknown force signal `{path}`" + ))) + })?; + if !target.unpacked_dims.is_empty() || target.domain_kind != celox_design::DomainKind::Other + { + return Err(codegen_err(CodegenError::message(format!( + "force signal `{path}` must be a packed non-clock variable" + )))); + } + let mut found = false; + for instance in program.design.instances() { + for address in instance.state_addresses() { + let var = program.design.variable(address).unwrap(); + if instance.resolves_path_to(&var.path, *address) + && var.path.len() > 1 + && var.var_kind.is_port() + && layout.offsets[address] == target.signal.offset + { + return Err(codegen_message(format!( + "force signal `{path}` is a structured port alias; select the owning interface variable" + ))); + } + if layout.offsets[address] != target.signal.offset + || layout.widths[address] != target.signal.width + { + continue; + } + let flat_name = var.path.join("$"); + let control = |prefix: &str| { + instance.state_addresses().iter().find(|addr| { + program.design.variable(addr).unwrap().path + == [format!("{prefix}{flat_name}")] + }) + }; + if let (Some(enabled), Some(value)) = + (control("@force-enable:"), control("@force-value:")) + { + result.push(NativeForceBinding { + signal: celox_runtime::ReflectionSignalId(index as u32), + enabled: signal_ref(enabled), + value: signal_ref(value), + }); + found = true; + } + } + } + if !found { + return Err(codegen_err(CodegenError::message(format!( + "no force instrumentation for `{path}`" + )))); + } + } + Ok(result) +} + fn codegen_err(error: CodegenError) -> SimulatorError { error.into() } @@ -1798,6 +1914,8 @@ fn compile_program( ) -> Result<(NativeProgramImage, Option), SimulatorError> { let sir = laid_out; let layout = laid_out.layout(); + let force_bindings = + build_force_bindings(sir.runtime(), layout, &options.signal_access.force_signals)?; let (compile_tasks, task_bindings) = collect_ff_compile_tasks(sir); let comb_blocks = sir .sir @@ -1961,7 +2079,8 @@ fn compile_program( // A foreign-interface image can request per-unit entries so force/release // can reapply overrides between procedural store boundaries. Ordinary // images do not compile or retain this duplicate combinational code. - let force_store_boundaries = options.optimize_options.opt_level() == crate::OptLevel::O0; + let force_store_boundaries = + options.native_force_support && options.optimize_options.opt_level() == crate::OptLevel::O0; let comb_runtime_units = if options.native_force_support { sir.sir .eval_comb @@ -2262,6 +2381,7 @@ fn compile_program( design: sir.runtime().design.clone(), testbench: sir.runtime().testbench.clone(), runtime_schema: NativeRuntimeSchema { + force_bindings, runtime_errors: sir.runtime().runtime_schema.runtime_errors.clone(), runtime_event_sites: sir.runtime().runtime_schema.runtime_event_sites.clone(), extern_functions: sir.runtime().runtime_schema.extern_functions.clone(), diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 2e5337891b2..5af6f77a7f9 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 15; +const CONTAINER_VERSION: u16 = 16; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index 7795f7cb7a6..271f4523a44 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -288,9 +288,21 @@ impl NativeProgramInstance { value: BigUint, mask: BigUint, ) -> bool { - if !self.shared.supports_forces() { + let bindings = self + .runtime_schema() + .force_bindings + .iter() + .filter(|binding| binding.signal == id) + .cloned() + .collect::>(); + if !self.shared.supports_forces() && bindings.is_empty() { return false; } + for binding in bindings { + self.backend + .set_four_state(binding.value, value.clone(), mask.clone()); + self.backend.set(binding.enabled, 1u8); + } let Some(identity) = self.signal_identity(id) else { return false; }; @@ -305,6 +317,19 @@ impl NativeProgramInstance { /// Restore normal design-driver control for a reflected signal. pub fn release_signal(&mut self, id: celox_runtime::ReflectionSignalId) { + let bindings = self + .runtime_schema() + .force_bindings + .iter() + .filter(|binding| binding.signal == id) + .cloned() + .collect::>(); + if !self.shared.supports_forces() && bindings.is_empty() { + return; + } + for binding in bindings { + self.backend.set(binding.enabled, 0u8); + } if let Some(identity) = self.signal_identity(id) { self.forced_values.remove(&identity); } @@ -447,6 +472,16 @@ impl NativeProgramInstance { self.backend .set_four_state(*signal, value.clone(), mask.clone()); } + // Explicit force targets use compiler-inserted override inputs. They + // execute the ordinary optimized kernel, including parallel kernels. + if !self.shared.supports_forces() { + let result = self.backend.eval_comb(); + for (signal, value, mask) in &overrides { + self.backend + .set_four_state(*signal, value.clone(), mask.clone()); + } + return result.map_err(|error| self.decorate_runtime_error(error)); + } self.backend .eval_comb_units_with(|backend| { for (signal, value, mask) in &overrides { diff --git a/crates/celox/src/diagnostic_policy.rs b/crates/celox/src/diagnostic_policy.rs new file mode 100644 index 00000000000..b417d2b7dc0 --- /dev/null +++ b/crates/celox/src/diagnostic_policy.rs @@ -0,0 +1,115 @@ +//! Per-code compilation diagnostic severity. Runtime failures are unaffected. + +use std::collections::BTreeMap; +use std::path::Path; + +use miette::Diagnostic; + +use crate::{CompilationWarning, SimulatorError, SimulatorErrorKind}; + +/// The action for a recoverable compilation diagnostic. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum DiagnosticLevel { + Allow, + Warn, + Error, +} + +/// Overrides keyed by the code shown in a compilation diagnostic. +/// Unlisted diagnostics retain their default severity. Only explicitly +/// recoverable errors (currently `mixed_timescale`) can be relaxed. +#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(transparent)] +pub struct DiagnosticPolicy(pub BTreeMap); + +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/ir.rs b/crates/celox/src/ir.rs index 9336c758cd3..563b6ad66c4 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -841,6 +841,7 @@ impl RuntimeProgram { layout: &crate::backend::MemoryLayout, ) -> DesignReflection { struct ScopeSource { + is_instance: bool, instance_id: InstanceId, name: String, full_name: String, @@ -877,6 +878,7 @@ impl RuntimeProgram { } }); ScopeSource { + is_instance: true, instance_id: instance.id, name, full_name, @@ -885,6 +887,50 @@ impl RuntimeProgram { } }) .collect::>(); + // A module instance can own structured variables (interface members, + // generate scopes, and aggregate members) without owning child module + // instances. Retain their source path segments as navigable scopes. + let real_scopes = scope_sources + .iter() + .map(|scope| scope.full_name.clone()) + .collect::>(); + let mut member_scopes = HashMap::default(); + for scope in &scope_sources { + let instance = self.design.instance(scope.instance_id).unwrap(); + for address in instance.state_addresses() { + let variable = self.design.variable(address).unwrap(); + if instance.path_index.get(&variable.path) != Some(&Some(*address)) { + continue; + } + for depth in 1..variable.path.len() { + let full_name = + format!("{}.{}", scope.full_name, variable.path[..depth].join(".")); + if real_scopes.contains(&full_name) { + continue; + } + let parent_name = if depth == 1 { + scope.full_name.clone() + } else { + format!( + "{}.{}", + scope.full_name, + variable.path[..depth - 1].join(".") + ) + }; + member_scopes + .entry(full_name.clone()) + .or_insert_with(|| ScopeSource { + is_instance: false, + instance_id: scope.instance_id, + name: variable.path[depth - 1].clone(), + full_name, + parent_name: Some(parent_name), + module_name: String::new(), + }); + } + } + } + scope_sources.extend(member_scopes.into_values()); scope_sources.sort_by(|left, right| left.full_name.cmp(&right.full_name)); let scope_ids = scope_sources @@ -897,16 +943,6 @@ impl RuntimeProgram { ) }) .collect::>(); - let instance_scopes = scope_sources - .iter() - .enumerate() - .map(|(index, scope)| { - ( - scope.instance_id, - ReflectionScopeId(u32::try_from(index).expect("scope count exceeds u32")), - ) - }) - .collect::>(); let mut scopes = scope_sources .iter() .map(|scope| ReflectionScope { @@ -942,7 +978,7 @@ impl RuntimeProgram { let event_kinds = self.design.event_kinds(); let mut signals = Vec::new(); - for scope in &scope_sources { + for scope in scope_sources.iter().filter(|scope| scope.is_instance) { let instance = self.design.instance(scope.instance_id).unwrap(); for state_address in instance.state_addresses() { let variable = self.design.variable(state_address).unwrap(); @@ -956,7 +992,15 @@ impl RuntimeProgram { continue; } let metadata = &self.design.state_objects[state_address]; - let name = variable.path.join("."); + let (name, parents) = variable + .path + .split_last() + .expect("visible variable has a source path"); + let parent_name = if parents.is_empty() { + scope.full_name.clone() + } else { + format!("{}.{}", scope.full_name, parents.join(".")) + }; let array_layout = layout .unpacked_arrays @@ -974,9 +1018,9 @@ impl RuntimeProgram { _ => SignalDirection::Internal, }; signals.push(ReflectionSignal { - full_name: format!("{}.{}", scope.full_name, name), - name, - parent: instance_scopes[&scope.instance_id], + full_name: format!("{parent_name}.{name}"), + name: name.clone(), + parent: scope_ids[&parent_name], state_address: *state_address, signal: SignalRef { offset: layout.offsets[state_address], @@ -1033,6 +1077,34 @@ impl RuntimeProgram { )) } + /// Resolve an exact reflected hierarchy path without guessing where module + /// instance paths end and interface/member paths begin. + #[cfg(feature = "host-runtime")] + pub(crate) fn hierarchical_signal_addr(&self, path: &str) -> Option { + let root = &self.design.root_instance()?.module_name; + let mut found = None; + for instance in self.design.instances() { + let prefix = if instance.display_path.is_empty() { + root.clone() + } else { + format!("{root}.{}", instance.display_path.join(".")) + }; + for address in instance.state_addresses() { + let variable = self.design.variable(address)?; + if !instance.resolves_path_to(&variable.path, *address) { + continue; + } + if format!("{prefix}.{}", variable.path.join(".")) == path { + if found.is_some() { + return None; + } + found = Some(*address); + } + } + } + found + } + pub fn get_addr( &self, instance_path: &[(&str, usize)], diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index 892bc41a031..28c1c259d82 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -220,3 +220,9 @@ pub use simulator::{ #[cfg(test)] mod flatting_tests; + +mod diagnostic_policy; +pub use diagnostic_policy::{DiagnosticLevel, DiagnosticPolicy}; + +mod signal_access; +pub use signal_access::SignalAccessOptions; diff --git a/crates/celox/src/parser.rs b/crates/celox/src/parser.rs index a6d96f03382..1072ec8ad5f 100644 --- a/crates/celox/src/parser.rs +++ b/crates/celox/src/parser.rs @@ -589,15 +589,17 @@ 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, component_file_base: Option, warnings: &mut Vec, + force_signals: &[String], ) -> 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_force_signals( sources, top, parameter_overrides, @@ -608,6 +610,8 @@ pub fn parse_sv( &frontend_trace_options, trace.is_some().then_some(&mut frontend_trace), warnings, + diagnostic_policy.sv_options(), + force_signals, ) .map_err(|error| match error { celox_frontend_sv::FrontendError::Lowering(error) => error.into(), @@ -680,6 +684,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 +823,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/signal_access.rs b/crates/celox/src/signal_access.rs new file mode 100644 index 00000000000..f2ea689bafe --- /dev/null +++ b/crates/celox/src/signal_access.rs @@ -0,0 +1,10 @@ +//! Explicit observation and intervention contracts for compiled designs. + +/// Hierarchical signal paths, including the top module (for example `Top.uut.state`). +/// Force targets are also live roots. Empty lists preserve ordinary optimization. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct SignalAccessOptions { + pub live_signals: Vec, + pub force_signals: Vec, +} 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..a76a0547bbf 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -176,6 +176,20 @@ pub(super) fn elaborate_parameterized_module( .map(|(name, value)| (resource_table::insert_str(name), value.clone())) .collect(); + for name in values.keys() { + if !property + .parameters + .iter() + .any(|parameter| parameter.name == *name) + { + return Err(ParserError::illegal_context( + "top-level parameter override", + format!("unknown top-level parameter override `{name}`"), + Some(&top_token), + )); + } + } + // push_override expects expressions that have already been evaluated in // the formal parameter type (as get_overridden_params does for HDL insts). // Resolve the header in declaration order so dependent widths/defaults see @@ -290,6 +304,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 +316,8 @@ fn analyze( Vec, Vec, ) { + #[cfg(not(feature = "systemverilog"))] + let _ = diagnostic_policy; symbol_table::clear(); attribute_table::clear(); @@ -378,10 +395,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 +604,7 @@ fn analyze( trace_out, optimize_options, diagnostics, + diagnostic_policy, preserve_element_storage_layout, testbench_random_seed, component_libraries, @@ -751,6 +770,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 +886,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 +919,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 +979,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 +1002,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,7 +1078,9 @@ pub fn compile_sv_to_sir( param_overrides, optimize_options, &crate::RuntimeDiagnostics::default(), + &crate::DiagnosticPolicy::default(), crate::backend::memory_layout::MemoryLayoutMode::Packed, + &[], ) } @@ -1081,7 +1107,9 @@ 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, + force_signals: &[String], ) -> Result<(OptimizedSir, Vec), SimulatorError> { let metadata = metadata.unwrap_or_else(|| Metadata::create_default("prj").unwrap()); let mut build_config = BuildConfig::from(&metadata.build); @@ -1105,11 +1133,13 @@ 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, component_file_base, &mut sv_warnings, + force_signals, ); let warnings = sv_warnings .into_iter() @@ -1210,6 +1240,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 +1273,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 +1296,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,12 +1359,20 @@ 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, allow_always_ff_function_effects: bool, file_dependencies: &celox_frontend_veryl::FileDependencyCollector, + force_signals: &[String], ) -> Result<(OptimizedSir, Vec), SimulatorError> { + if !force_signals.is_empty() && !sources.is_empty() { + return Err(crate::CodegenError::message( + "force_signals currently require pure SystemVerilog sources", + ) + .into()); + } #[cfg(not(feature = "systemverilog"))] { debug_assert!(sv_sources.is_empty()); @@ -1349,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, @@ -1372,6 +1414,7 @@ fn compile_hdl_to_sir_with_layout_mode( param_overrides, optimize_options, diagnostics, + diagnostic_policy, injected_manifests, layout_mode, recover_comb_loops, @@ -1392,7 +1435,9 @@ fn compile_hdl_to_sir_with_layout_mode( param_overrides, optimize_options, diagnostics, + diagnostic_policy, layout_mode, + force_signals, ), (false, false) => compile_mixed_to_sir_with_layout_mode( sources, @@ -1409,6 +1454,7 @@ fn compile_hdl_to_sir_with_layout_mode( param_overrides, optimize_options, diagnostics, + diagnostic_policy, injected_manifests, layout_mode, recover_comb_loops, @@ -1461,12 +1507,15 @@ 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, /// Emit the additional combinational entries needed to reapply foreign /// force overrides between procedural store boundaries. pub native_force_support: bool, + /// Explicit hierarchical observation and native force targets. + pub signal_access: crate::SignalAccessOptions, /// Dead store elimination policy. pub dead_store_policy: DeadStorePolicy, /// When the tiered backend adopts background-compiled code. @@ -1661,8 +1710,10 @@ 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, + signal_access: crate::SignalAccessOptions::default(), dead_store_policy: DeadStorePolicy::Off, tier_promotion: TierPromotion::Always, allow_always_ff_function_effects: false, @@ -2037,6 +2088,14 @@ mod host { self } + /// Declare hierarchical observation and native force targets. + /// This preserves the requested optimization level. Force targets currently + /// require a pure SystemVerilog design and the native backend. + pub fn signal_access(mut self, options: crate::SignalAccessOptions) -> Self { + self.options.signal_access = options; + self + } + /// Mark a signal as externally observable (live) for dead store elimination. pub fn live_signal( mut self, @@ -2053,7 +2112,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 +2441,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 +2453,7 @@ mod host { &self.options.optimize_options, &self.options.diagnostics, layout_mode, - )? + ) } else { compile_frontend_testbench_to_sir_with_layout_mode( artifact, @@ -2404,12 +2469,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 +2493,18 @@ 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, - )? + &self.options.signal_access.force_signals, + ) }; + 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()); } @@ -2449,6 +2520,7 @@ mod host { tracing::debug!("[phase-timing] build_layout: {:?}", start.elapsed()); } + validate_signal_access(&laid_out, &self.options.signal_access)?; if self.options.dead_store_policy != DeadStorePolicy::Off { let dse_start = phase_timing.then(crate::timing::now); run_dead_store_elimination(&mut laid_out, &self.live_signals, &self.options); @@ -3025,6 +3097,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,21 +3121,27 @@ 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, + &self.options.signal_access.force_signals, ) }; + 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() { laid_out.enable_vcd_tracking(); } + validate_signal_access(&laid_out, &self.options.signal_access)?; if self.options.dead_store_policy != DeadStorePolicy::Off { run_dead_store_elimination(&mut laid_out, &self.live_signals, &self.options); } @@ -3319,6 +3398,21 @@ mod host { } } + fn validate_signal_access( + program: &LaidOutProgram, + access: &crate::SignalAccessOptions, + ) -> Result<(), SimulatorError> { + for path in access.live_signals.iter().chain(&access.force_signals) { + if program.hierarchical_signal_addr(path).is_none() { + return Err(crate::CodegenError::message(format!( + "unknown or ambiguous signal `{path}`" + )) + .into()); + } + } + Ok(()) + } + /// Resolve user-specified `(instance_path, var_path)` to `AbsoluteAddr` and run DSE. fn run_dead_store_elimination( program: &mut LaidOutProgram, @@ -3333,8 +3427,21 @@ mod host { // signals named with `live_signal()`. externally_live.extend(program.runtime_schema.testbench_read_roots.iter().copied()); - // User-specified live signals let mut listed = HashSet::default(); + for path in options + .signal_access + .live_signals + .iter() + .chain(&options.signal_access.force_signals) + { + let addr = program + .hierarchical_signal_addr(path) + .expect("validated signal path"); + externally_live.insert(addr); + listed.insert(addr); + } + + // User-specified live signals for (inst_path, var_path) in live_signals { let inst_refs: Vec<(&str, usize)> = inst_path.iter().map(|(s, i)| (s.as_str(), *i)).collect(); 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/crates/celox/tests/param_override.rs b/crates/celox/tests/param_override.rs index 8111ca3a862..60f80a41e95 100644 --- a/crates/celox/tests/param_override.rs +++ b/crates/celox/tests/param_override.rs @@ -329,7 +329,7 @@ fn test_top_param_override_does_not_change_child_default() { } #[test] -fn test_unknown_top_param_does_not_override_child_param() { +fn test_unknown_top_param_cannot_target_child_param() { let code = r#" module Child #( param WIDTH: u32 = 3, @@ -348,10 +348,29 @@ fn test_unknown_top_param_does_not_override_child_param() { } "#; - let mut sim = Simulator::builder(code, "Top") + let error = Simulator::builder(code, "Top") .param("WIDTH", 16) .build() - .unwrap(); + .err() + .unwrap() + .to_string(); + assert!( + error.contains("unknown top-level parameter override `WIDTH`"), + "{error}" + ); +} - assert_eq!(sim.get(sim.signal("value")), 3u32.into()); +#[test] +fn unknown_top_parameter_override_is_rejected() { + let source = "module Top #(param WIDTH: u32 = 8) (y: output logic) { assign y=0; }"; + let error = Simulator::builder(source, "Top") + .param("WIDHT", 16) + .build() + .err() + .unwrap() + .to_string(); + assert!( + error.contains("unknown top-level parameter override `WIDHT`"), + "{error}" + ); } diff --git a/docs/guide/celox-toml.md b/docs/guide/celox-toml.md index fe1a4d40cbb..7709d31d8b9 100644 --- a/docs/guide/celox-toml.md +++ b/docs/guide/celox-toml.md @@ -128,3 +128,139 @@ 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. + +## CLI optimization and signal access + +`celox run` and `celox vpi build` accept these project/target settings: + +```toml +sources = ["top.sv"] +top = "Top" +opt_level = "O2" +live_signals = ["Top.uut.debug_count"] +force_signals = ["Top.uut.state"] + +[targets.observe] +opt_level = "O1" +force_signals = [] +``` + +The default optimization level is `O2` for `celox run` and `O1` for `celox vpi build`. Signal lists default to empty. `O2` may remove internal +computations that do not affect design outputs; `live_signals` retains the +listed objects for external observation. `force_signals` also implies liveness +and emits external override controls before symbolic evaluation and SIR +optimization, so blocking assignments and downstream expressions observe the +forced value. It does not switch the whole design to `O0`. Force permission is +retained in the standalone native image; undeclared force requests fail. + +Use exact hierarchy paths including the top module, as reported by VPI (for +example `Top.uut.s_axis.tdata`). Missing or ambiguous paths fail compilation; +wildcards are not expanded. Explicit force currently supports whole packed +SystemVerilog variables, including owned interface members. For an interface member, select its owning +variable rather than a child modport alias; structured port alias targets are +rejected. Unpacked arrays, clock +and reset event signals, and Veryl/mixed-language force targets are rejected. +Observation roots support both source languages. + +```sh +celox vpi build --project celox.toml -O O2 \ + --live-signal Top.uut.debug_count --force-signal Top.uut.state -o dut-sim +celox run --project celox.toml --target observe --no-force-signals +``` + +Priority is common settings → selected target → CLI. Each signal list replaces +the preceding list as a whole; an omitted target list inherits the common list, +and `[]` clears it. Repeat `--live-signal` or `--force-signal` for multiple paths. +`--no-live-signals` and `--no-force-signals` clear inherited lists and conflict +with the corresponding path options. These settings apply to the two CLI +compilation commands; JavaScript simulator options are configured separately. + +## CLI top parameter overrides + +Both `run` and `vpi build` accept repeatable `-G NAME=VALUE` or +`--parameter NAME=VALUE` (`--param` is an alias). These override numeric +parameters of the selected top module in SystemVerilog or Veryl, before +elaboration, without modifying source files. + +```sh +celox vpi build --project celox.toml -G ID_EN=1 -G DEST_EN=1 -o dut-sim +``` + +```toml +sources = ["top.sv"] +top = "Top" + +[parameters] +ID_EN = 1 +DEST_EN = 1 +DATA_W = 8 + +[targets.wide.parameters] +DATA_W = 64 +``` + +Common parameters are merged with the selected target's parameters, followed +by CLI assignments. The last assignment to each name wins; unrelated entries +are inherited. Values are unsigned 64-bit integers: decimal, `0x` hexadecimal, +`0o` octal, or `0b` binary. Digit separators such as `0x12_34` are accepted. +TOML values can be integers or strings (`DATA_W = "0x40"`); use strings for +values above TOML's signed 64-bit integer range. Negative numbers, HDL +expressions/literals, strings as HDL values, and type parameters are not +supported by this interface. Declared HDL parameter types still determine +conversion and truncation. Invalid assignments and unknown parameter names +produce errors. diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index 80b1fa10033..a6946a7e75d 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -59,6 +59,97 @@ limit before completion fails the command. This limit does not bound compilation or work within a single step/tick; use an external process timeout when a wall clock limit is needed. Source languages cannot be mixed in one invocation. +## Manage a multi-file project + +Save common inputs and named targets in `celox.toml`: + +```toml +sources = ["rtl/pkg.sv"] +filelists = ["rtl/design.f"] +include_dirs = ["include"] +default_target = "smoke" + +[defines] +SIMULATION = "1" + +[diagnostics] +mixed_timescale = "warn" + +[targets.smoke] +sources = ["test/Tb.sv"] +top = "Tb" +opt_level = "O1" +max_steps = 1000000 + +[targets.dut] +top = "Dut" +``` + +Both commands resolve the same sources, include directories, macros and top: + +```sh +celox run --target smoke +celox vpi build --target dut -o build/dut-sim +celox run --project /path/to/celox.toml --target smoke +``` + +With no explicit sources or `-f` arguments, or when `--target` is present, Celox +searches the current directory and its parents for `celox.toml`. Explicit +`--project FILE` selects a manifest directly. Relative manifest paths resolve +from the manifest's directory, including paths in its targets. Positional +sources and `-f` alone run independently of any nearby manifest. + +Targets inherit the root settings. Sources are collected in this order: root +`sources`, root `filelists`, target `sources`, target `filelists`, then CLI +sources and `-f` expansions in command-line order. Each list retains its source order. Include +directories accumulate in the same layer order. Macro definitions are global +to the invocation; later definitions win, with CLI `-D` definitions applied last. +TOML macro values are strings. Configured macros apply to each source; macros +defined in HDL files retain the frontend's per-file compilation-unit scope. `--top` overrides the selected top; `run`'s `-O` +and `--max-steps` override the target/root run settings. VPI builds retain the +existing force-compatible compilation settings. + +Without `--target`, Celox uses `default_target`, otherwise the root `top`, +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 +celox run -f test/all.f --top Tb +celox vpi build -f rtl/design.f --top Dut -o build/dut-sim +``` + +A `.f` file contains whitespace-separated source paths and can contain nested +lists and preprocessing options: + +```text +# Paths resolve from this file's directory. +../rtl/pkg.sv +-f ../rtl/design.f ++incdir+../include ++define+SIMULATION=1 +"../test/with spaces/Tb.sv" +``` + +Supported options are `-f FILE`, `-I DIR`/`-IDIR`, `-D NAME[=VALUE]`/`-DNAME[=VALUE]`, +`+incdir+DIR[+DIR...]` and `+define+NAME[=VALUE][+NAME[=VALUE]...]`. +Bare macro names expand to `1`. Paths may be quoted or use backslash escapes; +`#` and `//` start comments at a token boundary, and `/* ... */` comments are +also accepted. Every nested list resolves paths from its own directory. +The file-list reader performs no environment, wildcard or shell expansion. +Unknown options, unknown TOML fields and cyclic file lists are errors. +The CLI accepts `-I`/`--include-dir` and `-D`/`--define` directly as well. +Include directories and macros require SystemVerilog inputs and a build with +`--features systemverilog`. + ## Compile a design Pass one source in the Veryl project and name the top-level module: diff --git a/docs/ja/guide/celox-toml.md b/docs/ja/guide/celox-toml.md index 057346f1173..df0b71e3556 100644 --- a/docs/ja/guide/celox-toml.md +++ b/docs/ja/guide/celox-toml.md @@ -116,3 +116,91 @@ 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` は抑制していない警告を表示します。診断レベルを変更しても、最適化設定や実行時エラーの扱いは変わりません。 + +## CLIの最適化と信号アクセス + +`celox run` と `celox vpi build` は、共通設定とターゲット設定に次の項目を指定できます。 + +```toml +sources = ["top.sv"] +top = "Top" +opt_level = "O2" +live_signals = ["Top.uut.debug_count"] +force_signals = ["Top.uut.state"] + +[targets.observe] +opt_level = "O1" +force_signals = [] +``` + +最適化レベルの既定値は `celox run` では `O2`、`celox vpi build` では `O1` です。信号リストの既定値は空です。`O2` では出力に影響しない内部の計算を削除することがあるため、外部から観測する信号を `live_signals` で保持します。`force_signals` は保持対象にもなり、シンボリック評価とSIR最適化より前に外部から値を切り替える制御を追加します。これにより、blocking代入と後続の式もforceされた値を参照できます。設計全体を `O0` に変更することはありません。forceの許可対象は生成した実行バイナリにも保存され、宣言外へのforceは失敗します。 + +パスはtopを含むVPI上の完全名を指定します(例: `Top.uut.s_axis.tdata`)。存在しない名前や曖昧な名前はコンパイルエラーとなり、ワイルドカードは展開しません。明示的なforceは、現在SystemVerilogのpacked変数全体とinterfaceが所有するメンバーに対応しています。interfaceメンバーは子のmodport側の別名ではなく、所有する変数を指定してください。構造化ポートの別名をforce対象にするとエラーになります。unpacked配列、clock/resetのイベント信号、Verylまたは混在設計のforce対象はエラーになります。観測対象の指定は両方の言語に対応しています。 + +```sh +celox vpi build --project celox.toml -O O2 \ + --live-signal Top.uut.debug_count --force-signal Top.uut.state -o dut-sim +celox run --project celox.toml --target observe --no-force-signals +``` + +共通設定→選択したターゲット→CLIの順に優先されます。信号リストは全体を置き換えます。ターゲットで省略したリストは共通設定を継承し、`[]` で空にできます。CLIでは `--live-signal` / `--force-signal` を繰り返して列挙し、`--no-live-signals` / `--no-force-signals` で継承したリストを空にできます。リストを空にするオプションと、対応するパス指定は併用できません。これらの設定はCLIの2つのコンパイルコマンドに適用されます。JavaScriptのシミュレータオプションは別に指定します。 + +## CLIのtopパラメータ指定 + +`run` と `vpi build` では、`-G NAME=VALUE` または `--parameter NAME=VALUE` を繰り返し指定できます(`--param` も同じ意味です)。選択したtopモジュールの数値パラメータをエラボレーション前に上書きします。SystemVerilog・Verylの両方で使え、ソースの書き換えは不要です。 + +```sh +celox vpi build --project celox.toml -G ID_EN=1 -G DEST_EN=1 -o dut-sim +``` + +```toml +sources = ["top.sv"] +top = "Top" + +[parameters] +ID_EN = 1 +DEST_EN = 1 +DATA_W = 8 + +[targets.wide.parameters] +DATA_W = 64 +``` + +共通設定→選択したターゲット→CLIの順に、パラメータ名ごとに上書きします。同じ名前の最後の指定が有効になり、他の名前の指定は継承します。値は符号なし64bit整数で、10進数・`0x`(16進)・`0o`(8進)・`0b`(2進)を使えます。`0x12_34` のような桁区切りも使えます。TOMLでは整数または文字列(`DATA_W = "0x40"`)で指定し、TOMLの符号付き64bit整数の範囲を超える値は文字列にします。負数、HDLの式やリテラル、HDLの文字列値、型パラメータには対応していません。型変換と切り詰めには、HDL側で宣言したパラメータの型が使われます。不正な指定や存在しないパラメータ名はエラーになります。 diff --git a/docs/ja/guide/cocotb.md b/docs/ja/guide/cocotb.md index 60a031f5f07..f29a09e3a43 100644 --- a/docs/ja/guide/cocotb.md +++ b/docs/ja/guide/cocotb.md @@ -53,6 +53,90 @@ Verylでは完了前にtick上限に達すると失敗します。 コンパイルや1ステップ・tick内の処理時間は制限しないため、実時間の制限が必要な場合は 外部のタイムアウト機能を使ってください。1回の実行で言語を混在させることはできません。 +## 複数ファイルのプロジェクトを管理する + +共通の入力と名前付きターゲットを`celox.toml`に保存できます。 + +```toml +sources = ["rtl/pkg.sv"] +filelists = ["rtl/design.f"] +include_dirs = ["include"] +default_target = "smoke" + +[defines] +SIMULATION = "1" + +[diagnostics] +mixed_timescale = "warn" + +[targets.smoke] +sources = ["test/Tb.sv"] +top = "Tb" +opt_level = "O1" +max_steps = 1000000 + +[targets.dut] +top = "Dut" +``` + +`run`と`vpi build`は同じソース一覧、includeディレクトリ、マクロ、topを読みます。 + +```sh +celox run --target smoke +celox vpi build --target dut -o build/dut-sim +celox run --project /path/to/celox.toml --target smoke +``` + +ソースや`-f`を指定しない場合、または`--target`を指定した場合は、現在のディレクトリから +親方向へ`celox.toml`を探索します。`--project FILE`で直接指定することもできます。 +TOML内の相対パスは、ターゲット内も含めてTOMLのあるディレクトリを基準にします。 +ソースや`-f`だけを指定した場合は、近くのTOMLを自動では読みません。 + +ターゲットはルート設定を継承します。ソースの順序は、ルートの`sources`、 +ルートの`filelists`、ターゲットの`sources`、ターゲットの`filelists`、 +CLIのソースと`-f`(引数に指定した順)の順です。各一覧内の順序を保持します。 +includeディレクトリも同じ階層順で追加します。マクロは実行全体に適用し、 +後の定義が優先されます。CLIの`-D`は最後に適用します。TOMLのマクロ値は文字列です。 +設定されたマクロは各ソースに適用し、HDL内のマクロ定義は既存のファイル単位のスコープに従います。 +`--top`は選択されたtopを上書きし、`run`の`-O`と`--max-steps`はターゲット・ルートの +実行設定を上書きします。VPIビルドは既存のforce対応コンパイル設定を使用します。 + +`--target`を省略すると、`default_target`、ルートの`top`、唯一のターゲットの順に選びます。 +複数ターゲットがあり既定値もない場合は`--target`が必要です。 +単独の`.veryl`エントリーファイルをプロジェクトに指定することもでき、 +Veryl側のソース探索には引き続き`Veryl.toml`を使います。 + +コンパイル時の診断レベルは `[diagnostics]` で設定でき、`[targets.NAME.diagnostics]`、両コマンドの `--diagnostic CODE=allow|warn|error` の順に上書きできます。CLI オプションは繰り返し指定できます。緩和時の動作と使用例は [診断設定](./celox-toml.md#diagnostics) を参照してください。 + +### ファイル一覧を直接使う + +```sh +celox run -f test/all.f --top Tb +celox vpi build -f rtl/design.f --top Dut -o build/dut-sim +``` + +`.f`には空白区切りのソースパスを記述し、別の一覧やプリプロセッサ設定も指定できます。 + +```text +# 相対パスはこのファイルの場所を基準にします。 +../rtl/pkg.sv +-f ../rtl/design.f ++incdir+../include ++define+SIMULATION=1 +"../test/with spaces/Tb.sv" +``` + +対応するオプションは`-f FILE`、`-I DIR`/`-IDIR`、 +`-D NAME[=VALUE]`/`-DNAME[=VALUE]`、`+incdir+DIR[+DIR...]`、 +`+define+NAME[=VALUE][+NAME[=VALUE]...]`です。値のないマクロは`1`になります。 +パスには引用符やバックスラッシュのエスケープを使えます。 +トークンの先頭にある`#`・`//`による行コメントと、`/* ... */`コメントに対応します。 +ネストした一覧の相対パスは、それぞれの一覧があるディレクトリを基準にします。 +環境変数・ワイルドカード・シェルの展開は行いません。 +未対応オプション、未知のTOMLフィールド、一覧の循環参照はエラーにします。 +CLIからも`-I`/`--include-dir`と`-D`/`--define`を直接指定できます。 +include・マクロ指定にはSV入力と`--features systemverilog`によるビルドが必要です。 + ## 設計をコンパイルする Verylプロジェクト内のソースを1つ指定し、トップレベルモジュール名を渡します。 diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 01dcfd5452d..45069ab5bf4 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -358,7 +358,7 @@ test("PR caches cannot evict the shared default-branch Rust caches", () => { / - uses: Swatinem\/rust-cache@v2\n([\s\S]*?)(?=\n -|\n [a-z]|$)/g, ), ]; - assert.equal(cacheSteps.length, 8); + assert.equal(cacheSteps.length, 9); for (const [, step] of cacheSteps) { assert.match( step, @@ -453,11 +453,23 @@ test("cocotb retains Celox features without enabling unrelated adapter features" const args = cargoArguments("rust-tests", "Run cocotb VPI end-to-end test", { FEATURES: "celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus", }); - assert.deepEqual(args, ["test", "--locked", "-p", "celox-vpi", "--features", "celox/systemverilog", "--test", "cocotb_e2e", - "cocotb_drives_an_attached_native_flip_flop", "--", "--exact", "--ignored"]); + assert.deepEqual(args, ["test", "--locked", "-p", "celox-vpi", "--features", "systemverilog", "--features", "celox/systemverilog", "--test", "cocotb_e2e", + "cocotb_", "--", "--ignored"]); assert.match(job("rust-tests"), /name: Run cocotb VPI end-to-end test\n if: needs.changes.outputs.rust_vpi_e2e != 'false'/); }); test("full Clippy validation covers every workspace crate", () => { assert.match(job("lint"), /run: cargo clippy --locked --workspace --all-targets --features/); }); + +test("upstream SV TB runs on full CI and feeds failure reporting", () => { + const upstream = job("common-cells"); + assert.match(upstream, /github.event_name == 'schedule' \|\| github.event_name == 'workflow_dispatch'/); + assert.doesNotMatch(upstream, /continue-on-error/); + assert.match(upstream, /conformance\/common-cells\/revision/); + assert.match(upstream, /cargo build --locked -p celox-vpi --features systemverilog --bin celox/); + assert.match(upstream, /node scripts\/run-common-cells.mjs/); + assert.match(upstream, /if: always\(\)/); + assert.match(upstream, /retention-days: 14/); + assert.match(job("report-full-validation"), /common-cells,/); +}); diff --git a/scripts/run-common-cells.mjs b/scripts/run-common-cells.mjs new file mode 100644 index 00000000000..ca6bb5333f8 --- /dev/null +++ b/scripts/run-common-cells.mjs @@ -0,0 +1,70 @@ +import { spawnSync } from "node:child_process"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { resolve, join } from "node:path"; +import { pathToFileURL } from "node:url"; + +export const revision = readFileSync( + new URL("../conformance/common-cells/revision", import.meta.url), "utf8", +).trim(); +const sources = [ + "src/cc_binary_to_gray.sv", + "src/cc_gray_to_binary.sv", + "test/cc_graycode_tb.sv", +]; + +export function run({ source, celox, output }) { + source = resolve(source); + celox = resolve(celox); + output = resolve(output); + mkdirSync(output, { recursive: true }); + rmSync(join(output, "result.json"), { force: true }); + const head = spawnSync("git", ["-C", source, "rev-parse", "HEAD"], { encoding: "utf8" }); + if (head.status !== 0 || head.stdout.trim() !== revision) { + throw new Error(`Expected common_cells revision ${revision}; fetch the pinned checkout first`); + } + const manifest = (files) => `sources = [${files.map((file) => JSON.stringify(file)).join(", ")}]\ntop = "cc_graycode_tb"\n`; + const original = sources.map((file) => join(source, file)); + const project = join(output, "celox.toml"); + writeFileSync(project, manifest(original)); + const execute = (name, projectFile, negative = false) => { + const result = spawnSync(celox, ["run", "--project", projectFile], { + encoding: "utf8", timeout: 120_000, maxBuffer: 8 * 1024 * 1024, + }); + const log = `${result.stdout ?? ""}${result.stderr ?? ""}`; + writeFileSync(join(output, `${name}.log`), log); + if (result.error || result.signal || (negative + ? result.status !== 1 || !log.includes("assert failed") + : result.status !== 0)) { + throw new Error(`${name} failed (exit ${result.status}, signal ${result.signal}): ${result.error ?? log}`); + } + }; + execute("graycode", project); + + // Mutate only a separate RTL copy: prove that the upstream assertions execute. + const text = readFileSync(original[0], "utf8"); + const assignment = "assign z_o = a_i ^ a_ext[Width:1];"; + if (text.split(assignment).length !== 2) throw new Error("Cannot locate the pinned Gray code assignment"); + const broken = join(output, "negative_binary_to_gray.sv"); + writeFileSync(broken, text.replace(assignment, "assign z_o = '0;")); + const negativeProject = join(output, "negative.toml"); + writeFileSync(negativeProject, manifest([broken, ...original.slice(1)])); + execute("graycode-negative", negativeProject, true); + writeFileSync(join(output, "result.json"), `${JSON.stringify({ + revision, top: "cc_graycode_tb", positive: "passed", negative: "assertion failure detected", + }, null, 2)}\n`); + console.log(`common_cells ${revision}: upstream Gray code TB passed; broken RTL rejected`); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { + if (process.argv.length !== 5) { + console.error("Usage: node scripts/run-common-cells.mjs SOURCE CELOX_BIN OUTPUT_DIR"); + process.exitCode = 1; + } else { + try { + run({ source: process.argv[2], celox: process.argv[3], output: process.argv[4] }); + } catch (error) { + console.error(error.message); + process.exitCode = 1; + } + } +} diff --git a/scripts/run-common-cells.test.mjs b/scripts/run-common-cells.test.mjs new file mode 100644 index 00000000000..35948733316 --- /dev/null +++ b/scripts/run-common-cells.test.mjs @@ -0,0 +1,51 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import test from "node:test"; +import { revision } from "./run-common-cells.mjs"; + +test("upstream gate rejects wrong revisions, broken positives, and false negative controls", () => { + const root = mkdtempSync(join(tmpdir(), "common-cells-test-")); + try { + const source = join(root, "source with spaces"); + const bin = join(root, "bin"); + mkdirSync(join(source, "src"), { recursive: true }); + mkdirSync(join(source, "test")); + mkdirSync(bin); + const original = "assign z_o = a_i ^ a_ext[Width:1];"; + writeFileSync(join(source, "src/cc_binary_to_gray.sv"), original); + writeFileSync(join(source, "src/cc_gray_to_binary.sv"), ""); + writeFileSync(join(source, "test/cc_graycode_tb.sv"), ""); + writeFileSync(join(bin, "git"), `#!/usr/bin/env node\nconsole.log(process.env.TEST_REVISION || ${JSON.stringify(revision)});\n`); + const celox = join(bin, "celox"); + writeFileSync(celox, `#!/usr/bin/env node +const negative = process.argv.at(-1).endsWith("negative.toml"); +const mode = process.env.TEST_MODE; +if (!negative) process.exit(mode === "positive-failure" ? 1 : 0); +if (mode === "false-pass") process.exit(0); +if (mode === "compile-error") { console.error("compilation failed"); process.exit(1); } +if (mode === "crash") { process.kill(process.pid, "SIGTERM"); } +console.error("assert failed"); process.exit(1); +`); + chmodSync(join(bin, "git"), 0o755); + chmodSync(celox, 0o755); + for (const mode of ["success", "positive-failure", "false-pass", "compile-error", "crash", "wrong-revision"]) { + const output = join(root, mode); + const result = spawnSync(process.execPath, [resolve("scripts/run-common-cells.mjs"), source, celox, output], { + encoding: "utf8", + env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, TEST_MODE: mode, + TEST_REVISION: mode === "wrong-revision" ? "bad" : revision }, + }); + assert.equal(result.status, mode === "success" ? 0 : 1, `${mode}: ${result.stderr}`); + if (mode === "success") { + assert.equal(JSON.parse(readFileSync(join(output, "result.json"))).positive, "passed"); + assert.match(readFileSync(join(output, "graycode-negative.log"), "utf8"), /assert failed/); + } + } + assert.equal(readFileSync(join(source, "src/cc_binary_to_gray.sv"), "utf8"), original); + } finally { + rmSync(root, { recursive: true, force: true }); + } +});