xlsynth 0.65.0

Accelerated Hardware Synthesis (XLS/XLSynth) via Rust
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
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
// SPDX-License-Identifier: Apache-2.0

//! Builder that creates SystemVerilog type definitions from DSLX type
//! definitions.

use std::collections::HashSet;

use crate::{
    IrValue, XlsynthError, dslx,
    dslx_bridge::{BridgeBuilder, StructMemberData},
    ir_value::IrFormatPreference,
};

/// The suffix used when we typedef logic to a type name.
const LOGIC_ALIAS_SUFFIX: &str = "_t";

/// The suffix used when we typedef an enum to a type name.
const ENUM_ALIAS_SUFFIX: &str = "_t";

/// The suffix used when we typedef a struct to a type name.
const STRUCT_ALIAS_SUFFIX: &str = "_t";

/// The suffix used when we typedef a type alias to a type name.
const TYPE_ALIAS_SUFFIX: &str = "_t";

/// Selects how DSLX enum case symbols are emitted into the generated SV
/// namespace.
///
/// This only affects enum member identifiers (for example `Read` vs
/// `OpType_Read`); it does not change the emitted enum typedef name. The bridge
/// still applies the existing case-normalization rules to each component before
/// combining them.
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[cfg_attr(feature = "clap", value(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SvEnumCaseNamingPolicy {
    /// Emit only the normalized case name (for example `Read`).
    Unqualified,
    /// Emit `<NormalizedEnumName>_<NormalizedCaseName>` (for example
    /// `OpType_Read`).
    EnumQualified,
}

/// Selects how DSLX struct members are ordered in emitted SV packed struct
/// declarations.
///
/// In SystemVerilog `typedef struct packed`, member declaration order defines
/// the packed bit layout. Choosing [`SvStructFieldOrderingPolicy::Reversed`]
/// therefore changes the generated wire contract, not just the textual output
/// order. This does not change the DSLX-side type model or the enum naming
/// policy.
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[cfg_attr(feature = "clap", value(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SvStructFieldOrderingPolicy {
    /// Emit members in the same order they are declared in DSLX.
    AsDeclared,
    /// Emit members in the reverse of their DSLX declaration order, which also
    /// reverses their packed-layout positions in the generated SV.
    Reversed,
}

/// Accumulates SV type declarations for a DSLX module while enforcing a flat
/// generated-name namespace.
///
/// DSLX allows enum members from different enums to share the same case name,
/// but the generated SV emitted by this builder places those case symbols in a
/// single namespace. `defined` tracks all emitted symbols so collisions are
/// reported deterministically during generation instead of surfacing later in a
/// downstream parser or linter.
pub struct SvBridgeBuilder {
    lines: Vec<String>,
    /// We keep a record of all the names we define flat within the namespace so
    /// that we can detect and report collisions at generation time instead
    /// of in a subsequent linting step.
    defined: HashSet<String>,
    /// Controls how enum member symbols are derived before collision checks.
    enum_case_naming_policy: SvEnumCaseNamingPolicy,
    /// Controls the emitted order of packed struct members.
    struct_field_ordering_policy: SvStructFieldOrderingPolicy,
}

fn camel_to_snake(name: &str) -> String {
    let mut snake = String::new();
    for (i, c) in name.chars().enumerate() {
        if c.is_uppercase() && i > 0 {
            snake.push('_');
        }
        snake.push(c.to_ascii_lowercase());
    }
    snake
}

fn screaming_snake_to_upper_camel(name: &str) -> String {
    name.split('_')
        .filter(|s| !s.is_empty())
        .map(|s| {
            let mut chars = s.chars();
            chars
                .next()
                .map(|c| c.to_ascii_uppercase().to_string())
                .unwrap_or_default()
                + &chars.as_str().to_ascii_lowercase()
        })
        .collect()
}

fn is_screaming_snake_case(name: &str) -> bool {
    name.chars().all(|c| {
        if c.is_ascii_alphabetic() {
            c.is_ascii_uppercase()
        } else {
            true
        }
    })
}

/// Formats an evaluated bits value as a width- and signedness-preserving SV
/// literal.
fn format_bits_constant(
    ir_value: &IrValue,
    is_signed: bool,
    bit_count: usize,
) -> Result<String, XlsynthError> {
    let hex_prefix = if is_signed { "sh" } else { "h" };
    let hex_digits = ir_value
        .to_string_fmt_no_prefix(IrFormatPreference::ZeroPaddedHex)?
        .replace('_', "");
    Ok(format!("{bit_count}'{hex_prefix}{hex_digits}"))
}

/// Formats assignment-pattern entries with one indented entry per line.
fn format_assignment_pattern(entries: &[String], indent_level: usize) -> String {
    if entries.is_empty() {
        return "'{}".to_string();
    }

    let entry_indent = "    ".repeat(indent_level + 1);
    let closing_indent = "    ".repeat(indent_level);
    let lines = entries
        .iter()
        .map(|entry| format!("{entry_indent}{entry}"))
        .collect::<Vec<_>>()
        .join(",\n");
    format!("'{{\n{lines}\n{closing_indent}}}")
}

fn make_bit_span_suffix(bit_count: usize) -> String {
    // More study required on how compatible
    assert!(bit_count > 0);
    if bit_count == 1 {
        "".to_string()
    } else {
        format!(" [{}:0]", bit_count - 1)
    }
}

/// Note: this only supports a very simple package naming and associated
/// hierarchy for the time being.
fn import_to_pkg_name(import: &dslx::Import) -> String {
    let subject = import.get_subject();
    assert!(
        !subject.is_empty(),
        "import subjects always have at least one token"
    );
    format!("{}_sv_pkg", subject.last().unwrap())
}

/// Converts a DSLX enum name in CamelCase to a SystemVerilog enum name in
/// snake_case with an _t suffix i.e. `MyEnum` -> `my_enum_t`
fn enum_name_to_sv(dslx_name: &str) -> String {
    format!("{}{}", camel_to_snake(dslx_name), ENUM_ALIAS_SUFFIX)
}

/// Converts a DSLX struct name in CamelCase to a SystemVerilog struct name
/// in snake_case with a _t suffix
fn struct_name_to_sv(dslx_name: &str) -> String {
    format!("{}{}", camel_to_snake(dslx_name), STRUCT_ALIAS_SUFFIX)
}

/// Returns the extern type reference if the type annotation is an extern type.
fn get_extern_type_ref(
    type_annotation: &dslx::TypeAnnotation,
    concrete_ty: &dslx::Type,
) -> Option<String> {
    if let Some(type_ref_type_annotation) = type_annotation.to_type_ref_type_annotation() {
        let type_ref = type_ref_type_annotation.get_type_ref();

        // Inspect whether the type definition is a colon-reference where the subject is
        // another module.
        let type_definition: dslx::TypeDefinition = type_ref.get_type_definition();
        if let Some(colon_ref) = type_definition.to_colon_ref()
            && let Some(import) = colon_ref.resolve_import_subject()
        {
            // It is a reference to a type defined in another module -- refer to its in
            // its external module.
            let pkg_name = import_to_pkg_name(&import);
            let extern_ref =
                convert_extern_type(&pkg_name, Some(&colon_ref.get_attr()), concrete_ty, None)
                    .unwrap();
            return Some(extern_ref);
        }
    }
    None
}

/// A version of `dslx::Type`'s meaningful contents that we can match on in
/// match expressions.
enum MatchableDslxType {
    BitsLike {
        is_signed: bool,
        bit_count: usize,
    },
    Enum(dslx::EnumDef),
    Struct(dslx::StructDef),
    Array {
        element_ty: Box<DslxType>,
        size: usize,
    },
}

struct DslxType {
    ty: dslx::Type,
    matchable_ty: MatchableDslxType,
}

/// Converts a DSLX type into a Rust-matchable version.
fn dslx_type_to_matchable(ty: &dslx::Type) -> Result<DslxType, XlsynthError> {
    if let Some((is_signed, bit_count)) = ty.is_bits_like() {
        Ok(DslxType {
            ty: ty.clone(),
            matchable_ty: MatchableDslxType::BitsLike {
                is_signed,
                bit_count,
            },
        })
    } else if ty.is_enum() {
        Ok(DslxType {
            ty: ty.clone(),
            matchable_ty: MatchableDslxType::Enum(ty.get_enum_def().unwrap()),
        })
    } else if ty.is_struct() {
        Ok(DslxType {
            ty: ty.clone(),
            matchable_ty: MatchableDslxType::Struct(ty.get_struct_def().unwrap()),
        })
    } else if ty.is_array() {
        Ok(DslxType {
            ty: ty.clone(),
            matchable_ty: MatchableDslxType::Array {
                element_ty: Box::new(dslx_type_to_matchable(&ty.get_array_element_type())?),
                size: ty.get_array_size(),
            },
        })
    } else {
        Err(XlsynthError(format!(
            "Unsupported type for conversion from DSLX to matchable type: {:?}",
            ty.to_string()?
        )))
    }
}

/// Helper for making the packed array representation string suffix -- this
/// comes after the type name.
fn make_array_span_suffix(array_sizes: Vec<usize>) -> String {
    let mut suffix_parts = Vec::new();
    for array_size in array_sizes.iter() {
        suffix_parts.push(format!(" [{}:0]", array_size - 1));
    }
    suffix_parts.join("")
}

// Converts a DSLX type into a SystemVerilog type string.
fn convert_type(ty: &dslx::Type, array_sizes: Option<Vec<usize>>) -> Result<String, XlsynthError> {
    let matchable_ty = dslx_type_to_matchable(ty)?;

    match matchable_ty.matchable_ty {
        MatchableDslxType::BitsLike {
            is_signed,
            bit_count,
        } => {
            let leader = if is_signed { "logic signed" } else { "logic" };
            Ok(format!(
                "{}{}{}",
                leader,
                make_array_span_suffix(array_sizes.unwrap_or_default()),
                make_bit_span_suffix(bit_count)
            ))
        }
        MatchableDslxType::Enum(enum_def) => Ok(format!(
            "{}{}",
            enum_name_to_sv(&enum_def.get_identifier()),
            make_array_span_suffix(array_sizes.unwrap_or_default())
        )),
        MatchableDslxType::Struct(struct_def) => Ok(format!(
            "{}{}",
            struct_name_to_sv(&struct_def.get_identifier()),
            make_array_span_suffix(array_sizes.unwrap_or_default())
        )),
        MatchableDslxType::Array { element_ty, size } => {
            let mut array_sizes = array_sizes.unwrap_or_default();
            array_sizes.push(size);
            convert_type(&element_ty.ty, Some(array_sizes))
        }
    }
}

/// Converts a DSLX type -- one that was determined to be an extern type
/// reference -- into a SystemVerilog type string.
fn convert_extern_type(
    pkg_name: &str,
    attr: Option<&str>,
    ty: &dslx::Type,
    array_sizes: Option<Vec<usize>>,
) -> Result<String, XlsynthError> {
    let matchable_ty = dslx_type_to_matchable(ty)?;
    match matchable_ty.matchable_ty {
        MatchableDslxType::BitsLike { .. } => {
            if let Some(attr) = attr {
                let attr_sv = format!("{}{}", camel_to_snake(attr), LOGIC_ALIAS_SUFFIX);
                Ok(format!("{pkg_name}::{attr_sv}"))
            } else {
                convert_type(ty, array_sizes)
            }
        }
        MatchableDslxType::Enum(enum_def) => Ok(format!(
            "{pkg_name}::{ty_name}",
            ty_name = enum_name_to_sv(&enum_def.get_identifier())
        )),
        MatchableDslxType::Struct(struct_def) => Ok(format!(
            "{pkg_name}::{ty_name}",
            ty_name = struct_name_to_sv(&struct_def.get_identifier())
        )),
        MatchableDslxType::Array { element_ty, size } => {
            let mut array_sizes = array_sizes.unwrap_or_default();
            array_sizes.push(size);
            Ok(convert_extern_type(
                pkg_name,
                None,
                &element_ty.ty,
                Some(array_sizes),
            )?)
        }
    }
}

impl SvBridgeBuilder {
    /// Creates a builder with explicit enum and struct emission policies.
    pub fn with_policies(
        enum_case_naming_policy: SvEnumCaseNamingPolicy,
        struct_field_ordering_policy: SvStructFieldOrderingPolicy,
    ) -> Self {
        Self {
            lines: vec![],
            defined: HashSet::new(),
            enum_case_naming_policy,
            struct_field_ordering_policy,
        }
    }

    /// Creates a builder with an explicit policy for enum member symbol
    /// naming.
    ///
    /// Callers must choose a policy at construction time so the generated SV
    /// enum member spelling is explicit at each call site. Using
    /// [`SvEnumCaseNamingPolicy::Unqualified`] keeps the historical output
    /// shape, while [`SvEnumCaseNamingPolicy::EnumQualified`] prefixes each
    /// case with the containing enum name to avoid cross-enum collisions in
    /// the flat generated SV namespace.
    pub fn with_enum_case_policy(enum_case_naming_policy: SvEnumCaseNamingPolicy) -> Self {
        Self::with_policies(
            enum_case_naming_policy,
            SvStructFieldOrderingPolicy::AsDeclared,
        )
    }

    /// Returns the generated SV source accumulated so far.
    ///
    /// Callers typically invoke this after `dslx_bridge` conversion has emitted
    /// all reachable type definitions into the builder.
    pub fn build(&self) -> String {
        self.lines.join("\n")
    }

    fn define_or_error(&mut self, name: &str, ctx: &str) -> Result<(), XlsynthError> {
        let inserted = self.defined.insert(name.to_string());
        if inserted {
            Ok(())
        } else {
            Err(XlsynthError(format!(
                "Building SV; name collision detected for SV name in generated module namespace: `{name}` context: {ctx}"
            )))
        }
    }

    /// Normalizes one enum-name or case-name component using the existing case
    /// conversion rules.
    fn enum_case_name_component_to_sv(dslx_name: &str) -> String {
        if is_screaming_snake_case(dslx_name) {
            screaming_snake_to_upper_camel(dslx_name)
        } else {
            dslx_name.to_string()
        }
    }

    /// Computes the emitted SV enum member symbol under the active naming
    /// policy.
    ///
    /// Both `enum_name` and `member_name` are normalized with the same helper
    /// so the `EnumQualified` policy composes exactly with the historical
    /// `Unqualified` formatting behavior.
    fn enum_member_name_to_sv(&self, enum_name: &str, member_name: &str) -> String {
        match self.enum_case_naming_policy {
            SvEnumCaseNamingPolicy::Unqualified => {
                Self::enum_case_name_component_to_sv(member_name)
            }
            SvEnumCaseNamingPolicy::EnumQualified => format!(
                "{}_{}",
                Self::enum_case_name_component_to_sv(enum_name),
                Self::enum_case_name_component_to_sv(member_name)
            ),
        }
    }

    fn struct_member_line(member: &StructMemberData) -> Result<String, XlsynthError> {
        let member_name = &member.name;

        // Note: this is the type that type inference determined the member is; i.e. it
        // will be something like `BitsType`, `StructType`, `ArrayType`,
        // etc.
        let member_concrete_ty = &member.concrete_type;

        let member_annotated_ty = &member.type_annotation;

        if let Some(extern_ref) = get_extern_type_ref(member_annotated_ty, member_concrete_ty) {
            Ok(format!("    {extern_ref} {member_name};"))
        } else if let Some(type_ref_type_annotation) =
            member_annotated_ty.to_type_ref_type_annotation()
        {
            let type_ref = type_ref_type_annotation.get_type_ref();
            let type_def = type_ref.get_type_definition();
            if let Some(type_alias) = type_def.to_type_alias() {
                let sv_type_name = struct_name_to_sv(&type_alias.get_identifier());
                Ok(format!("    {sv_type_name} {member_name};"))
            } else {
                let member_sv_ty = convert_type(member_concrete_ty, None)?;
                Ok(format!("    {member_sv_ty} {member_name};"))
            }
        } else {
            let member_sv_ty = convert_type(member_concrete_ty, None)?;
            Ok(format!("    {member_sv_ty} {member_name};"))
        }
    }

    /// Recursively renders an evaluated DSLX value as a typed SV initializer.
    fn format_constant_value(
        &self,
        ty: &dslx::Type,
        ir_value: &IrValue,
        type_annotation: Option<&dslx::TypeAnnotation>,
        indent_level: usize,
    ) -> Result<String, XlsynthError> {
        let matchable_ty = dslx_type_to_matchable(ty)?;
        match matchable_ty.matchable_ty {
            MatchableDslxType::BitsLike {
                is_signed,
                bit_count,
            } => format_bits_constant(ir_value, is_signed, bit_count),
            MatchableDslxType::Enum(enum_def) => {
                let enum_type = type_annotation
                    .and_then(|annotation| get_extern_type_ref(annotation, ty))
                    .unwrap_or_else(|| enum_name_to_sv(&enum_def.get_identifier()));
                let literal = format_bits_constant(ir_value, false, ir_value.bit_count()?)?;
                Ok(format!("{enum_type}'({literal})"))
            }
            MatchableDslxType::Struct(struct_def) => {
                let member_count = struct_def.get_member_count();
                let value_count = ir_value.get_element_count()?;
                if member_count != value_count {
                    return Err(XlsynthError(format!(
                        "DSLX struct constant `{}` has {member_count} fields but its evaluated value has {value_count} elements",
                        struct_def.get_identifier()
                    )));
                }

                let mut fields = Vec::with_capacity(member_count);
                for index in 0..member_count {
                    let member = struct_def.get_member(index);
                    let member_type = ty.get_struct_member_type(index);
                    let member_annotation = member.get_type();
                    let member_value = ir_value.get_element(index)?;
                    let initializer = self.format_constant_value(
                        &member_type,
                        &member_value,
                        Some(&member_annotation),
                        indent_level + 1,
                    )?;
                    fields.push(format!("{}: {initializer}", member.get_name()));
                }
                Ok(format_assignment_pattern(&fields, indent_level))
            }
            MatchableDslxType::Array { element_ty, size } => {
                let value_count = ir_value.get_element_count()?;
                if size != value_count {
                    return Err(XlsynthError(format!(
                        "DSLX array constant has {size} elements in its type but {value_count} evaluated values"
                    )));
                }

                let element_annotation = type_annotation
                    .and_then(dslx::TypeAnnotation::to_array_type_annotation)
                    .map(|annotation| annotation.get_element_type());
                let mut elements = Vec::with_capacity(size);
                for index in 0..size {
                    let element_value = ir_value.get_element(index)?;
                    let initializer = self.format_constant_value(
                        &element_ty.ty,
                        &element_value,
                        element_annotation.as_ref(),
                        indent_level + 1,
                    )?;
                    // Explicit indices preserve DSLX indexing even though SV
                    // packed arrays are declared with descending ranges.
                    elements.push(format!("{index}: {initializer}"));
                }
                Ok(format_assignment_pattern(&elements, indent_level))
            }
        }
    }
}

impl BridgeBuilder for SvBridgeBuilder {
    fn start_module(&mut self, _module_name: &str) -> Result<(), XlsynthError> {
        Ok(())
    }

    fn end_module(&mut self, _module_name: &str) -> Result<(), XlsynthError> {
        Ok(())
    }

    fn add_enum_def(
        &mut self,
        dslx_name: &str,
        is_signed: bool,
        underlying_bit_count: usize,
        members: &[(String, IrValue)],
    ) -> Result<(), XlsynthError> {
        let mut lines = vec![];
        let sv_name = enum_name_to_sv(dslx_name);
        lines.push(format!(
            "typedef enum logic{} {{",
            make_bit_span_suffix(underlying_bit_count)
        ));
        let ctx = format!("DSLX enum `{dslx_name}`");
        for (i, (member_name, member_value)) in members.iter().enumerate() {
            let format = if is_signed {
                IrFormatPreference::SignedDecimal
            } else {
                IrFormatPreference::UnsignedDecimal
            };
            let member_value_str = member_value.to_string_fmt(format)?;
            let digits = member_value_str.split(':').nth(1).expect("split success");
            let maybe_comma = if i < members.len() - 1 { "," } else { "" };
            let sv_member_name = self.enum_member_name_to_sv(dslx_name, member_name);
            self.define_or_error(&sv_member_name, &ctx)?;
            lines.push(format!(
                "    {sv_member_name} = {underlying_bit_count}'d{digits}{maybe_comma}"
            ));
        }
        lines.push(format!("}} {sv_name};\n"));
        self.lines.push(lines.join("\n"));
        Ok(())
    }

    fn add_struct_def(
        &mut self,
        dslx_name: &str,
        members: &[StructMemberData],
    ) -> Result<(), XlsynthError> {
        let mut lines = vec![];
        lines.push("typedef struct packed {".to_string());
        let member_lines =
            if self.struct_field_ordering_policy == SvStructFieldOrderingPolicy::AsDeclared {
                members
                    .iter()
                    .map(Self::struct_member_line)
                    .collect::<Result<Vec<_>, _>>()?
            } else {
                members
                    .iter()
                    .rev()
                    .map(Self::struct_member_line)
                    .collect::<Result<Vec<_>, _>>()?
            };
        for member_line in member_lines {
            lines.push(member_line);
        }
        lines.push(format!("}} {};\n", struct_name_to_sv(dslx_name)));
        self.lines.push(lines.join("\n"));
        Ok(())
    }

    fn add_alias(
        &mut self,
        dslx_name: &str,
        type_annotation: &dslx::TypeAnnotation,
        ty: &dslx::Type,
    ) -> Result<(), XlsynthError> {
        let sv_name = format!("{}{}", camel_to_snake(dslx_name), TYPE_ALIAS_SUFFIX);
        if let Some(extern_ref) = get_extern_type_ref(type_annotation, ty) {
            self.lines
                .push(format!("typedef {extern_ref} {sv_name};\n"));
        } else {
            let sv_ty = convert_type(ty, None)?;
            self.lines.push(format!("typedef {sv_ty} {sv_name};\n"));
        }
        Ok(())
    }

    fn add_constant(
        &mut self,
        name: &str,
        _constant_def: &dslx::ConstantDef,
        ty: &dslx::Type,
        ir_value: &IrValue,
    ) -> Result<(), XlsynthError> {
        let sv_name = if is_screaming_snake_case(name) {
            screaming_snake_to_upper_camel(name)
        } else {
            name.to_string()
        };
        let declaration = if let Some((is_signed, bit_count)) = ty.is_bits_like() {
            let value_str = format_bits_constant(ir_value, is_signed, bit_count)?;
            Some(format!(
                "localparam bit {signedness} [{}:0] {name} = {value_str};\n",
                bit_count - 1,
                name = sv_name,
                signedness = if is_signed { "signed" } else { "unsigned" }
            ))
        } else if dslx_type_to_matchable(ty).is_ok() {
            let sv_type = convert_type(ty, None)?;
            let initializer = self.format_constant_value(ty, ir_value, None, 0)?;
            Some(format!("localparam {sv_type} {sv_name} = {initializer};\n"))
        } else {
            log::warn!("Unsupported constant type: {ir_value:?}");
            None
        };

        if let Some(declaration) = declaration {
            let ctx = format!("DSLX constant `{name}`");
            self.define_or_error(&sv_name, &ctx)?;
            self.lines.push(declaration);
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use crate::dslx_bridge::{convert_imported_module, convert_leaf_module};

    use super::*;

    /// Reusable scaffolding for converting a single DSLX module contents to SV.
    fn simple_convert_for_test(dslx: &str) -> Result<String, XlsynthError> {
        simple_convert_for_test_with_policy(dslx, SvEnumCaseNamingPolicy::Unqualified)
    }

    fn simple_convert_for_test_with_policy(
        dslx: &str,
        enum_case_naming_policy: SvEnumCaseNamingPolicy,
    ) -> Result<String, XlsynthError> {
        simple_convert_for_test_with_policies(
            dslx,
            enum_case_naming_policy,
            SvStructFieldOrderingPolicy::AsDeclared,
        )
    }

    fn simple_convert_for_test_with_policies(
        dslx: &str,
        enum_case_naming_policy: SvEnumCaseNamingPolicy,
        struct_field_ordering_policy: SvStructFieldOrderingPolicy,
    ) -> Result<String, XlsynthError> {
        let mut import_data = dslx::ImportData::default();
        let path = std::path::PathBuf::from_str("/memfile/my_module.x").unwrap();
        let mut builder =
            SvBridgeBuilder::with_policies(enum_case_naming_policy, struct_field_ordering_policy);
        convert_leaf_module(&mut import_data, dslx, &path, &mut builder)?;
        Ok(builder.build())
    }

    #[test]
    fn test_type_alias_of_u64_array() {
        let dslx = "type MyType = u64[4];";
        let sv = simple_convert_for_test(dslx).unwrap();
        assert_eq!(sv, "typedef logic [3:0] [63:0] my_type_t;\n");
        xlsynth_test_helpers::assert_valid_sv(&sv);
    }

    /// Demonstrates that we do not change the case of enum members that are
    /// defined as UpperCamelCase in DSLX.
    #[test]
    fn test_convert_leaf_module_enum_def_only() {
        let dslx = r#"
        enum OpType : u2 { Read = 0, Write = 1 }
        "#;
        let sv = simple_convert_for_test(dslx).unwrap();
        xlsynth_test_helpers::assert_valid_sv(&sv);
        assert_eq!(
            sv,
            r#"typedef enum logic [1:0] {
    Read = 2'd0,
    Write = 2'd1
} op_type_t;
"#
        );
    }

    /// Demonstrates that we convert enums that are defined as
    /// SCREAMING_SNAKE_CASE in DSLX into enums defined with UpperCamelCase
    /// in SystemVerilog.
    #[test]
    fn test_convert_leaf_module_enum_def_camel_case() {
        let dslx = r#"
        enum MyEnum : u2 { MY_FIRST_VALUE = 0, MY_SECOND_VALUE = 1 }
        "#;
        let sv = simple_convert_for_test(dslx).unwrap();
        xlsynth_test_helpers::assert_valid_sv(&sv);
        assert_eq!(
            sv,
            r#"typedef enum logic [1:0] {
    MyFirstValue = 2'd0,
    MySecondValue = 2'd1
} my_enum_t;
"#
        );
    }

    // Verifies: EnumQualified prefixes normalized enum names onto normalized
    // case names in emitted SV.
    // Catches: Regressions where enum-qualified mode reuses the unqualified
    // symbol path or skips normalization.
    #[test]
    fn test_convert_leaf_module_enum_def_enum_qualified_case_names() {
        let dslx = r#"
        enum MyEnum : u2 { MY_FIRST_VALUE = 0, MY_SECOND_VALUE = 1 }
        "#;
        let sv = simple_convert_for_test_with_policy(dslx, SvEnumCaseNamingPolicy::EnumQualified)
            .unwrap();
        xlsynth_test_helpers::assert_valid_sv(&sv);
        assert_eq!(
            sv,
            r#"typedef enum logic [1:0] {
    MyEnum_MyFirstValue = 2'd0,
    MyEnum_MySecondValue = 2'd1
} my_enum_t;
"#
        );
    }

    #[test]
    fn test_convert_leaf_module_struct_def_only() {
        let dslx = r#"
        struct MyStruct {
            byte_array: u8[10],
            word_data: u16,
        }
        "#;
        let sv = simple_convert_for_test(dslx).unwrap();
        assert_eq!(
            sv,
            r#"typedef struct packed {
    logic [9:0] [7:0] byte_array;
    logic [15:0] word_data;
} my_struct_t;
"#
        );
    }

    #[test]
    fn test_convert_leaf_module_struct_def_reversed_field_order() {
        let dslx = r#"
        struct MyStruct {
            byte_array: u8[10],
            word_data: u16,
        }
        "#;
        let sv = simple_convert_for_test_with_policies(
            dslx,
            SvEnumCaseNamingPolicy::Unqualified,
            SvStructFieldOrderingPolicy::Reversed,
        )
        .unwrap();
        assert_eq!(
            sv,
            r#"typedef struct packed {
    logic [15:0] word_data;
    logic [9:0] [7:0] byte_array;
} my_struct_t;
"#
        );
    }

    /// Verifies that struct constants retain their nominal type and named
    /// fields.
    #[test]
    fn test_convert_leaf_module_struct_constant() {
        let dslx = r#"
struct Sample {
    channel: u32,
    value: u32,
}

const DEFAULT_SAMPLE = Sample { channel: 16, value: 7 };
"#;
        let sv = simple_convert_for_test(dslx).unwrap();
        assert_eq!(
            sv,
            r#"typedef struct packed {
    logic [31:0] channel;
    logic [31:0] value;
} sample_t;

localparam sample_t DefaultSample = '{
    channel: 32'h00000010,
    value: 32'h00000007
};
"#
        );
        xlsynth_test_helpers::assert_valid_sv(&sv);
    }

    /// Verifies nested structs, signed members, Boolean members, and wide
    /// values.
    #[test]
    fn test_convert_leaf_module_nested_struct_constant() {
        let dslx = r#"
struct Inner {
    delta: s8,
    enabled: bool,
}

struct Outer {
    inner: Inner,
    wide: uN[129],
}

const DEFAULT_OUTER = Outer {
    inner: Inner { delta: s8:-3, enabled: true },
    wide: uN[129]:0x100000000000000000000000000000000,
};
"#;
        let sv = simple_convert_for_test(dslx).unwrap();
        assert_eq!(
            sv,
            r#"typedef struct packed {
    logic signed [7:0] delta;
    logic enabled;
} inner_t;

typedef struct packed {
    inner_t inner;
    logic [128:0] wide;
} outer_t;

localparam outer_t DefaultOuter = '{
    inner: '{
        delta: 8'shfd,
        enabled: 1'h1
    },
    wide: 129'h100000000000000000000000000000000
};
"#
        );
        xlsynth_test_helpers::assert_valid_sv(&sv);
    }

    /// Verifies that indexed array patterns preserve DSLX array element
    /// indices.
    #[test]
    fn test_convert_leaf_module_array_of_nested_struct_constants() {
        let dslx = r#"
struct Sample {
    channel: u32,
    value: u32,
}

struct Reading {
    sample: Sample,
    timestamp: u32,
}

struct Report {
    first: Reading,
    second: Reading,
}

const REPORTS = [
    Report {
        first: Reading { sample: Sample { channel: 16, value: 7 }, timestamp: 0 },
        second: Reading { sample: Sample { channel: 2, value: 8 }, timestamp: 112 },
    },
    Report {
        first: Reading { sample: Sample { channel: 16, value: 6 }, timestamp: 0 },
        second: Reading { sample: Sample { channel: 4, value: 8 }, timestamp: 96 },
    },
];
"#;
        let sv = simple_convert_for_test(dslx).unwrap();
        assert_eq!(
            sv,
            r#"typedef struct packed {
    logic [31:0] channel;
    logic [31:0] value;
} sample_t;

typedef struct packed {
    sample_t sample;
    logic [31:0] timestamp;
} reading_t;

typedef struct packed {
    reading_t first;
    reading_t second;
} report_t;

localparam report_t [1:0] Reports = '{
    0: '{
        first: '{
            sample: '{
                channel: 32'h00000010,
                value: 32'h00000007
            },
            timestamp: 32'h00000000
        },
        second: '{
            sample: '{
                channel: 32'h00000002,
                value: 32'h00000008
            },
            timestamp: 32'h00000070
        }
    },
    1: '{
        first: '{
            sample: '{
                channel: 32'h00000010,
                value: 32'h00000006
            },
            timestamp: 32'h00000000
        },
        second: '{
            sample: '{
                channel: 32'h00000004,
                value: 32'h00000008
            },
            timestamp: 32'h00000060
        }
    }
};
"#
        );
        xlsynth_test_helpers::assert_valid_sv(&sv);
    }

    /// Verifies that every packed dimension keeps its DSLX element indices.
    #[test]
    fn test_convert_leaf_module_multidimensional_array_constant() {
        let dslx = "const VALUES = u8[2][2]:[[1, 2], [3, 4]];";
        let sv = simple_convert_for_test(dslx).unwrap();
        assert_eq!(
            sv,
            r#"localparam logic [1:0] [1:0] [7:0] Values = '{
    0: '{
        0: 8'h01,
        1: 8'h02
    },
    1: '{
        0: 8'h03,
        1: 8'h04
    }
};
"#
        );
        xlsynth_test_helpers::assert_valid_sv(&sv);
    }

    /// Verifies typed enum casts for standalone and struct-member constants.
    #[test]
    fn test_convert_leaf_module_enum_constants() {
        let dslx = r#"
enum State : u2 {
    IDLE = 0,
    ACTIVE = 1,
}

const DEFAULT_STATE = State::ACTIVE;

struct Record {
    state: State,
}

const DEFAULT_RECORD = Record { state: State::ACTIVE };
"#;
        let sv = simple_convert_for_test(dslx).unwrap();
        assert_eq!(
            sv,
            r#"typedef enum logic [1:0] {
    Idle = 2'd0,
    Active = 2'd1
} state_t;

localparam state_t DefaultState = state_t'(2'h1);

typedef struct packed {
    state_t state;
} record_t;

localparam record_t DefaultRecord = '{
    state: state_t'(2'h1)
};
"#
        );
        xlsynth_test_helpers::assert_valid_sv(&sv);
    }

    /// Verifies named struct fields stay correct when packed layout is
    /// reversed.
    #[test]
    fn test_convert_leaf_module_struct_constant_reversed_field_order() {
        let dslx = r#"
struct Sample {
    channel: u8,
    value: u16,
}

const DEFAULT_SAMPLE = Sample { channel: 16, value: 7 };
"#;
        let sv = simple_convert_for_test_with_policies(
            dslx,
            SvEnumCaseNamingPolicy::Unqualified,
            SvStructFieldOrderingPolicy::Reversed,
        )
        .unwrap();
        assert_eq!(
            sv,
            r#"typedef struct packed {
    logic [15:0] value;
    logic [7:0] channel;
} sample_t;

localparam sample_t DefaultSample = '{
    channel: 8'h10,
    value: 16'h0007
};
"#
        );
        xlsynth_test_helpers::assert_valid_sv(&sv);
    }

    /// Verifies unsupported tuple constants remain ignored for compatibility.
    #[test]
    fn test_convert_leaf_module_tuple_constants_remain_unsupported() {
        let dslx = r#"
const PAIR = (u8:1, u16:2);
const PAIRS = [(u8:1, u16:2), (u8:3, u16:4)];
"#;
        assert_eq!(simple_convert_for_test(dslx).unwrap(), "");
    }

    #[test]
    fn test_convert_leaf_module_type_alias_to_bits_type_only() {
        let dslx = "type MyType = u8;";
        let sv = simple_convert_for_test(dslx).unwrap();
        assert_eq!(sv, "typedef logic [7:0] my_type_t;\n");
        xlsynth_test_helpers::assert_valid_sv(&sv);
    }

    /// Demonstrates that we get an error when we attempt to emit two enums who
    /// have the same member name -- while this is acceptable in DSLX the
    /// fact we flatten the enum names into a single namespace in SV means
    /// we have an error to flag, in which case we currently expect
    /// user correction.
    #[test]
    fn test_convert_leaf_module_enum_defs_with_collision() {
        let dslx = "enum MyFirstEnum : u1 { A = 0, B = 1 }
        enum MySecondEnum: u3 { A = 3, B = 4 }";
        let result = simple_convert_for_test(dslx);
        // We expect this caused a collision error on `A`.
        let err = result.expect_err("expect collision");
        assert!(err.to_string().contains("name collision detected for SV name in generated module namespace: `A` context: DSLX enum `MySecondEnum`"));
    }

    /// Rejects scalar constants that collide with an emitted enum member.
    #[test]
    fn test_convert_leaf_module_scalar_constant_with_enum_member_collision() {
        let dslx = r#"
enum Status: u8 { DEFAULT_RECORD = 0 }
const DEFAULT_RECORD = u8:7;
"#;
        let err = simple_convert_for_test(dslx).expect_err("expect scalar constant collision");
        assert_eq!(
            err.0,
            "Building SV; name collision detected for SV name in generated module namespace: `DefaultRecord` context: DSLX constant `DEFAULT_RECORD`"
        );
    }

    /// Rejects aggregate constants that collide with an emitted enum member.
    #[test]
    fn test_convert_leaf_module_aggregate_constant_with_enum_member_collision() {
        let dslx = r#"
enum Status: u8 { DEFAULT_RECORD = 0 }
struct Record { value: u8 }
const DEFAULT_RECORD = Record { value: u8:7 };
"#;
        let err = simple_convert_for_test(dslx).expect_err("expect aggregate constant collision");
        assert_eq!(
            err.0,
            "Building SV; name collision detected for SV name in generated module namespace: `DefaultRecord` context: DSLX constant `DEFAULT_RECORD`"
        );
    }

    /// Rejects enum members that collide with a previously emitted constant.
    #[test]
    fn test_convert_leaf_module_enum_member_with_prior_constant_collision() {
        let dslx = r#"
const DEFAULT_RECORD = u8:7;
enum Status: u8 { DEFAULT_RECORD = 0 }
"#;
        let err = simple_convert_for_test(dslx).expect_err("expect enum member collision");
        assert_eq!(
            err.0,
            "Building SV; name collision detected for SV name in generated module namespace: `DefaultRecord` context: DSLX enum `Status`"
        );
    }

    /// Rejects distinct DSLX constant names that normalize to the same SV name.
    #[test]
    fn test_convert_leaf_module_constants_with_normalized_name_collision() {
        let dslx = r#"
const DEFAULT_RECORD = u8:7;
const DefaultRecord = u8:8;
"#;
        let err = simple_convert_for_test(dslx).expect_err("expect constant name collision");
        assert_eq!(
            err.0,
            "Building SV; name collision detected for SV name in generated module namespace: `DefaultRecord` context: DSLX constant `DefaultRecord`"
        );
    }

    /// Skipped tuple constants must not reserve names in the emitted namespace.
    #[test]
    fn test_convert_leaf_module_unsupported_constant_does_not_reserve_name() {
        let dslx = r#"
const DEFAULT_RECORD = (u8:1, u16:2);
enum Status: u8 { DEFAULT_RECORD = 0 }
"#;
        let sv = simple_convert_for_test(dslx).unwrap();
        assert_eq!(
            sv,
            r#"typedef enum logic [7:0] {
    DefaultRecord = 8'd0
} status_t;
"#
        );
        xlsynth_test_helpers::assert_valid_sv(&sv);
    }

    // Verifies: EnumQualified allows two DSLX enums to reuse member names
    // without SV symbol collisions.
    // Catches: Regressions where collision detection still sees flat
    // unqualified names under EnumQualified mode.
    #[test]
    fn test_convert_leaf_module_enum_defs_with_enum_qualified_case_names_no_collision() {
        let dslx = "enum MyFirstEnum : u1 { A = 0, B = 1 }
        enum MySecondEnum: u3 { A = 3, B = 4 }";
        let sv = simple_convert_for_test_with_policy(dslx, SvEnumCaseNamingPolicy::EnumQualified)
            .unwrap();
        xlsynth_test_helpers::assert_valid_sv(&sv);
        assert!(sv.contains("MyFirstEnum_A = 1'd0"));
        assert!(sv.contains("MySecondEnum_A = 3'd3"));
    }

    #[test]
    fn test_is_screaming_snake_case() {
        assert!(is_screaming_snake_case("FOO_BAR"));
        assert!(is_screaming_snake_case("ONEWORD"));

        assert!(!is_screaming_snake_case("FooBar"));
        assert!(!is_screaming_snake_case("blah"));
    }

    #[test]
    fn test_struct_with_extern_type_ref_member_type_ref_member() {
        let imported_dslx = "pub struct MyImportedStruct { a: u8 }";
        let importer_dslx = "import imported; struct MyStruct { a: imported::MyImportedStruct }";

        let mut import_data = dslx::ImportData::default();
        let _imported_typechecked =
            dslx::parse_and_typecheck(imported_dslx, "imported.x", "imported", &mut import_data)
                .unwrap();
        let importer_typechecked =
            dslx::parse_and_typecheck(importer_dslx, "importer.x", "importer", &mut import_data)
                .unwrap();

        let mut builder =
            SvBridgeBuilder::with_enum_case_policy(SvEnumCaseNamingPolicy::Unqualified);
        convert_imported_module(&importer_typechecked, &mut builder).unwrap();
        let sv = builder.build();
        assert_eq!(
            sv,
            "typedef struct packed {
    imported_sv_pkg::my_imported_struct_t a;
} my_struct_t;
"
        );
    }
}