From 187b05f5c86dc0305bca0d665031035ce8ba99ca Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 20 Oct 2026 03:43:12 +0900 Subject: [PATCH 1/3] feat(cli): support celox.toml projects and SV file lists Let `celox run` and `celox vpi build` share project inputs from celox.toml, including common sources, named targets, include directories, macro definitions, top selection and run defaults. Resolve manifest paths from the manifest directory and discover a project from the current directory or its parents when appropriate. Explicit CLI settings override the selected target. Preserve the O2 production default when neither the CLI nor the project sets an optimization level, with precedence coverage for .sv, .v, and .veryl inputs. Support standalone and nested -f file lists with quoted paths, comments, -I/-D and +incdir+/+define+ options. Expand CLI source and file-list arguments in their authored order. Reject unknown configuration fields, unsupported file-list options and recursive lists. Use the existing SV preprocessing API for includes and defines; compiler lowering, state-machine construction and optimizers are unchanged. Add integration coverage for both commands, target selection, preprocessing, relative paths, CLI overrides, disabled SV builds and malformed configuration. Document the schema, path rules, ordering and supported file-list syntax in English and Japanese. Validation: - cargo test --locked -p celox-vpi - cargo test --locked -p celox-vpi --features systemverilog - cargo clippy --locked -p celox-vpi --all-targets -- -D warnings - cargo clippy --locked -p celox-vpi --all-targets --features systemverilog -- -D warnings - cargo fmt --all -- --check - pnpm run lint - Parse the TOML examples from both guides with Python tomllib. The two cocotb-dependent integration tests also pass when explicitly enabled with the configured Python interpreter. Change-Id: I620aad8541eb0f53364e4b32f571c56a9669f4f0 --- Cargo.lock | 3 + crates/celox-vpi/Cargo.toml | 6 +- crates/celox-vpi/src/bin/celox.rs | 250 +++++++++---- crates/celox-vpi/src/bin/celox/project.rs | 424 ++++++++++++++++++++++ crates/celox-vpi/tests/project_cli.rs | 328 +++++++++++++++++ docs/guide/cocotb.md | 82 +++++ docs/ja/guide/cocotb.md | 79 ++++ 7 files changed, 1102 insertions(+), 70 deletions(-) create mode 100644 crates/celox-vpi/src/bin/celox/project.rs create mode 100644 crates/celox-vpi/tests/project_cli.rs 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/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..39fcd943d70 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,78 @@ enum CliCommand { #[derive(Args)] struct RunArgs { - /// SystemVerilog sources in compilation order, or one Veryl project entry file. - #[arg(required = true)] - sources: Vec, - - /// Top-level testbench module name. - #[arg(long)] - top: String, + #[command(flatten)] + design: DesignArgs, - /// Compiler optimization level: O0, O1, O2. - #[arg(short = 'O', long, default_value = "O2", value_parser = parse_opt_level)] - opt_level: celox::OptLevel, + /// Compiler optimization level: O0, O1, O2 (default: project setting or O2). + #[arg(short = 'O', long, value_parser = parse_opt_level)] + opt_level: Option, - /// Maximum SV scheduler steps or Veryl testbench ticks before failing. + /// 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, default_value_t = 1_000_000, value_parser = clap::value_parser!(u64).range(1..))] + #[arg(long, value_parser = clap::value_parser!(u64).range(1..))] + max_steps: Option, +} + +struct RunConfig { + design: Design, + opt_level: celox::OptLevel, 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: arguments + .opt_level + .or(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 +121,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,7 +165,7 @@ 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); @@ -148,21 +196,13 @@ fn run_testbench(arguments: RunArgs) -> Result<(), String> { } #[cfg(feature = "systemverilog")] -fn run_sv(arguments: RunArgs) -> Result<(), String> { - let contents = arguments - .sources +fn run_sv(arguments: RunConfig) -> Result<(), String> { + let sources = arguments.design.sv_sources()?; + let source_refs = sources .iter() - .map(|path| { - std::fs::read_to_string(path) - .map_err(|error| format!("failed to read {}: {error}", path.display())) - }) - .collect::, _>>()?; - let sources = contents - .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 simulation = celox::Simulation::from_sv_sources(source_refs, &arguments.design.top) .four_state(true) .opt_level(arguments.opt_level) .build() @@ -311,13 +351,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 +391,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 +415,46 @@ 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 simulator = celox::Simulator::from_sv_sources(refs, &design.top) + .four_state(true) + .native_force_support(true) + .opt_level(celox::OptLevel::O0) + .build() + .map_err(|error| format!("compilation failed:\n{error}"))?; + 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()); + } + celox_vpi::driver::compile_native_image(&design.sources[0], &design.top) +} + fn environment_path(name: &str) -> Option { env::var_os(name).map(PathBuf::from) } @@ -731,7 +795,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 +824,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..15822f80617 --- /dev/null +++ b/crates/celox-vpi/src/bin/celox/project.rs @@ -0,0 +1,424 @@ +//! 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, + /// 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, + /// 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 { + sources: Vec, + filelists: Vec, + include_dirs: Vec, + defines: BTreeMap, + top: Option, + opt_level: Option, + max_steps: Option, + default_target: Option, + targets: BTreeMap, +} + +#[derive(Default, Deserialize)] +#[serde(default, deny_unknown_fields)] +struct Target { + sources: Vec, + filelists: Vec, + include_dirs: Vec, + defines: BTreeMap, + top: Option, + opt_level: Option, + max_steps: Option, +} + +#[derive(Default)] +pub(super) struct Design { + pub sources: Vec, + pub include_dirs: Vec, + pub defines: BTreeMap, + pub top: String, + pub opt_level: Option, + 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.top = config.top.clone().unwrap_or_default(); + let mut opt_level = config.opt_level.as_deref(); + design.max_steps = config.max_steps; + if let Some(target) = selected { + design.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); + 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()); + } + } + 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())? + } + } + } + design.include_dirs.extend(self.include_dirs); + for define in &self.defines { + design.define(define)?; + } + 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) + } +} + +impl Design { + 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/tests/project_cli.rs b/crates/celox-vpi/tests/project_cli.rs new file mode 100644 index 00000000000..09d279af2ae --- /dev/null +++ b/crates/celox-vpi/tests/project_cli.rs @@ -0,0 +1,328 @@ +//! Project configuration belongs to the CLI, rather than the language suite. + +use std::{ + fs, + path::Path, + process::{Command, Output}, +}; + +fn invoke(cwd: &Path, args: &[&str]) -> 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 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"), + ( + "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")); + } +} diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index 80b1fa10033..dba2f166a5b 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -59,6 +59,88 @@ 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" + +[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`. + +### 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/cocotb.md b/docs/ja/guide/cocotb.md index 60a031f5f07..248e22a2ad7 100644 --- a/docs/ja/guide/cocotb.md +++ b/docs/ja/guide/cocotb.md @@ -53,6 +53,85 @@ 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" + +[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`を使います。 + +### ファイル一覧を直接使う + +```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つ指定し、トップレベルモジュール名を渡します。 From fac28284c4418e40436ed3a58f0463cb7b14c1ae Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 20 Oct 2026 04:05:26 +0900 Subject: [PATCH 2/3] ci: run pinned upstream SystemVerilog testbench daily Run PULP common_cells' unmodified Gray code testbench through the SystemVerilog CLI and celox.toml project input on scheduled and manually dispatched full CI, including develop's nightly dispatch. Pin the upstream revision and retain execution logs for 14 days. Feed failures into the existing full CI issue reporter. Require a separate RTL mutation to fail with an assertion diagnostic, so a skipped checker, compilation failure, or simulator crash cannot satisfy the negative control. Add local reproduction instructions and runner/workflow regressions. Validation: all 268 repository script tests, pnpm lint, the SystemVerilog CLI build, and the real pinned upstream positive/negative runs passed. Actionlint passed with only its outdated ubuntu-26.04-arm label catalogue diagnostic suppressed; that runner label predates this change. Change-Id: I8cbb5649658a09f4dfa500dba90745cd0d5b37f8 --- .github/workflows/ci.yml | 44 +++++++++++++++++++ CONTRIBUTING.md | 1 + conformance/common-cells/README.md | 38 ++++++++++++++++ conformance/common-cells/revision | 1 + scripts/ci-workflow.test.mjs | 14 +++++- scripts/run-common-cells.mjs | 70 ++++++++++++++++++++++++++++++ scripts/run-common-cells.test.mjs | 51 ++++++++++++++++++++++ 7 files changed, 218 insertions(+), 1 deletion(-) create mode 100644 conformance/common-cells/README.md create mode 100644 conformance/common-cells/revision create mode 100644 scripts/run-common-cells.mjs create mode 100644 scripts/run-common-cells.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7f46105596e..8227e3c7eb8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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/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/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 01dcfd5452d..dd96e7a17c5 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, @@ -461,3 +461,15 @@ test("cocotb retains Celox features without enabling unrelated adapter features" 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 }); + } +}); From c9628e707984faf9d81e296c0933f0bb41524754 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 20 Oct 2026 09:33:33 +0000 Subject: [PATCH 3/3] chore(deps): update rust toolchain to 5424e1e --- flake.lock | 8 ++++---- flake.nix | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/flake.lock b/flake.lock index aad2340f531..60c6320088b 100644 --- a/flake.lock +++ b/flake.lock @@ -50,17 +50,17 @@ ] }, "locked": { - "lastModified": 1792395246, - "narHash": "sha256-SfVFE7TKuByeQRwhVbaVrvTV/lI41AYK9CYSfB+pIis=", + "lastModified": 1792480937, + "narHash": "sha256-arni7i+yH5ZnkvAN9UotvhMml5+fZyXcMHpiOvI3WFY=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "550547cefc67e01a6fd11a09e4096a3c844ca840", + "rev": "5424e1e6dda30b0626935d2a03a6526db4858d60", "type": "github" }, "original": { "owner": "oxalica", "repo": "rust-overlay", - "rev": "550547cefc67e01a6fd11a09e4096a3c844ca840", + "rev": "5424e1e6dda30b0626935d2a03a6526db4858d60", "type": "github" } } diff --git a/flake.nix b/flake.nix index c73d36d0ccc..41d76f47370 100644 --- a/flake.nix +++ b/flake.nix @@ -9,7 +9,7 @@ }; rust-overlay = { # Pin the revision explicitly so Renovate can group overlay and Rust updates. - url = "github:oxalica/rust-overlay/550547cefc67e01a6fd11a09e4096a3c844ca840"; + url = "github:oxalica/rust-overlay/5424e1e6dda30b0626935d2a03a6526db4858d60"; inputs.nixpkgs.follows = "nixpkgs"; }; };