stm32ral 0.8.0

Register access layer for all STM32 microcontrollers
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
#!/usr/bin/env python3
"""
stm32ral.py
Copyright 2018 Adam Greig
Licensed under MIT and Apache 2.0, see LICENSE_MIT and LICENSE_APACHE.
"""

import os
import copy
import argparse
import itertools
import subprocess
import multiprocessing
import xml.etree.ElementTree as ET
from fnmatch import fnmatch


CRATE_LIB_PREAMBLE = """\
// Copyright 2018 Adam Greig
// See LICENSE-APACHE and LICENSE-MIT for license details.

//! This project provides a register access layer (RAL) for all
//! STM32 microcontrollers.
//!
//! When built, you must specify a device feature, such as `stm32f405`.
//! This will cause all modules in that device's module to be re-exported
//! from the top level, so that for example `stm32ral::gpio` will resolve to
//! `stm32ral::stm32f4::stm32f405::gpio`.
//!
//! In the generated documentation, all devices are visible inside their family
//! modules, but when built for a specific device, only that devices' constants
//! will be available.
//!
//! See the
//! [README](https://github.com/adamgreig/stm32ral/blob/master/README.md)
//! for example usage.

#![no_std]

#[cfg(feature="rt")]
extern crate cortex_m_rt;

mod register;

#[cfg(feature="rt")]
pub use cortex_m_rt::interrupt;

pub use crate::register::{RORegister, UnsafeRORegister};
pub use crate::register::{WORegister, UnsafeWORegister};
pub use crate::register::{RWRegister, UnsafeRWRegister};
"""


CRATE_CARGO_TOML_PREAMBLE = """\
# Generated by stm32ral.py. Do not edit manually.

[package]
name = "stm32ral"
authors = ["Adam Greig <adam@adamgreig.com>"]
description = "Register access layer for all STM32 microcontrollers"
repository = "https://github.com/adamgreig/stm32ral"
documentation = "https://docs.rs/stm32ral"
readme = "README.md"
keywords = ["stm32", "embedded", "no_std"]
categories = ["embedded", "no-std"]
license = "MIT/Apache-2.0"
edition = "2018"
exclude = ["/stm32-rs"]

# Change version in stm32ral.py, not in Cargo.toml!
version = "0.8.0"

[package.metadata.docs.rs]
features = ["doc"]
no-default-features = true
targets = []

[dependencies]
# Change dependency versions in stm32ral.py, not here!
external_cortex_m = { package = "cortex-m", version = "0.7.3" }
cortex-m-rt = { version = ">=0.6.15,<0.8", optional = true }

[features]
default = ["rt"]
rt = ["cortex-m-rt/device"]
inline-asm = ["external_cortex_m/inline-asm"]
rtfm = ["rtic"]
rtic = []
nosync = []
doc = []
"""


BUILD_RS_TEMPLATE = """\
use std::env;
use std::fs;
use std::path::PathBuf;
fn main() {{
    if env::var_os("CARGO_FEATURE_RT").is_some() {{
        let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
        println!("cargo:rustc-link-search={{}}", out.display());
        let device_file = {device_clauses};
        fs::copy(device_file, out.join("device.x")).unwrap();
        println!("cargo:rerun-if-changed={{}}", device_file);
    }}
    println!("cargo:rerun-if-changed=build.rs");
}}
"""


UNSAFE_REGISTERS = [
    # DMA peripheral and memory address registers
    "S?PAR", "S?M?AR", "CPAR?", "CMAR?",

    # DMA2D address registers
    "FGMAR", "BGMAR", "FGCMAR", "BGCMAR", "OMAR",

    # LTDC frame buffer address register
    "L?CFBAR",

    # USB OTG DMA address register
    "DIEPDMA*", "DOEPDMA*", "HCDMA*",

    # Ethernet DMA descriptor list address register
    "DMARDLAR", "DMATDLAR",

    # Cache operations
    "ICIALLU", "?C?MVA?", "DC?SW", "DCCIMVAC", "DCCISW", "BPIALL",
]


class Node:
    """
    A node in the overall graph.
    """
    pass


class EnumeratedValue(Node):
    """
    Represents a possible named value for a field.

    Has a name, description, and value.
    Belongs to one or more parent Fields.
    """
    def __init__(self, name, desc, value, register_size):
        self.name = name
        self.desc = desc
        self.value = value
        self.register_size = register_size
        if self.name[0] in "0123456789":
            self.name = "_" + self.name
            print("Name started with a number:", self.name)

    def to_dict(self):
        return {"name": self.name, "desc": self.desc, "value": self.value}

    def to_rust(self, field_width):
        return f"""
        /// 0b{self.value:0{field_width}b}: {escape_desc(self.desc)}
        pub const {self.name}: u{self.register_size} = 0b{self.value:0{field_width}b};"""

    @classmethod
    def from_svd(cls, svd, node, register_size):
        name = get_string(node, 'name')
        desc = get_string(node, 'description')
        value = get_int(node, 'value')
        return cls(name, desc, value, register_size)

    def __eq__(self, other):
        return (
            self.name == other.name and
            self.value == other.value and
            self.desc == other.desc)

    def __lt__(self, other):
        return self.value < other.value


class EnumeratedValues(Node):
    """
    Represents possible named values for a field, emitted as a concrete Enum.

    Contains many child EnumeratedValues.
    """
    def __init__(self, name):
        self.name = name
        self.values = []

    def to_dict(self):
        return {"name": self.name,
                "values": [v.to_dict() for v in self.values]}

    def to_rust(self, field_width):
        values = "\n".join(v.to_rust(field_width) for v in self.values)
        if self.name == "R":
            desc = "Read-only values"
        elif self.name == "W":
            desc = "Write-only values"
        else:
            desc = "Read-write values"
        if not values:
            desc += " (empty)"
        return f"""\
        /// {desc}
        pub mod {self.name} {{
            {values}
        }}"""

    @classmethod
    def from_svd(cls, svd, node, register_size):
        usage = get_string(node, 'usage')
        if usage == "read":
            name = "R"
        elif usage == "write":
            name = "W"
        else:
            name = "RW"
        evs = cls(name)
        for ev in node.findall('enumeratedValue'):
            evs.values.append(EnumeratedValue.from_svd(svd, ev, register_size))
        return evs

    @classmethod
    def empty(cls, name):
        return cls(name)

    def __eq__(self, other):
        return (
            self.name == other.name and
            len(self.values) == len(other.values) and
            all(v1 == v2 for v1, v2
                in zip(sorted(self.values), sorted(other.values))))


class EnumeratedValuesLink(Node):
    """
    Represents an EnumeratedValues enum which is included with 'use'.
    """
    def __init__(self, field, evs):
        self.field = field
        self.evs = evs

    def to_dict(self):
        return {"field": self.field.name, "evs": self.evs.name}

    def to_rust(self, field_width):
        return f"pub use ::super::{self.field.name}::{self.evs.name};"

    def __eq__(self, other):
        return self.evs.__eq__(other)

    @property
    def name(self):
        return self.evs.name

    @property
    def values(self):
        return self.evs.values


class Field(Node):
    """
    Represents a field in a register.

    Has a name, description, width, offset, access, and three child
    EnumeratedValues: R, W, and RW.
    Belongs to a parent Register.
    May contain one or more child EnumeratedValues.
    register_size is the size of the register containing this field
    """
    def __init__(self, name, desc, register_size, width, offset, access, r, w, rw):
        self.name = name
        self.desc = desc
        self.width = width
        self.offset = offset
        self.access = access
        self.r = r
        self.w = w
        self.rw = rw
        self.register_size = register_size
        if self.name[0] in "0123456789":
            self.name = "_" + self.name
            print("Name started with a number:", self.name)

    def to_dict(self):
        return {"name": self.name, "desc": self.desc, "width": self.width,
                "offset": self.offset, "access": self.access,
                "r": self.r.to_dict(), "w": self.w.to_dict(),
                "rw": self.rw.to_dict()}

    def to_rust(self):
        mask = 2**self.width - 1
        if self.width == 1:
            mask = "1"
        elif self.width < 6:
            mask = f"0b{mask:b}"
        else:
            mask = f"0x{mask:x}"
        bits = f"bit{'s' if self.width>1 else ''}"
        ty = f"u{self.register_size}"
        return f"""
        /// {escape_desc(self.desc)}
        pub mod {self.name} {{
            /// Offset ({self.offset} bits)
            pub const offset: {ty} = {self.offset};
            /// Mask ({self.width} {bits}: {mask} << {self.offset})
            pub const mask: {ty} = {mask} << offset;
            {self.r.to_rust(self.width)}
            {self.w.to_rust(self.width)}
            {self.rw.to_rust(self.width)}
        }}"""

    @classmethod
    def from_svd(cls, svd, node, ctx):
        ctx = ctx.inherit(node)
        name = get_string(node, 'name')
        desc = get_string(node, 'description')
        width = get_int(node, 'bitWidth')
        offset = get_int(node, 'bitOffset')
        access = ctx.access
        # Round up register_size to a size that's representable as a Rust
        # unsigned integer. We probably will never see a register that's
        # not a multiple of 8, so this might be overkill.
        register_size = (ctx.size + 7) & (~7)
        if register_size != ctx.size:
            print(f"Field {name} will be represented using u{register_size}s, "
                  f"although the register size is {ctx.size} bits")
        r = EnumeratedValues.empty("R")
        w = EnumeratedValues.empty("W")
        rw = EnumeratedValues.empty("RW")
        for evs in node.findall('enumeratedValues'):
            if 'derivedFrom' in evs.attrib:
                df = evs.attrib['derivedFrom']
                evs = svd.find(f".//enumeratedValues[name='{df}']")
                if evs is None:
                    raise ValueError(f"Can't find derivedFrom {df}")
            evs = EnumeratedValues.from_svd(svd, evs, register_size)
            evsname = evs.name
            if evsname == "R":
                r = evs
            elif evsname == "W":
                w = evs
            else:
                rw = evs
        field = cls(name, desc, register_size, width, offset, access, r, w, rw)
        return field

    def __eq__(self, other):
        return (
            self.name == other.name and
            self.width == other.width and
            self.offset == other.offset and
            self.access == other.access and
            self.r == other.r and self.w == other.w and self.rw == other.rw)

    def __lt__(self, other):
        return (self.offset, self.name) < (other.offset, other.name)


class FieldLink(Node):
    """
    A Field which outputs a `use` statement instead of a module.
    """
    def __init__(self, parent, path):
        self.parent = parent
        self.path = path
        self.r = parent.r
        self.w = parent.w
        self.rw = parent.rw

    def to_dict(self):
        return {"parent": self.parent.name, "path": self.path}

    def to_rust(self):
        return f"pub use {self.path}::{self.parent.name};"

    def __lt__(self, other):
        return self.parent.__lt__(other)

    def __eq__(self, other):
        return self.parent.__eq__(other)

    @property
    def name(self):
        return self.parent.name

    @property
    def desc(self):
        return self.parent.desc

    @property
    def width(self):
        return self.parent.width

    @property
    def offset(self):
        return self.parent.offset

    @property
    def access(self):
        return self.parent.access


class RegisterCtx:
    """
    The inheritance context for register properties.
    Equivalent to an SVD `registerPropertiesGroup`.
    """
    def __init__(self, size, access, reset_value, reset_mask):
        self.size = size
        self.access = access
        self.reset_value = reset_value
        self.reset_mask = reset_mask

    @classmethod
    def empty(cls):
        """Make an empty context."""
        return cls(None, None, None, None)

    def copy(self):
        """Return a copy of self."""
        return RegisterCtx(self.size, self.access, self.reset_value,
                           self.reset_mask)

    def update_from_node(self, node):
        """
        Copies any specified properties from the given node into self,
        leaving unspecified properties unchanged. Returns self for
        easier chaining.
        """
        size = get_int(node, 'size')
        access = get_string(node, 'access')
        reset_value = get_int(node, 'resetValue')
        reset_mask = get_int(node, 'resetMask')
        if size is not None:
            self.size = size
        if access is not None:
            self.access = access
        if reset_value is not None:
            self.reset_value = reset_value
        if reset_mask is not None:
            self.reset_mask = reset_mask
        return self

    def inherit(self, node):
        """Return a copy of self which has been updated using `node`."""
        return self.copy().update_from_node(node)


class Register(Node):
    """
    Represents a register in a peripheral.

    Has a name, description, offset, size, access, reset value and mask.
    Belongs to a parent Peripheral.
    May contain one or more child Fields.
    """
    def __init__(self, name, desc, offset, size, access, reset_value,
                 reset_mask):
        self.name = name
        self.desc = desc
        self.offset = offset
        self.size = size
        self.access = access
        self.reset_value = reset_value
        self.reset_mask = reset_mask
        self.fields = []

    def to_dict(self):
        return {"name": self.name, "desc": self.desc, "offset": self.offset,
                "size": self.size, "access": self.access,
                "reset_value": self.reset_value, "reset_mask": self.reset_mask,
                "fields": [x.to_dict() for x in self.fields]}

    def to_rust_mod(self):
        """
        Returns a Rust public module containing a public module for each
        of this register's fields.
        """
        fields = "\n".join(f.to_rust() for f in self.fields)
        return f"""
        /// {escape_desc(self.desc)}
        pub mod {self.name} {{
            {fields}
        }}"""

    def to_regtype(self):
        """
        Return the type of register (RORegister, UnsafeWORegister, etc)
        used for this Register.
        """
        regtype = {"read-only": "RORegister", "write-only": "WORegister",
                   "read-write": "RWRegister"}[self.access]
        for unsafe in UNSAFE_REGISTERS:
            if fnmatch(self.name, unsafe):
                regtype = "Unsafe" + regtype
                break
        return regtype

    def to_rust_struct_entry(self):
        """Returns the RegisterBlock entry for this register."""
        regtype = self.to_regtype()
        return f"""
        /// {escape_desc(self.desc)}
        pub {self.name}: {regtype}<u{self.size}>,
        """

    @classmethod
    def from_svd(cls, svd, node, ctx):
        ctx = ctx.inherit(node)
        name = get_string(node, 'name')
        desc = get_string(node, 'description')
        offset = get_int(node, 'addressOffset')
        register = cls(name, desc, offset, ctx.size, ctx.access,
                       ctx.reset_value, ctx.reset_mask)
        fields = node.find('fields')
        if fields is not None:
            for field in fields.findall('field'):
                register.fields.append(Field.from_svd(svd, field, ctx))
        if register.access is None:
            # This happens if access is defined per-field, typically because
            # there is one or two read-write among many read-only registers.
            field_accesses = [f.access for f in register.fields]
            if all(access == "read-only" for access in field_accesses):
                register.access = "read-only"
            elif all(access == "write-only" for access in field_accesses):
                register.access = "write-only"
            else:
                register.access = "read-write"
        return register

    def __eq__(self, other):
        return (
            self.name == other.name and
            self.offset == other.offset and
            self.size == other.size and
            self.access == other.access and
            sorted(self.fields) == sorted(other.fields)
        )

    def __lt__(self, other):
        return (self.offset, self.name) < (other.offset, other.name)

    def refactor_common_field_values(self):
        """
        Go through all fields in this register and where two fields have the
        same set of enumated values, replace the latter's with a link to the
        former's.
        """
        replace = []
        to_replace = set()
        fields = enumerate(self.fields)
        for (idx1, f1), (idx2, f2) in itertools.combinations(fields, 2):
            if f1 is f2 or idx1 in to_replace or idx2 in to_replace:
                continue
            if f1.r == f2.r and f1.r.values:
                replace.append((idx1, idx2, 'r'))
                to_replace.add(idx2)
            if f1.w == f2.w and f1.w.values:
                replace.append((idx1, idx2, 'w'))
                to_replace.add(idx2)
            if f1.rw == f2.rw and f1.rw.values:
                replace.append((idx1, idx2, 'rw'))
                to_replace.add(idx2)
        for idx1, idx2, name in replace:
            f1 = self.fields[idx1]
            evs1 = getattr(f1, name)
            f2 = EnumeratedValuesLink(f1, evs1)
            setattr(self.fields[idx2], name, f2)

    def consume(self, other, parent):
        """
        Adds any fields from other to self, and adjusts self's name to the
        common prefix of the two names, if such a prefix is at least
        2 letters long.
        """
        my_field_names = set(f.name for f in self.fields)
        for field in other.fields:
            if field.name not in my_field_names:
                self.fields.append(field)
        self.desc = "\n/// ".join([
            f"{self.name} and {other.name}",
            f"{self.name}: {escape_desc(self.desc)}",
            f"{other.name}: {escape_desc(other.desc)}",
        ])
        self.size = max(self.size, other.size)
        self.access = "read-write"
        newname = common_name(self.name, other.name, parent.name)
        if newname != self.name[:len(newname)]:
            print(f"Warning [{parent.name}]: {self.name}+{other.name} "
                  f"-> {newname}: suspected name compaction failure")
        if newname != self.name:
            if newname not in [r.name for r in parent.registers]:
                self.name = newname
            else:
                print(f"Warning [{parent.name}]: {self.name} + {other.name} "
                      f"-> {newname}: name already exists, using {self.name}")


class PeripheralInstance(Node):
    """
    Represents a specific peripheral instance in a device.

    For example, GPIOA is a PeripheralInstance, while GPIO is a
    PeripheralPrototype which would contain GPIOA. For many
    peripherals there is a single PeripheralPrototype containing
    a single PeripheralInstance.

    Has a name and base address.
    Belongs to a parent PeripheralPrototype.
    """
    def __init__(self, name, addr, reset_values):
        self.name = name
        self.addr = addr
        self.reset_values = reset_values

    def to_dict(self):
        return {"name": self.name, "addr": self.addr,
                "reset_values": self.reset_values}

    def to_rust(self, registers):
        registers = {r.offset: r.name for r in registers}
        resets = ", ".join(
            f"{registers[k]}: 0x{v:08X}" for k, v in self.reset_values.items())
        return f"""
        /// Access functions for the {self.name} peripheral instance
        pub mod {self.name} {{
            use super::ResetValues;

            #[cfg(not(feature="nosync"))]
            use super::Instance;

            #[cfg(not(feature="nosync"))]
            const INSTANCE: Instance = Instance {{
                addr: 0x{self.addr:08x},
                _marker: ::core::marker::PhantomData,
            }};

            /// Reset values for each field in {self.name}
            pub const reset: ResetValues = ResetValues {{
                {resets}
            }};

            #[cfg(not(feature="nosync"))]
            #[allow(renamed_and_removed_lints)]
            #[allow(private_no_mangle_statics)]
            #[no_mangle]
            static mut {self.name}_TAKEN: bool = false;

            /// Safe access to {self.name}
            ///
            /// This function returns `Some(Instance)` if this instance is not
            /// currently taken, and `None` if it is. This ensures that if you
            /// do get `Some(Instance)`, you are ensured unique access to
            /// the peripheral and there cannot be data races (unless other
            /// code uses `unsafe`, of course). You can then pass the
            /// `Instance` around to other functions as required. When you're
            /// done with it, you can call `release(instance)` to return it.
            ///
            /// `Instance` itself dereferences to a `RegisterBlock`, which
            /// provides access to the peripheral's registers.
            #[cfg(not(feature="nosync"))]
            #[inline]
            pub fn take() -> Option<Instance> {{
                external_cortex_m::interrupt::free(|_| unsafe {{
                    if {self.name}_TAKEN {{
                        None
                    }} else {{
                        {self.name}_TAKEN = true;
                        Some(INSTANCE)
                    }}
                }})
            }}

            /// Release exclusive access to {self.name}
            ///
            /// This function allows you to return an `Instance` so that it
            /// is available to `take()` again. This function will panic if
            /// you return a different `Instance` or if this instance is not
            /// already taken.
            #[cfg(not(feature="nosync"))]
            #[inline]
            pub fn release(inst: Instance) {{
                external_cortex_m::interrupt::free(|_| unsafe {{
                    if {self.name}_TAKEN && inst.addr == INSTANCE.addr {{
                        {self.name}_TAKEN = false;
                    }} else {{
                        panic!("Released a peripheral which was not taken");
                    }}
                }});
            }}

            /// Unsafely steal {self.name}
            ///
            /// This function is similar to take() but forcibly takes the
            /// Instance, marking it as taken irregardless of its previous
            /// state.
            #[cfg(not(feature="nosync"))]
            #[inline]
            pub unsafe fn steal() -> Instance {{
                {self.name}_TAKEN = true;
                INSTANCE
            }}
        }}

        /// Raw pointer to {self.name}
        ///
        /// Dereferencing this is unsafe because you are not ensured unique
        /// access to the peripheral, so you may encounter data races with
        /// other users of this peripheral. It is up to you to ensure you
        /// will not cause data races.
        ///
        /// This constant is provided for ease of use in unsafe code: you can
        /// simply call for example `write_reg!(gpio, GPIOA, ODR, 1);`.
        pub const {self.name}: *const RegisterBlock =
            0x{self.addr:08x} as *const _;"""

    def __lt__(self, other):
        return self.name < other.name

    def __eq__(self, other):
        return (self.name == other.name and
                self.addr == other.addr and
                self.reset_values == other.reset_values)


class PeripheralPrototype(Node):
    """
    Represents a generic peripheral with registers.

    Has a name and description.
    Belongs to a parent Device.
    Contains child PeripheralInstances and Registers.

    Also contains a list of device names which contain this peripheral,
    used to ensure shared peripherals are only compiled when the crate
    is built for a device which uses them.
    """
    def __init__(self, name, desc):
        self.name = name.lower()
        self.desc = desc
        self.registers = []
        self.instances = []
        self.parent_device_names = []

    def to_dict(self):
        return {"name": self.name, "desc": self.desc,
                "registers": [x.to_dict() for x in self.registers],
                "instances": [x.to_dict() for x in self.instances]}

    def to_rust_register_block(self):
        """Creates a RegisterBlock for this peripheral."""
        lines = []
        address = 0
        reservedctr = 1
        for register in sorted(self.registers):
            if register.offset < address:
                raise RuntimeError("Unexpected register aliasing")
            if register.offset != address:
                gaps = []
                u8s = register.offset - address
                if u8s != 0:
                    gaps.append(f"[u8; {u8s}]")
                    address += u8s
                for gaptype in gaps:
                    lines.append(f"_reserved{reservedctr}: {gaptype},")
                    reservedctr += 1
            lines.append(register.to_rust_struct_entry())
            address += register.size // 8
        lines = "\n".join(lines)
        return f"""
        #[repr(C)]
        pub struct RegisterBlock {{
            {lines}
        }}"""

    def to_rust_reset_values(self):
        """Creates a ResetValues struct for this peripheral."""
        lines = []
        for register in sorted(self.registers):
            lines.append(f"pub {register.name}: u{register.size},")
        lines = "\n".join(lines)
        return f"""
        pub struct ResetValues {{
            {lines}
        }}"""

    def to_rust_instance(self):
        """Creates an Instance struct for this peripheral."""
        return """
        #[cfg(not(feature="nosync"))]
        pub struct Instance {
            pub(crate) addr: u32,
            pub(crate) _marker: PhantomData<*const RegisterBlock>,
        }
        #[cfg(not(feature="nosync"))]
        impl ::core::ops::Deref for Instance {
            type Target = RegisterBlock;
            #[inline(always)]
            fn deref(&self) -> &RegisterBlock {
                unsafe { &*(self.addr as *const _) }
            }
        }
        #[cfg(feature="rtic")]
        unsafe impl Send for Instance {}

        """

    def to_rust_file(self, path):
        """
        Creates {peripheral}.rs in path, and writes all register modules,
        field modules, the register block, and any instances to that file.
        Finally runs rustfmt over the new file.
        """
        regtypes = set(r.to_regtype() for r in self.registers)
        regtypes = ", ".join(regtypes)
        if self.desc is None:
            print(self.to_dict())
        desc = "\n//! ".join(escape_desc(self.desc).split("\n"))
        if len(self.parent_device_names) > 1:
            desc += "\n//!\n"
            desc += "//! Used by: " + ', '.join(
                sorted(set(self.parent_device_names)))
        preamble = "\n".join([
            "#![allow(non_snake_case, non_upper_case_globals)]",
            "#![allow(non_camel_case_types)]",
            f"//! {desc}",
            "",
            "#[cfg(not(feature=\"nosync\"))]",
            "use core::marker::PhantomData;",
            f"use crate::{{{regtypes}}};",
            "",
        ])
        modules = "\n".join(r.to_rust_mod() for r in self.registers)
        instances = "\n".join(i.to_rust(self.registers)
                              for i in sorted(self.instances))
        fname = os.path.join(path, f"{self.name}.rs")
        with open(fname, "w") as f:
            f.write(preamble)
            f.write(modules)
            f.write(self.to_rust_register_block())
            f.write(self.to_rust_reset_values())
            f.write(self.to_rust_instance())
            f.write(instances)
        rustfmt(fname)

    def to_parent_entry(self):
        return f"pub mod {self.name};\n"

    def to_struct_entry(self):
        lines = []
        for instance in self.instances:
            lines.append(f"pub {instance.name}: {self.name}::Instance,")
        return "\n".join(lines)

    def to_struct_steal(self):
        lines = []
        for instance in self.instances:
            lines.append(
                f"{instance.name}: "
                f"{self.name}::{instance.name}::steal(),")
        return "\n".join(lines) + "\n"

    @classmethod
    def from_svd(cls, svd, node, register_ctx):
        name = get_string(node, 'name')
        addr = get_int(node, 'baseAddress')
        desc = get_string(node, 'description')
        registers = node.find('registers')
        if 'derivedFrom' in node.attrib:
            df = node.attrib['derivedFrom']
            df_node = svd.find(f".//peripheral[name='{df}']")
            if df_node is None:
                raise ValueError("Can't find derivedFrom[{df}]")
            desc = get_string(df_node, 'description', default=desc)
            addr = get_int(node, 'baseAddress', addr)
            registers = df_node.find('registers')
            register_ctx = register_ctx.inherit(df_node)
        register_ctx = register_ctx.inherit(node)
        peripheral = cls(name, desc)
        if registers is None:
            raise ValueError(f"No registers found for peripheral {name}")
        ctx = register_ctx
        for register in registers.findall('register'):
            # If register has a 'dim' field, expand to multiple registers
            for dimr in expand_dim(register):
                peripheral.registers.append(Register.from_svd(svd, dimr, ctx))
        for cluster in registers.findall('cluster'):
            for dimc in expand_dim(cluster):
                for clusr in expand_cluster(dimc):
                    reg = Register.from_svd(svd, clusr, ctx)
                    peripheral.registers.append(reg)
        resets = {r.offset: r.reset_value for r in peripheral.registers}
        peripheral.instances.append(PeripheralInstance(name, addr, resets))
        return peripheral

    def consume(self, other, parent):
        """
        Adds any PeripheralInstances from other to self, and adjusts self's
        name to the common prefix of the two names, if such a prefix is
        at least 3 letters long.
        """
        self.instances += other.instances
        newname = common_name(self.name, other.name, parent.name)
        if newname != self.name:
            if newname not in [p.name for p in parent.peripherals]:
                self.name = newname
            else:
                print(f"Warning [{parent.name}]: {self.name} + {other.name} "
                      f"-> {newname}: name already exists, using {self.name}")

    def refactor_common_register_fields(self):
        """
        Go through all registers in this peripheral and where two registers
        have the same set of fields, replace the latter's with links to the
        former's.
        """
        replace = []
        to_replace = set()
        registers = enumerate(self.registers)
        for (idx1, r1), (idx2, r2) in itertools.combinations(registers, 2):
            if r1 is r2 or idx1 in to_replace or idx2 in to_replace:
                continue
            if r1.fields == r2.fields and r1.fields:
                replace.append((idx1, idx2))
                to_replace.add(idx2)
        for idx1, idx2 in replace:
            r1 = self.registers[idx1]
            r2 = self.registers[idx2]
            path = f"super::{r1.name}"
            r2.fields = [FieldLink(f, path) for f in r1.fields]

    def refactor_aliased_registers(self):
        """
        Go through all registers in this peripheral and where two registers
        have the same offset (i.e., are aliased), merge the fields, replace
        the name with the common prefix.
        """
        to_delete = set()
        registers = enumerate(self.registers)
        for (idx1, r1), (idx2, r2) in itertools.combinations(registers, 2):
            if r1 is r2 or idx1 in to_delete or idx2 in to_delete:
                continue
            if r1.offset == r2.offset:
                r1.consume(r2, parent=self)
                to_delete.add(idx2)
        for idx in sorted(to_delete, reverse=True):
            del self.registers[idx]

    def __lt__(self, other):
        return self.name < other.name


class PeripheralPrototypeLink(Node):
    """
    Represents use of an externally defined RegisterBlock and registers,
    with local instances.
    """
    def __init__(self, name, prototype, path):
        """
        `path`: the relative path to the prototype module,
                so that `use {path}::RegisterBlock;` works from the
                context of this module,
                e.g., `super::tim1`, or `super::super::stm32f401::gpio`.
        """
        self.name = name
        self.prototype = prototype
        self.path = path
        self.instances = []
        self.parent_device_names = []

    def to_dict(self):
        return {"prototype": self.prototype.name, "path": self.path,
                "instances": [x.to_dict() for x in self.instances]}

    def to_rust_file(self, path):
        """
        Creates {peripheral}.rs in the path, writes `use` statements
        for all register modules and the register block, and writes any
        instances to that file.
        Finally runs rustfmt over the new file.
        """
        desc = "\n//! ".join(self.prototype.desc.split("\n"))
        if len(self.parent_device_names) > 1:
            desc += "\n//!\n"
            desc += "//! Used by: " + ', '.join(
                sorted(set(self.parent_device_names)))
        preamble = "\n".join([
            "#![allow(non_snake_case, non_upper_case_globals)]",
            "#![allow(non_camel_case_types)]",
            f"//! {desc}",
            "",
            f"pub use crate::{self.path}::{{RegisterBlock, ResetValues}};",
            "#[cfg(not(feature = \"nosync\"))]",
            f"pub use crate::{self.path}::{{Instance}};",
            "",
        ])
        registers = ", ".join(m.name for m in self.prototype.registers)
        registers = f"pub use crate::{self.path}::{{{registers}}};\n"
        instances = "\n".join(i.to_rust(self.registers)
                              for i in sorted(self.instances))
        fname = os.path.join(path, f"{self.name}.rs")
        with open(fname, "w") as f:
            f.write(preamble)
            f.write(registers)
            f.write("\n")
            f.write(instances)
        rustfmt(fname)

    def to_parent_entry(self):
        return f"pub mod {self.name};\n"

    def to_struct_entry(self, usename=None):
        if usename is None:
            usename = self.name
        lines = []
        for instance in self.instances:
            lines.append(f"pub {instance.name}: {usename}::Instance,")
        return "\n".join(lines)

    def to_struct_steal(self, usename=None):
        if usename is None:
            usename = self.name
        lines = []
        for instance in self.instances:
            lines.append(
                f"{instance.name}: "
                f"{usename}::{instance.name}::steal(),")
        return "\n".join(lines)

    @classmethod
    def from_peripherals(cls, p1, p2, path):
        plink = cls(p2.name, p1, path)
        plink.instances = p2.instances
        return plink

    @property
    def registers(self):
        return self.prototype.registers

    @property
    def desc(self):
        return self.prototype.desc

    def refactor_common_register_fields(self):
        pass

    def refactor_common_instances(self):
        pass

    def refactor_aliased_registers(self):
        pass

    def __lt__(self, other):
        return self.name < other.name


class PeripheralSharedInstanceLink(Node):
    def __init__(self, name, usename, prototype):
        self.name = name
        self.usename = usename
        self.prototype = prototype

    def to_parent_entry(self):
        if self.usename == self.name:
            return f"pub use super::instances::{self.name};\n"
        else:
            return (f"pub use super::instances::{self.usename} "
                    f"as {self.name};\n")

    def to_struct_entry(self):
        return self.prototype.to_struct_entry(self.name)

    def to_struct_steal(self):
        return self.prototype.to_struct_steal(self.name)

    def to_rust_file(self, path):
        pass

    @property
    def registers(self):
        return self.prototype.registers

    @property
    def desc(self):
        return self.prototype.desc

    def refactor_common_register_fields(self):
        pass

    def refactor_common_instances(self):
        pass

    def refactor_aliased_registers(self):
        pass

    def __lt__(self, other):
        return self.name < other.name


class CPU(Node):
    """
    Represents the CPU in a device.

    Has a name and nvicPrioBits.
    Belongs to a parent Device.
    """
    def __init__(self, name, nvic_prio_bits):
        self.name = name
        self.nvic_prio_bits = nvic_prio_bits

    def get_architecture(self):
        if self.name == "CM0":
            return "ARMv6-M"
        elif self.name == "CM0+":
            return "ARMv6-M"
        elif self.name == "CM3":
            return "ARMv7-M"
        elif self.name == "CM4":
            return "ARMv7E-M"
        elif self.name == "CM7":
            return "ARMv7E-M"
        elif self.name == "CM33":
            return "ARMv8-M"

    def to_dict(self):
        return {"name": self.name, "nvic_prio_bits": self.nvic_prio_bits}

    @classmethod
    def from_svd(cls, svd, node):
        """Load a CPU node from the CPU node of a parsed XML file."""
        name = get_string(node, 'name')
        nvic_prio_bits = node.find('nvicPrioBits').text
        return cls(name, nvic_prio_bits)


class Interrupt(Node):
    """
    Represents an interrupt in a device.

    Has a name, description, and value (interrupt number).
    Belongs to a parent Device.
    """
    def __init__(self, name, desc, value):
        self.name = name
        self.desc = desc
        self.value = value

    def to_dict(self):
        return {"name": self.name, "desc": self.desc, "value": self.value}

    @classmethod
    def from_svd(cls, svd, node):
        name = get_string(node, 'name')
        desc = get_string(node, 'description')
        value = get_int(node, 'value')
        return cls(name, desc, value)

    def __lt__(self, other):
        return self.value < other.value


class Device(Node):
    """
    Represents a device corresponding to a single input SVD file.

    Has a name.
    Contains a child CPU, PeripheralPrototypes, and Interrupts.
    """
    def __init__(self, name, cpu):
        self.name = name.lower().replace("-", "_")
        self.cpu = cpu
        self.peripherals = []
        self.interrupts = []
        self.special = False

    def to_dict(self):
        return {"name": self.name, "cpu": self.cpu.to_dict(),
                "peripherals": [x.to_dict() for x in self.peripherals],
                "interrupts": [x.to_dict() for x in self.interrupts]}

    def to_interrupt_file(self, familypath):
        devicepath = os.path.join(familypath, self.name)
        iname = os.path.join(devicepath, "interrupts.rs")
        with open(iname, "w") as f:
            f.write('#[cfg(feature="rt")]\nextern "C" {\n')
            for interrupt in self.interrupts:
                f.write(f'    fn {interrupt.name}();\n')
            f.write('}\n\n')
            vectors = []
            offset = 0
            for interrupt in self.interrupts:
                while interrupt.value != offset:
                    vectors.append("Vector { _reserved: 0 },")
                    offset += 1
                vectors.append(f"Vector {{ _handler: {interrupt.name} }},")
                offset += 1
            nvectors = len(vectors)
            vectors = "\n".join(vectors)

            f.write(f"""\
                #[doc(hidden)]
                pub union Vector {{
                    _handler: unsafe extern "C" fn(),
                    _reserved: u32,
                }}

                #[cfg(feature="rt")]
                #[doc(hidden)]
                #[link_section=".vector_table.interrupts"]
                #[no_mangle]
                pub static __INTERRUPTS: [Vector; {nvectors}] = [
                {vectors}
                ];

                /// Available interrupts for this device
                #[repr(u16)]
                #[derive(Copy,Clone,Debug,PartialEq,Eq)]
                #[allow(non_camel_case_types)]
                pub enum Interrupt {{""")
            for interrupt in self.interrupts:
                f.write(f"/// {interrupt.value}: ")
                f.write(f"{escape_desc(interrupt.desc)}\n")
                f.write(f"{interrupt.name} = {interrupt.value},\n")
            f.write("}\n")
            f.write("""\
                    unsafe impl external_cortex_m::interrupt::InterruptNumber for Interrupt {
                    #[inline(always)]
                    fn number(self) -> u16 {
                        self as u16
                    }
                }\n""")
        rustfmt(iname)

    def to_files(self, familypath):
        devicepath = os.path.join(familypath, self.name)
        os.makedirs(devicepath, exist_ok=True)
        for peripheral in self.peripherals:
            peripheral.to_rust_file(devicepath)
        pnames = [p.name for p in self.peripherals]
        dupnames = set(name for name in pnames if pnames.count(name) > 1)
        if dupnames:
            print(f"Warning [{self.name}]: duplicate peripherals: ", end='')
            print(dupnames)
        if not self.special:
            self.to_interrupt_file(familypath)
        pname = "CorePeripherals" if self.special else "Peripherals"
        mname = os.path.join(devicepath, "mod.rs")
        with open(mname, "w") as f:
            f.write(f"//! stm32ral module for {self.name}\n\n")
            prio_bits = self.cpu.nvic_prio_bits
            if not self.special:
                f.write("/// Number of priority bits implemented by the NVIC")
                f.write(f"\npub const NVIC_PRIO_BITS: u8 = {prio_bits};\n\n")
                f.write("/// Interrupt-related magic for this device\n")
                f.write("pub mod interrupts;\n")
                f.write("pub use self::interrupts::Interrupt;\n")
                f.write("pub use self::interrupts::Interrupt as interrupt;\n")
                f.write("\n\n")
            for peripheral in self.peripherals:
                f.write(peripheral.to_parent_entry())
            f.write("\n\n")
            f.write("#[cfg(all(feature=\"rtic\", not(feature=\"nosync\")))]")
            f.write("\n#[allow(non_snake_case)]\n")
            f.write(f"pub struct {pname} {{\n")
            for peripheral in self.peripherals:
                f.write("    " + peripheral.to_struct_entry())
            f.write("}\n\n")
            f.write("#[cfg(all(feature=\"rtic\", feature=\"nosync\"))]\n")
            f.write("#[allow(non_snake_case)]\n")
            f.write(f"pub struct {pname} {{}}\n\n")
            f.write("#[cfg(all(feature=\"rtic\", not(feature=\"nosync\")))]")
            f.write(f"\nimpl {pname} {{\n")
            f.write("    pub unsafe fn steal() -> Self {\n")
            f.write(f"        {pname} {{\n")
            for peripheral in self.peripherals:
                f.write("        " + peripheral.to_struct_steal())
            f.write("        }\n    }\n}\n\n")
            f.write("#[cfg(all(feature=\"rtic\", feature=\"nosync\"))]\n")
            f.write(f"impl {pname} {{\n    pub fn steal() -> Self {{\n")
            f.write(f"        {pname} {{}}\n    }}\n}}")
        rustfmt(mname)
        if not self.special:
            dname = os.path.join(devicepath, "device.x")
            with open(dname, "w") as f:
                for interrupt in self.interrupts:
                    f.write(f"PROVIDE({interrupt.name} = DefaultHandler);\n")

    @classmethod
    def from_svd(cls, svd, device_name):
        """Load a Device node and children from a parsed SVD XML file."""
        name = device_name
        try:
            cpu = CPU.from_svd(svd, svd.find('cpu'))
        except AttributeError as e:
            print(device_name)
            raise e
        device = cls(name, cpu)
        register_ctx = RegisterCtx.empty()
        register_ctx = register_ctx.inherit(svd)
        interrupt_nums = set()
        for interrupt in svd.findall('.//interrupt'):
            interrupt = Interrupt.from_svd(svd, interrupt)
            if interrupt.value in interrupt_nums:
                # Many SVDs have duplicated interrupts. Skip them.
                continue
            device.interrupts.append(interrupt)
            interrupt_nums.add(interrupt.value)
        device.interrupts.sort()
        for peripheral in svd.findall('.//peripheral'):
            device.peripherals.append(
                PeripheralPrototype.from_svd(svd, peripheral, register_ctx))
        for peripheral in device.peripherals:
            peripheral.parent_device_names.append(device.name)
        return device

    @classmethod
    def from_svdfile(cls, svdfile):
        device_name = os.path.basename(svdfile).split('.')[0]
        svd = ET.parse(svdfile)
        return cls.from_svd(svd, device_name)

    def refactor_peripheral_instances(self):
        """
        Go through all peripherals and where two have the same RegisterBlock,
        combine them into a single PeripheralPrototype with multiple
        PeripheralInstances.
        """
        to_delete = set()
        to_link = set()
        links = []
        periphs = enumerate(self.peripherals)
        for (idx1, p1), (idx2, p2) in itertools.combinations(periphs, 2):
            if p1 is p2 or idx1 in to_delete or idx2 in to_delete:
                continue
            elif idx1 in to_link or idx2 in to_link:
                continue
            elif p1.registers == p2.registers:
                if p1.name.startswith("tim"):
                    # Similar timers we have to special case, because they
                    # just do not group up well at all.
                    links.append((idx1, idx2))
                    to_link.add(idx2)
                else:
                    # Other peripherals we just move instances together.
                    p1.consume(p2, parent=self)
                    to_delete.add(idx2)
        for idx1, idx2 in links:
            p1 = self.peripherals[idx1]
            p2 = self.peripherals[idx2]
            path = f"super::{p1.name}"
            plink = PeripheralPrototypeLink.from_peripherals(p1, p2, path)
            self.peripherals[idx2] = plink
        for idx in sorted(to_delete, reverse=True):
            del self.peripherals[idx]


class Family(Node):
    """
    Represents a group of devices in a common family.

    Peripheral prototypes (i.e. the register block and registers and fields)
    which are used by more than one device in this family live in `peripherals`
    and instances (i.e. specific memory addresses for GPIOA, GPIOB, ...)
    which are used by more than one device live in `instances`.
    """
    def __init__(self, name):
        self.name = name
        self.devices = []
        self.peripherals = []
        self.instances = []

    def to_dict(self):
        return {"name": self.name,
                "devices": [d.to_dict() for d in self.devices],
                "peripherals": [p.to_dict() for p in self.peripherals],
                "instances": [i.to_dict()
                              for i in self.instances]}

    def to_files(self, path, pool):
        familypath = os.path.join(path, self.name)
        os.makedirs(familypath, exist_ok=True)
        periphpath = os.path.join(familypath, "peripherals")
        instpath = os.path.join(familypath, "instances")
        os.makedirs(periphpath, exist_ok=True)
        os.makedirs(instpath, exist_ok=True)
        pool_results = []
        with open(os.path.join(familypath, "mod.rs"), "w") as f:
            uname = self.name.upper()
            f.write(f"//! Parent module for all {uname} devices.\n\n")
            f.write("/// Peripherals shared by multiple devices\n")
            f.write('pub mod peripherals;\n\n')
            f.write("/// Peripheral instances shared by multiple devices\n")
            f.write("pub(crate) mod instances;\n\n")
            for device in self.devices:
                dname = device.name
                result = pool.apply_async(device.to_files, (familypath,))
                pool_results.append(result)
                f.write(f'#[cfg(any(feature="{dname}", feature="doc"))]\n')
                f.write(f'pub mod {dname};\n\n')
        with open(os.path.join(periphpath, "mod.rs"), "w") as f:
            for peripheral in self.peripherals:
                r = pool.apply_async(peripheral.to_rust_file, (periphpath,))
                pool_results.append(r)
                features = ", ".join(
                    f'feature="{d}"' for d in peripheral.parent_device_names)
                f.write(f'#[cfg(any(feature="doc", {features}))]\n')
                f.write(f'pub mod {peripheral.name};\n\n')
        with open(os.path.join(instpath, "mod.rs"), "w") as f:
            for instance in self.instances:
                r = pool.apply_async(instance.to_rust_file, (instpath,))
                pool_results.append(r)
                features = ", ".join(
                    f'feature="{d}"' for d in instance.parent_device_names)
                f.write(f'#[cfg(any(feature="doc", {features}))]\n')
                f.write(f'pub mod {instance.name};\n\n')
        return pool_results

    def _enumerate_peripherals(self):
        peripherals = []
        for didx, device in enumerate(self.devices):
            for pidx, peripheral in enumerate(device.peripherals):
                peripherals.append((didx, pidx, peripheral))
        return peripherals

    def _match_peripherals(self):
        """Gather all pairs of matching peripherals in this family"""
        to_link = set()
        links = dict()
        peripherals = self._enumerate_peripherals()
        for pt1, pt2 in itertools.combinations(peripherals, 2):
            didx1, pidx1, p1 = pt1
            didx2, pidx2, p2 = pt2
            idx1 = (didx1, pidx1)
            idx2 = (didx2, pidx2)
            if p1 is p2 or idx1 in to_link or idx2 in to_link:
                continue
            elif p1.registers == p2.registers:
                to_link.add(idx2)
                if idx1 not in links:
                    links[idx1] = []
                links[idx1].append(idx2)
        return links

    def refactor_common_peripherals(self):
        """
        Find peripherals shared between devices which are identical and
        refactor them into the family-level shared peripherals.
        """
        # Find all pairs of matching peripherals in the family
        links = self._match_peripherals()

        # Determine which peripherals need versioned names
        # (any with multiple peripherals that share the same name).
        pnames = set()
        dupnames = set()
        for idx in links:
            didx, pidx = idx
            p = self.devices[didx].peripherals[pidx]
            if p.name in pnames:
                dupnames.add(p.name)
            pnames.add(p.name)

        # Now create new crate-level peripherals and replace the old ones
        # with links to the new ones
        versions = {}
        for idx in links:
            # Get the primary member of the link group
            didx, pidx = idx
            device = self.devices[didx]
            p = device.peripherals[pidx]
            # Modify the name to gpio_v1, gpio_v2, etc
            name = p.name
            if name in dupnames:
                if name not in versions:
                    versions[name] = 0
                versions[name] += 1
                name = f'{name}_v{versions[name]}'
            # Make a new PeripheralPrototype for the family, with no instances
            familyp = PeripheralPrototype(name, p.desc)
            familyp.registers = p.registers
            familyp.parent_device_names.append(device.name)
            self.peripherals.append(familyp)
            # Make a link for the primary member
            path = f"{self.name}::peripherals::{name}"
            linkp = PeripheralPrototypeLink(p.name, familyp, path)
            linkp.instances = p.instances
            self.devices[didx].peripherals[pidx] = linkp
            # Make a link for each other member
            for childidx in links[idx]:
                cdidx, cpidx = childidx
                childd = self.devices[cdidx]
                childp = childd.peripherals[cpidx]
                familyp.parent_device_names.append(childd.name)
                linkp = PeripheralPrototypeLink(childp.name, familyp, path)
                linkp.instances = childp.instances
                childd.peripherals[cpidx] = linkp

        self.refactor_common_instances(links)

    def refactor_common_instances(self, links):
        to_group = set()
        groups = dict()
        for primary, children in links.items():
            members = [primary] + list(children)
            for l1, l2 in itertools.combinations(members, 2):
                didx1, pidx1 = l1
                didx2, pidx2 = l2
                p1 = self.devices[didx1].peripherals[pidx1]
                p2 = self.devices[didx2].peripherals[pidx2]
                if p1 is p2 or l1 in to_group or l2 in to_group:
                    continue
                elif p1.instances == p2.instances:
                    to_group.add(l2)
                    if l1 not in groups:
                        groups[l1] = []
                    groups[l1].append(l2)
        pnames = set()
        dupnames = set()
        for (didx, pidx) in groups:
            p = self.devices[didx].peripherals[pidx]
            if p.name in pnames:
                dupnames.add(p.name)
            pnames.add(p.name)
        for idx in groups:
            didx, pidx = idx
            d = self.devices[didx]
            p = d.peripherals[pidx]
            name = p.name
            if name in dupnames:
                name += "_" + d.name[5:]
                for cidx in groups[idx]:
                    cdidx, _ = cidx
                    cd = self.devices[cdidx]
                    name += "_" + cd.name[5:]
            linkp = PeripheralSharedInstanceLink(p.name, name, p)
            self.devices[didx].peripherals[pidx] = linkp
            groupp = p
            groupp.name = name
            groupp.parent_device_names.append(d.name)
            self.instances.append(groupp)
            for cidx in groups[idx]:
                cdidx, cpidx = cidx
                cd = self.devices[cdidx]
                groupp.parent_device_names.append(cd.name)
                cd.peripherals[cpidx] = linkp


class Crate:
    """
    Represents the overall crate of devices and shared peripherals.

    Contains one or more child Families and shared Peripherals.
    """
    def __init__(self):
        self.families = []
        self.peripherals = []

    def to_dict(self):
        return {"families": [x.to_dict() for x in self.families],
                "peripherals": [x.to_dict() for x in self.peripherals]}

    def write_build_script(self, path):
        """
        Generates build.rs which copies the relevant device.x into the build
        path for the selected device.
        """
        devices = []
        for family in self.families:
            for device in family.devices:
                if not device.special:
                    devices.append((family.name, device.name))
        clauses = " else ".join("""\
            if env::var_os("CARGO_FEATURE_{}").is_some() {{
                "src/{}/{}/device.x"
            }}""".format(d.upper(), f, d) for (f, d) in sorted(devices))
        clauses += " else { panic!(\"No device features selected\"); }"
        fname = os.path.join(path, "build.rs")
        with open(fname, "w") as f:
            f.write(BUILD_RS_TEMPLATE.format(device_clauses=clauses))
        rustfmt(fname)

    def to_files(self, path, pool):
        """
        Writes src/lib.rs, Cargo.toml, src/mod.rs, build.rs, writes out all
        child peripherals, and triggers all child families to write their own
        files out.
        """
        srcpath = os.path.join(path, 'src')
        if not os.path.isdir(srcpath):
            raise ValueError(f"{srcpath} does not exist")
        periphpath = os.path.join(srcpath, "peripherals")
        os.makedirs(periphpath, exist_ok=True)

        lib_f = open(os.path.join(srcpath, "lib.rs"), "w")
        lib_f.write(CRATE_LIB_PREAMBLE)

        cargo_f = open(os.path.join(path, "Cargo.toml"), "w")
        cargo_f.write(CRATE_CARGO_TOML_PREAMBLE)

        self.write_build_script(path)

        periph_f = open(os.path.join(periphpath, "mod.rs"), "w")

        pool_results = []
        for family in sorted(self.families, key=lambda x: x.name):
            fname = family.name
            pool_results += family.to_files(srcpath, pool)
            features = [f'feature="{d.name}"' for d in family.devices]
            lib_f.write(f'#[cfg(any(feature="doc", {", ".join(features)}))]\n')
            lib_f.write(f'pub mod {fname};\n\n')
            for device in family.devices:
                dname = device.name
                arch = device.cpu.get_architecture().lower().replace("-", "")
                if device.special:
                    cargo_f.write(f'{dname} = []\n')
                else:
                    cargo_f.write(f'{dname} = ["{arch}"]\n')
                lib_f.write(f'#[cfg(feature="{dname}")]\n')
                lib_f.write(f'pub use {fname}::{dname}::*;\n\n')
        if self.peripherals:
            lib_f.write("//! Peripherals shared between multiple families\n")
            lib_f.write("pub mod peripherals;\n\n")
        for peripheral in self.peripherals:
            result = pool.apply_async(peripheral.to_rust_file, (periphpath,))
            pool_results.append(result)
            features = ", ".join(
                f'feature="{d}"' for d in peripheral.parent_device_names)
            periph_f.write(f'#[cfg(any(feature="doc", {features}))]\n')
            periph_f.write(f'pub mod {peripheral.name};\n\n')
        return pool_results


def get_int(node, tag, default=None):
    """Parses and returns an integer from the specified child tag in node."""
    text = get_string(node, tag, default=default)
    if text == default:
        return text
    text = text.lower().strip()
    if text == "true":
        return 1
    elif text == "false":
        return 0
    elif text[:2] == "0x":
        return int(text[2:], 16)
    elif text[:2] == "0b":
        return int(text[2:], 2)
    else:
        # Annoyingly sometimes constants are base-10 with leading zeros,
        # so int(text, 0) for autodetection does not work.
        return int(text, 10)


def get_string(node, tag, default=None):
    """Finds and returns a string from the specified child tag in node."""
    text = node.findtext(tag, default=default)
    if text == default:
        return text
    return " ".join(text.split())


def expand_dim(node):
    """
    Returns an expanded list of nodes per the dimElementGroup, or just
    a list containing node if no dimElementGroup specified.
    """
    dim = get_int(node, 'dim')
    if dim is None:
        return [node]

    inc = get_int(node, 'dimIncrement')
    idxs = get_string(node, 'dimIndex')
    if idxs is None:
        idxs = list(range(dim))
    else:
        if "," in idxs:
            idxs = idxs.split(",")
        elif "-" in idxs:
            li, ri = idxs.split("-")
            idxs = list(range(int(li), int(ri)+1))
        else:
            raise ValueError("Unknown dimIndex: '{}'".format(idxs))

    nodes = []
    for cnt, idx in enumerate(idxs):
        name = get_string(node, 'name').replace("%s", str(idx))
        dim_node = copy.deepcopy(node)
        dim_node.find('name').text = name
        addr = get_int(dim_node, 'addressOffset') + cnt * inc
        dim_node.find('addressOffset').text = "0x{:08x}".format(addr)
        dim_node.attrib['dim_index'] = idx
        nodes.append(dim_node)
    return nodes


def expand_cluster(node):
    if node.attrib.get('dim_index') is None:
        raise ValueError("Can't process a cluster without dim_index set")
    cluster_idx = node.attrib['dim_index']
    cluster_addr = get_int(node, 'addressOffset')
    nodes = []
    for register in node.findall('register'):
        addr = cluster_addr + get_int(register, 'addressOffset')
        name = get_string(register, 'name') + str(cluster_idx)
        clusr = copy.deepcopy(register)
        clusr.find('addressOffset').text = "0x{:08x}".format(addr)
        clusr.find('name').text = name
        nodes.append(clusr)
    return nodes


def escape_desc(desc):
    """Escape `desc` suitable for a doc comment."""
    if desc is None:
        return ""
    else:
        return desc.replace("[", "\\[").replace("]", "\\]")


def rustfmt(fname):
    """Runs rustfmt over the given filename."""
    subprocess.run(["rustfmt", fname])


def common_name(a, b, ctx=""):
    """
    Returns the best common name between `a` and `b`.

    Ideally finds a single character different between `a` and `b` which
    is then removed, e.g., GPIOA + GPIOB = GPIO, TIM1 + TIM2 = TIM,
    I2S2EXT + I2S3EXT = I2SEXT. `a` may have already been merged into
    such a form, so GPIO + GPIOB = GPIO, etc, as well.

    If that does not succeed, the next best guess is a common prefix,
    e.g., CCMR1_Input + CCMR1_Output = CCMR1.

    Failing a common prefix, a warning is printed and `a` is returned.

    Special cases:
    * `spi?` and `i2s?ext` will produce `spi`
    * `usart?` and `uart?` will produce `usart`
    * `adc1_2` and `adc3_4` wil produce `adc_common`
    * `adc3_common` and `adc12_common` will produce `adc_common`
    * `delay_block_*` and `delay_block_*` will produce `dlyb`

    `ctx` is optional and printed in any warnings emitted.

    >>> common_name("gpioa", "gpiob")
    'gpio'
    >>> common_name("gpio", "gpiob")
    'gpio'
    >>> common_name("ccmr1_input", "ccmr1_output")
    'ccmr1'
    >>> common_name("i2s2ext", "i2s3ext")
    'i2sext'
    >>> common_name("i2sext", "i2s3ext")
    'i2sext'
    >>> common_name("spi2", "i2s2ext")
    'spi'
    >>> common_name("i2sext", "spi3")
    'spi'
    >>> common_name("usart3", "uart4")
    'usart'
    >>> common_name("usart", "uart7")
    'usart'
    >>> common_name("adc1_2", "adc3_4")
    'adc_common'
    >>> common_name("adc3_common", "adc12_common")
    'adc_common'
    >>> common_name("delay_block_quadspi", "delay_block_sdmmc1")
    'dlyb'
    """
    # Find position of all differences up to the end of the shortest name
    diffpos = [i for i in range(min(len(a), len(b))) if a[i] != b[i]]

    # Special cases
    for x, y in ((a, b), (b, a)):
        if x.startswith("i2s") and x.endswith("ext") and y.startswith("spi"):
            return "spi"
        if x.startswith("usart") and y.startswith("uart"):
            return "usart"
        if x == "adc1_2" and y == "adc3_4":
            return "adc_common"
        if x == "adc12_common" and y == "adc3_common":
            return "adc_common"
        if x.startswith("delay_block_") and y.startswith("delay_block_"):
            return "dlyb"
        if x == "dlyb" and y.startswith("delay_block_"):
            return "dlyb"

    if len(diffpos) == 0:
        # Either names are the same or one name is the prefix of the other
        if a == b:
            print(f"Warning [{ctx}]: {a} and {b} are identical")
            return a
        elif b[:len(a)] == a:
            return a
        elif a[:len(b)] == b:
            return b
    elif len(diffpos) == 1:
        # Names have a single character difference which we can try removing
        p = diffpos[0]
        an = a[:p] + a[p+1:]
        bn = b[:p] + b[p+1:]
        if an == bn:
            return an
        else:
            print(f"Warning [{ctx}]: {a}->{an} and {b}->{bn} failed")
            return a
    else:
        p = diffpos[0]
        # First check if removing the first difference makes the names align,
        # as will be the case for e.g. I2SEXT + I2S3EXT.
        if a == b[:p] + b[p+1:]:
            return a
        # Names might at least have a common prefix
        ap = a[:p]
        bp = b[:p]
        # Strip trailing underscore from suffix
        if ap.endswith("_"):
            ap = ap[:-1]
            bp = bp[:-1]
        if len(ap) > 0 and ap == bp:
            return ap
        else:
            print(f"Warning [{ctx}]: {a}->{ap} and {b}->{bp} failed")
            return a


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("cratepath", help="Path to crate root")
    parser.add_argument("svdfiles", nargs="+", help="SVD files to parse")
    return parser.parse_args()


def main():
    args = parse_args()
    crate = Crate()

    print("Parsing input files...")
    with multiprocessing.Pool() as p:
        devices = p.map(Device.from_svdfile, args.svdfiles)

    print("Collating families...")
    cortex_family = Family("cortex_m")
    crate.families.append(cortex_family)
    for device in devices:
        # Special case the ARMv*-M SVDs
        if device.name.startswith("armv"):
            device.special = True
            cortex_family.devices.append(device)
        else:
            device_family = device.name[:7].lower()
            if device_family not in [f.name for f in crate.families]:
                crate.families.append(Family(device_family))
            family = [f for f in crate.families if f.name == device_family][0]
            if device.name in [d.name for d in family.devices]:
                print(f"Warning: {device.name} already exists in {family},"
                      " skipping.")
                continue
            family.devices.append(device)

    print("Running refactors...")
    for device in devices:
        device.refactor_peripheral_instances()
        for peripheral in device.peripherals:
            peripheral.refactor_aliased_registers()
            peripheral.refactor_common_register_fields()
            for register in peripheral.registers:
                register.refactor_common_field_values()

    for family in crate.families:
        family.refactor_common_peripherals()

    print("Outputting crate...")
    pool_results = []
    with multiprocessing.Pool() as pool:
        pool_results += crate.to_files(args.cratepath, pool)
        for result in pool_results:
            result.get()


if __name__ == "__main__":
    main()