Skip to content
Merged
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
2 changes: 1 addition & 1 deletion crates/celox-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1428,7 +1428,7 @@ pub(crate) fn generated_time_declarations(
sources: &[(&str, &std::path::Path)],
roots: Option<&[&str]>,
) -> Result<String, AnalyzerError> {
timescales::generated_source_declarations(sources, roots, false)
timescales::generated_source_declarations(sources, roots, crate::AnalysisOptions::default())
}

const MAX_GENERATE_LOOP_EXPANSION: usize = 10_000;
Expand Down
7 changes: 3 additions & 4 deletions crates/celox-sv-analyzer/src/ast/interfaces.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,17 +89,16 @@ pub fn interface_prototypes_with_options(
.zip(sources)
.map(|(file, (_, path))| (&file.syntax_tree, *path))
.collect::<Vec<_>>(),
options.allow_mixed_timescales,
options,
)?)
};
let trees = files
.iter()
.zip(sources)
.map(|(file, (_, path))| (&file.syntax_tree, *path))
.collect::<Vec<_>>();
let packages =
packages::Packages::analyze_with_options(&trees, None, options.allow_mixed_timescales)
.map_err(|error| error.with_warnings(source_warnings))?;
let packages = packages::Packages::analyze_with_options(&trees, None, options)
.map_err(|error| error.with_warnings(source_warnings))?;
let package_warnings = packages.warnings().to_vec();
let mut used_names = design
.modules
Expand Down
11 changes: 5 additions & 6 deletions crates/celox-sv-analyzer/src/ast/packages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,19 +197,19 @@ impl Packages {
trees: &[(&SyntaxTree, &Path)],
roots: Option<&[&str]>,
) -> Result<Self, AnalyzerError> {
Self::analyze_with_options(trees, roots, false)
Self::analyze_with_options(trees, roots, crate::AnalysisOptions::default())
}

pub(crate) fn analyze_with_options(
trees: &[(&SyntaxTree, &Path)],
roots: Option<&[&str]>,
allow_mixed_timescales: bool,
options: crate::AnalysisOptions,
) -> Result<Self, AnalyzerError> {
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, allow_mixed_timescales) {
match Self::analyze_with_roots_impl(trees, roots, options) {
Ok(packages) => Ok(packages.with_warnings(warnings)),
Err(error) => Err(error.with_warnings(warnings)),
}
Expand All @@ -218,10 +218,9 @@ impl Packages {
fn analyze_with_roots_impl(
trees: &[(&SyntaxTree, &Path)],
roots: Option<&[&str]>,
allow_mixed_timescales: bool,
options: crate::AnalysisOptions,
) -> Result<Self, AnalyzerError> {
let mut timescales =
timescales::Timescales::collect_with_options(trees, allow_mixed_timescales)?;
let mut timescales = timescales::Timescales::collect_with_options(trees, options)?;
if let Some(roots) = roots {
timescales.select_roots(roots);
}
Expand Down
35 changes: 23 additions & 12 deletions crates/celox-sv-analyzer/src/ast/timescales.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ pub(super) struct Timescales {
instantiated: HashSet<String>,
roots: Option<HashSet<String>>,
specified: [u8; 2],
allow_mixed_timescales: bool,
options: crate::AnalysisOptions,
}

/// Time-query state owned by one analysis, shared explicitly by nested scopes.
Expand Down Expand Up @@ -361,7 +361,7 @@ fn time_declarations(unit: Option<i32>, precision: Option<i32>) -> String {
pub(crate) fn generated_source_declarations(
sources: &[(&str, &Path)],
roots: Option<&[&str]>,
allow_mixed_timescales: bool,
options: crate::AnalysisOptions,
) -> Converted<String> {
let trees = sources
.iter()
Expand All @@ -372,7 +372,7 @@ pub(crate) fn generated_source_declarations(
.iter()
.map(|(tree, path)| (tree, *path))
.collect::<Vec<_>>(),
allow_mixed_timescales,
options,
)?;
if let Some(roots) = roots {
scales.select_roots(roots);
Expand Down Expand Up @@ -516,13 +516,12 @@ impl Timescales {
self.precision.unwrap_or(DEFAULT.precision)
}
fn including_tree(&self, tree: &SyntaxTree) -> Converted<Self> {
let local =
Self::collect_with_options(&[(tree, Path::new(""))], self.allow_mixed_timescales)?;
let local = Self::collect_with_options(&[(tree, Path::new(""))], self.options)?;
let specified = [
self.specified[0] | local.specified[0],
self.specified[1] | local.specified[1],
];
if specified.contains(&3) && !self.allow_mixed_timescales {
if specified.contains(&3) && !self.options.allow_mixed_timescales {
return Err(unsupported(
"mixed explicit and default time units or precisions across design elements",
));
Expand Down Expand Up @@ -577,17 +576,29 @@ impl Timescales {

#[cfg(test)]
pub(super) fn collect(trees: &[(&SyntaxTree, &Path)]) -> Converted<Self> {
Self::collect_with_options(trees, false)
Self::collect_with_options(trees, crate::AnalysisOptions::default())
}

pub(super) fn collect_with_options(
trees: &[(&SyntaxTree, &Path)],
allow_mixed_timescales: bool,
options: crate::AnalysisOptions,
) -> Converted<Self> {
#[cfg(test)]
COLLECTIONS.with(|count| count.set(count.get() + 1));
let default = match options.default_timescale {
Some((unit, precision))
if (-15..=2).contains(&unit)
&& (-15..=2).contains(&precision)
&& precision <= unit =>
{
Scale { unit, precision }
}
Some(_) => return Err(unsupported("invalid default time unit or precision")),
None => DEFAULT,
};
let mut design = Self {
allow_mixed_timescales,
precision: options.default_timescale.map(|(_, precision)| precision),
options,
..Self::default()
};
// Each bit records whether a design element uses a default (1) or an
Expand Down Expand Up @@ -686,8 +697,8 @@ impl Timescales {
}
directives.sort_by_key(|(at, _)| *at);
let unit = Scale {
unit: unit_decl.0.unwrap_or(DEFAULT.unit),
precision: unit_decl.1.unwrap_or(DEFAULT.precision),
unit: unit_decl.0.unwrap_or(default.unit),
precision: unit_decl.1.unwrap_or(default.precision),
};
if unit.precision > unit.unit {
return Err(unsupported("timeprecision coarser than timeunit"));
Expand Down Expand Up @@ -740,7 +751,7 @@ impl Timescales {
}),
);
}
if specified.contains(&3) && !allow_mixed_timescales {
if specified.contains(&3) && !options.allow_mixed_timescales {
return Err(unsupported(
"mixed explicit and default time units or precisions across design elements",
));
Expand Down
6 changes: 4 additions & 2 deletions crates/celox-sv-analyzer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,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.
/// Language compatibility checks and implementation-defined timing defaults.
#[derive(Debug, Clone, Copy, Default)]
pub struct AnalysisOptions {
pub allow_mixed_timescales: bool,
/// Default unit/precision exponents; precision also bounds global resolution.
pub default_timescale: Option<(i32, i32)>,
}

/// Errors reported by the SystemVerilog analyzer.
Expand Down Expand Up @@ -246,7 +248,7 @@ pub fn generated_time_declarations_with_options(
roots: Option<&[&str]>,
options: AnalysisOptions,
) -> Result<String, AnalyzerError> {
ast::timescales::generated_source_declarations(sources, roots, options.allow_mixed_timescales)
ast::timescales::generated_source_declarations(sources, roots, options)
}

/// Parse and analyze a SystemVerilog source string.
Expand Down
3 changes: 1 addition & 2 deletions crates/celox-sv-analyzer/src/parsed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,7 @@ impl ParsedSource {
}
}
}
let mut packages =
Packages::analyze_with_options(&trees, roots, options.allow_mixed_timescales)?;
let mut packages = Packages::analyze_with_options(&trees, roots, options)?;
packages.interface_names = design_units
.into_iter()
.filter_map(|(name, kind)| {
Expand Down
2 changes: 2 additions & 0 deletions crates/celox-vpi/src/bin/celox.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> {
.threads(arguments.execution.threads as usize)
.opt_level(arguments.opt_level)
.diagnostic_policy(arguments.design.diagnostics.clone())
.sv_timescale(arguments.design.timescale)
.signal_access(arguments.design.signal_access.clone());
let builder = arguments.design.apply_parameters(builder);
let max_steps = if arguments.execution.unlimited {
Expand Down Expand Up @@ -405,6 +406,7 @@ fn compile_native_design(design: &Design) -> Result<NativeProgramImage, String>
let builder = celox::Simulator::from_sv_sources(refs, &design.top)
.four_state(design.four_state.unwrap_or(false))
.diagnostic_policy(design.diagnostics.clone())
.sv_timescale(design.timescale)
.signal_access(design.signal_access.clone())
.opt_level(design.opt_level.unwrap_or(celox::OptLevel::O1));
let simulator = design
Expand Down
15 changes: 15 additions & 0 deletions crates/celox-vpi/src/bin/celox/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ pub(super) struct DesignArgs {
/// Override a compilation diagnostic: CODE=allow|warn|error (repeatable).
#[arg(long = "diagnostic", value_name = "CODE=LEVEL")]
diagnostics: Vec<String>,
/// Default SV UNIT/PRECISION and global scheduler resolution, e.g. 1ns/1fs.
#[arg(long, value_name = "UNIT/PRECISION")]
timescale: Option<String>,
/// Use two-state simulation, resolving X/Z to zero.
#[arg(long, conflicts_with = "four_state")]
two_state: bool,
Expand Down Expand Up @@ -102,6 +105,7 @@ struct Manifest {
top: Option<String>,
opt_level: Option<String>,
four_state: Option<bool>,
timescale: Option<String>,
live_signals: Option<Vec<String>>,
force_signals: Option<Vec<String>>,
max_steps: Option<u64>,
Expand Down Expand Up @@ -135,6 +139,7 @@ struct Target {
top: Option<String>,
opt_level: Option<String>,
four_state: Option<bool>,
timescale: Option<String>,
live_signals: Option<Vec<String>>,
force_signals: Option<Vec<String>>,
max_steps: Option<u64>,
Expand All @@ -152,6 +157,7 @@ pub(super) struct Design {
pub top: String,
pub opt_level: Option<celox::OptLevel>,
pub four_state: Option<bool>,
pub timescale: Option<celox::SvTimescale>,
pub signal_access: celox::SignalAccessOptions,
pub max_steps: Option<u64>,
}
Expand Down Expand Up @@ -281,6 +287,7 @@ impl DesignArgs {
design.diagnostics = config.diagnostics.clone();
design.top = config.top.clone().unwrap_or_default();
let mut opt_level = config.opt_level.as_deref();
let mut timescale = config.timescale.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();
Expand All @@ -300,6 +307,7 @@ impl DesignArgs {
design.top.clone_from(top);
}
opt_level = target.opt_level.as_deref().or(opt_level);
timescale = target.timescale.as_deref().or(timescale);
if let Some(paths) = &target.live_signals {
design.signal_access.live_signals.clone_from(paths);
}
Expand All @@ -309,6 +317,7 @@ impl DesignArgs {
design.max_steps = target.max_steps.or(design.max_steps);
design.four_state = target.four_state.or(design.four_state);
}
design.timescale = timescale.map(str::parse).transpose()?;
design.opt_level = opt_level
.map(|value| {
celox::OptLevel::parse(value).ok_or_else(|| {
Expand All @@ -334,6 +343,9 @@ impl DesignArgs {
}
}));
design.opt_level = self.opt_level.or(design.opt_level);
if let Some(timescale) = self.timescale {
design.timescale = Some(timescale.parse()?);
}
if self.two_state {
design.four_state = Some(false);
}
Expand Down Expand Up @@ -390,6 +402,9 @@ impl DesignArgs {
if design.top.trim().is_empty() {
return Err("provide --top MODULE or set top in celox.toml".to_string());
}
if !design.is_sv() && design.timescale.is_some() {
return Err("timescale requires SystemVerilog sources".into());
}
if !design.is_sv() && !design.sv_parameters.is_empty() {
return Err("SV parameter literals require .sv/.v sources".to_string());
}
Expand Down
21 changes: 21 additions & 0 deletions crates/celox-vpi/tests/cocotb_e2e.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,27 @@ fn cocotb_observes_edges_before_nonblocking_updates() {
check_cocotb_native_design(&["edge_phase.sv"], "test_edge_phase", "edge_precedes_nba");
}

#[test]
#[ignore = "requires a cocotb installation; CI runs this test explicitly"]
fn cocotb_accepts_femtosecond_clock_periods() {
check_cocotb_native_design_with_options(
&["edge_phase.sv"],
"test_fs_clock",
"femtosecond_clock",
&["--timescale", "1ns/1fs"],
);
}

fn check_cocotb_native_design(source: &[&str], module: &str, filter: &str) {
check_cocotb_native_design_with_options(source, module, filter, &[]);
}

fn check_cocotb_native_design_with_options(
source: &[&str],
module: &str,
filter: &str,
options: &[&str],
) {
let python = env::var_os("CELOX_COCOTB_PYTHON")
.expect("CELOX_COCOTB_PYTHON must name the cocotb Python interpreter");
let python = python.to_string_lossy().into_owned();
Expand All @@ -115,6 +135,7 @@ fn check_cocotb_native_design(source: &[&str], module: &str, filter: &str) {
.arg("vpi")
.arg("build")
.args(source.iter().map(|path| fixture.join(path)))
.args(options)
.args(["--top", "Top", "--output"])
.arg(&executable)
.output()
Expand Down
18 changes: 18 additions & 0 deletions crates/celox-vpi/tests/fixtures/cocotb/test_fs_clock.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""The original 1ps SV scope can be driven by a 1fs-resolution testbench."""
import cocotb
from cocotb.clock import Clock
from cocotb.triggers import RisingEdge, Timer
from cocotb.utils import get_sim_time


@cocotb.test()
async def femtosecond_clock(dut):
dut.d.value = 1
clock = Clock(dut.clk, 6.206206, unit="ns")
cocotb.start_soon(clock.start())
await RisingEdge(dut.clk)
first = get_sim_time(unit="fs")
await RisingEdge(dut.clk)
assert get_sim_time(unit="fs") - first == 6206206
await Timer(1, unit="fs")
assert int(dut.q.value) == 1
Loading
Loading