Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions crates/celox-vpi/src/bin/celox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,7 @@ fn run_testbench(arguments: RunArgs) -> Result<(), String> {
.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);
}
Expand Down Expand Up @@ -198,11 +199,14 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> {
.iter()
.map(|(text, path)| (text.as_str(), path.as_path()))
.collect();
let simulation = celox::Simulation::from_sv_sources(source_refs, &arguments.design.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())
.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())?;
Expand Down Expand Up @@ -430,11 +434,13 @@ fn compile_native_design(design: &Design) -> Result<NativeProgramImage, String>
.iter()
.map(|(text, path)| (text.as_str(), path.as_path()))
.collect();
let simulator = celox::Simulator::from_sv_sources(refs, &design.top)
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))
.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())?;
Expand All @@ -453,12 +459,13 @@ fn compile_native_design(design: &Design) -> Result<NativeProgramImage, String>
{
return Err("pass .sv/.v sources, or one .veryl project entry file".to_string());
}
let (image, warnings) = celox_vpi::driver::compile_native_image_with_options(
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)
Expand Down
92 changes: 92 additions & 0 deletions crates/celox-vpi/src/bin/celox/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@ pub(super) struct DesignArgs {
/// SystemVerilog macro, NAME or NAME=VALUE (repeatable; last value wins).
#[arg(short = 'D', long = "define", value_name = "NAME[=VALUE]")]
defines: Vec<String>,
/// Override a numeric top parameter (repeatable; last value wins).
#[arg(
short = 'G',
long = "parameter",
visible_alias = "param",
value_name = "NAME=VALUE"
)]
parameters: Vec<String>,
/// Top-level module; overrides the selected target.
#[arg(long)]
top: Option<String>,
Expand All @@ -73,6 +81,7 @@ struct Manifest {
filelists: Vec<PathBuf>,
include_dirs: Vec<PathBuf>,
defines: BTreeMap<String, String>,
parameters: BTreeMap<String, ParameterValue>,
top: Option<String>,
opt_level: Option<String>,
live_signals: Option<Vec<String>>,
Expand All @@ -90,6 +99,7 @@ struct Target {
filelists: Vec<PathBuf>,
include_dirs: Vec<PathBuf>,
defines: BTreeMap<String, String>,
parameters: BTreeMap<String, ParameterValue>,
top: Option<String>,
opt_level: Option<String>,
live_signals: Option<Vec<String>>,
Expand All @@ -103,6 +113,7 @@ pub(super) struct Design {
pub sources: Vec<PathBuf>,
pub include_dirs: Vec<PathBuf>,
pub defines: BTreeMap<String, String>,
pub parameters: BTreeMap<String, u64>,
pub top: String,
pub opt_level: Option<celox::OptLevel>,
pub signal_access: celox::SignalAccessOptions,
Expand Down Expand Up @@ -194,13 +205,15 @@ impl DesignArgs {
&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,
Expand Down Expand Up @@ -266,6 +279,12 @@ impl DesignArgs {
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;
}
Expand All @@ -286,7 +305,80 @@ impl DesignArgs {
}
}

/// 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<u64, String> {
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<String, ParameterValue>,
) -> 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()
Expand Down
36 changes: 30 additions & 6 deletions crates/celox-vpi/src/driver.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! 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::{
CompilationWarning, DiagnosticPolicy, NativeProgramImage, NativeProgramInstance, Simulator,
Expand Down Expand Up @@ -61,6 +61,7 @@ pub fn compile_native_image_with_diagnostics(
celox::OptLevel::O0,
celox::SignalAccessOptions::default(),
true,
&BTreeMap::new(),
)
}

Expand All @@ -72,7 +73,19 @@ pub fn compile_native_image_with_options(
level: celox::OptLevel,
access: celox::SignalAccessOptions,
) -> Result<(NativeProgramImage, Vec<CompilationWarning>), String> {
compile_native_image_configured(source, top, policy, level, access, false)
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<String, u64>,
) -> Result<(NativeProgramImage, Vec<CompilationWarning>), String> {
compile_native_image_configured(source, top, policy, level, access, false, parameters)
}

fn compile_native_image_configured(
Expand All @@ -82,6 +95,7 @@ fn compile_native_image_configured(
level: celox::OptLevel,
access: celox::SignalAccessOptions,
legacy_force: bool,
parameters: &BTreeMap<String, u64>,
) -> Result<(NativeProgramImage, Vec<CompilationWarning>), String> {
let simulator = if let Ok(metadata_path) = Metadata::search_from(source) {
let mut metadata = Metadata::load(&metadata_path)
Expand All @@ -101,23 +115,33 @@ fn compile_native_image_configured(
.iter()
.map(|(contents, path)| (contents.as_str(), path.as_path()))
.collect::<Vec<_>>();
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(legacy_force)
.signal_access(access.clone())
.opt_level(level)
.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(legacy_force)
.signal_access(access.clone())
.opt_level(level)
.opt_level(level);
parameters
.iter()
.fold(builder, |builder, (name, value)| {
builder.param(name, *value)
})
.build()
}
.map_err(|error| format!("compilation failed: {error}"))?;
Expand Down
Loading
Loading