xlsynth-driver 0.42.0

Binary that integrates XLS capabilities into a driver program
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
// SPDX-License-Identifier: Apache-2.0

//! Prover configuration helpers.
//!
//! This module defines configuration structs for invoking xlsynth-driver
//! subcommands programmatically. Each configuration translates to a complete
//! command line for the driver, suitable for running in parallel processes.
//!
//! JSON DSL overview
//! - A single task is an object with a `kind` discriminator (`ir-equiv`,
//!   `dslx-equiv`, `prove-quickcheck`, `dslx-fn-prove-assertions`).
//! - Tasks can be composed into groups with `kind` = `all` | `any` | `first`
//!   and a `tasks` array.
//!
//! Example (single task):
//!
//! ```json
//! { "kind": "ir-equiv", "lhs_ir_file": "lhs.ir", "rhs_ir_file": "rhs.ir", "top": "main" }
//! ```
//!
//! See the driver README section "Prover configuration JSON (task-spec DSL)"
//! for the full schema and examples.

use std::path::PathBuf;
use std::process::Command;

use serde::{Deserialize, Serialize};
use xlsynth_prover::prover::types::AssertionSemantics;
use xlsynth_prover::prover::types::EquivParallelism;
use xlsynth_prover::prover::types::QuickCheckAssertionSemantics;
use xlsynth_prover::prover::SolverChoice;

fn add_flag(cmd: &mut Command, name: &str, value: &str) {
    cmd.arg(format!("--{}", name)).arg(value);
}

fn add_bool(cmd: &mut Command, name: &str, value: Option<bool>) {
    if let Some(v) = value {
        add_flag(cmd, name, if v { "true" } else { "false" });
    }
}

fn resolve_driver_exe() -> std::path::PathBuf {
    if let Ok(p) = std::env::var("CARGO_BIN_EXE_xlsynth-driver") {
        return std::path::PathBuf::from(p);
    }
    let cur = std::env::current_exe().expect("resolve current exe");
    if let Some(deps_dir) = cur.parent() {
        if let Some(debug_dir) = deps_dir.parent() {
            let candidate = debug_dir.join("xlsynth-driver");
            if candidate.exists() {
                return candidate;
            }
        }
    }
    cur
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct IrEquivConfig {
    pub lhs_ir_file: PathBuf,
    pub rhs_ir_file: PathBuf,
    /// --top if both sides have same name, otherwise use lhs_ir_top/rhs_ir_top
    pub top: Option<String>,
    pub lhs_ir_top: Option<String>,
    pub rhs_ir_top: Option<String>,

    pub solver: Option<SolverChoice>,
    pub flatten_aggregates: Option<bool>,
    pub drop_params: Option<Vec<String>>, // comma joined
    pub parallelism_strategy: Option<EquivParallelism>,
    pub assertion_semantics: Option<AssertionSemantics>,
    pub lhs_fixed_implicit_activation: Option<bool>,
    pub rhs_fixed_implicit_activation: Option<bool>,
    /// Include only assertions whose label matches this regex.
    pub assert_label_filter: Option<String>,

    pub json: Option<bool>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct DslxEquivConfig {
    pub lhs_dslx_file: PathBuf,
    pub rhs_dslx_file: PathBuf,

    /// Either set `dslx_top` or both `lhs_dslx_top` and `rhs_dslx_top`.
    pub dslx_top: Option<String>,
    pub lhs_dslx_top: Option<String>,
    pub rhs_dslx_top: Option<String>,

    // Optional search paths
    pub dslx_path: Option<Vec<PathBuf>>, // joined with ';'
    pub dslx_stdlib_path: Option<PathBuf>,

    // Behavior flags
    pub solver: Option<SolverChoice>,
    pub flatten_aggregates: Option<bool>,
    pub drop_params: Option<Vec<String>>, // comma joined
    pub parallelism_strategy: Option<EquivParallelism>,
    pub assertion_semantics: Option<AssertionSemantics>,
    pub lhs_fixed_implicit_activation: Option<bool>,
    pub rhs_fixed_implicit_activation: Option<bool>,
    pub assume_enum_in_bound: Option<bool>,
    pub type_inference_v2: Option<bool>, // external toolchain only
    /// Include only assertions whose label matches this regex.
    pub assert_label_filter: Option<String>,

    /// Treat DSLX function on the LHS/RHS as uninterpreted function (repeated).
    /// Each entry is "func_name:uf_name".
    pub lhs_uf: Option<Vec<String>>, // each entry is "func_name:uf_name"
    pub rhs_uf: Option<Vec<String>>, // each entry is "func_name:uf_name"

    pub json: Option<bool>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct ProveQuickcheckConfig {
    pub dslx_input_file: PathBuf,
    pub dslx_path: Option<Vec<PathBuf>>,
    pub dslx_stdlib_path: Option<PathBuf>,
    pub test_filter: Option<String>,
    pub solver: Option<SolverChoice>,
    pub assertion_semantics: Option<QuickCheckAssertionSemantics>,
    /// Treat DSLX function as uninterpreted function (repeated), entries
    /// "func_name:uf_name".
    pub uf: Option<Vec<String>>,
    /// Include only assertions whose label matches this regex.
    pub assert_label_filter: Option<String>,
    pub json: Option<bool>,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct DslxFnProveAssertionsConfig {
    pub dslx_input_file: PathBuf,
    pub dslx_top: String,
    pub dslx_path: Option<Vec<PathBuf>>,
    pub dslx_stdlib_path: Option<PathBuf>,
    pub solver: Option<SolverChoice>,
    /// Include only assertions whose label matches this regex.
    pub assert_label_filter: Option<String>,
    pub assume_enum_in_bound: Option<bool>,
    /// Treat DSLX function as uninterpreted function (repeated), entries
    /// "func_name:uf_name".
    pub uf: Option<Vec<String>>,
}

pub trait ToDriverCommand {
    fn to_command(&self) -> Command;
}

impl ToDriverCommand for IrEquivConfig {
    fn to_command(&self) -> Command {
        let exe = resolve_driver_exe();
        let mut cmd = Command::new(exe);
        cmd.arg("ir-equiv");
        cmd.arg(self.lhs_ir_file.as_os_str());
        cmd.arg(self.rhs_ir_file.as_os_str());
        if let Some(top) = &self.top {
            add_flag(&mut cmd, "top", top);
        }
        if let Some(lhs_top) = &self.lhs_ir_top {
            add_flag(&mut cmd, "lhs_ir_top", lhs_top);
        }
        if let Some(rhs_top) = &self.rhs_ir_top {
            add_flag(&mut cmd, "rhs_ir_top", rhs_top);
        }
        if let Some(solver) = &self.solver {
            add_flag(&mut cmd, "solver", &solver.to_string());
        }
        add_bool(&mut cmd, "flatten_aggregates", self.flatten_aggregates);
        if let Some(drop) = &self.drop_params {
            if !drop.is_empty() {
                add_flag(&mut cmd, "drop_params", &drop.join(","));
            }
        }
        if let Some(strategy) = &self.parallelism_strategy {
            add_flag(&mut cmd, "parallelism-strategy", &strategy.to_string());
        }
        if let Some(sem) = &self.assertion_semantics {
            add_flag(&mut cmd, "assertion-semantics", &sem.to_string());
        }
        if let Some(pat) = &self.assert_label_filter {
            add_flag(&mut cmd, "assert-label-filter", pat);
        }
        add_bool(
            &mut cmd,
            "lhs_fixed_implicit_activation",
            self.lhs_fixed_implicit_activation,
        );
        add_bool(
            &mut cmd,
            "rhs_fixed_implicit_activation",
            self.rhs_fixed_implicit_activation,
        );
        add_bool(&mut cmd, "json", self.json);
        cmd
    }
}

impl ToDriverCommand for DslxEquivConfig {
    fn to_command(&self) -> Command {
        let exe = resolve_driver_exe();
        let mut cmd = Command::new(exe);
        cmd.arg("dslx-equiv");
        cmd.arg(self.lhs_dslx_file.as_os_str());
        cmd.arg(self.rhs_dslx_file.as_os_str());

        if let Some(top) = &self.dslx_top {
            add_flag(&mut cmd, "dslx_top", top);
        }
        if let Some(lhs_top) = &self.lhs_dslx_top {
            add_flag(&mut cmd, "lhs_dslx_top", lhs_top);
        }
        if let Some(rhs_top) = &self.rhs_dslx_top {
            add_flag(&mut cmd, "rhs_dslx_top", rhs_top);
        }
        if let Some(stdlib) = &self.dslx_stdlib_path {
            add_flag(&mut cmd, "dslx_stdlib_path", &stdlib.display().to_string());
        }
        if let Some(paths) = &self.dslx_path {
            if !paths.is_empty() {
                let joined = paths
                    .iter()
                    .map(|p| p.display().to_string())
                    .collect::<Vec<_>>()
                    .join(";");
                add_flag(&mut cmd, "dslx_path", &joined);
            }
        }

        if let Some(solver) = &self.solver {
            add_flag(&mut cmd, "solver", &solver.to_string());
        }
        add_bool(&mut cmd, "flatten_aggregates", self.flatten_aggregates);
        if let Some(drop) = &self.drop_params {
            if !drop.is_empty() {
                add_flag(&mut cmd, "drop_params", &drop.join(","));
            }
        }
        if let Some(strategy) = &self.parallelism_strategy {
            add_flag(&mut cmd, "parallelism-strategy", &strategy.to_string());
        }
        if let Some(sem) = &self.assertion_semantics {
            add_flag(&mut cmd, "assertion-semantics", &sem.to_string());
        }
        if let Some(pat) = &self.assert_label_filter {
            add_flag(&mut cmd, "assert-label-filter", pat);
        }
        add_bool(
            &mut cmd,
            "lhs_fixed_implicit_activation",
            self.lhs_fixed_implicit_activation,
        );
        add_bool(
            &mut cmd,
            "rhs_fixed_implicit_activation",
            self.rhs_fixed_implicit_activation,
        );
        add_bool(&mut cmd, "assume-enum-in-bound", self.assume_enum_in_bound);
        add_bool(&mut cmd, "type_inference_v2", self.type_inference_v2);

        if let Some(list) = &self.lhs_uf {
            for entry in list {
                add_flag(&mut cmd, "lhs_uf", entry);
            }
        }
        if let Some(list) = &self.rhs_uf {
            for entry in list {
                add_flag(&mut cmd, "rhs_uf", entry);
            }
        }

        add_bool(&mut cmd, "json", self.json);
        cmd
    }
}

impl ToDriverCommand for ProveQuickcheckConfig {
    fn to_command(&self) -> Command {
        let exe = resolve_driver_exe();
        let mut cmd = Command::new(exe);
        cmd.arg("prove-quickcheck");
        add_flag(
            &mut cmd,
            "dslx_input_file",
            &self.dslx_input_file.display().to_string(),
        );
        if let Some(paths) = &self.dslx_path {
            if !paths.is_empty() {
                let joined = paths
                    .iter()
                    .map(|p| p.display().to_string())
                    .collect::<Vec<_>>()
                    .join(";");
                add_flag(&mut cmd, "dslx_path", &joined);
            }
        }
        if let Some(stdlib) = &self.dslx_stdlib_path {
            add_flag(&mut cmd, "dslx_stdlib_path", &stdlib.display().to_string());
        }
        if let Some(filter) = &self.test_filter {
            add_flag(&mut cmd, "test_filter", filter);
        }
        if let Some(solver) = &self.solver {
            add_flag(&mut cmd, "solver", &solver.to_string());
        }
        if let Some(sem) = &self.assertion_semantics {
            add_flag(&mut cmd, "assertion-semantics", &sem.to_string());
        }
        if let Some(list) = &self.uf {
            for entry in list {
                add_flag(&mut cmd, "uf", entry);
            }
        }
        if let Some(pat) = &self.assert_label_filter {
            add_flag(&mut cmd, "assert-label-filter", pat);
        }
        add_bool(&mut cmd, "json", self.json);
        cmd
    }
}

impl ToDriverCommand for DslxFnProveAssertionsConfig {
    fn to_command(&self) -> Command {
        let exe = resolve_driver_exe();
        let mut cmd = Command::new(exe);
        cmd.arg("dslx-fn-prove-assertions");
        add_flag(
            &mut cmd,
            "dslx_input_file",
            &self.dslx_input_file.display().to_string(),
        );
        add_flag(&mut cmd, "dslx_top", &self.dslx_top);
        if let Some(paths) = &self.dslx_path {
            if !paths.is_empty() {
                let joined = paths
                    .iter()
                    .map(|p| p.display().to_string())
                    .collect::<Vec<_>>()
                    .join(";");
                add_flag(&mut cmd, "dslx_path", &joined);
            }
        }
        if let Some(stdlib) = &self.dslx_stdlib_path {
            add_flag(&mut cmd, "dslx_stdlib_path", &stdlib.display().to_string());
        }
        if let Some(solver) = &self.solver {
            add_flag(&mut cmd, "solver", &solver.to_string());
        }
        if let Some(pat) = &self.assert_label_filter {
            add_flag(&mut cmd, "assert-label-filter", pat);
        }
        add_bool(&mut cmd, "assume-enum-in-bound", self.assume_enum_in_bound);
        if let Some(list) = &self.uf {
            for entry in list {
                add_flag(&mut cmd, "uf", entry);
            }
        }
        cmd
    }
}

// -------------------------------
// Fake task definition (available for fuzzing, tests, and local use)
// -------------------------------
#[cfg(feature = "enable-fake-task")]
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct FakeTaskConfig {
    /// Optional delay before the fake task reports a result.
    /// - When `Some(d)`, sleeps for `d` milliseconds then exits and writes
    ///   JSON.
    /// - When `None`, sleeps indefinitely and never finishes (until
    ///   canceled/timeout).
    pub delay_ms: Option<u32>,
    /// Whether the task should report success.
    pub success: bool,
    /// Number of bytes to write to stdout.
    pub stdout_len: u16,
    /// Number of bytes to write to stderr.
    pub stderr_len: u16,
}

#[cfg(feature = "enable-fake-task")]
impl ToDriverCommand for FakeTaskConfig {
    fn to_command(&self) -> Command {
        // Use a POSIX shell snippet to sleep and then locate the --output_json path
        // from argv.
        let script = r#"
delay_ms="${FAKE_DELAY_MS:-}"
# If delay_ms is empty, sleep indefinitely (never complete).
if [ -z "$delay_ms" ]; then
  # Sleep forever to simulate a non-terminating task; will be killed on timeout/cancel.
  tail -f /dev/null
fi
# Otherwise, sleep for the requested milliseconds.
secs=$(printf "%s" "$delay_ms" | awk '{ printf("%.3f", $1/1000.0) }')
sleep "$secs"
# Emit stdout noise
ol=${FAKE_STDOUT_LEN:-0}
if [ "$ol" -gt 0 ]; then head -c "$ol" < /dev/zero | tr '\0' 'X'; echo; fi
# Emit stderr noise
el=${FAKE_STDERR_LEN:-0}
if [ "$el" -gt 0 ]; then (head -c "$el" < /dev/zero | tr '\0' 'Y'; echo) >&2; fi
# Parse --output_json DEST from arguments
out=""
while [ $# -gt 0 ]; do
  if [ "$1" = "--output_json" ]; then
    shift
    out="$1"
    break
  fi
  shift
done
if [ -n "$out" ]; then
  if [ "${FAKE_SUCCESS:-1}" -eq 1 ]; then
    printf '{"success":true}\n' > "$out"
  else
    printf '{"success":false}\n' > "$out"
  fi
fi
"#;
        let mut cmd = Command::new("/bin/sh");
        cmd.arg("-c").arg(script).arg("sh");
        if let Some(ms) = self.delay_ms {
            cmd.env("FAKE_DELAY_MS", ms.to_string());
        }
        cmd.env("FAKE_SUCCESS", if self.success { "1" } else { "0" });
        cmd.env("FAKE_STDOUT_LEN", self.stdout_len.to_string());
        cmd.env("FAKE_STDERR_LEN", self.stderr_len.to_string());
        cmd
    }
}

// -----------------------------------------------------------------------------
// Unified enum for collections of prover tasks
// -----------------------------------------------------------------------------

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum ProverTask {
    #[serde(rename = "ir-equiv")]
    IrEquiv {
        #[serde(flatten)]
        config: IrEquivConfig,
    },
    #[serde(rename = "dslx-equiv")]
    DslxEquiv {
        #[serde(flatten)]
        config: DslxEquivConfig,
    },
    #[serde(rename = "prove-quickcheck")]
    ProveQuickcheck {
        #[serde(flatten)]
        config: ProveQuickcheckConfig,
    },
    #[serde(rename = "dslx-fn-prove-assertions")]
    DslxFnProveAssertions {
        #[serde(flatten)]
        config: DslxFnProveAssertionsConfig,
    },
    #[cfg(feature = "enable-fake-task")]
    #[serde(rename = "fake")]
    Fake {
        #[serde(flatten)]
        config: FakeTaskConfig,
    },
}

// No common fields on ProverTask variants; common per-task metadata lives on
// the ProverPlan::Task node for consolidation.

impl ToDriverCommand for ProverTask {
    fn to_command(&self) -> Command {
        match self {
            ProverTask::IrEquiv { config, .. } => config.to_command(),
            ProverTask::DslxEquiv { config, .. } => config.to_command(),
            ProverTask::ProveQuickcheck { config, .. } => config.to_command(),
            ProverTask::DslxFnProveAssertions { config, .. } => config.to_command(),
            #[cfg(feature = "enable-fake-task")]
            ProverTask::Fake { config, .. } => config.to_command(),
        }
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum GroupKind {
    All,
    Any,
    First,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ProverPlan {
    Task {
        #[serde(flatten)]
        task: ProverTask,
        /// Optional timeout for this task node.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        timeout_ms: Option<u64>,
        /// Optional user-provided identifier for tracking/reporting.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        task_id: Option<String>,
    },
    Group {
        kind: GroupKind,
        tasks: Vec<ProverPlan>,
        // When true, do not cancel or prune sibling tasks upon this group's
        // resolution; allow them to continue running until they naturally
        // complete. Default is false.
        #[serde(default)]
        keep_running_till_finish: bool,
    },
}

#[cfg(test)]
mod tests {
    use super::*;

    fn args_of(cmd: Command) -> Vec<String> {
        cmd.get_args()
            .map(|s| s.to_string_lossy().into_owned())
            .collect()
    }

    fn head_of(plan: &ProverPlan) -> String {
        match plan {
            ProverPlan::Task { task, .. } => args_of(task.to_command())[0].clone(),
            ProverPlan::Group { kind, .. } => match kind {
                GroupKind::All => "all".to_string(),
                GroupKind::Any => "any".to_string(),
                GroupKind::First => "first".to_string(),
            },
        }
    }

    #[test]
    fn test_ir_equiv_to_command_args() {
        let cfg = IrEquivConfig {
            lhs_ir_file: "lhs.ir".into(),
            rhs_ir_file: "rhs.ir".into(),
            top: Some("main".to_string()),
            solver: Some(SolverChoice::Toolchain),
            parallelism_strategy: Some(EquivParallelism::OutputBits),
            assertion_semantics: Some(AssertionSemantics::Same),
            flatten_aggregates: Some(true),
            drop_params: Some(vec!["p0".into(), "p1".into()]),
            json: Some(true),
            ..Default::default()
        };
        let got = args_of(cfg.to_command());
        assert_eq!(
            got,
            vec![
                "ir-equiv",
                "lhs.ir",
                "rhs.ir",
                "--top",
                "main",
                "--solver",
                "toolchain",
                "--flatten_aggregates",
                "true",
                "--drop_params",
                "p0,p1",
                "--parallelism-strategy",
                "output-bits",
                "--assertion-semantics",
                "same",
                "--json",
                "true",
            ]
        );
    }

    #[test]
    fn test_dslx_equiv_to_command_args() {
        let cfg = DslxEquivConfig {
            lhs_dslx_file: "lhs.x".into(),
            rhs_dslx_file: "rhs.x".into(),
            dslx_top: Some("foo".into()),
            dslx_path: Some(vec!["a".into(), "b".into()]),
            dslx_stdlib_path: Some("stdlib".into()),
            solver: Some(SolverChoice::Toolchain),
            assertion_semantics: Some(AssertionSemantics::Assume),
            parallelism_strategy: Some(EquivParallelism::SingleThreaded),
            flatten_aggregates: Some(false),
            lhs_fixed_implicit_activation: Some(true),
            rhs_fixed_implicit_activation: Some(false),
            assume_enum_in_bound: Some(true),
            json: Some(true),
            ..Default::default()
        };
        let got = args_of(cfg.to_command());
        assert_eq!(
            got,
            vec![
                "dslx-equiv",
                "lhs.x",
                "rhs.x",
                "--dslx_top",
                "foo",
                "--dslx_stdlib_path",
                "stdlib",
                "--dslx_path",
                "a;b",
                "--solver",
                "toolchain",
                "--flatten_aggregates",
                "false",
                "--parallelism-strategy",
                "single-threaded",
                "--assertion-semantics",
                "assume",
                "--lhs_fixed_implicit_activation",
                "true",
                "--rhs_fixed_implicit_activation",
                "false",
                "--assume-enum-in-bound",
                "true",
                "--json",
                "true",
            ]
        );
    }

    #[test]
    fn test_prove_quickcheck_to_command_args() {
        let cfg = ProveQuickcheckConfig {
            dslx_input_file: "qc.x".into(),
            dslx_path: Some(vec!["a".into(), "b".into()]),
            dslx_stdlib_path: Some("stdlib".into()),
            test_filter: Some(".*mytest".into()),
            solver: Some(SolverChoice::Toolchain),
            assertion_semantics: Some(QuickCheckAssertionSemantics::Assume),
            json: Some(true),
            ..Default::default()
        };
        let got = args_of(cfg.to_command());
        assert_eq!(
            got,
            vec![
                "prove-quickcheck",
                "--dslx_input_file",
                "qc.x",
                "--dslx_path",
                "a;b",
                "--dslx_stdlib_path",
                "stdlib",
                "--test_filter",
                ".*mytest",
                "--solver",
                "toolchain",
                "--assertion-semantics",
                "assume",
                "--json",
                "true",
            ]
        );
    }

    #[test]
    fn test_dslx_fn_prove_assertions_to_command_args() {
        let cfg = DslxFnProveAssertionsConfig {
            dslx_input_file: "assertions.x".into(),
            dslx_top: "main".into(),
            dslx_path: Some(vec!["a".into(), "b".into()]),
            dslx_stdlib_path: Some("stdlib".into()),
            solver: Some(SolverChoice::Auto),
            assert_label_filter: Some("red|blue".into()),
            assume_enum_in_bound: Some(false),
            uf: Some(vec!["helper:F".into()]),
        };
        let got = args_of(cfg.to_command());
        assert_eq!(
            got,
            vec![
                "dslx-fn-prove-assertions",
                "--dslx_input_file",
                "assertions.x",
                "--dslx_top",
                "main",
                "--dslx_path",
                "a;b",
                "--dslx_stdlib_path",
                "stdlib",
                "--solver",
                "auto",
                "--assert-label-filter",
                "red|blue",
                "--assume-enum-in-bound",
                "false",
                "--uf",
                "helper:F",
            ]
        );
    }

    #[test]
    fn test_serde_ir_equiv_parse() {
        let json = r#"{
            "lhs_ir_file": "lhs.ir",
            "rhs_ir_file": "rhs.ir",
            "top": "main",
            "solver": "toolchain",
            "parallelism_strategy": "input-bit-split",
            "assertion_semantics": "never",
            "json": true
        }"#;
        let cfg: IrEquivConfig = serde_json::from_str(json).unwrap();
        assert_eq!(cfg.solver, Some(SolverChoice::Toolchain));
        assert_eq!(
            cfg.parallelism_strategy,
            Some(EquivParallelism::InputBitSplit)
        );
        assert_eq!(cfg.assertion_semantics, Some(AssertionSemantics::Never));
        assert_eq!(cfg.json, Some(true));
    }

    #[test]
    fn test_prover_task_json_roundtrip() {
        let json = r#"[
          {
            "kind": "ir-equiv",
            "lhs_ir_file": "lhs.ir",
            "rhs_ir_file": "rhs.ir",
            "top": "main",
            "solver": "toolchain",
            "json": true
          },
          {
            "kind": "dslx-equiv",
            "lhs_dslx_file": "lhs.x",
            "rhs_dslx_file": "rhs.x",
            "dslx_top": "foo",
            "solver": "toolchain",
            "json": true
          },
          {
            "kind": "prove-quickcheck",
            "dslx_input_file": "qc.x",
            "assertion_semantics": "assume",
            "solver": "toolchain",
            "json": true
          },
          {
            "kind": "dslx-fn-prove-assertions",
            "dslx_input_file": "assertions.x",
            "dslx_top": "main",
            "solver": "auto"
          }
        ]"#;
        let tasks: Vec<ProverTask> = serde_json::from_str(json).unwrap();
        assert_eq!(tasks.len(), 4);
        // Smoke test command arg heads
        let head: Vec<String> = args_of(tasks[0].to_command());
        assert_eq!(head[0], "ir-equiv");
        let head: Vec<String> = args_of(tasks[1].to_command());
        assert_eq!(head[0], "dslx-equiv");
        let head: Vec<String> = args_of(tasks[2].to_command());
        assert_eq!(head[0], "prove-quickcheck");
        let head: Vec<String> = args_of(tasks[3].to_command());
        assert_eq!(head[0], "dslx-fn-prove-assertions");
    }

    // -----------------------
    // ProverPlan tests
    // -----------------------

    #[test]
    fn test_prover_plan_all_deserialize_and_heads() {
        let json = r#"{
          "kind": "all",
          "tasks": [
            { "kind": "ir-equiv", "lhs_ir_file": "lhs.ir", "rhs_ir_file": "rhs.ir" },
            { "kind": "dslx-equiv", "lhs_dslx_file": "lhs.x", "rhs_dslx_file": "rhs.x", "dslx_top": "foo" },
            { "kind": "prove-quickcheck", "dslx_input_file": "qc.x" },
            { "kind": "dslx-fn-prove-assertions", "dslx_input_file": "assertions.x", "dslx_top": "main" }
          ]
        }"#;
        let plan: ProverPlan = serde_json::from_str(json).unwrap();
        match plan {
            ProverPlan::Group {
                kind: GroupKind::All,
                tasks,
                keep_running_till_finish,
            } => {
                assert_eq!(tasks.len(), 4);
                let heads: Vec<String> = tasks.iter().map(head_of).collect();
                assert_eq!(
                    heads,
                    vec![
                        "ir-equiv",
                        "dslx-equiv",
                        "prove-quickcheck",
                        "dslx-fn-prove-assertions"
                    ]
                );
                assert!(!keep_running_till_finish);
            }
            _ => panic!("expected ProverPlan::Group(All)"),
        }
    }

    #[test]
    fn test_prover_plan_any_deserialize_and_heads() {
        let json = r#"{
          "kind": "any",
          "tasks": [
            { "kind": "ir-equiv", "lhs_ir_file": "lhs.ir", "rhs_ir_file": "rhs.ir" },
            { "kind": "prove-quickcheck", "dslx_input_file": "qc.x" }
          ],
          "keep_running_till_finish": true
        }"#;
        let plan: ProverPlan = serde_json::from_str(json).unwrap();
        match plan {
            ProverPlan::Group {
                kind: GroupKind::Any,
                tasks,
                keep_running_till_finish,
            } => {
                assert_eq!(tasks.len(), 2);
                let heads: Vec<String> = tasks.iter().map(head_of).collect();
                assert_eq!(heads, vec!["ir-equiv", "prove-quickcheck"]);
                assert!(keep_running_till_finish);
            }
            _ => panic!("expected ProverPlan::Group(Any)"),
        }
    }

    #[test]
    fn test_prover_plan_first_deserialize_and_heads() {
        let json = r#"{
          "kind": "first",
          "tasks": [
            { "kind": "ir-equiv", "lhs_ir_file": "lhs.ir", "rhs_ir_file": "rhs.ir" },
            { "kind": "dslx-equiv", "lhs_dslx_file": "lhs.x", "rhs_dslx_file": "rhs.x", "dslx_top": "foo" }
          ]
        }"#;
        let plan: ProverPlan = serde_json::from_str(json).unwrap();
        match plan {
            ProverPlan::Group {
                kind: GroupKind::First,
                tasks,
                ..
            } => {
                assert_eq!(tasks.len(), 2);
                let heads: Vec<String> = tasks.iter().map(head_of).collect();
                assert_eq!(heads, vec!["ir-equiv", "dslx-equiv"]);
            }
            _ => panic!("expected ProverPlan::Group(First)"),
        }
    }

    #[test]
    fn test_prover_plan_all_serialize_shape() {
        let plan = ProverPlan::Group {
            kind: GroupKind::All,
            tasks: vec![ProverPlan::Task {
                task: ProverTask::IrEquiv {
                    config: IrEquivConfig {
                        lhs_ir_file: "lhs.ir".into(),
                        rhs_ir_file: "rhs.ir".into(),
                        ..Default::default()
                    },
                },
                timeout_ms: None,
                task_id: None,
            }],
            keep_running_till_finish: false,
        };
        let v = serde_json::to_value(&plan).unwrap();
        assert_eq!(v["kind"], "all");
        assert!(v["tasks"].is_array());
        assert_eq!(v["tasks"][0]["kind"], "ir-equiv");
        assert_eq!(v["tasks"][0]["lhs_ir_file"], "lhs.ir");
        assert_eq!(v["tasks"][0]["rhs_ir_file"], "rhs.ir");
    }

    #[test]
    fn test_prover_plan_task_with_metadata_serde() {
        // Build a task plan with metadata and ensure it serializes and parses
        // correctly.
        let plan = ProverPlan::Task {
            task: ProverTask::IrEquiv {
                config: IrEquivConfig {
                    lhs_ir_file: "lhs.ir".into(),
                    rhs_ir_file: "rhs.ir".into(),
                    ..Default::default()
                },
            },
            timeout_ms: Some(1234),
            task_id: Some("task-xyz".to_string()),
        };
        let v = serde_json::to_value(&plan).unwrap();
        assert_eq!(v["kind"], "ir-equiv");
        assert_eq!(v["lhs_ir_file"], "lhs.ir");
        assert_eq!(v["rhs_ir_file"], "rhs.ir");
        assert_eq!(v["timeout_ms"], 1234);
        assert_eq!(v["task_id"], "task-xyz");

        // Round-trip back to ProverPlan and verify fields.
        let parsed: ProverPlan = serde_json::from_value(v).unwrap();
        match parsed {
            ProverPlan::Task {
                task: ProverTask::IrEquiv { .. },
                timeout_ms,
                task_id,
            } => {
                assert_eq!(timeout_ms, Some(1234));
                assert_eq!(task_id.as_deref(), Some("task-xyz"));
            }
            _ => panic!("expected ProverPlan::Task::IrEquiv"),
        }
    }

    #[test]
    fn test_prover_plan_task_parse_metadata_from_json() {
        let json = r#"{
            "kind": "ir-equiv",
            "lhs_ir_file": "lhs.ir",
            "rhs_ir_file": "rhs.ir",
            "timeout_ms": 5000,
            "task_id": "tid-123"
        }"#;
        let plan: ProverPlan = serde_json::from_str(json).unwrap();
        match plan {
            ProverPlan::Task {
                task: ProverTask::IrEquiv { .. },
                timeout_ms,
                task_id,
            } => {
                assert_eq!(timeout_ms, Some(5000));
                assert_eq!(task_id.as_deref(), Some("tid-123"));
            }
            _ => panic!("expected ProverPlan::Task::IrEquiv"),
        }
    }

    #[test]
    fn test_prover_plan_task_serialize_and_parse_behavior() {
        let plan = ProverPlan::Task {
            task: ProverTask::IrEquiv {
                config: IrEquivConfig {
                    lhs_ir_file: "lhs.ir".into(),
                    rhs_ir_file: "rhs.ir".into(),
                    ..Default::default()
                },
            },
            timeout_ms: None,
            task_id: None,
        };
        let v = serde_json::to_value(&plan).unwrap();
        // The inner task tag is used on serialization.
        assert_eq!(v["kind"], "ir-equiv");
        // It can be parsed as a ProverTask...
        let task: ProverTask = serde_json::from_value(v.clone()).unwrap();
        match task {
            ProverTask::IrEquiv { .. } => {}
            _ => panic!("expected ProverTask::IrEquiv"),
        }
        // ...and can be parsed back as a ProverPlan::Task as well.
        let plan2: ProverPlan = serde_json::from_value(v.clone()).unwrap();
        match plan2 {
            ProverPlan::Task {
                task: ProverTask::IrEquiv { .. },
                ..
            } => {}
            _ => panic!("expected ProverPlan::Task::IrEquiv"),
        }
    }
}