xlsynth/
lib.rs

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

pub mod dslx;
pub mod dslx_bridge;
pub mod ir_package;
pub mod ir_value;
pub mod vast;
pub mod xlsynth_error;

pub mod rust_bridge_builder;
pub mod sv_bridge_builder;

use std::ffi::{CStr, CString};
use std::sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard};

use ir_package::{IrFunctionType, IrPackagePtr, IrType};
pub use ir_value::{IrBits, IrSBits, IrUBits};
use xlsynth_sys::{CIrBits, CIrPackage, CIrValue};
use xlsynth_sys::{CIrFunction, CIrFunctionType, CIrType, XlsFormatPreference};

pub use ir_package::IrFunction;
pub use ir_package::IrPackage;
pub use ir_value::IrValue;
pub use xlsynth_error::XlsynthError;

/// Converts a C string that was given from the XLS library into a Rust string
/// and deallocates the original C string.
unsafe fn c_str_to_rust(xls_c_str: *mut std::os::raw::c_char) -> String {
    if xls_c_str.is_null() {
        return String::new();
    }

    let c_str: &CStr = CStr::from_ptr(xls_c_str);
    let result: String = String::from_utf8_lossy(c_str.to_bytes()).to_string();

    // We release the C string via a call to the XLS library so that it can use the
    // same allocator it used to allocate the string for deallocation and we don't
    // need to assume the Rust code and dynmic library are using the same underlying
    // allocator.
    xlsynth_sys::xls_c_str_free(xls_c_str);
    result
}

pub fn dslx_path_to_module_name(path: &std::path::Path) -> Result<&str, XlsynthError> {
    let stem = path.file_stem();
    match stem {
        None => {
            return Err(XlsynthError(
                "Failed to extract module name from path".to_string(),
            ));
        }
        Some(stem) => {
            return Ok(stem.to_str().unwrap());
        }
    }
}

pub struct DslxConvertOptions<'a> {
    pub dslx_stdlib_path: Option<&'a std::path::Path>,
    pub additional_search_paths: Vec<&'a std::path::Path>,
}

impl<'a> Default for DslxConvertOptions<'a> {
    fn default() -> Self {
        DslxConvertOptions {
            dslx_stdlib_path: None,
            additional_search_paths: vec![],
        }
    }
}

pub fn xls_convert_dslx_to_ir(
    dslx: &str,
    path: &std::path::Path,
    options: &DslxConvertOptions,
) -> Result<String, XlsynthError> {
    // Extract the module name from the path; e.g. "foo/bar/baz.x" -> "baz"
    let module_name = dslx_path_to_module_name(path)?;
    let path_str = path.to_str().unwrap();
    let stdlib_path = options
        .dslx_stdlib_path
        .unwrap_or_else(|| std::path::Path::new(xlsynth_sys::DSLX_STDLIB_PATH));
    let stdlib_path = stdlib_path.to_str().unwrap();
    let search_paths = options
        .additional_search_paths
        .iter()
        .map(|p| p.to_str().unwrap())
        .collect::<Vec<&str>>();

    let mut search_paths_cstrs = vec![];
    for p in search_paths {
        search_paths_cstrs.push(CString::new(p).unwrap());
    }

    let dslx = CString::new(dslx).unwrap();
    let c_path = CString::new(path_str).unwrap();
    let c_module_name = CString::new(module_name).unwrap();
    let dslx_stdlib_path = CString::new(stdlib_path).unwrap();

    eprintln!("dslx_stdlib_path: {:?}", dslx_stdlib_path);

    unsafe {
        let additional_search_paths_ptrs: Vec<*const std::os::raw::c_char> = search_paths_cstrs
            .iter()
            .map(|cstr| cstr.as_ptr())
            .collect();

        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let mut ir_out: *mut std::os::raw::c_char = std::ptr::null_mut();

        // Call the function
        let success = xlsynth_sys::xls_convert_dslx_to_ir(
            dslx.as_ptr(),
            c_path.as_ptr(),
            c_module_name.as_ptr(),
            dslx_stdlib_path.as_ptr(),
            additional_search_paths_ptrs.as_ptr(),
            additional_search_paths_ptrs.len(),
            &mut error_out,
            &mut ir_out,
        );

        if success {
            return Ok(c_str_to_rust(ir_out));
        } else {
            let error_out_str = c_str_to_rust(error_out);
            return Err(XlsynthError(error_out_str));
        }
    }
}

pub fn xls_parse_typed_value(s: &str) -> Result<IrValue, XlsynthError> {
    unsafe {
        let c_str = CString::new(s).unwrap();
        let mut ir_value_out: *mut CIrValue = std::ptr::null_mut();
        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let success =
            xlsynth_sys::xls_parse_typed_value(c_str.as_ptr(), &mut error_out, &mut ir_value_out);
        if success {
            return Ok(IrValue { ptr: ir_value_out });
        } else {
            let error_out_str: String = c_str_to_rust(error_out);
            return Err(XlsynthError(error_out_str));
        }
    }
}

pub(crate) fn xls_value_free(p: *mut CIrValue) -> Result<(), XlsynthError> {
    unsafe {
        xlsynth_sys::xls_value_free(p);
        return Ok(());
    }
}

pub(crate) fn xls_package_free(p: *mut CIrPackage) -> Result<(), XlsynthError> {
    unsafe {
        xlsynth_sys::xls_package_free(p);
        return Ok(());
    }
}

pub(crate) fn xls_value_to_string(p: *mut CIrValue) -> Result<String, XlsynthError> {
    unsafe {
        let mut c_str_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let success = xlsynth_sys::xls_value_to_string(p, &mut c_str_out);
        if success {
            return Ok(c_str_to_rust(c_str_out));
        }
        return Err(XlsynthError(
            "Failed to convert XLS value to string via C API".to_string(),
        ));
    }
}

pub(crate) fn xls_value_get_bits(p: *const CIrValue) -> Result<IrBits, XlsynthError> {
    unsafe {
        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let mut bits_out: *mut CIrBits = std::ptr::null_mut();
        let success = xlsynth_sys::xls_value_get_bits(p, &mut error_out, &mut bits_out);
        if success {
            return Ok(IrBits { ptr: bits_out });
        }
        let error_out_str: String = c_str_to_rust(error_out);
        return Err(XlsynthError(error_out_str));
    }
}

pub(crate) fn xls_format_preference_from_string(
    s: &str,
) -> Result<XlsFormatPreference, XlsynthError> {
    unsafe {
        let c_str = CString::new(s).unwrap();
        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let mut result_out: XlsFormatPreference = -1;
        let success = xlsynth_sys::xls_format_preference_from_string(
            c_str.as_ptr(),
            &mut error_out,
            &mut result_out,
        );
        if success {
            return Ok(result_out);
        }
        let error_out_str: String = c_str_to_rust(error_out);
        return Err(XlsynthError(error_out_str));
    }
}

pub(crate) fn xls_value_to_string_format_preference(
    p: *mut CIrValue,
    fmt: XlsFormatPreference,
) -> Result<String, XlsynthError> {
    unsafe {
        let mut c_str_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let success = xlsynth_sys::xls_value_to_string_format_preference(
            p,
            fmt,
            &mut error_out,
            &mut c_str_out,
        );
        if success {
            return Ok(c_str_to_rust(c_str_out));
        }
        return Err(XlsynthError(
            "Failed to convert XLS value to string via C API".to_string(),
        ));
    }
}

pub(crate) fn xls_value_eq(
    lhs: *const CIrValue,
    rhs: *const CIrValue,
) -> Result<bool, XlsynthError> {
    unsafe {
        return Ok(xlsynth_sys::xls_value_eq(lhs, rhs));
    }
}

/// Bindings for the C API function:
/// ```c
/// bool xls_parse_ir_package(
///     const char* ir, const char* filename,
///     char** error_out,
///     struct xls_package** xls_package_out);
/// ```
pub(crate) fn xls_parse_ir_package(
    ir: &str,
    filename: Option<&str>,
) -> Result<crate::ir_package::IrPackage, XlsynthError> {
    unsafe {
        let ir = CString::new(ir).unwrap();
        // The filename is allowed to be a null pointer if there is no filename.
        let filename_ptr = filename
            .map(|s| CString::new(s).unwrap())
            .map(|s| s.as_ptr())
            .unwrap_or(std::ptr::null());
        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let mut xls_package_out: *mut CIrPackage = std::ptr::null_mut();
        let success = xlsynth_sys::xls_parse_ir_package(
            ir.as_ptr(),
            filename_ptr,
            &mut error_out,
            &mut xls_package_out,
        );
        if success {
            let package = crate::ir_package::IrPackage {
                ptr: Arc::new(RwLock::new(IrPackagePtr(xls_package_out))),
                filename: filename.map(|s| s.to_string()),
            };
            return Ok(package);
        }
        let error_out_str: String = c_str_to_rust(error_out);
        return Err(XlsynthError(error_out_str));
    }
}

/// Bindings for the C API function:
/// ```c
/// bool xls_type_to_string(struct xls_type* type, char** error_out,
/// char** result_out);
/// ```
pub(crate) fn xls_type_to_string(t: *const CIrType) -> Result<String, XlsynthError> {
    unsafe {
        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let mut c_str_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let success = xlsynth_sys::xls_type_to_string(t, &mut error_out, &mut c_str_out);
        if success {
            return Ok(c_str_to_rust(c_str_out));
        }
        let error_out_str: String = c_str_to_rust(error_out);
        return Err(XlsynthError(error_out_str));
    }
}

/// Bindings for the C API function:
/// ```c
/// bool xls_package_get_type_for_value(struct xls_package* package,
// struct xls_value* value, char** error_out,
// struct xls_type** result_out);
// ```
pub(crate) fn xls_package_get_type_for_value(
    package: *const CIrPackage,
    value: *const CIrValue,
) -> Result<IrType, XlsynthError> {
    unsafe {
        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let mut result_out: *mut CIrType = std::ptr::null_mut();
        let success = xlsynth_sys::xls_package_get_type_for_value(
            package,
            value,
            &mut error_out,
            &mut result_out,
        );
        if success {
            let ir_type = IrType { ptr: result_out };
            return Ok(ir_type);
        }
        let error_out_str: String = c_str_to_rust(error_out);
        return Err(XlsynthError(error_out_str));
    }
}
/// Bindings for the C API function:
/// ```c
/// bool xls_package_get_function(s
///    struct xls_package* package,
///    const char* function_name, char** error_out,
///    struct xls_function** result_out);
/// ```
pub(crate) fn xls_package_get_function(
    package: &Arc<RwLock<IrPackagePtr>>,
    guard: RwLockReadGuard<IrPackagePtr>,
    function_name: &str,
) -> Result<crate::ir_package::IrFunction, XlsynthError> {
    unsafe {
        let function_name = CString::new(function_name).unwrap();
        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let mut result_out: *mut CIrFunction = std::ptr::null_mut();
        let success = xlsynth_sys::xls_package_get_function(
            guard.const_c_ptr(),
            function_name.as_ptr(),
            &mut error_out,
            &mut result_out,
        );
        if success {
            let function = crate::ir_package::IrFunction {
                parent: package.clone(),
                ptr: result_out,
            };
            return Ok(function);
        }
        let error_out_str: String = c_str_to_rust(error_out);
        return Err(XlsynthError(error_out_str));
    }
}

/// Bindings for the C API function:
/// ```c
/// bool xls_function_get_type(struct xls_function* function, char** error_out,
/// struct xls_function_type** xls_fn_type_out);
/// ```
pub(crate) fn xls_function_get_type(
    _package_write_guard: &RwLockWriteGuard<IrPackagePtr>,
    function: *const CIrFunction,
) -> Result<IrFunctionType, XlsynthError> {
    unsafe {
        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let mut xls_fn_type_out: *mut CIrFunctionType = std::ptr::null_mut();
        let success =
            xlsynth_sys::xls_function_get_type(function, &mut error_out, &mut xls_fn_type_out);
        if success {
            let ir_type = IrFunctionType {
                ptr: xls_fn_type_out,
            };
            return Ok(ir_type);
        }
        let error_out_str: String = c_str_to_rust(error_out);
        return Err(XlsynthError(error_out_str));
    }
}

/// Bindings for the C API function:
/// ```c
/// bool xls_function_type_to_string(struct xls_function_type* xls_function_type,
/// char** error_out, char** string_out);
/// ```
pub(crate) fn xls_function_type_to_string(
    t: *const CIrFunctionType,
) -> Result<String, XlsynthError> {
    unsafe {
        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let mut c_str_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let success = xlsynth_sys::xls_function_type_to_string(t, &mut error_out, &mut c_str_out);
        if success {
            return Ok(c_str_to_rust(c_str_out));
        }
        let error_out_str: String = c_str_to_rust(error_out);
        return Err(XlsynthError(error_out_str));
    }
}

pub(crate) fn xls_function_get_name(function: *const CIrFunction) -> Result<String, XlsynthError> {
    unsafe {
        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let mut c_str_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let success = xlsynth_sys::xls_function_get_name(function, &mut error_out, &mut c_str_out);
        if success {
            return Ok(c_str_to_rust(c_str_out));
        }
        let error_out_str: String = c_str_to_rust(error_out);
        return Err(XlsynthError(error_out_str));
    }
}

/// Bindings for the C API function:
/// ```c
/// bool xls_interpret_function(
///     struct xls_function* function, size_t argc,
///     const struct xls_value** args, char** error_out,
///     struct xls_value** result_out);
/// ```
pub(crate) fn xls_interpret_function(
    _package_guard: &RwLockReadGuard<IrPackagePtr>,
    function: *const CIrFunction,
    args: &[IrValue],
) -> Result<IrValue, XlsynthError> {
    unsafe {
        let args_ptrs: Vec<*const CIrValue> =
            args.iter().map(|v| -> *const CIrValue { v.ptr }).collect();
        let argc = args_ptrs.len();
        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let mut result_out: *mut CIrValue = std::ptr::null_mut();
        let success = xlsynth_sys::xls_interpret_function(
            function,
            argc,
            args_ptrs.as_ptr(),
            &mut error_out,
            &mut result_out,
        );
        if success {
            let result = IrValue { ptr: result_out };
            return Ok(result);
        }
        let error_out_str: String = c_str_to_rust(error_out);
        return Err(XlsynthError(error_out_str));
    }
}

/// Binding for the C API function:
/// ```c
/// bool xls_optimize_ir(const char* ir, const char* top, char** error_out,
/// char** ir_out);
/// ```
pub(crate) fn xls_optimize_ir(ir: &str, top: &str) -> Result<String, XlsynthError> {
    unsafe {
        let ir = CString::new(ir).unwrap();
        let top = CString::new(top).unwrap();
        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let mut ir_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let success =
            xlsynth_sys::xls_optimize_ir(ir.as_ptr(), top.as_ptr(), &mut error_out, &mut ir_out);
        if success {
            return Ok(c_str_to_rust(ir_out));
        }
        let error_out_str: String = c_str_to_rust(error_out);
        return Err(XlsynthError(error_out_str));
    }
}

/// Binding for the C API function:
/// ```c
/// bool xls_mangle_dslx_name(const char* module_name, const char* function_name,
/// char** error_out, char** mangled_out);
/// ```
pub(crate) fn xls_mangle_dslx_name(
    module_name: &str,
    function_name: &str,
) -> Result<String, XlsynthError> {
    unsafe {
        let module_name = CString::new(module_name).unwrap();
        let function_name = CString::new(function_name).unwrap();
        let mut error_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let mut mangled_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let success = xlsynth_sys::xls_mangle_dslx_name(
            module_name.as_ptr(),
            function_name.as_ptr(),
            &mut error_out,
            &mut mangled_out,
        );
        if success {
            return Ok(c_str_to_rust(mangled_out));
        }
        let error_out_str: String = c_str_to_rust(error_out);
        return Err(XlsynthError(error_out_str));
    }
}

/// Binding for the C API function:
/// ```c
/// bool xls_package_to_string(const struct xls_package* p, char** string_out) {
/// ```
pub(crate) fn xls_package_to_string(p: *const CIrPackage) -> Result<String, XlsynthError> {
    unsafe {
        let mut c_str_out: *mut std::os::raw::c_char = std::ptr::null_mut();
        let success = xlsynth_sys::xls_package_to_string(p, &mut c_str_out);
        if success {
            return Ok(c_str_to_rust(c_str_out));
        }
        return Err(XlsynthError(
            "Failed to convert XLS package to string via C API".to_string(),
        ));
    }
}

pub fn convert_dslx_to_ir(dslx: &str, path: &std::path::Path) -> Result<IrPackage, XlsynthError> {
    let ir_text = xls_convert_dslx_to_ir(dslx, path, &DslxConvertOptions::default())?;
    // Get the filename as an Option<&str>
    let filename = path.file_name().and_then(|s| s.to_str());
    IrPackage::parse_ir(&ir_text, filename)
}

pub fn optimize_ir(ir: &IrPackage, top: &str) -> Result<IrPackage, XlsynthError> {
    let ir_text = xls_optimize_ir(&ir.to_string(), top)?;
    IrPackage::parse_ir(&ir_text, ir.filename())
}

pub fn mangle_dslx_name(module: &str, name: &str) -> Result<String, XlsynthError> {
    xls_mangle_dslx_name(module, name)
}

fn x_path_to_rs_filename(path: &std::path::Path) -> String {
    let mut out = path.file_stem().unwrap().to_str().unwrap().to_string();
    out.push_str(".rs");
    out
}

/// Converts a DSLX module (i.e. `.x` file) into its corresponding Rust bridge
/// code, and emits that Rust code to a corresponding filename in the `out_dir`.
pub fn x_path_to_rs_bridge(
    relpath: &str,
    out_dir: &std::path::Path,
    root_dir: &std::path::Path,
) -> std::path::PathBuf {
    let mut import_data = dslx::ImportData::new(None, &[root_dir]);
    let path = std::path::PathBuf::from(relpath);
    let dslx =
        std::fs::read_to_string(&path).expect(&format!("DSLX file should be readable: {path:?}"));

    // Generate the bridge code.
    let mut builder = rust_bridge_builder::RustBridgeBuilder::new();
    dslx_bridge::convert_leaf_module(&mut import_data, &dslx, &path, &mut builder)
        .expect("expect bridge building success");
    let rs = builder.build();

    // Write this out to the corresponding Rust filename in the `out_dir`.
    let out_path = out_dir.join(x_path_to_rs_filename(&path));
    std::fs::write(&out_path, rs).unwrap();
    out_path
}

// Wrapper around `x_path_to_rs_bridge` where:
//
// - the `out_dir` comes from the environment variable `OUT_DIR` which is
//   populated e.g. by `cargo` in `build.rs` execution.
// - the working directory comes from the repository root
pub fn x_path_to_rs_bridge_via_env(relpath: &str) -> std::path::PathBuf {
    let out_dir = std::env::var("OUT_DIR").expect("OUT_DIR should be set");
    let metadata = cargo_metadata::MetadataCommand::new()
        .exec()
        .expect("cargo metadata should be available");
    let root_dir = metadata.workspace_root.as_path().as_std_path();
    x_path_to_rs_bridge(relpath, std::path::Path::new(&out_dir), root_dir)
}

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

    #[test]
    fn test_convert_dslx_to_ir() {
        let ir = xls_convert_dslx_to_ir(
            "fn f(x: u32) -> u32 { x }",
            std::path::Path::new("/memfile/test_mod.x"),
            &DslxConvertOptions::default(),
        )
        .expect("ir conversion should succeed");
        assert_eq!(
            ir,
            "package test_mod

file_number 0 \"/memfile/test_mod.x\"

fn __test_mod__f(x: bits[32] id=1) -> bits[32] {
  ret x: bits[32] = param(name=x, id=1)
}
"
        );
    }

    #[test]
    fn test_parse_typed_value_garbage() {
        let e: XlsynthError = xls_parse_typed_value("asdf").expect_err("should not parse");
        assert_eq!(
            e.0,
            "INVALID_ARGUMENT: Expected token of type \"(\" @ 1:1, but found: Token(\"ident\", value=\"asdf\") @ 1:1"
        );
    }

    #[test]
    fn test_parse_typed_value_bits32_42() {
        let v: IrValue = xls_parse_typed_value("bits[32]:42").expect("should parse ok");
        assert_eq!(v.to_string(), "bits[32]:42");
    }

    #[test]
    fn test_xls_format_preference_from_string() {
        let fmt: XlsFormatPreference = xls_format_preference_from_string("default")
            .expect("should convert to format preference");
        assert_eq!(fmt, 0);

        let fmt: XlsFormatPreference =
            xls_format_preference_from_string("hex").expect("should convert to format preference");
        assert_eq!(fmt, 4);

        xls_format_preference_from_string("blah")
            .expect_err("should not convert to format preference");
    }
}