dbc-codegen 0.4.0

CAN DBC code-gen for embedded 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
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
#![deny(missing_docs)]
#![deny(clippy::arithmetic_side_effects)]
#![allow(clippy::needless_doctest_main)]
#![cfg_attr(feature = "std", doc = include_str!("../README.md"))]
#![cfg_attr(
    not(feature = "std"),
    doc = "Documentation is only available with the `std` feature."
)]

mod feature_config;
mod keywords;
mod pad;
mod signal_type;
mod utils;

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fs::OpenOptions;
use std::io::{BufWriter, Write};
use std::path::Path;

use anyhow::{Context, Error, Result, anyhow, ensure};
use can_dbc::ByteOrder::{BigEndian, LittleEndian};
use can_dbc::MultiplexIndicator::{
    MultiplexedSignal, Multiplexor, MultiplexorAndMultiplexedSignal, Plain,
};
use can_dbc::ValueType::Signed;
use can_dbc::{
    AttributeValue, AttributeValueForRelationType, Dbc, Message, MessageId, Signal, ValDescription,
    ValueDescription,
};
use heck::ToSnakeCase;
use quote::ToTokens;
use typed_builder::TypedBuilder;

pub use crate::feature_config::FeatureConfig;
use crate::pad::PadAdapter;
use crate::signal_type::{IntSize, ValType};
use crate::utils::{
    MessageExt as _, SignalExt as _, enum_name, enum_variant_name, is_screaming_snake_case,
    is_valid_ident, is_valid_type_path, multiplex_enum_name, multiplexed_enum_variant_name,
    multiplexed_enum_variant_wrapper_name, node_field_name,
};

static ALLOW_DEADCODE: &str = "#[allow(dead_code)]";
static ALLOW_LINTS: &str = r"#[allow(
    clippy::absurd_extreme_comparisons,
    clippy::excessive_precision,
    clippy::manual_range_contains,
    clippy::unnecessary_cast,
    clippy::useless_conversion,
    unused_comparisons,
    unused_variables,
)]";

/// Code generator configuration. See module-level docs for an example.
#[derive(TypedBuilder)]
#[non_exhaustive]
pub struct Config<'a> {
    /// Name of the dbc-file. Used for generated docs only.
    pub dbc_name: &'a str,

    /// Content of a dbc-file as a UTF-8 string. Use [`can_dbc::decode_cp1252`] or other encodings if needed.
    pub dbc_content: &'a str,

    /// Optional: Print debug info to stdout while generating code. Default: `false`.
    #[builder(default)]
    pub debug_prints: bool,

    /// Optional: `impl Debug` for generated types. Default: `Never`.
    #[builder(default)]
    pub impl_debug: FeatureConfig<'a>,

    /// Optional: `impl defmt::Format` for generated types. Default: `Never`.
    #[builder(default)]
    pub impl_defmt: FeatureConfig<'a>,

    /// Optional: `impl Arbitrary` for generated types. Default: `Never`.
    #[builder(default)]
    pub impl_arbitrary: FeatureConfig<'a>,

    /// Optional: `impl Serialize` and `impl Deserialize` for generated types.. Default: `Never`.
    #[builder(default)]
    pub impl_serde: FeatureConfig<'a>,

    /// Optional: `impl core::error::Error` for the generated `CanError` type. Default: `Never`.
    #[builder(default)]
    pub impl_error: FeatureConfig<'a>,

    /// Optional: Generate `embedded_can::Frame` impl for each frame. Default: `Always`
    #[builder(default = FeatureConfig::Always)]
    pub impl_embedded_can_frame: FeatureConfig<'a>,

    /// Optional: Validate min and max values in generated signal setters. Default: `Always`
    #[builder(default = FeatureConfig::Always)]
    pub check_ranges: FeatureConfig<'a>,

    /// Optional: Allow dead code in the generated module. Default: `false`.
    #[builder(default)]
    pub allow_dead_code: bool,

    /// Optional: Padding bit value used; set all unused bits to 1 if true else to 0. Default: `false`.
    #[builder(default)]
    pub padding_bit_value: bool,

    /// Optional: User-defined structs populated from DBC attributes.
    /// These are emitted as associated constants in the generated message types.
    /// Default: empty.
    #[builder(default)]
    pub attribute_structs: &'a [AttributeStruct<'a>],
}

/// A user-defined struct that [`Config`] fills from DBC attributes and emits as an
/// associated constant in the generated message type.
#[derive(Debug, Clone)]
pub struct AttributeStruct<'a> {
    /// Fully-qualified path of the target Rust type.
    pub type_path: &'a str,

    /// Base name of the emitted associated constant.
    pub const_name: &'a str,

    /// Whether one constant is emitted per message or per matching signal.
    pub scope: AttributeScope,

    /// Only emit the constant when this attribute has an assigned value on the
    /// scoped object (the message for [`AttributeScope::Message`] or the signal
    /// for [`AttributeScope::Signal`]).
    pub require: &'a str,

    /// The struct fields, written in this order.
    pub fields: &'a [AttributeField<'a>],

    /// Restrict [`AttributeScope::NodeSignal`]/[`AttributeScope::NodeMessage`]
    /// emission to this one node and remove the node name from the generated
    /// const. Set to `None` to keep the default behavior (one constant per
    /// matching node).
    pub for_node: Option<&'a str>,
}

/// Whether an [`AttributeStruct`] is emitted once per message or once per signal.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub enum AttributeScope {
    /// One const per message (`BO_` attribute).
    Message,
    /// One const per signal (`SG_` attribute).
    Signal,
    /// One const per node related to a message (`BU_BO_REL_` relation attribute).
    NodeMessage,
    /// One const per receiving node of a signal (`BU_SG_REL_` relation attribute).
    NodeSignal,
}

/// One field of an [`AttributeStruct`] and where its value comes from.
#[derive(Debug, Clone)]
pub struct AttributeField<'a> {
    /// The target struct field name.
    pub name: &'a str,
    /// Where the field's value comes from.
    pub source: FieldSource<'a>,
}

/// Source of a generated [`AttributeField`] value.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum FieldSource<'a> {
    /// Value of an attribute on the scoped object: a signal-level attribute in
    /// [`AttributeScope::Signal`] or a message-level attribute in
    /// [`AttributeScope::Message`].
    Attr(&'a str),
    /// Value of a message-level attribute.
    MessageAttr(&'a str),
    /// The signal's raw DBC start bit. [`AttributeScope::Signal`] only.
    StartBit,
    /// The signal's start byte. [`AttributeScope::Signal`] only.
    StartByte,
    /// The signal's width in bits. [`AttributeScope::Signal`] only.
    BitWidth,
    /// The message size in bytes.
    MessageSize,
    /// A literal integer.
    Int(i64),
    /// A literal string.
    Str(&'a str),
    /// The name of the related node.
    /// [`AttributeScope::NodeSignal`] and [`AttributeScope::NodeMessage`] only.
    NodeName,
}

/// Message/signal/node context used to resolve an [`AttributeStruct`]'s fields.
struct AttrTarget<'a> {
    msg: &'a Message,
    dbc: &'a Dbc,
    signal: Option<&'a Signal>,
    node: Option<&'a str>,
}

impl Config<'_> {
    /// Write Rust structs matching DBC input description to `out` buffer
    fn codegen(&self, out: impl Write) -> Result<()> {
        self.validate_attribute_structs()?;
        let dbc = Dbc::try_from(self.dbc_content).map_err(|e| {
            let msg = "Could not parse dbc file";
            if self.debug_prints {
                anyhow!("{msg}: {e:#?}")
            } else {
                anyhow!("{msg}")
            }
        })?;
        if self.debug_prints {
            eprintln!("{dbc:#?}");
        }
        let mut w = BufWriter::new(out);

        writeln!(
            w,
            "/// The name of the DBC file this code was generated from"
        )?;
        writeln!(w, "#[allow(dead_code)]")?;
        let dbc_name = self.dbc_name.to_token_stream();
        writeln!(w, "pub const DBC_FILE_NAME: &str = {dbc_name};")?;
        writeln!(
            w,
            "/// The version of the DBC file this code was generated from"
        )?;
        writeln!(w, "#[allow(dead_code)]")?;
        let dbc_version = dbc.version.0.to_token_stream();
        writeln!(w, "pub const DBC_FILE_VERSION: &str = {dbc_version};")?;

        writeln!(w, "#[allow(unused_imports)]")?;
        writeln!(w, "use core::ops::BitOr;")?;
        writeln!(w, "#[allow(unused_imports)]")?;
        writeln!(w, "use bitvec::prelude::*;")?;
        writeln!(w, "#[allow(unused_imports)]")?;
        writeln!(w, "use embedded_can::{{Id, StandardId, ExtendedId}};")?;

        self.impl_arbitrary.fmt_cfg(&mut w, |w| {
            writeln!(w, "use arbitrary::{{Arbitrary, Unstructured}};")
        })?;

        self.impl_serde.fmt_cfg(&mut w, |w| {
            writeln!(w, "use serde::{{Serialize, Deserialize}};")
        })?;

        writeln!(w)?;
        self.render_dbc(&mut w, &dbc)?;
        writeln!(w)?;
        self.render_error(&mut w)?;
        self.render_arbitrary_helpers(&mut w)?;
        writeln!(w)?;

        Ok(())
    }

    fn render_dbc(&self, w: &mut impl Write, dbc: &Dbc) -> Result<()> {
        self.render_root_enum(w, dbc)?;

        for msg in get_relevant_messages(dbc) {
            self.render_message(w, msg, dbc)
                .with_context(|| format!("write message `{}`", msg.name))?;
            writeln!(w)?;
        }

        Ok(())
    }

    fn render_root_enum(&self, w: &mut impl Write, dbc: &Dbc) -> Result<()> {
        writeln!(w, "/// All messages")?;
        writeln!(w, "{ALLOW_LINTS}")?;
        self.write_allow_dead_code(w)?;
        writeln!(w, "#[derive(Clone)]")?;
        self.impl_debug.fmt_attr(w, "derive(Debug)")?;
        self.impl_defmt.fmt_attr(w, "derive(defmt::Format)")?;
        self.impl_serde.fmt_attr(w, "derive(Serialize)")?;
        self.impl_serde.fmt_attr(w, "derive(Deserialize)")?;
        writeln!(w, "pub enum Messages {{")?;
        {
            let mut w = PadAdapter::wrap(w);
            for msg in get_relevant_messages(dbc) {
                writeln!(w, "/// {}", msg.name)?;
                writeln!(w, "{0}({0}),", msg.type_name())?;
            }
        }
        writeln!(w, "}}")?;
        writeln!(w)?;

        writeln!(w, "{ALLOW_LINTS}")?;
        self.write_allow_dead_code(w)?;
        writeln!(w, "impl Messages {{")?;
        {
            let mut w = PadAdapter::wrap(w);
            writeln!(w, "/// Read message from CAN frame")?;
            writeln!(w, "#[inline(never)]")?;
            writeln!(
                w,
                "pub fn from_can_message(id: Id, payload: &[u8]) -> Result<Self, CanError> {{",
            )?;

            {
                let mut w = PadAdapter::wrap(&mut w);
                let messages: Vec<_> = get_relevant_messages(dbc).collect();
                if messages.is_empty() {
                    writeln!(w, "Err(CanError::UnknownMessageId(id))")?;
                } else {
                    writeln!(w)?;
                    writeln!(w, "let res = match id {{")?;
                    {
                        let mut w = PadAdapter::wrap(&mut w);
                        for msg in messages {
                            writeln!(
                                w,
                                "{0}::MESSAGE_ID => Messages::{0}({0}::try_from(payload)?),",
                                msg.type_name(),
                            )?;
                        }
                        writeln!(w, r"id => return Err(CanError::UnknownMessageId(id)),")?;
                    }
                    writeln!(w, "}};")?;
                    writeln!(w, "Ok(res)")?;
                }
            }

            writeln!(w, "}}")?;
        }
        writeln!(w, "}}")?;
        writeln!(w)?;

        Ok(())
    }

    fn render_message(&self, w: &mut impl Write, msg: &Message, dbc: &Dbc) -> Result<()> {
        writeln!(w, "/// {}", msg.name)?;
        writeln!(w, "///")?;
        match msg.id {
            MessageId::Standard(id) => writeln!(w, "/// - Standard ID: {id} (0x{id:x})"),
            MessageId::Extended(id) => writeln!(w, "/// - Extended ID: {id} (0x{id:x})"),
        }?;
        writeln!(w, "/// - Size: {} bytes", msg.size)?;
        if let Some(transmitter) = &msg.transmitter {
            writeln!(w, "/// - Transmitter: {transmitter}")?;
        }
        if let Some(comment) = dbc.message_comment(msg.id) {
            writeln!(w, "///")?;
            for line in comment.trim().lines() {
                writeln!(w, "/// {line}")?;
            }
        }
        writeln!(w, "#[derive(Clone, Copy)]")?;
        self.impl_serde.fmt_attr(w, "derive(Serialize)")?;
        self.impl_serde.fmt_attr(w, "derive(Deserialize)")?;
        writeln!(w, "pub struct {} {{", msg.type_name())?;
        {
            let mut w = PadAdapter::wrap(w);
            self.impl_serde
                .fmt_attr(&mut w, "serde(with = \"serde_bytes\")")?;
            writeln!(w, "raw: [u8; {}],", msg.size)?;
        }
        writeln!(w, "}}")?;
        writeln!(w)?;

        writeln!(w, "{ALLOW_LINTS}")?;
        self.write_allow_dead_code(w)?;
        writeln!(w, "impl {} {{", msg.type_name())?;
        {
            let mut w = PadAdapter::wrap(w);

            writeln!(
                w,
                "pub const MESSAGE_ID: embedded_can::Id = {};",
                match msg.id {
                    MessageId::Standard(id) =>
                        format!("Id::Standard(StandardId::new({id:#x}).unwrap())"),
                    MessageId::Extended(id) =>
                        format!("Id::Extended(ExtendedId::new({id:#x}).unwrap())"),
                }
            )?;
            writeln!(w)?;

            writeln!(w, "pub const MESSAGE_SIZE: usize = {};", msg.size)?;
            writeln!(w)?;

            Self::render_cycle_time(&mut w, msg, dbc)?;

            for signal in &msg.signals {
                let typ = ValType::from_signal(signal);
                if typ != ValType::Bool {
                    let sig = signal.field_name().to_uppercase();
                    let min = signal.min;
                    let max = signal.max;
                    writeln!(w, "pub const {sig}_MIN: {typ} = {min}_{typ};")?;
                    writeln!(w, "pub const {sig}_MAX: {typ} = {max}_{typ};")?;
                }
            }
            writeln!(w)?;

            self.render_attribute_structs(&mut w, msg, dbc)?;

            writeln!(
                w,
                "/// Constructs a new `{}` message from values.",
                msg.name
            )?;
            let args = msg
                .signals
                .iter()
                .filter_map(|signal| {
                    if matches!(signal.multiplexer_indicator, Plain | Multiplexor) {
                        let field = signal.field_name();
                        let typ = signal_pub_type(dbc, msg, signal);
                        Some(format!("{field}: {typ}"))
                    } else {
                        None
                    }
                })
                .collect::<Vec<_>>()
                .join(", ");
            writeln!(w, "pub fn new({args}) -> Result<Self, CanError> {{")?;
            {
                let mut w = PadAdapter::wrap(&mut w);
                let mutable = if msg.signals.is_empty() { "" } else { "mut " };
                let padding_value = if self.padding_bit_value {
                    "0xFF"
                } else {
                    "0x00"
                };
                let size = msg.size;
                writeln!(
                    w,
                    "let {mutable}res = Self {{ raw: [{padding_value}; {size}] }};"
                )?;
                for signal in &msg.signals {
                    if matches!(signal.multiplexer_indicator, Plain | Multiplexor) {
                        writeln!(w, "res.set_{0}({0})?;", signal.field_name())?;
                    }
                }
                writeln!(w, "Ok(res)")?;
            }
            writeln!(w, "}}")?;
            writeln!(w)?;

            writeln!(w, "/// Returns the raw `{}` message payload.", msg.name)?;
            writeln!(w, "pub fn raw(&self) -> &[u8; {}] {{", msg.size)?;
            {
                let mut w = PadAdapter::wrap(&mut w);
                writeln!(w, "&self.raw")?;
            }
            writeln!(w, "}}")?;
            writeln!(w)?;

            for signal in &msg.signals {
                match signal.multiplexer_indicator {
                    Plain => self
                        .render_signal(&mut w, signal, dbc, msg)
                        .with_context(|| format!("write signal impl `{}`", signal.name))?,
                    Multiplexor => {
                        self.render_multiplexor_signal(&mut w, signal, dbc, msg)?;
                    }
                    MultiplexedSignal(_) | MultiplexorAndMultiplexedSignal(_) => {}
                }
            }
        }

        writeln!(w, "}}")?;
        writeln!(w)?;

        let typ = msg.type_name();
        writeln!(w, "impl core::convert::TryFrom<&[u8]> for {typ} {{")?;
        {
            let mut w = PadAdapter::wrap(w);
            writeln!(w, "type Error = CanError;")?;
            writeln!(w)?;
            writeln!(w, "#[inline(always)]")?;
            writeln!(
                w,
                "fn try_from(payload: &[u8]) -> Result<Self, Self::Error> {{",
            )?;
            {
                let mut w = PadAdapter::wrap(&mut w);
                writeln!(
                    w,
                    r"if payload.len() != {} {{ return Err(CanError::InvalidPayloadSize); }}",
                    msg.size,
                )?;
                writeln!(w, "let mut raw = [0u8; {}];", msg.size)?;
                writeln!(w, "raw.copy_from_slice(&payload[..{}]);", msg.size)?;
                writeln!(w, "Ok(Self {{ raw }})")?;
            }
            writeln!(w, "}}")?;
        }
        writeln!(w, "}}")?;
        writeln!(w)?;

        self.render_embedded_can_frame(w, msg)?;

        self.impl_debug
            .fmt_cfg(&mut *w, |w| render_debug_impl(w, msg))?;
        self.impl_defmt
            .fmt_cfg(&mut *w, |w| render_defmt_impl(w, msg))?;
        self.impl_arbitrary
            .fmt_cfg(&mut *w, |w| self.render_arbitrary(w, dbc, msg))?;

        let enums_for_this_message = dbc.value_descriptions.iter().filter_map(|x| {
            if let ValueDescription::Signal {
                message_id,
                name,
                value_descriptions,
            } = x
            {
                if *message_id != msg.id {
                    return None;
                }
                dbc.signal_by_name(*message_id, name)
                    .map(|v| (v, value_descriptions))
            } else {
                None
            }
        });
        for (signal, variants) in enums_for_this_message {
            self.write_enum(w, signal, msg, variants.as_slice())?;
        }

        let multiplexor_signal = msg
            .signals
            .iter()
            .find(|s| s.multiplexer_indicator == Multiplexor);

        if let Some(multiplexor_signal) = multiplexor_signal {
            self.render_multiplexor_enums(w, dbc, msg, multiplexor_signal)?;
        }

        Ok(())
    }

    /// Validate the [`AttributeStruct`] specs.
    fn validate_attribute_structs(&self) -> Result<()> {
        for spec in self.attribute_structs {
            // Require SCREAMING_SNAKE_CASE to guarantee that the name never collides
            // with a generated method (all `snake_case`).
            ensure!(
                is_screaming_snake_case(spec.const_name),
                "attribute_structs: 'const_name' {:?} must be SCREAMING_SNAKE_CASE",
                spec.const_name
            );
            ensure!(
                is_valid_type_path(spec.type_path),
                "attribute_structs: 'type_path' {:?} for {:?} is not a valid Rust type path",
                spec.type_path,
                spec.const_name
            );
            ensure!(
                !spec.require.is_empty(),
                "attribute_structs: 'require' must not be empty for {:?}",
                spec.const_name
            );
            ensure!(
                !spec.fields.is_empty(),
                "attribute_structs: {:?} declares no fields",
                spec.const_name
            );

            let has_signal = matches!(
                spec.scope,
                AttributeScope::Signal | AttributeScope::NodeSignal
            );
            let has_node = matches!(
                spec.scope,
                AttributeScope::NodeSignal | AttributeScope::NodeMessage
            );
            if let Some(for_node) = spec.for_node {
                ensure!(
                    !for_node.is_empty(),
                    "attribute_structs: 'for_node' must not be empty for {:?}",
                    spec.const_name
                );
                ensure!(
                    has_node,
                    "attribute_structs: {:?} sets 'for_node' but its scope has no associated \
                     node (scope must be NodeSignal or NodeMessage)",
                    spec.const_name
                );
            }
            let mut seen = BTreeSet::new();
            for field in spec.fields {
                ensure!(
                    is_valid_ident(field.name),
                    "attribute_structs: field name {:?} in {:?} is not a valid Rust identifier",
                    field.name,
                    spec.const_name
                );
                ensure!(
                    seen.insert(field.name),
                    "attribute_structs: duplicate field {:?} in {:?}",
                    field.name,
                    spec.const_name
                );
                if !has_signal {
                    ensure!(
                        !matches!(
                            field.source,
                            FieldSource::StartBit | FieldSource::StartByte | FieldSource::BitWidth
                        ),
                        "attribute_structs: field {:?} of {:?} uses a signal-only source \
                         (StartBit/StartByte/BitWidth) but the struct has no associated signal",
                        field.name,
                        spec.const_name
                    );
                }
                if !has_node {
                    ensure!(
                        !matches!(field.source, FieldSource::NodeName),
                        "attribute_structs: field {:?} of {:?} uses NodeName but the struct has \
                         no associated node (scope must be NodeSignal or NodeMessage)",
                        field.name,
                        spec.const_name
                    );
                }
            }
        }
        Ok(())
    }

    /// Emit the configured [`AttributeStruct`]s as associated constants.
    fn render_attribute_structs(&self, w: &mut impl Write, msg: &Message, dbc: &Dbc) -> Result<()> {
        if self.attribute_structs.is_empty() {
            return Ok(());
        }

        // Track every associated item already emitted for this message type so
        // that colliding const names are rejected here instead of producing code
        // that fails to build. Using a BTree to ensure deterministic output.
        let mut used: BTreeSet<String> = BTreeSet::new();
        used.insert("MESSAGE_ID".to_string());
        for signal in &msg.signals {
            if ValType::from_signal(signal) != ValType::Bool {
                let sig = signal.field_name().to_uppercase();
                used.insert(format!("{sig}_MIN"));
                used.insert(format!("{sig}_MAX"));
            }
        }

        for spec in self.attribute_structs {
            match spec.scope {
                AttributeScope::Message => {
                    if dbc.message_attribute(msg.id, spec.require).is_none() {
                        continue;
                    }
                    Self::render_attribute_struct(
                        w,
                        spec,
                        spec.const_name,
                        &AttrTarget {
                            msg,
                            dbc,
                            signal: None,
                            node: None,
                        },
                        &mut used,
                    )?;
                }
                AttributeScope::Signal => {
                    for signal in &msg.signals {
                        if dbc
                            .signal_attribute(msg.id, &signal.name, spec.require)
                            .is_none()
                        {
                            continue;
                        }
                        let name =
                            format!("{}_{}", signal.field_name().to_uppercase(), spec.const_name);
                        Self::render_attribute_struct(
                            w,
                            spec,
                            &name,
                            &AttrTarget {
                                msg,
                                dbc,
                                signal: Some(signal),
                                node: None,
                            },
                            &mut used,
                        )?;
                    }
                }
                AttributeScope::NodeSignal => {
                    for signal in &msg.signals {
                        for node in &signal.receivers {
                            if spec.for_node.is_some_and(|target| node != target) {
                                continue;
                            }
                            if node_relation_attribute(
                                dbc,
                                node,
                                msg.id,
                                Some(&signal.name),
                                spec.require,
                            )
                            .is_none()
                            {
                                continue;
                            }
                            let name = if spec.for_node.is_some() {
                                format!(
                                    "{}_{}",
                                    signal.field_name().to_uppercase(),
                                    spec.const_name
                                )
                            } else {
                                let node_ident = node_field_name(node).to_uppercase();
                                format!(
                                    "{}_{node_ident}_{}",
                                    signal.field_name().to_uppercase(),
                                    spec.const_name
                                )
                            };
                            Self::render_attribute_struct(
                                w,
                                spec,
                                &name,
                                &AttrTarget {
                                    msg,
                                    dbc,
                                    signal: Some(signal),
                                    node: Some(node),
                                },
                                &mut used,
                            )?;
                        }
                    }
                }
                AttributeScope::NodeMessage => {
                    for node in &dbc.nodes {
                        if spec.for_node.is_some_and(|target| node.0 != target) {
                            continue;
                        }
                        if node_relation_attribute(dbc, &node.0, msg.id, None, spec.require)
                            .is_none()
                        {
                            continue;
                        }
                        let name = if spec.for_node.is_some() {
                            spec.const_name.to_string()
                        } else {
                            format!(
                                "{}_{}",
                                node_field_name(&node.0).to_uppercase(),
                                spec.const_name
                            )
                        };
                        Self::render_attribute_struct(
                            w,
                            spec,
                            &name,
                            &AttrTarget {
                                msg,
                                dbc,
                                signal: None,
                                node: Some(&node.0),
                            },
                            &mut used,
                        )?;
                    }
                }
            }
        }
        Ok(())
    }

    /// Emit a single struct constant.
    fn render_attribute_struct(
        w: &mut impl Write,
        spec: &AttributeStruct<'_>,
        const_name: &str,
        target: &AttrTarget<'_>,
        used: &mut BTreeSet<String>,
    ) -> Result<()> {
        ensure!(
            used.insert(const_name.to_string()),
            "attribute_structs: generated const '{const_name}' on message {:?} collides with \
             another const. Use a distinct 'const_name'.",
            target.msg.name
        );

        let mut fields = Vec::with_capacity(spec.fields.len());
        for field in spec.fields {
            let lit = resolve_field_source(&field.source, target).ok_or_else(|| {
                anyhow!(
                    "attribute_structs: const '{const_name}' field {:?} has no value in the DBC \
                     and no default (source: {:?})",
                    field.name,
                    field.source
                )
            })?;
            fields.push((field.name, lit));
        }

        let ty = spec.type_path;
        writeln!(w, "/// Generated from DBC attributes `{}`", spec.require)?;
        writeln!(w, "pub const {const_name}: {ty} = {ty} {{")?;
        {
            let mut w = PadAdapter::wrap(w);
            for (name, lit) in fields {
                writeln!(w, "{name}: {lit},")?;
            }
        }
        writeln!(w, "}};")?;
        writeln!(w)?;
        Ok(())
    }

    /// Emit the cycle time as a constant for messages that have an assigned
    /// `GenMsgCycleTime` (`BA_`) attribute.
    fn render_cycle_time(w: &mut impl Write, msg: &Message, dbc: &Dbc) -> Result<()> {
        let Some(ms) = message_cycle_time_ms(dbc, msg.id) else {
            return Ok(());
        };
        writeln!(w, "pub const MESSAGE_CYCLE_TIME_MS: u32 = {ms};")?;
        Ok(())
    }

    fn render_signal(
        &self,
        w: &mut impl Write,
        signal: &Signal,
        dbc: &Dbc,
        msg: &Message,
    ) -> Result<()> {
        writeln!(w, "/// Returns the value of `{}`.", signal.name)?;
        if let Some(comment) = dbc.signal_comment(msg.id, &signal.name) {
            writeln!(w, "///")?;
            for line in comment.trim().lines() {
                writeln!(w, "/// {line}")?;
            }
        }
        writeln!(w, "///")?;
        writeln!(w, "/// - Min: {}", signal.min)?;
        writeln!(w, "/// - Max: {}", signal.max)?;
        if signal.unit.is_empty() {
            writeln!(w, "/// - Unit: Not specified")?;
        } else {
            writeln!(w, "/// - Unit: {:?}", signal.unit)?;
        }
        if signal.receivers.is_empty() {
            writeln!(w, "/// - Receivers: Vector__XXX")?;
        } else {
            writeln!(w, "/// - Receivers: {}", signal.receivers.join(", "))?;
        }

        let fn_name = signal.field_name();
        let variants = dbc.value_descriptions_for_signal(msg.id, &signal.name);
        if variants.is_none() {
            writeln!(w, "/// - Factor: {}", signal.factor)?;
            writeln!(w, "/// - Offset: {}", signal.offset)?;
        }
        writeln!(w, "#[inline(always)]")?;
        if let Some(variants) = variants {
            let type_name = enum_name(msg, signal);
            let signal_ty = ValType::from_signal(signal);
            let variant_infos = generate_variant_info(variants, signal_ty);

            writeln!(w, "pub fn {fn_name}(&self) -> {type_name} {{")?;
            {
                let mut w = PadAdapter::wrap(w);

                // Use signed type for loading when signal is signed and has negative values
                let has_negative_values = variants.iter().any(|v| v.id < 0);
                let load_type = if signal.value_type == Signed && has_negative_values {
                    signal_ty
                } else {
                    ValType::from_signal_uint(signal)
                };

                let read = read_fn_with_type(signal, msg, load_type)?;
                writeln!(w, r"let signal = {read};")?;
                writeln!(w)?;
                writeln!(w, "match signal {{")?;
                {
                    let mut w = PadAdapter::wrap(&mut w);
                    for info in &variant_infos {
                        let literal = info.value;
                        let variant = &info.base_name;
                        match info.dup_type {
                            DuplicateType::Unique => {
                                writeln!(w, "{literal} => {type_name}::{variant},")?;
                            }
                            DuplicateType::FirstDuplicate | DuplicateType::Duplicate => {
                                writeln!(w, "{literal} => {type_name}::{variant}({literal}),")?;
                            }
                        }
                    }
                    writeln!(w, "_ => {type_name}::_Other(self.{fn_name}_phys_val()),")?;
                }
                writeln!(w, "}}")?;
            }
            writeln!(w, "}}")?;
            writeln!(w)?;

            // Private helper for the `_Other()` fallback above.
            writeln!(w, "#[inline(always)]")?;
            let typ = ValType::from_signal(signal);
            writeln!(w, "fn {fn_name}_phys_val(&self) -> {typ} {{")?;
            {
                let mut w = PadAdapter::wrap(w);
                signal_from_payload(&mut w, signal, msg).context("signal from payload")?;
            }
            writeln!(w, "}}")?;
            writeln!(w)?;
        } else {
            let typ = ValType::from_signal(signal);
            writeln!(w, "pub fn {fn_name}(&self) -> {typ} {{")?;
            {
                let mut w = PadAdapter::wrap(w);
                signal_from_payload(&mut w, signal, msg).context("signal from payload")?;
            }
            writeln!(w, "}}")?;
            writeln!(w)?;
        }

        render_raw_accessors(w, signal, msg)?;

        self.render_set_signal(w, signal, dbc, msg)?;

        Ok(())
    }

    fn render_set_signal(
        &self,
        w: &mut impl Write,
        signal: &Signal,
        dbc: &Dbc,
        msg: &Message,
    ) -> Result<()> {
        // To avoid accidentally changing the multiplexor value without changing
        // the signals accordingly this fn is kept private for multiplexors.
        let visibility = if signal.multiplexer_indicator == Multiplexor {
            ""
        } else {
            "pub "
        };

        let field = signal.field_name();
        let typ = ValType::from_signal(signal);
        let param_type = signal_pub_type(dbc, msg, signal);
        let is_enum_backed = param_type != typ.to_string();

        writeln!(w, "/// Sets the value of `{}`.", signal.name)?;
        writeln!(w, "#[inline(always)]")?;
        writeln!(
            w,
            "{visibility}fn set_{field}(&mut self, value: {param_type}) -> Result<(), CanError> {{",
        )?;
        {
            let mut w = PadAdapter::wrap(w);
            // Enum-backed signals accept the value-description enum; convert it to
            // the raw primitive before range checks and packing.
            if is_enum_backed {
                writeln!(w, "let value = {typ}::from(value);")?;
            }
            self.render_set_signal_body(&mut w, signal, msg)?;
        }
        writeln!(w, "}}")?;
        writeln!(w)?;

        Ok(())
    }

    fn render_set_signal_body(
        &self,
        w: &mut impl Write,
        signal: &Signal,
        msg: &Message,
    ) -> Result<()> {
        if signal.size != 1 {
            if let FeatureConfig::Gated(gate) = self.check_ranges {
                writeln!(w, r"#[cfg(feature = {gate:?})]")?;
            }

            if let FeatureConfig::Gated(..) | FeatureConfig::Always = self.check_ranges {
                let typ = ValType::from_signal(signal);
                let min = signal.min;
                let max = signal.max;
                writeln!(w, r"if value < {min}_{typ} || {max}_{typ} < value {{")?;

                {
                    let mut w = PadAdapter::wrap(&mut *w);
                    let typ = msg.type_name();
                    writeln!(
                        w,
                        r"return Err(CanError::ParameterOutOfRange {{ message_id: {typ}::MESSAGE_ID }});",
                    )?;
                }

                writeln!(w, r"}}")?;
            }
        }
        signal_to_payload(&mut *w, signal, msg).context("signal to payload")?;

        Ok(())
    }

    fn render_multiplexor_signal(
        &self,
        w: &mut impl Write,
        signal: &Signal,
        dbc: &Dbc,
        msg: &Message,
    ) -> Result<()> {
        let signal_typ = ValType::from_signal(signal);

        render_raw_accessors(w, signal, msg)?;

        let field = signal.field_name();
        let typ = multiplex_enum_name(msg, signal)?;
        writeln!(
            w,
            "/// Selects the active multiplexed sub-message for `{}`.",
            signal.name
        )?;
        writeln!(
            w,
            "pub fn {field}_multiplexed(&mut self) -> Result<{typ}, CanError> {{"
        )?;

        let multiplexer_indexes: BTreeSet<u64> = msg
            .signals
            .iter()
            .filter_map(|s| {
                if let MultiplexedSignal(index) = &s.multiplexer_indicator {
                    Some(index)
                } else {
                    None
                }
            })
            .copied()
            .collect();

        {
            let mut w = PadAdapter::wrap(w);
            writeln!(w, "match self.{}_raw_val() {{", signal.field_name())?;

            {
                let mut w = PadAdapter::wrap(&mut w);
                for idx in &multiplexer_indexes {
                    writeln!(
                        w,
                        "{idx} => Ok({enum_name}::{multiplexed_wrapper_name}({multiplexed_name}{{ raw: self.raw }})),",
                        enum_name = multiplex_enum_name(msg, signal)?,
                        multiplexed_wrapper_name = multiplexed_enum_variant_wrapper_name(*idx),
                        multiplexed_name = multiplexed_enum_variant_name(msg, signal, *idx)?,
                    )?;
                }
                let to_u16 = match signal_typ {
                    ValType::UnsignedInt(IntSize::Size8) => "multiplexor.into()",
                    ValType::UnsignedInt(IntSize::Size16) => "multiplexor",
                    _ => "u16::try_from(multiplexor).unwrap_or(u16::MAX)",
                };
                writeln!(
                    w,
                    "multiplexor => Err(CanError::InvalidMultiplexor {{ message_id: {}::MESSAGE_ID, multiplexor: {to_u16} }}),",
                    msg.type_name(),
                )?;
            }

            writeln!(w, "}}")?;
        }
        writeln!(w, "}}")?;

        self.render_set_signal(w, signal, dbc, msg)?;

        for switch_index in multiplexer_indexes {
            render_set_signal_multiplexer(w, signal, msg, switch_index)?;
        }

        Ok(())
    }

    fn write_enum(
        &self,
        w: &mut impl Write,
        signal: &Signal,
        msg: &Message,
        variants: &[ValDescription],
    ) -> Result<()> {
        let type_name = enum_name(msg, signal);
        let signal_ty = ValType::from_signal(signal);

        // Generate variant info to handle duplicates with tuple variants
        let variant_infos = generate_variant_info(variants, signal_ty);

        writeln!(w, "/// Defined values for {}", signal.name)?;
        writeln!(w, "{ALLOW_LINTS}")?;
        self.write_allow_dead_code(w)?;
        writeln!(w, "#[derive(Clone, Copy, PartialEq)]")?;
        self.impl_debug.fmt_attr(w, "derive(Debug)")?;
        self.impl_defmt.fmt_attr(w, "derive(defmt::Format)")?;
        self.impl_serde.fmt_attr(w, "derive(Serialize)")?;
        self.impl_serde.fmt_attr(w, "derive(Deserialize)")?;
        writeln!(w, "pub enum {type_name} {{")?;
        {
            let mut w = PadAdapter::wrap(w);
            for info in &variant_infos {
                let variant = &info.base_name;
                match info.dup_type {
                    DuplicateType::Unique => writeln!(w, "{variant},")?,
                    DuplicateType::FirstDuplicate => {
                        writeln!(w, "{variant}({}),", info.value_type)?;
                    }
                    DuplicateType::Duplicate => {}
                }
            }
            writeln!(w, "_Other({signal_ty}),")?;
        }
        writeln!(w, "}}")?;
        writeln!(w)?;

        writeln!(w, "impl From<{type_name}> for {signal_ty} {{")?;
        {
            let match_on_raw_type = match ValType::from_signal(signal) {
                ValType::Bool => |x: i64| format!("{}", x == 1),
                ValType::F32 => |x: i64| format!("{x}_f32"),
                _ => |x: i64| format!("{x}"),
            };

            let mut w = PadAdapter::wrap(w);
            writeln!(w, "fn from(val: {type_name}) -> {signal_ty} {{")?;
            {
                let mut w = PadAdapter::wrap(&mut w);
                writeln!(w, "match val {{")?;
                {
                    let mut w = PadAdapter::wrap(&mut w);
                    for info in &variant_infos {
                        match info.dup_type {
                            DuplicateType::Unique => {
                                let literal = match_on_raw_type(info.value);
                                writeln!(w, "{type_name}::{} => {literal},", info.base_name)?;
                            }
                            DuplicateType::FirstDuplicate => {
                                writeln!(w, "{type_name}::{}(v) => v,", info.base_name)?;
                            }
                            DuplicateType::Duplicate => {}
                        }
                    }
                    writeln!(w, "{type_name}::_Other(x) => x,")?;
                }
                writeln!(w, "}}")?;
            }
            writeln!(w, "}}")?;
        }
        writeln!(w, "}}")?;
        writeln!(w)?;
        Ok(())
    }
}

fn render_set_signal_multiplexer(
    w: &mut impl Write,
    multiplexor: &Signal,
    msg: &Message,
    switch_index: u64,
) -> Result<()> {
    writeln!(w, "/// Sets the value of `{}`.", multiplexor.name)?;
    writeln!(w, "#[inline(always)]")?;
    writeln!(
        w,
        "pub fn set_{enum_variant_wrapper}(&mut self, value: {enum_variant}) -> Result<(), CanError> {{",
        enum_variant_wrapper = multiplexed_enum_variant_wrapper_name(switch_index).to_snake_case(),
        enum_variant = multiplexed_enum_variant_name(msg, multiplexor, switch_index)?,
    )?;

    {
        let mut w = PadAdapter::wrap(w);

        writeln!(w, "let b0 = BitArray::<_, LocalBits>::new(self.raw);")?;
        writeln!(w, "let b1 = BitArray::<_, LocalBits>::new(value.raw);")?;
        writeln!(w, "self.raw = b0.bitor(b1).into_inner();")?;
        writeln!(w, "self.set_{}({switch_index})?;", multiplexor.field_name())?;
        writeln!(w, "Ok(())")?;
    }

    writeln!(w, "}}")?;
    writeln!(w)?;

    Ok(())
}

fn be_start_end_bit(signal: &Signal, msg: &Message) -> Result<(u64, u64)> {
    let err = "calculating start bit";

    let x = signal.start_bit.checked_div(8).context(err)?;
    let x = x.checked_mul(8).context(err)?;

    let y = signal.start_bit.checked_rem(8).context(err)?;
    let y = 7u64.checked_sub(y).context(err)?;

    let start_bit = x.checked_add(y).context(err)?;
    let end_bit = start_bit
        .checked_add(signal.size)
        .context("calculating last bit position")?;

    let msg_bits = msg.size.checked_mul(8).context("message size overflow")?;

    ensure!(
        start_bit <= msg_bits,
        "signal starts at {start_bit}, but message is only {msg_bits} bits",
    );
    ensure!(
        end_bit <= msg_bits,
        "signal ends at {end_bit}, but message is only {msg_bits} bits",
    );
    Ok((start_bit, end_bit))
}

fn le_start_end_bit(signal: &Signal, msg: &Message) -> Result<(u64, u64)> {
    let msg_bits = msg.size.checked_mul(8).context("message size overflow")?;
    let start_bit = signal.start_bit;
    ensure!(
        start_bit <= msg_bits,
        "signal starts at {start_bit}, but message is only {msg_bits} bits",
    );

    let end_bit = signal
        .start_bit
        .checked_add(signal.size)
        .context("overflow calculating last bit position")?;
    ensure!(
        end_bit <= msg_bits,
        "signal ends at {end_bit}, but message is only {msg_bits} bits",
    );
    Ok((start_bit, end_bit))
}

/// Public type of a signal as seen by `new()` and `set_*`. This is the
/// enum when the signal has one (and isn't the multiplexor selector), otherwise
/// it is the raw primitive type.
fn signal_pub_type(dbc: &Dbc, msg: &Message, signal: &Signal) -> String {
    if signal.multiplexer_indicator != Multiplexor
        && dbc
            .value_descriptions_for_signal(msg.id, &signal.name)
            .is_some()
    {
        enum_name(msg, signal)
    } else {
        ValType::from_signal(signal).to_string()
    }
}

/// Whether the signal has no scaling applied, i.e. its raw and physical values are identical.
/// The float comparison to exact values is intentional.
#[allow(clippy::float_cmp)]
fn is_unscaled(signal: &Signal) -> bool {
    signal.factor == 1.0 && signal.offset == 0.0
}

fn signal_from_payload(w: &mut impl Write, signal: &Signal, msg: &Message) -> Result<()> {
    if is_unscaled(signal) {
        let field = signal.field_name();
        if signal.size == 1 {
            writeln!(w, "self.{field}_raw_val() == 1")?;
        } else {
            writeln!(w, "self.{field}_raw_val()")?;
        }
        return Ok(());
    }

    writeln!(w, r"let signal = {};", read_fn(signal, msg)?)?;
    writeln!(w)?;

    let typ = ValType::from_signal(signal);
    match typ {
        ValType::Bool => {
            writeln!(w, "signal == 1")?;
        }
        ValType::F32 => {
            // Scaling is always done on floats
            writeln!(w, "let factor = {}_f32;", signal.factor)?;
            writeln!(w, "let offset = {}_f32;", signal.offset)?;
            writeln!(w, "(signal as f32) * factor + offset")?;
        }
        _ => {
            writeln!(w, "let factor = {};", signal.factor)?;
            if Some(typ) == ValType::from_signal_uint(signal).unsigned_to_signed() {
                // Can't do iNN::from(uNN) if they both fit in the same integer type,
                // so cast first
                writeln!(w, "let signal = signal as {typ};")?;
            }

            if signal.offset >= 0.0 {
                writeln!(
                    w,
                    "{typ}::from(signal).saturating_mul(factor).saturating_add({})",
                    signal.offset,
                )?;
            } else {
                writeln!(
                    w,
                    "{typ}::from(signal).saturating_mul(factor).saturating_sub({})",
                    signal.offset.abs(),
                )?;
            }
        }
    }
    Ok(())
}

fn read_fn(signal: &Signal, msg: &Message) -> Result<String> {
    read_fn_with_type(signal, msg, ValType::from_signal_int(signal))
}

fn read_fn_with_type(signal: &Signal, msg: &Message, typ: ValType) -> Result<String> {
    Ok(match signal.byte_order {
        LittleEndian => {
            let (start, end) = le_start_end_bit(signal, msg)?;
            format!("self.raw.view_bits::<Lsb0>()[{start}..{end}].load_le::<{typ}>()")
        }
        BigEndian => {
            let (start, end) = be_start_end_bit(signal, msg)?;
            format!("self.raw.view_bits::<Msb0>()[{start}..{end}].load_be::<{typ}>()")
        }
    })
}

fn signal_to_payload(w: &mut impl Write, signal: &Signal, msg: &Message) -> Result<()> {
    let typ = ValType::from_signal(signal);
    match typ {
        ValType::Bool => {
            // Map boolean to byte so we can pack it
            writeln!(w, "let value = value as u8;")?;
        }
        ValType::F32 => {
            // Massage value into an int
            writeln!(w, "let factor = {}_f32;", signal.factor)?;
            writeln!(w, "let offset = {}_f32;", signal.offset)?;
            let typ = ValType::from_signal_int(signal);
            writeln!(w, "let value = ((value - offset) / factor) as {typ};")?;
            writeln!(w)?;
        }
        _ if is_unscaled(signal) => {
            // `value` is already the raw type.
        }
        _ => {
            writeln!(w, "let factor = {};", signal.factor)?;
            if signal.offset >= 0.0 {
                writeln!(w, "let value = value.checked_sub({})", signal.offset)?;
            } else {
                writeln!(w, "let value = value.checked_add({})", signal.offset.abs())?;
            }
            writeln!(
                w,
                "    .ok_or(CanError::ParameterOutOfRange {{ message_id: {}::MESSAGE_ID }})?;",
                msg.type_name(),
            )?;
            let typ = ValType::from_signal_int(signal);
            writeln!(w, "let value = (value / factor) as {typ};")?;
            writeln!(w)?;
        }
    }

    pack_bits(w, signal, msg)?;

    writeln!(w, "Ok(())")?;
    Ok(())
}

/// Pack `value` into the message payload.
fn pack_bits(w: &mut impl Write, signal: &Signal, msg: &Message) -> Result<()> {
    if signal.value_type == Signed {
        let typ = ValType::from_signal_uint(signal);
        writeln!(w, "let value = {typ}::from_ne_bytes(value.to_ne_bytes());")?;
    }

    match signal.byte_order {
        LittleEndian => {
            let (start, end) = le_start_end_bit(signal, msg)?;
            writeln!(
                w,
                r"self.raw.view_bits_mut::<Lsb0>()[{start}..{end}].store_le(value);",
            )?;
        }
        BigEndian => {
            let (start, end) = be_start_end_bit(signal, msg)?;
            writeln!(
                w,
                r"self.raw.view_bits_mut::<Msb0>()[{start}..{end}].store_be(value);",
            )?;
        }
    }

    Ok(())
}

/// Generate the raw getter and setter for a signal.
fn render_raw_accessors(w: &mut impl Write, signal: &Signal, msg: &Message) -> Result<()> {
    let field = signal.field_name();
    let typ = ValType::from_signal_int(signal);

    writeln!(w, "/// Returns the raw value of `{}`.", signal.name)?;
    writeln!(w, "///")?;
    writeln!(w, "/// - Start bit: {}", signal.start_bit)?;
    writeln!(w, "/// - Signal size: {} bits", signal.size)?;
    writeln!(w, "/// - Byte order: {:?}", signal.byte_order)?;
    writeln!(w, "/// - Value type: {:?}", signal.value_type)?;
    writeln!(w, "#[inline(always)]")?;
    writeln!(w, "pub fn {field}_raw_val(&self) -> {typ} {{")?;
    {
        let mut w = PadAdapter::wrap(&mut *w);
        writeln!(w, "{}", read_fn(signal, msg)?)?;
    }
    writeln!(w, "}}")?;
    writeln!(w)?;

    // To avoid accidentally changing the multiplexor value without changing
    // the signals accordingly this fn is kept private for multiplexors.
    let visibility = if signal.multiplexer_indicator == Multiplexor {
        ""
    } else {
        "pub "
    };

    writeln!(w, "/// Sets the raw value of `{}`.", signal.name)?;
    if visibility.is_empty() {
        // Private multiplexor raw setters have no internal caller.
        writeln!(w, "#[allow(dead_code)]")?;
    }
    writeln!(w, "#[inline(always)]")?;
    writeln!(
        w,
        "{visibility}fn set_{field}_raw_val(&mut self, value: {typ}) {{",
    )?;
    {
        let mut w = PadAdapter::wrap(&mut *w);
        pack_bits(&mut w, signal, msg)?;
    }
    writeln!(w, "}}")?;
    writeln!(w)?;

    Ok(())
}

enum DuplicateType {
    Unique,
    FirstDuplicate,
    Duplicate,
}

/// Variant info for enum generation
struct VariantInfo {
    base_name: String,
    value: i64,
    dup_type: DuplicateType,
    value_type: String,
}

/// Generate variant info for enum generation.
/// For duplicates, uses tuple variants like `Reserved(u8)` instead of separate variants.
fn generate_variant_info(variants: &[ValDescription], signal_ty: ValType) -> Vec<VariantInfo> {
    // First pass: count occurrences of each base name
    let mut name_counts: HashMap<String, usize> = HashMap::new();
    for variant in variants {
        let base_name = enum_variant_name(&variant.description);
        name_counts
            .entry(base_name)
            .and_modify(|c| *c = c.saturating_add(1))
            .or_insert(1);
    }

    // Second pass: generate variant info
    let mut variant_infos = Vec::new();
    let mut seen_names: HashMap<String, usize> = HashMap::new();
    for variant in variants {
        let base_name = enum_variant_name(&variant.description);
        let count = name_counts.get(&base_name).copied().unwrap_or(0);
        let seen_count = seen_names.entry(base_name.clone()).or_insert(0);
        *seen_count = (*seen_count).saturating_add(1);

        let dup_type = if count == 1 {
            DuplicateType::Unique
        } else if *seen_count == 1 {
            DuplicateType::FirstDuplicate
        } else {
            DuplicateType::Duplicate
        };

        variant_infos.push(VariantInfo {
            base_name,
            value: variant.id,
            dup_type,
            value_type: signal_ty.to_string(),
        });
    }
    variant_infos
}

impl Config<'_> {
    fn render_embedded_can_frame(&self, w: &mut impl Write, msg: &Message) -> Result<()> {
        self.impl_embedded_can_frame.fmt_cfg(w, |w| {
            writeln!(
                w,
                "\
impl embedded_can::Frame for {0} {{
    fn new(id: impl Into<Id>, data: &[u8]) -> Option<Self> {{
        if id.into() != Self::MESSAGE_ID {{
            None
        }} else {{
            data.try_into().ok()
        }}
    }}

    fn new_remote(_id: impl Into<Id>, _dlc: usize) -> Option<Self> {{
        unimplemented!()
    }}

    fn is_extended(&self) -> bool {{
        match self.id() {{
            Id::Standard(_) => false,
            Id::Extended(_) => true,
        }}
    }}

    fn is_remote_frame(&self) -> bool {{
        false
    }}

    fn id(&self) -> Id {{
        Self::MESSAGE_ID
    }}

    fn dlc(&self) -> usize {{
        self.raw.len()
    }}

    fn data(&self) -> &[u8] {{
        &self.raw
    }}
}}",
                msg.type_name(),
            )
        })
    }
}

fn render_debug_impl(w: &mut impl Write, msg: &Message) -> Result<()> {
    let typ = msg.type_name();
    writeln!(w, r"impl core::fmt::Debug for {typ} {{")?;
    {
        let mut w = PadAdapter::wrap(w);
        writeln!(
            w,
            "fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {{",
        )?;
        {
            let mut w = PadAdapter::wrap(&mut w);
            writeln!(w, r"if f.alternate() {{")?;
            {
                let mut w = PadAdapter::wrap(&mut w);
                writeln!(w, r#"f.debug_struct("{typ}")"#)?;
                {
                    let mut w = PadAdapter::wrap(&mut w);
                    for signal in &msg.signals {
                        if signal.multiplexer_indicator == Plain {
                            writeln!(w, r#".field("{0}", &self.{0}())"#, signal.field_name())?;
                        }
                    }
                }
                writeln!(w, r".finish()")?;
            }
            writeln!(w, r"}} else {{")?;
            {
                let mut w = PadAdapter::wrap(&mut w);
                writeln!(w, r#"f.debug_tuple("{typ}").field(&self.raw).finish()"#)?;
            }
            writeln!(w, "}}")?;
        }
        writeln!(w, "}}")?;
    }
    writeln!(w, "}}")?;
    writeln!(w)?;
    Ok(())
}

fn render_defmt_impl(w: &mut impl Write, msg: &Message) -> Result<()> {
    let typ = msg.type_name();
    writeln!(w, r"impl defmt::Format for {typ} {{")?;
    {
        let mut w = PadAdapter::wrap(w);
        writeln!(w, "fn format(&self, f: defmt::Formatter) {{")?;
        {
            let mut w = PadAdapter::wrap(&mut w);
            writeln!(w, r"defmt::write!(f,")?;
            {
                let mut w = PadAdapter::wrap(&mut w);
                write!(w, r#""{typ} {{{{"#)?;
                {
                    for signal in &msg.signals {
                        if signal.multiplexer_indicator == Plain {
                            write!(w, r" {}={{:?}}", signal.name)?;
                        }
                    }
                }
                writeln!(w, r#" }}}}","#)?;

                for signal in &msg.signals {
                    if signal.multiplexer_indicator == Plain {
                        writeln!(w, "self.{}(),", signal.field_name())?;
                    }
                }
                writeln!(w, r");")?;
            }
            writeln!(w, "}}")?;
        }
    }
    writeln!(w, "}}")?;
    writeln!(w)?;
    Ok(())
}

impl Config<'_> {
    fn render_multiplexor_enums(
        &self,
        w: &mut impl Write,
        dbc: &Dbc,
        msg: &Message,
        multiplexor_signal: &Signal,
    ) -> Result<()> {
        ensure!(
            multiplexor_signal.multiplexer_indicator == Multiplexor,
            "signal {} is not the multiplexor",
            multiplexor_signal.name,
        );

        let mut multiplexed_signals = BTreeMap::new();
        for signal in &msg.signals {
            if let MultiplexedSignal(switch_index) = signal.multiplexer_indicator {
                multiplexed_signals
                    .entry(switch_index)
                    .and_modify(|v: &mut Vec<&Signal>| v.push(signal))
                    .or_insert_with(|| vec![&signal]);
            }
        }

        writeln!(w, "/// Defined values for multiplexed signal {}", msg.name)?;
        writeln!(w, "{ALLOW_LINTS}")?;
        self.write_allow_dead_code(w)?;

        self.impl_debug.fmt_attr(w, "derive(Debug)")?;
        self.impl_defmt.fmt_attr(w, "derive(defmt::Format)")?;
        self.impl_serde.fmt_attr(w, "derive(Serialize)")?;
        self.impl_serde.fmt_attr(w, "derive(Deserialize)")?;

        let enum_name = multiplex_enum_name(msg, multiplexor_signal)?;
        writeln!(w, "pub enum {enum_name} {{")?;

        {
            let mut w = PadAdapter::wrap(w);
            for switch_index in multiplexed_signals.keys() {
                writeln!(
                    w,
                    "{multiplexed_wrapper_name}({multiplexed_name}),",
                    multiplexed_wrapper_name = multiplexed_enum_variant_wrapper_name(*switch_index),
                    multiplexed_name =
                        multiplexed_enum_variant_name(msg, multiplexor_signal, *switch_index)?,
                )?;
            }
        }
        writeln!(w, "}}")?;
        writeln!(w)?;

        for (switch_index, multiplexed_signals) in &multiplexed_signals {
            let struct_name =
                multiplexed_enum_variant_name(msg, multiplexor_signal, *switch_index)?;

            writeln!(w, "{ALLOW_LINTS}")?;
            self.write_allow_dead_code(w)?;
            self.impl_debug.fmt_attr(w, "derive(Debug)")?;
            self.impl_defmt.fmt_attr(w, "derive(defmt::Format)")?;
            self.impl_serde.fmt_attr(w, "derive(Serialize)")?;
            self.impl_serde.fmt_attr(w, "derive(Deserialize)")?;
            writeln!(w, r"#[derive(Default)]")?;
            writeln!(w, "pub struct {struct_name} {{ raw: [u8; {}] }}", msg.size)?;
            writeln!(w)?;

            writeln!(w, "{ALLOW_LINTS}")?;
            self.write_allow_dead_code(w)?;
            writeln!(w, "impl {struct_name} {{")?;

            writeln!(
                w,
                "pub fn new() -> Self {{ Self {{ raw: [0u8; {}] }} }}",
                msg.size
            )?;

            for signal in multiplexed_signals {
                self.render_signal(w, signal, dbc, msg)?;
            }

            writeln!(w, "}}")?;
            writeln!(w)?;
        }

        Ok(())
    }

    fn render_arbitrary(&self, w: &mut impl Write, dbc: &Dbc, msg: &Message) -> Result<()> {
        writeln!(w, "{ALLOW_LINTS}")?;
        self.write_allow_dead_code(w)?;
        let typ = msg.type_name();
        writeln!(w, "impl<'a> Arbitrary<'a> for {typ} {{")?;
        {
            let filtered_signals: Vec<&Signal> = msg
                .signals
                .iter()
                .filter(|v| matches!(v.multiplexer_indicator, Plain | Multiplexor))
                .collect();
            let mut w = PadAdapter::wrap(w);
            writeln!(
                w,
                "fn arbitrary({}u: &mut Unstructured<'a>) -> Result<Self, arbitrary::Error> {{",
                if filtered_signals.is_empty() { "_" } else { "" },
            )?;
            {
                let mut w = PadAdapter::wrap(&mut w);

                for signal in &filtered_signals {
                    writeln!(
                        w,
                        "let {field_name} = {arbitrary_value};",
                        field_name = signal.field_name(),
                        arbitrary_value = signal_to_arbitrary(signal),
                    )?;
                }

                let args: Vec<String> = filtered_signals
                    .iter()
                    .map(|signal| {
                        let field = signal.field_name();
                        let is_enum_backed = signal_pub_type(dbc, msg, signal)
                            != ValType::from_signal(signal).to_string();
                        if is_enum_backed {
                            format!("{}::_Other({field})", enum_name(msg, signal))
                        } else {
                            field
                        }
                    })
                    .collect();

                writeln!(
                    w,
                    "{typ}::new({args}).map_err(|_| arbitrary::Error::IncorrectFormat)",
                    typ = msg.type_name(),
                    args = args.join(","),
                )?;
            }
            writeln!(w, "}}")?;
        }
        writeln!(w, "}}")?;

        Ok(())
    }

    fn render_error(&self, w: &mut impl Write) -> Result<()> {
        w.write_all(
            r#"
        #[allow(dead_code)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CanError {
    UnknownMessageId(embedded_can::Id),
    /// Signal parameter is not within the range
    /// defined in the dbc
    ParameterOutOfRange {
        /// dbc message id
        message_id: embedded_can::Id,
    },
    InvalidPayloadSize,
    /// Multiplexor value not defined in the dbc
    InvalidMultiplexor {
        /// dbc message id
        message_id: embedded_can::Id,
        /// Multiplexor value not defined in the dbc
        multiplexor: u16,
    },
}

impl core::fmt::Display for CanError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{self:?}")
    }
}
        "#
            .as_bytes(),
        )?;

        self.impl_error.fmt_cfg(w, |w| {
            writeln!(w, "impl core::error::Error for CanError {{}}")
        })
    }

    fn render_arbitrary_helpers(&self, w: &mut impl Write) -> Result<()> {
        self.impl_arbitrary.fmt_cfg(&mut *w, |w| {
            self.write_allow_dead_code(w)?;
            writeln!(w, "trait UnstructuredFloatExt {{")?;
            writeln!(w, "    fn float_in_range(&mut self, range: core::ops::RangeInclusive<f32>) -> arbitrary::Result<f32>;")?;
            writeln!(w, "}}")?;
            writeln!(w)?;
            Ok::<_, Error>(())
        })?;

        self.impl_arbitrary.fmt_cfg(w, |w| {
            writeln!(w, "impl UnstructuredFloatExt for arbitrary::Unstructured<'_> {{")?;
            writeln!(w, "    fn float_in_range(&mut self, range: core::ops::RangeInclusive<f32>) -> arbitrary::Result<f32> {{")?;
            writeln!(w, "        let min = range.start();")?;
            writeln!(w, "        let max = range.end();")?;
            writeln!(w, "        let steps = u32::MAX;")?;
            writeln!(w, "        let factor = (max - min) / (steps as f32);")?;
            writeln!(w, "        let random_int: u32 = self.int_in_range(0..=steps)?;")?;
            writeln!(w, "        let random = min + factor * (random_int as f32);")?;
            writeln!(w, "        Ok(random)")?;
            writeln!(w, "    }}")?;
            writeln!(w, "}}")?;
            writeln!(w)?;
            Ok::<_, Error>(())
        })
    }
}

fn signal_to_arbitrary(signal: &Signal) -> String {
    let typ = ValType::from_signal(signal);
    match typ {
        ValType::Bool => "u.int_in_range(0..=1)? == 1".to_string(),
        ValType::F32 => {
            let min = signal.min;
            let max = signal.max;
            format!("u.float_in_range({min}_f32..={max}_f32)?")
        }
        _ => {
            let min = signal.min;
            let max = signal.max;
            format!("u.int_in_range({min}..={max})?")
        }
    }
}

fn get_relevant_messages(dbc: &Dbc) -> impl Iterator<Item = &Message> {
    dbc.messages.iter().filter(|v| !message_ignored(v))
}

fn message_ignored(message: &Message) -> bool {
    // DBC internal message containing signals unassigned to any real message
    message.name == "VECTOR__INDEPENDENT_SIG_MSG"
}

/// Resolve a [`FieldSource`] to a Rust literal.
fn resolve_field_source(source: &FieldSource<'_>, target: &AttrTarget<'_>) -> Option<String> {
    let AttrTarget {
        msg,
        dbc,
        signal,
        node,
    } = *target;
    match source {
        FieldSource::Attr(name) => match (signal, node) {
            (Some(s), None) => dbc.resolved_signal_attribute(msg.id, &s.name, name),
            (None, None) => dbc.resolved_message_attribute(msg.id, name),
            (Some(s), Some(n)) => {
                resolved_node_relation_attribute(dbc, n, msg.id, Some(&s.name), name)
            }
            (None, Some(n)) => resolved_node_relation_attribute(dbc, n, msg.id, None, name),
        }
        .map(attr_value_literal),
        FieldSource::MessageAttr(name) => dbc
            .resolved_message_attribute(msg.id, name)
            .map(attr_value_literal),
        FieldSource::StartBit => signal.map(|s| s.start_bit.to_string()),
        FieldSource::StartByte => signal.map(|s| signal_start_byte(s).to_string()),
        FieldSource::BitWidth => signal.map(|s| s.size.to_string()),
        FieldSource::MessageSize => Some(msg.size.to_string()),
        FieldSource::Int(v) => Some(v.to_string()),
        FieldSource::Str(v) => Some(format!("{v:?}")),
        FieldSource::NodeName => node.map(|n| format!("{n:?}")),
    }
}

/// Lookup an assigned node relation attribute value. This can be either
/// node-to-signal (`BA_REL_ ... BU_SG_REL_`, `signal_name: Some`) or
/// node-to-message (`BA_REL_ ... BU_BO_REL_`, `signal_name: None`).
fn node_relation_attribute<'a>(
    dbc: &'a Dbc,
    node_name: &str,
    message_id: MessageId,
    signal_name: Option<&str>,
    name: &str,
) -> Option<&'a AttributeValue> {
    dbc.relation_attribute_values.iter().find_map(|rel| {
        if rel.name != name {
            return None;
        }
        match (&rel.details, signal_name) {
            (
                AttributeValueForRelationType::NodeToSignal {
                    node_name: n,
                    message_id: mid,
                    signal_name: sig,
                    value,
                },
                Some(want_sig),
            ) if n == node_name && *mid == message_id && sig == want_sig => Some(value),
            (
                AttributeValueForRelationType::NodeToMessage {
                    node_name: n,
                    message_id: mid,
                    value,
                },
                None,
            ) if n == node_name && *mid == message_id => Some(value),
            _ => None,
        }
    })
}

/// Lookup a node relation attribute value.
/// Uses the default (`BA_DEF_DEF_REL_`) if a value is not assigned.
fn resolved_node_relation_attribute<'a>(
    dbc: &'a Dbc,
    node_name: &str,
    message_id: MessageId,
    signal_name: Option<&str>,
    name: &str,
) -> Option<&'a AttributeValue> {
    node_relation_attribute(dbc, node_name, message_id, signal_name, name).or_else(|| {
        dbc.relation_attribute_defaults
            .iter()
            .find(|d| d.name == name)
            .map(|d| &d.value)
    })
}

/// Byte index of a signal's start bit.
fn signal_start_byte(signal: &Signal) -> u64 {
    signal.start_bit.checked_div(8).unwrap_or(0)
}

/// Render an attribute value as an un-suffixed Rust literal.
fn attr_value_literal(value: &AttributeValue) -> String {
    match value {
        AttributeValue::Uint(v) => v.to_string(),
        AttributeValue::Int(v) => v.to_string(),
        AttributeValue::Double(v) => format!("{v:?}"),
        AttributeValue::String(v) => format!("{v:?}"),
    }
}

/// Cycle time in milliseconds from an assigned `GenMsgCycleTime` (`BA_`)
/// attribute, if it is present and a non-negative integer that fits within a `u32`.
fn message_cycle_time_ms(dbc: &Dbc, id: MessageId) -> Option<u32> {
    match dbc.message_attribute(id, "GenMsgCycleTime")? {
        AttributeValue::Uint(v) => u32::try_from(*v).ok(),
        AttributeValue::Int(v) => u32::try_from(*v).ok(),
        AttributeValue::Double(_) | AttributeValue::String(_) => None,
    }
}

impl Config<'_> {
    /// Generate Rust structs matching DBC input description and return as String
    pub fn generate(self) -> Result<String> {
        let mut out = Vec::new();
        self.codegen(&mut out)
            .context("could not generate Rust code")?;
        // Parse and re-format the generated code to allow for future
        // syn/quote codegen migration. Note that this is inefficient at the moment,
        // but this shouldn't be significantly noticeable.
        let out = std::str::from_utf8(&out).context("Failed to convert output to str")?;
        let file = syn::parse_file(out).context("Failed to parse generated Rust code")?;
        Ok(prettyplease::unparse(&file))
    }

    /// Generate Rust structs matching DBC input description and write to `out`
    pub fn write(self, mut out: impl Write) -> Result<()> {
        out.write_all(self.generate()?.as_bytes())?;
        Ok(())
    }

    /// Generate Rust structs matching DBC input description and write to file at `path`
    pub fn write_to_file<P: AsRef<Path>>(self, path: P) -> Result<()> {
        let file = OpenOptions::new()
            .write(true)
            .truncate(true)
            .create(true)
            .open(path.as_ref())?;

        self.write(file)
    }

    fn write_allow_dead_code(&self, w: &mut impl Write) -> Result<()> {
        if self.allow_dead_code {
            writeln!(w, "{ALLOW_DEADCODE}")?;
        }
        Ok(())
    }
}