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
// SPDX-License-Identifier: Apache-2.0

use clap::ArgMatches;
use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::process;
use std::process::Command;
use xlsynth::mangle_dslx_name;

// By default in the driver we treat warnings as errors.
pub const DEFAULT_WARNINGS_AS_ERRORS: bool = true;

// Specification for a pipeline generation can be either stages-based or
// clock-period-based.
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum PipelineSpec {
    Stages(u64),
    ClockPeriodPs(u64),
}

/// Parses a boolean command-line flag where clap has already constrained the
/// possible values to the strings "true" or "false".
pub fn parse_bool_flag(matches: &ArgMatches, flag_name: &str) -> Option<bool> {
    matches
        .get_one::<String>(flag_name)
        .map(|value| value == "true")
}

/// Parses a boolean flag, falling back to the provided default when it is not
/// present on the command line.
pub fn parse_bool_flag_or(matches: &ArgMatches, flag_name: &str, default_value: bool) -> bool {
    parse_bool_flag(matches, flag_name).unwrap_or(default_value)
}

/// Determines the effective value of the experimental `type_inference_v2`
/// option. The command-line flag takes precedence, and we fall back to the
/// toolchain configuration when the flag is absent.
pub fn resolve_type_inference_v2(
    matches: &ArgMatches,
    config: &Option<crate::toolchain_config::ToolchainConfig>,
) -> Option<bool> {
    parse_bool_flag(matches, "type_inference_v2").or_else(|| {
        config
            .as_ref()
            .and_then(|c| c.dslx.as_ref()?.type_inference_v2)
    })
}

pub fn extract_pipeline_spec(matches: &ArgMatches) -> PipelineSpec {
    if let Some(pipeline_stages) = matches.get_one::<String>("pipeline_stages") {
        PipelineSpec::Stages(pipeline_stages.parse().unwrap())
    } else if let Some(clock_period_ps) = matches.get_one::<String>("clock_period_ps") {
        PipelineSpec::ClockPeriodPs(clock_period_ps.parse().unwrap())
    } else {
        eprintln!("Must provide either --pipeline_stages or --clock_period_ps");
        process::exit(1)
    }
}

pub fn write_stdout_line(line: &str) {
    let mut out = std::io::stdout().lock();
    if let Err(e) = writeln!(out, "{}", line) {
        if e.kind() == std::io::ErrorKind::BrokenPipe {
            process::exit(0);
        }
        eprintln!("error: failed to write stdout: {e}");
        process::exit(1);
    }
}

/// Writes text to stdout while treating broken pipes as a clean exit.
pub fn write_stdout(text: &str) {
    let mut out = std::io::stdout().lock();
    if let Err(e) = write!(out, "{}", text) {
        if e.kind() == std::io::ErrorKind::BrokenPipe {
            process::exit(0);
        }
        eprintln!("error: failed to write stdout: {e}");
        process::exit(1);
    }
}

#[derive(Debug, Clone)]
pub struct CodegenFlags {
    pub input_valid_signal: Option<String>,
    pub output_valid_signal: Option<String>,
    pub use_system_verilog: Option<bool>,
    pub flop_inputs: Option<bool>,
    pub flop_outputs: Option<bool>,
    pub add_idle_output: Option<bool>,
    pub add_invariant_assertions: Option<bool>,
    pub module_name: Option<String>,
    pub array_index_bounds_checking: Option<bool>,
    pub separate_lines: Option<bool>,
    pub reset: Option<String>,
    pub reset_active_low: Option<bool>,
    pub reset_asynchronous: Option<bool>,
    pub reset_data_path: Option<bool>,
    pub gate_format: Option<String>,
    pub assert_format: Option<String>,
    pub output_schedule_path: Option<String>,
    pub output_verilog_line_map_path: Option<String>,
    pub output_block_ir_path: Option<String>,
    pub output_residual_data_path: Option<String>,
    pub reference_residual_data_path: Option<String>,
}

/// Extracts flags that we pass to the "codegen" step of the process (i.e.
/// generating lowered Verilog).
pub fn extract_codegen_flags(
    matches: &ArgMatches,
    toolchain_config: Option<&crate::toolchain_config::ToolchainConfig>,
) -> CodegenFlags {
    let (gate_format, assert_format) = if let Some(config) = toolchain_config {
        (
            config.codegen.as_ref().and_then(|c| c.gate_format.clone()),
            config
                .codegen
                .as_ref()
                .and_then(|c| c.assert_format.clone()),
        )
    } else {
        (None, None)
    };
    let mut flags = CodegenFlags {
        input_valid_signal: matches
            .get_one::<String>("input_valid_signal")
            .map(|s| s.to_string()),
        output_valid_signal: matches
            .get_one::<String>("output_valid_signal")
            .map(|s| s.to_string()),
        use_system_verilog: matches
            .get_one::<String>("use_system_verilog")
            .map(|s| s == "true")
            .or_else(|| toolchain_config.and_then(|c| c.codegen.as_ref()?.use_system_verilog)),
        flop_inputs: matches
            .get_one::<String>("flop_inputs")
            .map(|s| s == "true"),
        flop_outputs: matches
            .get_one::<String>("flop_outputs")
            .map(|s| s == "true"),
        add_idle_output: matches
            .get_one::<String>("add_idle_output")
            .map(|s| s == "true"),
        add_invariant_assertions: matches
            .get_one::<String>("add_invariant_assertions")
            .map(|s| s == "true")
            .or_else(|| {
                toolchain_config
                    .and_then(|c| c.codegen.as_ref())
                    .and_then(|cg| cg.add_invariant_assertions)
            }),
        module_name: matches
            .get_one::<String>("module_name")
            .map(|s| s.to_string()),
        array_index_bounds_checking: matches
            .get_one::<String>("array_index_bounds_checking")
            .map(|s| s == "true"),
        separate_lines: matches
            .get_one::<String>("separate_lines")
            .map(|s| s == "true"),
        reset: matches.get_one::<String>("reset").map(|s| s.to_string()),
        reset_active_low: matches
            .get_one::<String>("reset_active_low")
            .map(|s| s == "true"),
        reset_asynchronous: matches
            .get_one::<String>("reset_asynchronous")
            .map(|s| s == "true"),
        reset_data_path: matches
            .get_one::<String>("reset_data_path")
            .map(|s| s == "true"),
        gate_format,
        assert_format,
        output_schedule_path: matches
            .get_one::<String>("output_schedule_path")
            .map(|s| s.to_string()),
        output_verilog_line_map_path: matches
            .get_one::<String>("output_verilog_line_map_path")
            .map(|s| s.to_string()),
        output_block_ir_path: matches
            .get_one::<String>("output_block_ir_path")
            .map(|s| s.to_string()),
        output_residual_data_path: matches
            .get_one::<String>("output_residual_data_path")
            .map(|s| s.to_string()),
        reference_residual_data_path: matches
            .get_one::<String>("reference_residual_data_path")
            .map(|s| s.to_string()),
    };

    // Fill in library-consistent defaults when still unspecified.
    if flags.use_system_verilog.is_none() {
        flags.use_system_verilog = Some(crate::flag_defaults::CODEGEN_USE_SYSTEM_VERILOG);
    }
    if flags.flop_inputs.is_none() {
        flags.flop_inputs = Some(crate::flag_defaults::CODEGEN_FLOP_INPUTS);
    }
    if flags.flop_outputs.is_none() {
        flags.flop_outputs = Some(crate::flag_defaults::CODEGEN_FLOP_OUTPUTS);
    }
    if flags.add_idle_output.is_none() {
        flags.add_idle_output = Some(crate::flag_defaults::CODEGEN_ADD_IDLE_OUTPUT);
    }
    if flags.add_invariant_assertions.is_none() {
        flags.add_invariant_assertions =
            Some(crate::flag_defaults::CODEGEN_ADD_INVARIANT_ASSERTIONS);
    }
    if flags.array_index_bounds_checking.is_none() {
        flags.array_index_bounds_checking =
            Some(crate::flag_defaults::CODEGEN_ARRAY_INDEX_BOUNDS_CHECKING);
    }

    flags
}

pub fn codegen_flags_to_textproto(codegen_flags: &CodegenFlags) -> String {
    log::debug!(
        "codegen_flags_to_textproto; codegen_flags: {:?}",
        codegen_flags
    );
    let mut pieces = vec![];
    if let Some(input_valid_signal) = &codegen_flags.input_valid_signal {
        pieces.push(format!("input_valid_signal: \"{input_valid_signal}\""));
    }
    if let Some(output_valid_signal) = &codegen_flags.output_valid_signal {
        pieces.push(format!("output_valid_signal: \"{output_valid_signal}\""));
    }
    if let Some(use_system_verilog) = codegen_flags.use_system_verilog {
        pieces.push(format!("use_system_verilog: {use_system_verilog}"));
    }
    if let Some(flop_inputs) = codegen_flags.flop_inputs {
        pieces.push(format!("flop_inputs: {flop_inputs}"));
    }
    if let Some(flop_outputs) = codegen_flags.flop_outputs {
        pieces.push(format!("flop_outputs: {flop_outputs}"));
    }
    if let Some(add_idle_output) = codegen_flags.add_idle_output {
        pieces.push(format!("add_idle_output: {add_idle_output}"));
    }
    if let Some(add_invariant_assertions) = codegen_flags.add_invariant_assertions {
        pieces.push(format!(
            "add_invariant_assertions: {add_invariant_assertions}"
        ));
    }
    if let Some(module_name) = &codegen_flags.module_name {
        pieces.push(format!("module_name: \"{module_name}\""));
    }
    if let Some(array_index_bounds_checking) = codegen_flags.array_index_bounds_checking {
        pieces.push(format!(
            "array_index_bounds_checking: {array_index_bounds_checking}"
        ));
    }
    if let Some(separate_lines) = codegen_flags.separate_lines {
        pieces.push(format!("separate_lines: {separate_lines}"));
    }
    if let Some(reset) = &codegen_flags.reset {
        pieces.push(format!("reset: \"{reset}\""));
    }
    if let Some(reset_active_low) = codegen_flags.reset_active_low {
        pieces.push(format!("reset_active_low: {reset_active_low}"));
    }
    if let Some(reset_asynchronous) = codegen_flags.reset_asynchronous {
        pieces.push(format!("reset_asynchronous: {reset_asynchronous}"));
    }
    if let Some(reset_data_path) = codegen_flags.reset_data_path {
        pieces.push(format!("reset_data_path: {reset_data_path}"));
    }
    if let Some(gate_format) = &codegen_flags.gate_format {
        pieces.push(format!("gate_format: {gate_format:?}"));
    }
    if let Some(assert_format) = &codegen_flags.assert_format {
        pieces.push(format!("assert_format: {assert_format:?}"));
    }
    if let Some(output_schedule_path) = &codegen_flags.output_schedule_path {
        pieces.push(format!("output_schedule_path: \"{output_schedule_path}\""));
    }
    if let Some(output_verilog_line_map_path) = &codegen_flags.output_verilog_line_map_path {
        pieces.push(format!(
            "output_verilog_line_map_path: \"{output_verilog_line_map_path}\""
        ));
    }
    if let Some(output_block_ir_path) = &codegen_flags.output_block_ir_path {
        pieces.push(format!("output_block_ir_path: \"{output_block_ir_path}\""));
    }
    if let Some(output_residual_data_path) = &codegen_flags.output_residual_data_path {
        pieces.push(format!(
            "output_residual_data_path: \"{output_residual_data_path}\""
        ));
    }
    if let Some(reference_residual_data_path) = &codegen_flags.reference_residual_data_path {
        pieces.push(format!(
            "reference_residual_data_path: \"{reference_residual_data_path}\""
        ));
    }
    pieces.push(format!("assertion_macro_names: \"ASSERT_ON\""));
    pieces.join("\n")
}

/// Adds the given code-generation flags to the command in command-line-arg
/// form.
pub fn add_codegen_flags(command: &mut Command, codegen_flags: &CodegenFlags) {
    log::info!("add_codegen_flags");
    if let Some(use_system_verilog) = codegen_flags.use_system_verilog {
        command.arg(format!("--use_system_verilog={use_system_verilog}"));
    }
    if let Some(input_valid_signal) = &codegen_flags.input_valid_signal {
        command.arg("--input_valid_signal").arg(input_valid_signal);
    }
    if let Some(output_valid_signal) = &codegen_flags.output_valid_signal {
        command
            .arg("--output_valid_signal")
            .arg(output_valid_signal);
    }
    if let Some(flop_inputs) = codegen_flags.flop_inputs {
        command.arg(format!("--flop_inputs={flop_inputs}"));
    }
    if let Some(flop_outputs) = codegen_flags.flop_outputs {
        command.arg(format!("--flop_outputs={flop_outputs}"));
    }
    if let Some(add_idle_output) = codegen_flags.add_idle_output {
        command.arg(format!("--add_idle_output={add_idle_output}"));
    }
    if let Some(add_invariant_assertions) = codegen_flags.add_invariant_assertions {
        command.arg(format!(
            "--add_invariant_assertions={add_invariant_assertions}"
        ));
    }
    if let Some(module_name) = &codegen_flags.module_name {
        command.arg("--module_name").arg(module_name);
    }
    if let Some(array_index_bounds_checking) = codegen_flags.array_index_bounds_checking {
        command.arg(format!(
            "--array_index_bounds_checking={array_index_bounds_checking}"
        ));
    }
    if let Some(separate_lines) = codegen_flags.separate_lines {
        command.arg(format!("--separate_lines={separate_lines}"));
    }
    if let Some(reset) = &codegen_flags.reset {
        command.arg(format!("--reset={reset}"));
    }
    if let Some(reset_active_low) = codegen_flags.reset_active_low {
        command.arg(format!("--reset_active_low={reset_active_low}"));
    }
    if let Some(reset_asynchronous) = codegen_flags.reset_asynchronous {
        command.arg(format!("--reset_asynchronous={reset_asynchronous}"));
    }
    if let Some(reset_data_path) = codegen_flags.reset_data_path {
        command.arg(format!("--reset_data_path={reset_data_path}"));
    }
    if let Some(gate_format) = &codegen_flags.gate_format {
        command.arg(format!("--gate_format={gate_format}"));
    }
    if let Some(assert_format) = &codegen_flags.assert_format {
        command.arg(format!("--assert_format={assert_format}"));
    }
    if let Some(output_schedule_path) = &codegen_flags.output_schedule_path {
        command
            .arg("--output_schedule_path")
            .arg(output_schedule_path);
    }
    if let Some(output_verilog_line_map_path) = &codegen_flags.output_verilog_line_map_path {
        command
            .arg("--output_verilog_line_map_path")
            .arg(output_verilog_line_map_path);
    }
    if let Some(output_block_ir_path) = &codegen_flags.output_block_ir_path {
        command.arg(format!("--output_block_ir_path={output_block_ir_path}"));
    }
    if let Some(output_residual_data_path) = &codegen_flags.output_residual_data_path {
        command.arg(format!(
            "--output_residual_data_path={output_residual_data_path}"
        ));
    }
    if let Some(reference_residual_data_path) = &codegen_flags.reference_residual_data_path {
        command.arg(format!(
            "--reference_residual_data_path={reference_residual_data_path}"
        ));
    }
}

/// Builds the textproto string for `SchedulingOptionsProto` given the delay
/// model and pipeline specification.
pub fn scheduling_options_proto(delay_model: &str, pipeline_spec: &PipelineSpec) -> String {
    let mut lines = vec![format!("delay_model: \"{}\"", delay_model)];
    match pipeline_spec {
        PipelineSpec::Stages(stages) => lines.push(format!("pipeline_stages: {}", stages)),
        PipelineSpec::ClockPeriodPs(clock_period_ps) => {
            lines.push(format!("clock_period_ps: {}", clock_period_ps))
        }
    }
    lines.join("\n")
}

/// Builds the textproto string for `CodegenFlagsProto` used by pipeline
/// generation.
pub fn pipeline_codegen_flags_proto(codegen_flags: &CodegenFlags) -> String {
    format!(
        "register_merge_strategy: STRATEGY_IDENTITY_ONLY\ngenerator: GENERATOR_KIND_PIPELINE\n{}",
        codegen_flags_to_textproto(codegen_flags)
    )
}

/// Gathers additional DSLX module search paths from:
///   • the `--dslx_path` command-line flag (semi-colon separated)
///   • `[toolchain.dslx].dslx_path` array in the toolchain config.
/// Returns a vector of unique `PathBuf`s in the order first–seen.
pub fn collect_dslx_search_paths(
    matches: &ArgMatches,
    config: &Option<crate::toolchain_config::ToolchainConfig>,
) -> Vec<std::path::PathBuf> {
    let mut out: Vec<std::path::PathBuf> = Vec::new();

    // --dslx_path flag: semicolon-separated list like "dirA;dirB" (kept for
    // consistency with other subcommands).
    if let Some(flag_value) = matches.get_one::<String>("dslx_path") {
        for entry in flag_value.split(';').filter(|s| !s.is_empty()) {
            out.push(std::path::PathBuf::from(entry));
        }
    }

    // toolchain.toml paths: Vec<String>.
    if let Some(cfg) = config {
        if let Some(dslx_cfg) = &cfg.dslx {
            if let Some(vec) = &dslx_cfg.dslx_path {
                for p in vec {
                    if !p.is_empty() {
                        out.push(std::path::PathBuf::from(p));
                    }
                }
            }
        }
    }

    // Deduplicate preserving the first occurrence.
    let mut seen: HashSet<std::path::PathBuf> = HashSet::new();
    out.retain(|p| seen.insert(p.clone()));
    out
}

/// Holds resolved locations for DSLX support files.
pub struct DslxPaths {
    /// Optional alternative stdlib root.
    pub stdlib_path: Option<std::path::PathBuf>,
    /// Additional search directories beyond the source file’s dir.
    pub search_paths: Vec<std::path::PathBuf>,
}

impl DslxPaths {
    /// Returns the additional search paths as borrowed `&Path` slice for APIs
    /// like `ImportData::new` or `DslxConvertOptions`.
    pub fn search_path_views(&self) -> Vec<&std::path::Path> {
        self.search_paths.iter().map(|p| p.as_path()).collect()
    }
}

/// Builds the `DslxPaths` structure from CLI flags / toolchain configuration.
pub fn get_dslx_paths(
    matches: &ArgMatches,
    config: &Option<crate::toolchain_config::ToolchainConfig>,
) -> DslxPaths {
    use crate::toolchain_config::get_dslx_stdlib_path;

    let stdlib_path_opt =
        get_dslx_stdlib_path(matches, config).map(|s| std::path::PathBuf::from(s));

    let search_paths = collect_dslx_search_paths(matches, config);

    DslxPaths {
        stdlib_path: stdlib_path_opt,
        search_paths,
    }
}

/// Locates an executable in PATH and verifies it can actually be executed.
///
/// This function:
/// 1. Uses `which` to find the executable in PATH
/// 2. Verifies the file has executable permissions (on Unix systems)
/// 3. Returns the path if valid, or a descriptive error if not
pub fn find_and_verify_executable(
    name: &str,
    install_hint: &str,
) -> anyhow::Result<std::path::PathBuf> {
    // Find the executable in PATH
    let exe_path = which::which(name).map_err(|_| {
        anyhow::anyhow!("`{}` executable not found in PATH. {}", name, install_hint)
    })?;

    // Verify the binary is actually executable
    if let Ok(metadata) = std::fs::metadata(&exe_path) {
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let perms = metadata.permissions();
            if perms.mode() & 0o111 == 0 {
                return Err(anyhow::anyhow!(
                    "{} binary at '{}' exists but is not executable (permissions: {:o})",
                    name,
                    exe_path.display(),
                    perms.mode()
                ));
            }
        }
    }

    Ok(exe_path)
}

/// Executes a command and provides a descriptive error message if execution
/// fails.
pub fn execute_command_with_context(
    mut cmd: std::process::Command,
    context: &str,
) -> anyhow::Result<std::process::Output> {
    log::debug!("execute_command_with_context: About to execute command");
    let result = cmd.output().map_err(|e| {
        anyhow::anyhow!(
            "{}: {}. This could indicate missing dynamic libraries or other execution issues.",
            context,
            e
        )
    });
    match &result {
        Ok(output) => log::debug!(
            "execute_command_with_context: Command completed with status: {}",
            output.status
        ),
        Err(e) => log::debug!("execute_command_with_context: Command failed: {}", e),
    }
    result
}

// -----------------------------------------------------------------------------
// DSLX helpers shared across subcommands
// -----------------------------------------------------------------------------

use xlsynth_prover::prover::types::ParamDomains;

pub fn get_enum_domain(
    tcm: &xlsynth::dslx::TypecheckedModule,
    enum_def: &xlsynth::dslx::EnumDef,
) -> Vec<xlsynth::IrValue> {
    let mut values = Vec::new();
    for mi in 0..enum_def.get_member_count() {
        let m = enum_def.get_member(mi);
        let expr = m.get_value();
        let owner_module = expr.get_owner_module();
        let owner_type_info = tcm
            .get_type_info_for_module(&owner_module)
            .expect("imported type info");
        let interp = owner_type_info.get_const_expr(&expr).expect("constexpr");
        let ir_val = interp.convert_to_ir().expect("convert");
        values.push(ir_val);
    }

    values
}

pub fn get_function_enum_param_domains(
    tcm: &xlsynth::dslx::TypecheckedModule,
    dslx_top: &str,
) -> Result<ParamDomains, String> {
    let module = tcm.get_module();
    let type_info = tcm.get_type_info();
    let mut domains: ParamDomains = std::collections::HashMap::new();
    let mut found = false;

    for i in 0..module.get_member_count() {
        if let Some(xlsynth::dslx::MatchableModuleMember::Function(f)) =
            module.get_member(i).to_matchable()
        {
            if f.get_identifier() == dslx_top {
                found = true;
                for pidx in 0..f.get_param_count() {
                    let p = f.get_param(pidx);
                    let name = p.get_name();
                    let ta = p.get_type_annotation();
                    let ty = type_info.get_type_for_type_annotation(&ta).unwrap();
                    if ty.is_enum() {
                        let enum_def = ty.get_enum_def().unwrap();
                        let values = get_enum_domain(tcm, &enum_def);
                        domains.insert(name, values);
                    }
                }
            }
        }
    }

    if found {
        Ok(domains)
    } else {
        Err(format!(
            "Function '{}' not found in module '{}': available members: {}",
            dslx_top,
            module.get_name(),
            (0..module.get_member_count())
                .filter_map(|idx| module.get_member(idx).to_matchable())
                .filter_map(|member| match member {
                    xlsynth::dslx::MatchableModuleMember::Function(func) =>
                        Some(func.get_identifier()),
                    _ => None,
                })
                .collect::<Vec<_>>()
                .join(", ")
        ))
    }
}

/// Parses uninterpreted-function mappings from CLI values into a map from
/// mangled function name -> UF symbol.
///
/// Format per entry: "<func_name>:<uf_name>".
/// Semantics: Functions that map to the same <uf_name> are treated as the same
/// uninterpreted symbol during proving: they are assumed equivalent at the
/// call-site interface, and any assertions within their bodies are ignored.
pub fn parse_uf_spec(
    module_name: &str,
    matches: Option<clap::parser::ValuesRef<String>>,
) -> HashMap<String, String> {
    let mut m = std::collections::HashMap::new();
    if let Some(vals) = matches {
        for v in vals {
            if let Some((fn_name, uf_name)) = v.split_once(':') {
                m.insert(
                    mangle_dslx_name(module_name, fn_name.trim()).unwrap(),
                    uf_name.trim().to_string(),
                );
            } else {
                eprintln!(
                    "Error: invalid uninterpreted function specification '{}'; expected <function-name>:<uf-name>",
                    v
                );
                std::process::exit(1);
            }
        }
    }
    m
}

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

    #[test]
    fn test_get_function_enum_param_domains_cross_module() {
        use xlsynth::dslx;

        // Temp directory housing the modules.
        let tmpdir = xlsynth_test_helpers::make_test_tmpdir("xlsynth_driver_dslx_test");
        let dir = tmpdir.path();

        // imported.x defines an enum whose member uses a local const.
        let imported_path = dir.join("imported.x");
        let imported_dslx = r#"
            const K = u3:5;
            pub enum ImpE : u3 { Z = 0, P = K }
        "#;
        std::fs::write(&imported_path, imported_dslx).expect("write imported.x");

        // main.x imports `imported` and exposes a top that takes the imported enum.
        let main_path = dir.join("main.x");
        let main_dslx = r#"
            import imported;
            pub fn top(x: imported::ImpE) -> u3 { u3:0 }
        "#;
        std::fs::write(&main_path, main_dslx).expect("write main.x");

        // Parse/typecheck the main module; imported will be resolved via search path.
        let mut import_data = dslx::ImportData::new(None, &[dir]);
        let tcm = dslx::parse_and_typecheck(
            main_dslx,
            main_path.to_str().unwrap(),
            "main",
            &mut import_data,
        )
        .expect("parse_and_typecheck success");

        // Exercise the helper under test.
        let domains = get_function_enum_param_domains(&tcm, "top").expect("function exists");
        assert!(domains.contains_key("x"));
        let values = domains.get("x").unwrap();
        assert_eq!(values.len(), 2);
        assert!(values.contains(&xlsynth::IrValue::make_ubits(3, 0).unwrap()));
        assert!(values.contains(&xlsynth::IrValue::make_ubits(3, 5).unwrap()));
    }
}