diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bbd9e1d4a46..eaae492ee86 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -37,6 +37,12 @@ jobs: rust: ${{ steps.classify.outputs.rust }} rust_full: ${{ steps.classify.outputs.rust_full }} rust_packages: ${{ steps.classify.outputs.rust_packages }} + rust_targets: ${{ steps.classify.outputs.rust_targets }} + rust_lint_packages: ${{ steps.classify.outputs.rust_lint_packages }} + rust_lint_features: ${{ steps.classify.outputs.rust_lint_features }} + rust_lint_targets: ${{ steps.classify.outputs.rust_lint_targets }} + rust_doc_libraries: ${{ steps.classify.outputs.rust_doc_libraries }} + rust_sv_tests: ${{ steps.classify.outputs.rust_sv_tests }} rust_features: ${{ steps.classify.outputs.rust_features }} rust_filter: ${{ steps.classify.outputs.rust_filter }} rust_libraries: ${{ steps.classify.outputs.rust_libraries }} @@ -139,15 +145,42 @@ jobs: fi - name: cargo clippy - if: needs.changes.result != 'success' || needs.changes.outputs.rust == 'true' + if: (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') && needs.changes.outputs.rust_full != 'false' run: cargo clippy --locked -p celox-test-suite -p celox -p celox-frontend-core -p celox-frontend-sv -p celox-frontend-veryl -p celox-macros -p celox-napi -p celox-sv-analyzer -p celox-ts-gen -p celox-vpi -p lydite-ir -p lydite -p lydite-celox -p lydite-solver -p lydite-syntax -p lydite-verify --all-targets --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus --no-deps + - name: Lint the crates this pull request can affect + if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_lint_packages != '' + env: + PACKAGES: ${{ needs.changes.outputs.rust_lint_packages }} + FEATURES: ${{ needs.changes.outputs.rust_lint_features }} + TARGETS: ${{ needs.changes.outputs.rust_lint_targets }} + run: | + args=() + for package in $PACKAGES; do args+=(-p "$package"); done + if [ -n "$FEATURES" ]; then args+=(--features "$FEATURES"); fi + if [ -n "$TARGETS" ]; then + for target in $TARGETS; do args+=(--test "$target"); done + else + args+=(--all-targets) + fi + cargo clippy --locked "${args[@]}" --no-deps + - name: Build Rust API documentation - if: needs.changes.result != 'success' || needs.changes.outputs.rust == 'true' + if: (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') && needs.changes.outputs.rust_full != 'false' env: RUSTDOCFLAGS: -D warnings run: cargo doc --locked --workspace --no-deps + - name: Build the API documentation this pull request can affect + if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_doc_libraries != '' + env: + RUSTDOCFLAGS: -D warnings + LIBRARIES: ${{ needs.changes.outputs.rust_doc_libraries }} + run: | + args=() + for package in $LIBRARIES; do args+=(-p "$package"); done + cargo doc --locked --no-deps "${args[@]}" + - uses: pnpm/action-setup@v6 if: needs.changes.result != 'success' || needs.changes.outputs.javascript == 'true' @@ -197,10 +230,12 @@ jobs: save-if: ${{ github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }} - uses: actions/setup-python@v7 + if: needs.changes.outputs.rust_full != 'false' || contains(format(' {0} ', needs.changes.outputs.rust_packages), ' celox-vpi ') with: python-version: "3.14" - name: Install cocotb + if: needs.changes.outputs.rust_full != 'false' || contains(format(' {0} ', needs.changes.outputs.rust_packages), ' celox-vpi ') run: python -m pip install cocotb==2.1.0 - name: Install cargo-nextest @@ -227,12 +262,14 @@ jobs: PACKAGES: ${{ needs.changes.outputs.rust_packages }} FEATURES: ${{ needs.changes.outputs.rust_features }} FILTER: ${{ needs.changes.outputs.rust_filter }} + TARGETS: ${{ needs.changes.outputs.rust_targets }} run: | echo "Packages: $PACKAGES" echo "Filter: $FILTER" args=() for package in $PACKAGES; do args+=(-p "$package"); done if [ -n "$FEATURES" ]; then args+=(--features "$FEATURES"); fi + for target in $TARGETS; do args+=(--test "$target"); done cargo nextest run --locked --profile ci \ --no-tests=pass "${args[@]}" -E "$FILTER" @@ -359,7 +396,7 @@ jobs: sv-tests: name: sv-tests conformance needs: changes - if: ${{ !cancelled() && (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') }} + if: ${{ !cancelled() && (needs.changes.result != 'success' || (needs.changes.outputs.rust == 'true' && needs.changes.outputs.rust_sv_tests != 'false')) }} runs-on: ubuntu-latest timeout-minutes: 60 steps: @@ -506,6 +543,7 @@ jobs: CHANGES_RESULT: ${{ needs.changes.result }} RUST_REQUIRED: ${{ needs.changes.outputs.rust }} RUST_RESULT: ${{ needs.rust-tests.result }} + SV_TESTS_REQUIRED: ${{ needs.changes.outputs.rust != 'false' && needs.changes.outputs.rust_sv_tests != 'false' }} SV_TESTS_RESULT: ${{ needs.sv-tests.result }} # Platform coverage is mandatory in queue and full validation runs. ARM64_REQUIRED: ${{ needs.changes.outputs.queue != 'false' && needs.changes.outputs.rust != 'false' }} @@ -524,7 +562,7 @@ jobs: if [ "$RUST_REQUIRED" != false ] || [ "$RUST_RESULT" != skipped ]; then test "$RUST_RESULT" = success fi - if [ "$RUST_REQUIRED" != false ] || [ "$SV_TESTS_RESULT" != skipped ]; then + if [ "$SV_TESTS_REQUIRED" != false ] || [ "$SV_TESTS_RESULT" != skipped ]; then test "$SV_TESTS_RESULT" = success fi if [ "$ARM64_REQUIRED" != false ] || [ "$ARM64_RESULT" != skipped ]; then diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ce3676d46d6..8d0588f704a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -241,10 +241,30 @@ Lydite has its own test cadence (`scripts/ci-lydite-changes.mjs`): excludes them, and fails on selected-job failures or cancellations. Repository branch protection must require this check to make it a merge gate. -The classifier selects CI jobs, not individual Rust tests. Selected Rust CI -still runs the Celox workspace suite with CI features, doctests, default-feature -checks, ARM64 backend checks, and the explicit cocotb test. Local validation -uses the finer behavior-based matrix above. +Ordinary PRs also scope Rust compilation and execution: + +- Library changes select the crate and its transitive consumers. Backend and + SV frontend changes narrow Celox integration tests to the affected variants; + shared implementation changes retain all affected variants. +- A single package's integration test or recognized Insta snapshot changes + select only the corresponding test binaries, using Cargo `--test` as well + as a nextest filter. Shared helpers and fixtures retain the package's tests; + mixed library/test changes combine their requirements. +- Clippy selects affected crates and test targets, including Lydite. Rust API + documentation and doctests select libraries reached through runtime/build + dependencies; dev-only consumers still run tests but do not rebuild their + API documentation. Test-only changes skip API documentation and doctests. +- sv-tests conformance runs when the Celox library or its runtime/build + dependencies change, or its runner/expectations change. Test infrastructure + and downstream consumers do not select this separate release-mode build. +- Python/cocotb setup runs only when VPI tests are selected. + +Queue drafts, merge groups, releases, `ci:full`, and daily/manual full runs +retain the existing workspace tests, lint, documentation, sv-tests and platform +coverage. Cargo manifest, lockfile, toolchain, unknown-path and failed scope +analysis changes fall back to broad validation. Required checks permit skips +only when explicitly unneeded and still reject failures and cancellations. +Local validation uses the behavior-based matrix above. | Cadence | Coverage | | --- | --- | diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 204e1520b64..eb74f6bdbfe 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -708,7 +708,7 @@ chapter-8/8.8--typed_constructor.sv fail chapter-8/8.8--typed_constructor_param.sv fail chapter-8/8.9--static_properties.sv fail chapter-9/9.2.1--initial.sv pass -chapter-9/9.2.2.1--always.sv fail +chapter-9/9.2.2.1--always.sv pass chapter-9/9.2.2.2--always_comb.sv pass chapter-9/9.2.2.3--always_latch.sv fail chapter-9/9.2.2.4--always_ff.sv pass @@ -732,8 +732,8 @@ chapter-9/9.4.2--event_control_negedge.sv pass chapter-9/9.4.2--event_control_posedge.sv pass chapter-9/9.4.2--event_control_sim.sv fail chapter-9/9.4.2--event_control_sim_minimal.sv fail -chapter-9/9.4.2.1--event_comma_op.sv fail -chapter-9/9.4.2.1--event_or_op.sv fail +chapter-9/9.4.2.1--event_comma_op.sv pass +chapter-9/9.4.2.1--event_or_op.sv pass chapter-9/9.4.2.2--event_implicit.sv pass chapter-9/9.4.2.3--event_conditional.sv fail chapter-9/9.4.2.4--event_sequence.sv fail diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index c177953bfcb..80cb127432b 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -2807,6 +2807,12 @@ fn lower_initial_processes( .get(&(1, index)) .copied() .unwrap_or(0x4d59_5df4); + // An `always` process never finishes, so it is never folded into + // initial state. + if process.repeats() { + runtime.push((process, random_seed)); + continue; + } let mut comb = comb::Comb::new(&mut pm, &mut arena); match comb.lower_initial(process.body(), process.is_initializer(), &seed) { Ok((written, store)) => { diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 1cc7da990b6..ef8b122a267 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1000,6 +1000,7 @@ impl Module { body: static_initializers, initializer: true, synthetic: false, + repeats: false, }, ); } @@ -2062,6 +2063,8 @@ pub struct InitialProcess { body: Vec, initializer: bool, synthetic: bool, + /// An `always` process: its body runs forever. + repeats: bool, } impl InitialProcess { @@ -2084,6 +2087,12 @@ impl InitialProcess { self.initializer } + /// Whether this is an `always` process, which runs its body forever and + /// never finishes on its own. + pub fn repeats(&self) -> bool { + self.repeats + } + pub fn body(&self) -> &[Stmt] { &self.body } diff --git a/crates/celox-sv-analyzer/src/ast/array_parameters.rs b/crates/celox-sv-analyzer/src/ast/array_parameters.rs index 75afe95e93d..1eae085c5fb 100644 --- a/crates/celox-sv-analyzer/src/ast/array_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/array_parameters.rs @@ -229,6 +229,7 @@ impl ArrayParameter<'_> { }], initializer: false, synthetic: true, + repeats: false, }) } } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 12a4ccdbfa5..6085343a7ef 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -596,15 +596,17 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } } - /// Timing controls suspend the process that executes them. An `initial` - /// body runs as a process; `always` bodies with timing controls and - /// subroutines with them are not lowered yet. - fn allow_timing(&self, construct: &str) -> Result<(), AnalyzerError> { + /// Timing controls suspend the process that executes them: an + /// `initial` or `always` process. An `always_comb` or `always_ff` body + /// and a function may not suspend; subroutines with timing controls are + /// not lowered yet. + fn allow_timing(&self, construct: &'static str) -> Result<(), AnalyzerError> { match self.body { system_functions::Body::Initial => Ok(()), - system_functions::Body::Always => Err(unsupported(format!( - "always and always_latch processes with a {construct}" - ))), + system_functions::Body::Always => Err(AnalyzerError::TimingControlOutsideProcess { + construct, + context: "an always_comb or always_ff body", + }), system_functions::Body::Subroutine => { Err(unsupported(format!("{construct} in a subroutine"))) } @@ -2214,6 +2216,7 @@ pub(super) fn initial_processes_from_module_node( body, initializer: true, synthetic: false, + repeats: false, }); } continue; @@ -2222,17 +2225,40 @@ pub(super) fn initial_processes_from_module_node( else { continue; }; - let sv_parser::ModuleCommonItem::InitialConstruct(initial) = &module_item.nodes.1 else { - continue; + let (statement, repeats) = match &module_item.nodes.1 { + sv_parser::ModuleCommonItem::InitialConstruct(initial) => { + (Some(&initial.nodes.1), false) + } + sv_parser::ModuleCommonItem::AlwaysConstruct(always) + if validation::always_kind(always) == validation::AlwaysKind::Process => + { + (None, true) + } + _ => continue, }; let (item_dimensions, literals) = views.get(item); + // A process statement runs in the body kind of an `initial` block: + // it may suspend and call any task. let mut builder = BodyBuilder::new( tree, item_dimensions, state, system_functions::Body::Initial, ); - let mut body = builder.statement_or_null(&initial.nodes.1)?; + let mut body = match (statement, &module_item.nodes.1) { + (Some(statement), _) => builder.statement_or_null(statement)?, + (None, sv_parser::ModuleCommonItem::AlwaysConstruct(always)) => { + // `always statement` repeats the statement forever. + vec![Stmt::Loop { + kind: LoopKind::Forever, + init: Vec::new(), + condition: None, + step: Vec::new(), + body: builder.statement(&always.nodes.1)?, + }] + } + _ => unreachable!("only initial and always constructs are collected"), + }; for stmt in &mut body { substitute_stmt_constants(stmt, &item.env, literals); qualify_stmt(item, stmt); @@ -2244,6 +2270,7 @@ pub(super) fn initial_processes_from_module_node( body, initializer: false, synthetic: false, + repeats, }); } initializers.extend(processes); diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index 0987ddfbabd..c3f0d248cae 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -306,6 +306,7 @@ impl ScopeSymbols { .collect(), initializer: process.initializer, synthetic: process.synthetic, + repeats: process.repeats, }) .collect(); self.signals.push(signal); @@ -505,6 +506,7 @@ impl ScopeSymbols { .collect(), initializer: process.initializer, synthetic: process.synthetic, + repeats: process.repeats, }) .collect(), aliases: HashMap::default(), diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index ef9e6402a03..a84144a3c27 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -38,12 +38,16 @@ pub(super) fn reject_unsupported_multidimensional_packed_bounds( pub(super) enum AlwaysKind { Comb, Ff, + /// A process that runs its statement forever, suspending at its timing + /// controls (IEEE 1800-2023 9.2.2.1). + Process, Unsupported, } /// `always_comb` and `always @*` are combinational; `always_ff` and an -/// `always` sensitive to clock edges are sequential. Other sensitivity lists -/// (incomplete level-sensitive lists, `always_latch`) are not supported. +/// `always` sensitive to clock edges are sequential, as long as their body +/// has no timing control of its own. Every other `always` is a process. +/// `always_latch` is not supported. pub(super) fn always_kind(always: &sv_parser::AlwaysConstruct) -> AlwaysKind { match always.nodes.0 { sv_parser::AlwaysKeyword::AlwaysComb(_) => AlwaysKind::Comb, @@ -53,11 +57,14 @@ pub(super) fn always_kind(always: &sv_parser::AlwaysConstruct) -> AlwaysKind { let sv_parser::StatementItem::ProceduralTimingControlStatement(timing) = &always.nodes.1.nodes.2 else { - return AlwaysKind::Unsupported; + return AlwaysKind::Process; }; let sv_parser::ProceduralTimingControl::EventControl(control) = &timing.nodes.0 else { - return AlwaysKind::Unsupported; + return AlwaysKind::Process; }; + if has_timing_control(RefNode::StatementOrNull(&timing.nodes.1)) { + return AlwaysKind::Process; + } match &**control { sv_parser::EventControl::Asterisk(_) | sv_parser::EventControl::ParenAsterisk(_) => AlwaysKind::Comb, @@ -68,12 +75,22 @@ pub(super) fn always_kind(always: &sv_parser::AlwaysConstruct) -> AlwaysKind { { AlwaysKind::Ff } - _ => AlwaysKind::Unsupported, + _ => AlwaysKind::Process, } } } } +/// Whether a statement contains a delay, an event control or a `wait`. +fn has_timing_control(node: RefNode<'_>) -> bool { + node.into_iter().any(|node| { + matches!( + node, + RefNode::ProceduralTimingControlStatement(_) | RefNode::WaitStatement(_) + ) + }) +} + /// The statement an combinational `always` evaluates, without its event control. pub(super) fn always_comb_body( always: &sv_parser::AlwaysConstruct, @@ -551,9 +568,7 @@ fn reject_silently_ignored_constructs_with_dimensions( } RefNode::AlwaysConstruct(always) => { if always_kind(always) == AlwaysKind::Unsupported { - return Err(AnalyzerError::Unsupported( - "always and always_latch processes".to_string(), - )); + return Err(AnalyzerError::Unsupported("always_latch process".to_string())); } let body = RefNode::Statement(&always.nodes.1); if always_kind(always) == AlwaysKind::Comb diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 2a6252fef15..dd619a5d65e 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -878,6 +878,8 @@ pub struct InitialProcess { body: Vec, initializer: bool, synthetic: bool, + /// An `always` process: its body runs forever. + repeats: bool, } impl InitialProcess { @@ -893,6 +895,7 @@ impl InitialProcess { body, initializer, synthetic: false, + repeats: false, } } @@ -907,6 +910,12 @@ impl InitialProcess { self.initializer } + /// Whether this is an `always` process, which runs its body forever and + /// never finishes on its own. + pub fn repeats(&self) -> bool { + self.repeats + } + /// The condition of the enclosing conditional generate block, if any. pub fn condition(&self) -> Option<&ConstExpr> { self.condition.as_ref() @@ -1245,6 +1254,7 @@ impl From for InitialProcess { ); result.creation_order = process.creation_order(); result.synthetic = process.is_synthetic(); + result.repeats = process.repeats(); result } } diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 23613967ae5..3fb274eef0b 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -44,6 +44,14 @@ pub enum AnalyzerError { Parse(String), #[error("Unsupported SystemVerilog construct: {0}")] Unsupported(String), + /// A delay, event control or wait statement in a function, an + /// `always_comb` or an `always_ff` body (IEEE 1800-2023 9.2.2.2, + /// 9.2.2.4, 13.4). + #[error("{construct} in {context}: only `initial` and `always` processes may suspend")] + TimingControlOutsideProcess { + construct: &'static str, + context: &'static str, + }, /// A memory file read by `$readmemh` or `$readmemb` is missing or invalid. #[error("Invalid memory file input: {0}")] MemoryFile(String), @@ -130,7 +138,7 @@ pub const SV_FRONTEND_TRACKING_ISSUE: u32 = 88; const UNSUPPORTED_CONSTRUCT_ISSUES: &[(&str, u32)] = &[ ("non-ANSI module port declarations", 426), ("ref port direction", 427), - ("always and always_latch processes", 431), + ("always_latch process", 431), ("non-zero-based multidimensional packed range", 438), ( "unpacked struct, union, or unsupported packed struct member", diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 468d13d2ecb..d9fd95686a2 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -3514,10 +3514,7 @@ fn rejects_unimplemented_timing_constructs() { "logic a; initial @* a = 1;", "`@*` event control in a process", ), - ( - "logic clk; always @(posedge clk) #1;", - "always and always_latch processes", - ), + ("logic a, y; always_latch y = a;", "always_latch process"), ( "task automatic t; #1; endtask", "delay control in a subroutine", @@ -3537,6 +3534,49 @@ fn rejects_unimplemented_timing_constructs() { ); } +/// `always_comb` and `always_ff` bodies may not suspend (IEEE 1800-2023 +/// 9.2.2.2, 9.2.2.4). +#[test] +fn rejects_timing_controls_in_always_comb_and_always_ff() { + for body in [ + "logic a; always_comb begin #1 a = 1; end", + "logic clk, a; always_ff @(posedge clk) begin @(a); end", + "logic clk, a; always_ff @(posedge clk) wait (a);", + ] { + let code = format!("module Top; {body} endmodule"); + let error = analyze_source(&code, Path::new("timing.sv")) + .expect_err(&format!("`{body}` must be rejected")); + assert!( + matches!(error, AnalyzerError::TimingControlOutsideProcess { .. }), + "`{body}`: {error:?}" + ); + } +} + +/// An `always` that is neither combinational nor edge-triggered RTL is a +/// process that repeats its statement. +#[test] +fn analyzes_always_processes() { + for body in [ + "logic clk; always #5 clk = ~clk;", + "logic a, b, y; always @(a or b) y = a & b;", + "logic clk, q; always @(posedge clk) begin #1 q = ~q; end", + "logic x; always x = ~x;", + ] { + let code = format!("module Top; {body} endmodule"); + let ir = analyze_source(&code, Path::new("process.sv")) + .unwrap_or_else(|error| panic!("`{body}`: {error}")); + let module = &ir.modules()[0]; + assert!( + module + .initial_processes() + .iter() + .any(|process| process.repeats()), + "`{body}` must be an always process" + ); + } +} + /// Delays, event controls and waits in an `initial` block keep their /// statement structure in the IR. #[test] diff --git a/crates/celox/src/simulation/runtime_core_tests.rs b/crates/celox/src/simulation/runtime_core_tests.rs index 6f94deab6e2..34ae5750e20 100644 --- a/crates/celox/src/simulation/runtime_core_tests.rs +++ b/crates/celox/src/simulation/runtime_core_tests.rs @@ -2270,6 +2270,29 @@ fn executor_call_traces_of_veryl_clock_domains_are_unchanged() { mod sv_traces { use super::*; + /// An `always` without a timing control repeats its statement forever at + /// time zero: the slot budget ends the step with an error instead of + /// hanging. + #[test] + fn an_always_without_timing_exhausts_the_slot_budget() { + let source = "module Top(output logic x); always x = ~x; endmodule"; + let mut sim = + Simulation::from_sv_sources(vec![(source, std::path::Path::new("spin.sv"))], "Top") + .build() + .unwrap(); + sim.state.set_slot_budgets(256, 2); + let error = sim.run_until(0).unwrap_err(); + assert!( + matches!( + &error, + crate::RuntimeErrorCode::Runtime { message, .. } + if message.contains("does not suspend") + ), + "{error}" + ); + assert_eq!(sim.time(), 0); + } + /// Clock and reset aliases, a combinationally gated clock, a register /// divided clock, both edges of one clock, and the timing suite's cases /// that Celox runs. diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 437920ea798..b6e5dfe0c0c 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -5406,7 +5406,7 @@ fn rejects_constructs_that_are_not_yet_lowered() { "#, ), ( - "always and always_latch processes", + "always_latch process", r#" module Top(input logic a, output logic y); always_latch y = a; endmodule "#, diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 27dfb7c846c..c328084f97b 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -50,22 +50,17 @@ macro_rules! timed_cases { timed_cases! { fn delays_resume_initial_blocks_at_later_times = "timing::delays_resume_initial_blocks_at_later_times"; - #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn always_with_a_delay_generates_a_clock = "timing::always_with_a_delay_generates_a_clock"; - #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn edge_waits_resume_before_the_registers_of_that_edge_update = "timing::edge_waits_resume_before_the_registers_of_that_edge_update"; fn any_change_waits_wake_on_every_value_change = "timing::any_change_waits_wake_on_every_value_change"; fn wait_statements_block_until_their_condition_holds = "timing::wait_statements_block_until_their_condition_holds"; - #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn level_sensitive_always_runs_as_a_process = "timing::level_sensitive_always_runs_as_a_process"; fn processes_wake_each_other_at_the_same_time = "timing::processes_wake_each_other_at_the_same_time"; - #[ignore = "the SV analyzer rejects plain always processes (#431)"] + #[ignore = "the SV frontend does not lower tasks with timing controls yet (#1123)"] fn tasks_with_timing_controls_run_in_processes = "timing::tasks_with_timing_controls_run_in_processes"; fn edge_waits_see_the_signals_the_script_drives = "timing::edge_waits_see_the_signals_the_script_drives"; - #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn finish_in_an_always_process_ends_the_simulation = "timing::finish_in_an_always_process_ends_the_simulation"; fn waiting_processes_do_not_keep_an_idle_simulation_running = "timing::waiting_processes_do_not_keep_an_idle_simulation_running"; - #[ignore = "flip-flop domains miss edges to and from z on a four-state clock (#1472)"] fn four_state_edges_count_transitions_through_unknown = "timing::four_state_edges_count_transitions_through_unknown"; fn unknown_delays_and_conditions_count_as_zero_and_false = "timing::unknown_delays_and_conditions_count_as_zero_and_false"; fn direct_reads_settle_waiting_processes = "timing::direct_reads_settle_waiting_processes"; @@ -73,17 +68,16 @@ timed_cases! { fn run_until_drains_target_time_before_later_writes = "timing::run_until_drains_target_time_before_later_writes"; fn repeated_settles_do_not_advance_design_time = "timing::repeated_settles_do_not_advance_design_time"; fn run_to_finish_has_no_simulated_time_deadline = "timing::run_to_finish_has_no_simulated_time_deadline"; - #[ignore = "blocking stores of an edge-triggered always are not visible before the inactive region (#1123)"] + #[ignore = "blocking stores of an edge-triggered always are committed with its nonblocking ones, not in the active region (#1470)"] fn blocking_ff_stores_are_visible_before_inactive_work = "timing::blocking_ff_stores_are_visible_before_inactive_work"; fn nonblocking_ff_stores_remain_pending_during_inactive_work = "timing::nonblocking_ff_stores_remain_pending_during_inactive_work"; - #[ignore = "blocking stores of an edge-triggered always are not visible before the inactive region (#1123)"] + #[ignore = "blocking stores of an edge-triggered always are committed with its nonblocking ones, not in the active region (#1470)"] fn mixed_ff_stores_keep_their_active_and_nba_values = "timing::mixed_ff_stores_keep_their_active_and_nba_values"; fn printed_finish_notice_is_design_output = "timing::printed_finish_notice_is_design_output"; fn combinational_finish_ends_timed_execution = "timing::combinational_finish_ends_timed_execution"; fn inactive_time_directives_do_not_change_scheduler_units = "timing::inactive_time_directives_do_not_change_scheduler_units"; #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn blocking_concatenation_publishes_one_event_update = "timing::blocking_concatenation_publishes_one_event_update"; - #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn finite_active_feedback_preserves_convergence = "timing::finite_active_feedback_preserves_convergence"; #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn pure_function_rhs_preserves_distinct_write_times = "timing::pure_function_rhs_preserves_distinct_write_times"; @@ -114,7 +108,7 @@ timed_cases! { fn repeated_active_edges_share_one_nba_batch = "timing::repeated_active_edges_share_one_nba_batch"; #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn false_wait_preserves_separate_hierarchical_write_times = "timing::false_wait_preserves_separate_hierarchical_write_times"; - #[ignore = "the SV analyzer rejects plain always processes (#431)"] + #[ignore = "the SV frontend does not lower tasks with timing controls yet (#1123)"] fn always_timed_task_without_inline_timing_executes = "timing::always_timed_task_without_inline_timing_executes"; fn constant_comb_if_discards_unreachable_pulse_branch = "timing::constant_comb_if_discards_unreachable_pulse_branch"; fn constant_child_ff_case_discards_unreachable_pulse_arm = "timing::constant_child_ff_case_discards_unreachable_pulse_arm"; diff --git a/scripts/ci-changes.mjs b/scripts/ci-changes.mjs index 4650415c6c6..ce67976f144 100644 --- a/scripts/ci-changes.mjs +++ b/scripts/ci-changes.mjs @@ -314,20 +314,30 @@ export function celoxRustTestScope(files, packages) { // Queue drafts, merge groups, releases and daily runs keep the Celox // workspace. Lydite tests run independently in lydite-checks.yml. -function rustScopeOutputs(files) { +export function rustScopeOutputs(files) { let scope = { full: true }; + let checks; if (files !== null) { try { const root = fileURLToPath(new URL("../", import.meta.url)); - scope = celoxRustTestScope(files, readWorkspace(root)); + const packages = readWorkspace(root); + scope = celoxRustTestScope(files, packages); + // Lydite owns its tests, but lint and API documentation still live here. + checks = rustTestScope(files, packages); } catch (error) { console.warn(`Unable to scope the Rust tests: ${error.message}`); } } - if (scope.full) { + if (scope.full || !checks || checks.full) { return { rust_full: true, rust_packages: "", + rust_targets: "", + rust_lint_packages: "", + rust_lint_features: "", + rust_lint_targets: "", + rust_doc_libraries: "", + rust_sv_tests: true, rust_features: "", rust_filter: "", rust_libraries: "", @@ -337,6 +347,14 @@ function rustScopeOutputs(files) { return { rust_full: false, rust_packages: scope.packages.join(" "), + rust_targets: scope.targets.join(" "), + rust_lint_packages: checks.packages.join(" "), + rust_lint_features: checks.features.join(","), + rust_lint_targets: checks.targets.join(" "), + rust_doc_libraries: checks.libraries.join(" "), + // Test-only and consumer changes cannot change sv-tests results. + rust_sv_tests: scope.libraries.includes("celox") || files.some((path) => + /^(?:\.\/)?(?:conformance\/sv-tests\/|crates\/celox\/examples\/sv_tests\.rs$)/.test(path)), rust_features: scope.features.join(","), rust_filter: scope.filter, rust_libraries: scope.libraries.join(" "), diff --git a/scripts/ci-changes.test.mjs b/scripts/ci-changes.test.mjs index 361bcbc0cf4..0465ae5211e 100644 --- a/scripts/ci-changes.test.mjs +++ b/scripts/ci-changes.test.mjs @@ -12,6 +12,7 @@ import { classifyFiles, cutsRelease, isReleaseMergeGroup, + rustScopeOutputs, } from "./ci-changes.mjs"; const none = { @@ -147,6 +148,12 @@ test("full validation overrides even an empty valid diff", () => { // The whole Rust workspace, with no package scope or filter. rust_full: true, rust_packages: false, + rust_targets: false, + rust_lint_packages: false, + rust_lint_features: false, + rust_lint_targets: false, + rust_doc_libraries: false, + rust_sv_tests: true, rust_features: false, rust_filter: false, rust_libraries: false, @@ -534,3 +541,48 @@ test("PR branches behind their base ignore unmerged base changes", (t) => { { ...none, docs: true, heliodor_arm64: false, release: false }, ); }); + + +test("test and consumer PRs skip sv-tests; implementation and full runs retain it", () => { + for (const path of [ + "crates/celox/tests/flip_flop.rs", + "crates/celox/tests/test_utils/mod.rs", + "crates/celox/tests/snapshots/flip_flop__optimized.snap", + "crates/celox-test-suite/src/lib.rs", + "crates/celox-vpi/src/lib.rs", + "crates/celox-napi/src/lib.rs", + "crates/lydite/src/lib.rs", + ]) { + assert.equal(rustScopeOutputs([path]).rust_sv_tests, false, path); + } + for (const files of [ + null, + ["Cargo.lock"], + ["conformance/sv-tests/expected.tsv"], + ["crates/celox/examples/sv_tests.rs"], + ["crates/celox/src/lib.rs"], + ["crates/celox-frontend-sv/src/lib.rs"], + ["crates/celox-runtime/src/lib.rs"], + ["crates/celox-backend-x86/src/lib.rs"], + ["crates/celox/tests/flip_flop.rs", "crates/celox/src/lib.rs"], + ]) { + assert.equal(rustScopeOutputs(files).rust_sv_tests, true, JSON.stringify(files)); + } + const testOnly = rustScopeOutputs(["crates/celox/tests/flip_flop.rs"]); + assert.equal(testOnly.rust_targets, "flip_flop"); + assert.equal(testOnly.rust_libraries, ""); + assert.equal(rustScopeOutputs(null).rust_full, true); +}); + + +test("Lydite lint and API documentation remain selected in CI", () => { + const scope = rustScopeOutputs(["crates/lydite-ir/src/lib.rs"]); + assert.equal(scope.rust_packages, ""); + assert.ok(scope.rust_lint_packages.split(" ").includes("lydite-ir")); + assert.ok(scope.rust_doc_libraries.split(" ").includes("lydite-ir")); + const mixed = rustScopeOutputs([ + "crates/celox/tests/flip_flop.rs", "crates/lydite-ir/src/lib.rs", + ]); + assert.equal(mixed.rust_targets, "flip_flop"); + assert.equal(mixed.rust_lint_targets, ""); +}); diff --git a/scripts/ci-rust-scope.mjs b/scripts/ci-rust-scope.mjs index 75a18ea9ed0..da536e14d16 100644 --- a/scripts/ci-rust-scope.mjs +++ b/scripts/ci-rust-scope.mjs @@ -95,8 +95,12 @@ export function rustTestScope(files, packages) { const byName = new Map(packages.map((pkg) => [pkg.name, pkg])); const owners = [...packages].sort((a, b) => b.dir.length - a.dir.length); const dependents = new Map(packages.map((pkg) => [pkg.name, new Set()])); + const libraryDependents = new Map(packages.map((pkg) => [pkg.name, new Set()])); for (const pkg of packages) { for (const dep of pkg.dependencies) dependents.get(dep)?.add(pkg.name); + for (const dep of pkg.libraryDependencies ?? pkg.dependencies) { + libraryDependents.get(dep)?.add(pkg.name); + } } const sources = new Set(); @@ -110,6 +114,7 @@ export function rustTestScope(files, packages) { for (const raw of files) { const path = raw.replace(/^\.\//, ""); if (!classifyFiles([path]).rust) continue; + if (/(?:^|\/)Cargo\.(?:toml|lock)$/.test(path)) return { full: true }; // lydite's tests read its examples and audits from the top-level folder. if (path.startsWith("lydite/")) { for (const pkg of packages) { @@ -121,8 +126,12 @@ export function rustTestScope(files, packages) { if (!owner) return { full: true }; const inner = path.slice(owner.dir.length + 1); const test = /^tests\/([^/]+)\.rs$/.exec(inner); + // Insta prefixes snapshots with their integration-test binary name. + const snapshot = /^tests\/snapshots\/([^/]+?)__[^/]+\.snap(?:\.new)?$/.exec(inner); if (test && owner.tests.includes(test[1])) { addBinary(owner.name, test[1]); + } else if (snapshot && owner.tests.includes(snapshot[1])) { + addBinary(owner.name, snapshot[1]); } else if ( owner.name === "celox" && inner.startsWith("tests/frontends/systemverilog/") @@ -136,6 +145,19 @@ export function rustTestScope(files, packages) { } // Everything each changed library reaches through its dependents. + const libraries = new Set(); + for (const seed of sources) { + const queue = [seed]; + libraries.add(seed); + while (queue.length > 0) { + for (const next of libraryDependents.get(queue.pop()) ?? []) { + if (!libraries.has(next)) { + libraries.add(next); + queue.push(next); + } + } + } + } const affected = new Set(); const celoxSeeds = []; for (const seed of sources) { @@ -201,8 +223,13 @@ export function rustTestScope(files, packages) { packages: [...selected].sort(), features: features(selected), filter: terms.join(" | "), - libraries: [...affected].sort(), - libraryFeatures: features(affected), + // A nextest filter controls execution, not Cargo compilation. When only + // specific binaries of one package changed, avoid building all its tests. + targets: affected.size === 0 && wholeTests.size === 0 && selected.size === 1 + ? [...binaries.get([...selected][0])].sort() + : [], + libraries: [...libraries].sort(), + libraryFeatures: features(libraries), }; } diff --git a/scripts/ci-rust-scope.test.mjs b/scripts/ci-rust-scope.test.mjs index b3021e961ed..4ae5a960427 100644 --- a/scripts/ci-rust-scope.test.mjs +++ b/scripts/ci-rust-scope.test.mjs @@ -94,6 +94,7 @@ test("a test file change runs only that binary and nothing downstream", () => { packages: ["celox"], features: ["celox/systemverilog"], filter: "binary_id(celox::flip_flop)", + targets: ["flip_flop"], libraries: [], libraryFeatures: [], }); @@ -127,6 +128,8 @@ test("lydite's shared folder runs every lydite package", () => { test("changes outside the workspace graph run every test", () => { for (const path of [ "Cargo.lock", + "crates/celox/Cargo.toml", + "crates/celox/tests/fixtures/custom/Cargo.lock", "Cargo.toml", "testdata/verilator/adder.sv", "rust-toolchain.toml", @@ -181,3 +184,39 @@ test("variant crates reach celox only through crates of the same variant", () => } } }); + + +test("test-only changes narrow Cargo compilation as well as nextest execution", () => { + const scope = rustTestScope([ + "crates/celox/tests/flip_flop.rs", + "crates/celox/tests/snapshots/flip_flop__optimized.snap", + "crates/celox/tests/frontends/systemverilog/operators.rs", + ], workspace); + assert.deepEqual(scope.targets, ["flip_flop", "systemverilog"]); + assert.deepEqual(scope.libraries, []); + assert.deepEqual(rustTestScope([ + "crates/celox/tests/flip_flop.rs", "crates/lib/src/lib.rs", + ], workspace).targets, []); + assert.deepEqual(rustTestScope([ + "crates/celox/tests/flip_flop.rs", "crates/consumer/tests/e2e.rs", + ], workspace).targets, []); + for (const path of [ + "crates/celox/tests/test_utils/mod.rs", + "crates/celox/tests/snapshots/unknown__result.snap", + "crates/celox/tests/fixtures/design.veryl", + ]) { + const shared = rustTestScope([path], workspace); + assert.deepEqual(shared.targets, [], path); + assert.equal(shared.filter, "package(celox)", path); + } +}); + +test("a dev dependency affects consumer tests but not consumer documentation", () => { + const packages = workspace.map((pkg) => ({ + ...pkg, + libraryDependencies: pkg.dependencies.filter((name) => name !== "lib"), + })); + const scope = rustTestScope(["crates/lib/src/lib.rs"], packages); + assert.ok(scope.packages.includes("celox")); + assert.deepEqual(scope.libraries, ["lib"]); +}); diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index 8d59674717b..bdc36d94395 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -37,6 +37,7 @@ test("the required gate rejects failures and only accepts explicitly optional sk CHANGES_RESULT: "success", RUST_REQUIRED: "true", RUST_RESULT: "success", + SV_TESTS_REQUIRED: "true", SV_TESTS_RESULT: "success", ARM64_REQUIRED: "true", ARM64_RESULT: "success", @@ -57,6 +58,7 @@ test("the required gate rejects failures and only accepts explicitly optional sk ...success, RUST_REQUIRED: "false", RUST_RESULT: "skipped", + SV_TESTS_REQUIRED: "false", SV_TESTS_RESULT: "skipped", }, passes: true, @@ -86,6 +88,19 @@ test("the required gate rejects failures and only accepts explicitly optional sk passes: false, }); } + // A scoped Rust PR may skip conformance only when explicitly unneeded. + for (const status of ["success", "skipped", "failure", "cancelled", ""]) { + cases.push({ + env: { ...success, SV_TESTS_REQUIRED: "false", SV_TESTS_RESULT: status }, + passes: status === "success" || status === "skipped", + }); + } + cases.push({ + env: { ...success, SV_TESTS_REQUIRED: "", SV_TESTS_RESULT: "skipped" }, + passes: false, + }); + assert.match(gate, /SV_TESTS_REQUIRED: .*outputs\.rust != 'false' && needs\.changes\.outputs\.rust_sv_tests != 'false'/); + assert.match(job("sv-tests"), /outputs\.rust == 'true' && needs\.changes\.outputs\.rust_sv_tests != 'false'/); // Only non-Rust changes may skip ARM64; other results fail closed. for (const status of ["success", "skipped", "failure", "cancelled", ""]) { cases.push({ @@ -373,3 +388,50 @@ test("cache warming shares the Rust Tests key and builds without running tests", const nextest = job("rust-tests").match(/tool: (cargo-nextest@\S+)/)[1]; assert.ok(warm.includes(`tool: ${nextest}`)); }); + +// Execute the workflow's actual shell with a recording Cargo function, so a +// correct classifier cannot accidentally turn into an unscoped Cargo build. +function cargoArguments(jobName, stepName, env) { + const step = job(jobName).split(` - name: ${stepName}\n`)[1]; + assert.ok(step, stepName); + const script = step.match(/ run: \|\n((?: [^\n]*\n|\n)*)/)[1]; + const result = spawnSync("bash", ["-e", "-c", `cargo() { printf '\\036%s' "$@"; };\n${script}`], { + env: { ...process.env, ...env }, encoding: "utf8", + }); + assert.ifError(result.error); + assert.equal(result.status, 0, result.stderr); + return result.stdout.split("\x1e").slice(1); +} + +test("scoped Cargo commands build only the selected integration targets", () => { + const env = { + PACKAGES: "celox", FEATURES: "celox/systemverilog", + TARGETS: "flip_flop systemverilog", FILTER: "binary_id(celox::flip_flop) | binary_id(celox::systemverilog)", + }; + assert.deepEqual(cargoArguments("rust-tests", "Run the tests this pull request can affect", env), [ + "nextest", "run", "--locked", "--profile", "ci", "--no-tests=pass", + "-p", "celox", "--features", "celox/systemverilog", + "--test", "flip_flop", "--test", "systemverilog", "-E", env.FILTER, + ]); + assert.deepEqual(cargoArguments("lint", "Lint the crates this pull request can affect", env), [ + "clippy", "--locked", "-p", "celox", "--features", "celox/systemverilog", + "--test", "flip_flop", "--test", "systemverilog", "--no-deps", + ]); + assert.deepEqual(cargoArguments("lint", "Lint the crates this pull request can affect", { + PACKAGES: "celox-runtime celox", FEATURES: "", TARGETS: "", + }), ["clippy", "--locked", "-p", "celox-runtime", "-p", "celox", "--all-targets", "--no-deps"]); + assert.deepEqual(cargoArguments("lint", "Build the API documentation this pull request can affect", { + LIBRARIES: "celox-runtime celox", + }), ["doc", "--locked", "--no-deps", "-p", "celox-runtime", "-p", "celox"]); +}); + +test("scoped checks preserve full-run fallbacks and use their own package scopes", () => { + const lint = job("lint"); + assert.match(lint, /name: cargo clippy\n if: .*outputs\.rust_full != 'false'/); + assert.match(lint, /name: Build Rust API documentation\n if: .*outputs\.rust_full != 'false'/); + assert.match(lint, /name: Lint the crates this pull request can affect\n if: .*outputs\.rust_lint_packages != ''/); + assert.match(lint, /PACKAGES: \$\{\{ needs\.changes\.outputs\.rust_lint_packages \}\}/); + assert.match(lint, /FEATURES: \$\{\{ needs\.changes\.outputs\.rust_lint_features \}\}/); + assert.match(lint, /TARGETS: \$\{\{ needs\.changes\.outputs\.rust_lint_targets \}\}/); + assert.match(lint, /name: Build the API documentation this pull request can affect\n if: .*outputs\.rust_doc_libraries != ''/); +});