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
use std::borrow::Cow;
use std::cmp::Ordering;
use std::collections::HashMap;

use crate::svd::{
    Cluster, ClusterInfo, DeriveFrom, DimElement, Peripheral, Register, RegisterCluster,
    RegisterProperties,
};
use log::{debug, trace, warn};
use proc_macro2::{Ident, Punct, Spacing, Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{parse_str, Token};

use crate::util::{
    self, handle_cluster_error, handle_reg_error, Config, FullName, ToSanitizedSnakeCase,
    ToSanitizedUpperCase, BITS_PER_BYTE,
};
use anyhow::{anyhow, bail, Context, Result};

use crate::generate::register;

pub fn render(
    p_original: &Peripheral,
    all_peripherals: &[Peripheral],
    defaults: &RegisterProperties,
    config: &Config,
) -> Result<TokenStream> {
    let mut out = TokenStream::new();

    let p_derivedfrom = p_original
        .derived_from
        .as_ref()
        .and_then(|s| all_peripherals.iter().find(|x| x.name == *s));

    let p_merged = p_derivedfrom.map(|ancestor| p_original.derive_from(ancestor));
    let p = p_merged.as_ref().unwrap_or(p_original);

    if let (Some(df), None) = (p_original.derived_from.as_ref(), &p_derivedfrom) {
        eprintln!(
            "Couldn't find derivedFrom original: {} for {}, skipping",
            df, p_original.name
        );
        return Ok(out);
    }

    let span = Span::call_site();
    let name_str = p.name.to_sanitized_upper_case();
    let name_pc = Ident::new(&name_str, span);
    let address = util::hex(p.base_address as u64);
    let description = util::respace(p.description.as_ref().unwrap_or(&p.name));

    let name_sc = Ident::new(&p.name.to_sanitized_snake_case(), span);
    let (derive_regs, base) = if let (Some(df), None) = (p_derivedfrom, &p_original.registers) {
        (true, Ident::new(&df.name.to_sanitized_snake_case(), span))
    } else {
        (false, name_sc.clone())
    };

    // Insert the peripheral structure
    out.extend(quote! {
        #[doc = #description]
        pub struct #name_pc { _marker: PhantomData<*const ()> }

        unsafe impl Send for #name_pc {}

        impl #name_pc {
            ///Pointer to the register block
            pub const PTR: *const #base::RegisterBlock = #address as *const _;

            ///Return the pointer to the register block
            #[inline(always)]
            pub const fn ptr() -> *const #base::RegisterBlock {
                Self::PTR
            }
        }

        impl Deref for #name_pc {
            type Target = #base::RegisterBlock;

            #[inline(always)]
            fn deref(&self) -> &Self::Target {
                unsafe { &*Self::PTR }
            }
        }

        impl core::fmt::Debug for #name_pc {
            fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
                f.debug_struct(#name_str).finish()
            }
        }
    });

    // Derived peripherals may not require re-implementation, and will instead
    // use a single definition of the non-derived version.
    if derive_regs {
        // re-export the base module to allow deriveFrom this one
        out.extend(quote! {
            #[doc = #description]
            pub use #base as #name_sc;
        });
        return Ok(out);
    }

    // erc: *E*ither *R*egister or *C*luster
    let ercs = p.registers.as_ref().map(|x| x.as_ref()).unwrap_or(&[][..]);

    // make a pass to expand derived registers and clusters.  Ideally, for the most minimal
    // code size, we'd do some analysis to figure out if we can 100% reuse the
    // code that we're deriving from.  For the sake of proving the concept, we're
    // just going to emit a second copy of the accessor code.  It'll probably
    // get inlined by the compiler anyway, right? :-)

    // Build a map so that we can look up registers within this peripheral
    let mut erc_map = HashMap::new();
    for erc in ercs {
        erc_map.insert(util::erc_name(erc), erc.clone());
    }

    // Build up an alternate erc list by expanding any derived registers/clusters
    let ercs: Vec<RegisterCluster> = ercs
        .iter()
        .filter_map(|erc| match util::erc_derived_from(erc) {
            Some(ref derived) => {
                let ancestor = match erc_map.get(derived) {
                    Some(erc) => erc,
                    None => {
                        eprintln!(
                            "register/cluster {} derivedFrom missing register/cluster {}",
                            util::erc_name(erc),
                            derived
                        );
                        return None;
                    }
                };

                match (erc, ancestor) {
                    (RegisterCluster::Register(reg), RegisterCluster::Register(other_reg)) => {
                        Some(RegisterCluster::Register(reg.derive_from(other_reg)))
                    }
                    (
                        RegisterCluster::Cluster(cluster),
                        RegisterCluster::Cluster(other_cluster),
                    ) => Some(RegisterCluster::Cluster(cluster.derive_from(other_cluster))),
                    _ => {
                        eprintln!(
                            "{} can't derive from {}",
                            util::erc_name(erc),
                            util::erc_name(ancestor)
                        );
                        None
                    }
                }
            }
            None => Some(erc.clone()),
        })
        .collect();

    // And revise registers, clusters and ercs to refer to our expanded versions
    let registers: &[&Register] = &util::only_registers(&ercs)[..];
    let clusters = util::only_clusters(&ercs);

    // No `struct RegisterBlock` can be generated
    if registers.is_empty() && clusters.is_empty() {
        // Drop the definition of the peripheral
        return Ok(TokenStream::new());
    }

    let defaults = p.default_register_properties.derive_from(defaults);

    // Push any register or cluster blocks into the output
    debug!(
        "Pushing {} register or cluster blocks into output",
        ercs.len()
    );
    let mut mod_items = TokenStream::new();
    mod_items.extend(register_or_cluster_block(&ercs, &defaults, None, config)?);

    debug!("Pushing cluster information into output");
    // Push all cluster related information into the peripheral module
    for c in &clusters {
        trace!("Cluster: {}", c.name);
        mod_items.extend(cluster_block(c, &defaults, p, all_peripherals, config)?);
    }

    debug!("Pushing register information into output");
    // Push all register related information into the peripheral module
    for reg in registers {
        trace!("Register: {}", reg.name);
        match register::render(reg, registers, p, all_peripherals, &defaults, config) {
            Ok(rendered_reg) => mod_items.extend(rendered_reg),
            Err(e) => {
                let res: Result<TokenStream> = Err(e);
                return handle_reg_error("Error rendering register", *reg, res);
            }
        };
    }

    let description =
        util::escape_brackets(util::respace(p.description.as_ref().unwrap_or(&p.name)).as_ref());

    let open = Punct::new('{', Spacing::Alone);
    let close = Punct::new('}', Spacing::Alone);

    out.extend(quote! {
        #[doc = #description]
        pub mod #name_sc #open
    });

    out.extend(mod_items);

    close.to_tokens(&mut out);

    Ok(out)
}

#[derive(Clone, Debug)]
struct RegisterBlockField {
    field: syn::Field,
    description: String,
    offset: u32,
    size: u32,
}

#[derive(Clone, Debug)]
struct Region {
    rbfs: Vec<RegisterBlockField>,
    offset: u32,
    end: u32,
    /// This is only used for regions with `rbfs.len() > 1`
    pub ident: Option<String>,
}

impl Region {
    fn shortest_ident(&self) -> Option<String> {
        let mut idents: Vec<_> = self
            .rbfs
            .iter()
            .filter_map(|f| f.field.ident.as_ref().map(|ident| ident.to_string()))
            .collect();
        if idents.is_empty() {
            return None;
        }
        idents.sort_by(|a, b| {
            // Sort by length and then content
            match a.len().cmp(&b.len()) {
                Ordering::Equal => a.cmp(b),
                cmp => cmp,
            }
        });
        Some(idents[0].to_owned())
    }

    fn common_ident(&self) -> Option<String> {
        // https://stackoverflow.com/a/40296745/4284367
        fn split_keep(text: &str) -> Vec<&str> {
            let mut result = Vec::new();
            let mut last = 0;
            for (index, matched) in
                text.match_indices(|c: char| c.is_numeric() || !c.is_alphabetic())
            {
                if last != index {
                    result.push(&text[last..index]);
                }
                result.push(matched);
                last = index + matched.len();
            }
            if last < text.len() {
                result.push(&text[last..]);
            }
            result
        }

        let idents: Vec<_> = self
            .rbfs
            .iter()
            .filter_map(|f| f.field.ident.as_ref().map(|ident| ident.to_string()))
            .collect();

        if idents.is_empty() {
            return None;
        }

        let x: Vec<_> = idents.iter().map(|i| split_keep(i)).collect();
        let mut index = 0;
        let first = &x[0];
        // Get first elem, check against all other, break on mismatch
        'outer: while index < first.len() {
            for ident_match in x.iter().skip(1) {
                if let Some(match_) = ident_match.get(index) {
                    if match_ != &first[index] {
                        break 'outer;
                    }
                } else {
                    break 'outer;
                }
            }
            index += 1;
        }
        if index <= 1 {
            None
        } else {
            Some(match first.get(index) {
                Some(elem) if elem.chars().all(|c| c.is_numeric()) => {
                    first.iter().take(index).cloned().collect()
                }
                _ => first.iter().take(index - 1).cloned().collect(),
            })
        }
    }

    fn compute_ident(&self) -> Option<String> {
        if let Some(ident) = self.common_ident() {
            Some(ident)
        } else {
            self.shortest_ident()
        }
    }

    fn is_union(&self) -> bool {
        self.rbfs.len() > 1
    }
}

/// FieldRegions keeps track of overlapping field regions,
/// merging rbfs into appropriate regions as we process them.
/// This allows us to reason about when to create a union
/// rather than a struct.
#[derive(Default, Debug)]
struct FieldRegions {
    /// The set of regions we know about.  This is maintained
    /// in sorted order, keyed by Region::offset.
    regions: Vec<Region>,
}

impl FieldRegions {
    /// Track a field.  If the field overlaps with 1 or more existing
    /// entries, they will be merged together.
    fn add(&mut self, rbf: &RegisterBlockField) -> Result<()> {
        // When merging, this holds the indices in self.regions
        // that the input `rbf` will be merging with.
        let mut indices = Vec::new();

        let rbf_start = rbf.offset;
        let rbf_end = rbf_start + (rbf.size + BITS_PER_BYTE - 1) / BITS_PER_BYTE;

        // The region that we're going to insert
        let mut new_region = Region {
            rbfs: vec![rbf.clone()],
            offset: rbf.offset,
            end: rbf_end,
            ident: None,
        };

        // Locate existing region(s) that we intersect with and
        // fold them into the new region we're creating.  There
        // may be multiple regions that we intersect with, so
        // we keep looping to find them all.
        for (idx, f) in self.regions.iter_mut().enumerate() {
            let f_start = f.offset;
            let f_end = f.end;

            // Compute intersection range
            let begin = f_start.max(rbf_start);
            let end = f_end.min(rbf_end);

            if end > begin {
                // We're going to remove this element and fold it
                // into our new region
                indices.push(idx);

                // Expand the existing entry
                new_region.offset = new_region.offset.min(f_start);
                new_region.end = new_region.end.max(f_end);

                // And merge in the rbfs
                new_region.rbfs.append(&mut f.rbfs);
            }
        }

        // Now remove the entries that we collapsed together.
        // We do this in reverse order to ensure that the indices
        // are stable in the face of removal.
        for idx in indices.iter().rev() {
            self.regions.remove(*idx);
        }

        new_region.rbfs.sort_by_key(|f| f.offset);

        // maintain the regions ordered by starting offset
        let idx = self
            .regions
            .binary_search_by_key(&new_region.offset, |r| r.offset);
        match idx {
            Ok(idx) => {
                bail!(
                    "we shouldn't exist in the vec, but are at idx {} {:#?}\n{:#?}",
                    idx,
                    new_region,
                    self.regions
                );
            }
            Err(idx) => self.regions.insert(idx, new_region),
        };

        Ok(())
    }

    /// Resolves type name conflicts
    pub fn resolve_idents(&mut self) -> Result<()> {
        let idents: Vec<_> = {
            self.regions
                .iter_mut()
                .filter(|r| r.rbfs.len() > 1)
                .map(|r| {
                    r.ident = r.compute_ident();
                    r.ident.clone()
                })
                .collect()
        };
        self.regions
            .iter_mut()
            .filter(|r| r.ident.is_some())
            .filter(|r| {
                r.rbfs.len() > 1 && (idents.iter().filter(|&ident| ident == &r.ident).count() > 1)
            })
            .for_each(|r| {
                let new_ident = r.shortest_ident();
                warn!(
                    "Found type name conflict with region {:?}, renamed to {:?}",
                    r.ident, new_ident
                );
                r.ident = new_ident;
            });
        Ok(())
    }
}

fn register_or_cluster_block(
    ercs: &[RegisterCluster],
    defs: &RegisterProperties,
    name: Option<&str>,
    config: &Config,
) -> Result<TokenStream> {
    let mut rbfs = TokenStream::new();
    let mut accessors = TokenStream::new();
    let mut have_accessors = false;

    let ercs_expanded = expand(ercs, defs, name, config)
        .with_context(|| "Could not expand register or cluster block")?;

    // Locate conflicting regions; we'll need to use unions to represent them.
    let mut regions = FieldRegions::default();

    for reg_block_field in &ercs_expanded {
        regions.add(reg_block_field)?;
    }

    // We need to compute the idents of each register/union block first to make sure no conflicts exists.
    regions.resolve_idents()?;
    // The end of the region for which we previously emitted a rbf into `rbfs`
    let mut last_end = 0;

    let span = Span::call_site();
    for (i, region) in regions.regions.iter().enumerate() {
        // Check if we need padding
        let pad = region.offset - last_end;
        if pad != 0 {
            let name = Ident::new(&format!("_reserved{}", i), span);
            let pad = util::hex(pad as u64);
            rbfs.extend(quote! {
                #name : [u8; #pad],
            });
        }

        let mut region_rbfs = TokenStream::new();
        let is_region_a_union = region.is_union();

        for reg_block_field in &region.rbfs {
            let comment = if reg_block_field.size > 32 {
                format!(
                    "0x{:02x}..0x{:02x} - {}",
                    reg_block_field.offset,
                    reg_block_field.offset + reg_block_field.size / 8,
                    util::escape_brackets(util::respace(&reg_block_field.description).as_ref()),
                )
            } else {
                format!(
                    "0x{:02x} - {}",
                    reg_block_field.offset,
                    util::escape_brackets(util::respace(&reg_block_field.description).as_ref()),
                )
            };

            if is_region_a_union {
                let name = &reg_block_field.field.ident;
                let ty = &reg_block_field.field.ty;
                let offset = reg_block_field.offset as usize;
                have_accessors = true;
                accessors.extend(quote! {
                    #[doc = #comment]
                    #[inline(always)]
                    pub fn #name(&self) -> &#ty {
                        unsafe {
                            &*(((self as *const Self) as *const u8).add(#offset) as *const #ty)
                        }
                    }
                });
            } else {
                region_rbfs.extend(quote! {
                    #[doc = #comment]
                });

                reg_block_field.field.to_tokens(&mut region_rbfs);
                Punct::new(',', Spacing::Alone).to_tokens(&mut region_rbfs);
            }
        }

        if !is_region_a_union {
            rbfs.extend(region_rbfs);
        } else {
            // Emit padding for the items that we're not emitting
            // as rbfs so that subsequent rbfs have the correct
            // alignment in the struct.  We could omit this and just
            // not updated `last_end`, so that the padding check in
            // the outer loop kicks in, but it is nice to be able to
            // see that the padding is attributed to a union when
            // visually inspecting the alignment in the struct.
            //
            // Include the computed ident for the union in the padding
            // name, along with the region number, falling back to
            // the offset and end in case we couldn't figure out a
            // nice identifier.
            let name = Ident::new(
                &format!(
                    "_reserved_{}_{}",
                    i,
                    region
                        .compute_ident()
                        .unwrap_or_else(|| format!("{}_{}", region.offset, region.end))
                ),
                span,
            );
            let pad = util::hex((region.end - region.offset) as u64);
            rbfs.extend(quote! {
                #name: [u8; #pad],
            })
        }
        last_end = region.end;
    }

    let name = Ident::new(
        &match name {
            Some(name) => name.to_sanitized_upper_case(),
            None => "RegisterBlock".into(),
        },
        span,
    );

    let accessors = if have_accessors {
        quote! {
            impl #name {
                #accessors
            }
        }
    } else {
        quote! {}
    };

    Ok(quote! {
        ///Register block
        #[repr(C)]
        pub struct #name {
            #rbfs
        }

        #accessors
    })
}

/// Expand a list of parsed `Register`s or `Cluster`s, and render them to
/// `RegisterBlockField`s containing `Field`s.
fn expand(
    ercs: &[RegisterCluster],
    defs: &RegisterProperties,
    name: Option<&str>,
    config: &Config,
) -> Result<Vec<RegisterBlockField>> {
    let mut ercs_expanded = vec![];

    debug!("Expanding registers or clusters into Register Block Fields");
    for erc in ercs {
        match &erc {
            RegisterCluster::Register(register) => {
                match expand_register(register, defs, name, config) {
                    Ok(expanded_reg) => {
                        trace!("Register: {}", register.name);
                        ercs_expanded.extend(expanded_reg);
                    }
                    Err(e) => {
                        let res = Err(e);
                        return handle_reg_error("Error expanding register", register, res);
                    }
                }
            }
            RegisterCluster::Cluster(cluster) => {
                match expand_cluster(cluster, defs, name, config) {
                    Ok(expanded_cluster) => {
                        trace!("Cluster: {}", cluster.name);
                        ercs_expanded.extend(expanded_cluster);
                    }
                    Err(e) => {
                        let res = Err(e);
                        return handle_cluster_error(
                            "Error expanding register cluster",
                            cluster,
                            res,
                        );
                    }
                }
            }
        };
    }

    ercs_expanded.sort_by_key(|x| x.offset);

    Ok(ercs_expanded)
}

/// Calculate the size of a Cluster.  If it is an array, then the dimensions
/// tell us the size of the array.  Otherwise, inspect the contents using
/// [cluster_info_size_in_bits].
fn cluster_size_in_bits(
    cluster: &Cluster,
    defs: &RegisterProperties,
    config: &Config,
) -> Result<u32> {
    match cluster {
        Cluster::Single(info) => cluster_info_size_in_bits(info, defs, config),
        // If the contained array cluster has a mismatch between the
        // dimIncrement and the size of the array items, then the array
        // will get expanded in expand_cluster below.  The overall size
        // then ends at the last array entry.
        Cluster::Array(info, dim) => {
            if dim.dim == 0 {
                return Ok(0); // Special case!
            }
            let last_offset = (dim.dim - 1) * dim.dim_increment * BITS_PER_BYTE;
            let last_size = cluster_info_size_in_bits(info, defs, config);
            Ok(last_offset + last_size?)
        }
    }
}

/// Recursively calculate the size of a ClusterInfo. A cluster's size is the
/// maximum end position of its recursive children.
fn cluster_info_size_in_bits(
    info: &ClusterInfo,
    defs: &RegisterProperties,
    config: &Config,
) -> Result<u32> {
    let mut size = 0;

    for c in &info.children {
        let end = match c {
            RegisterCluster::Register(reg) => {
                let reg_size: u32 = expand_register(reg, defs, None, config)?
                    .iter()
                    .map(|rbf| rbf.size)
                    .sum();

                (reg.address_offset * BITS_PER_BYTE) + reg_size
            }
            RegisterCluster::Cluster(clust) => {
                (clust.address_offset * BITS_PER_BYTE) + cluster_size_in_bits(clust, defs, config)?
            }
        };

        size = size.max(end);
    }
    Ok(size)
}

/// Render a given cluster (and any children) into `RegisterBlockField`s
fn expand_cluster(
    cluster: &Cluster,
    defs: &RegisterProperties,
    name: Option<&str>,
    config: &Config,
) -> Result<Vec<RegisterBlockField>> {
    let mut cluster_expanded = vec![];

    let defs = cluster.default_register_properties.derive_from(defs);

    let cluster_size = cluster_info_size_in_bits(cluster, &defs, config)
        .with_context(|| format!("Cluster {} has no determinable `size` field", cluster.name))?;

    match cluster {
        Cluster::Single(info) => cluster_expanded.push(RegisterBlockField {
            field: convert_svd_cluster(cluster, name)?,
            description: info.description.as_ref().unwrap_or(&info.name).into(),
            offset: info.address_offset,
            size: cluster_size,
        }),
        Cluster::Array(info, array_info) => {
            let sequential_addresses = cluster_size == array_info.dim_increment * BITS_PER_BYTE;

            // if dimIndex exists, test if it is a sequence of numbers from 0 to dim
            let sequential_indexes = array_info.dim_index.as_ref().map_or(true, |dim_index| {
                dim_index
                    .iter()
                    .map(|element| element.parse::<u32>())
                    .eq((0..array_info.dim).map(Ok))
            });

            let array_convertible = sequential_indexes && sequential_addresses;

            if array_convertible {
                cluster_expanded.push(RegisterBlockField {
                    field: convert_svd_cluster(cluster, name)?,
                    description: info.description.as_ref().unwrap_or(&info.name).into(),
                    offset: info.address_offset,
                    size: cluster_size * array_info.dim,
                });
            } else if sequential_indexes && config.const_generic {
                // Include a ZST ArrayProxy giving indexed access to the
                // elements.
                cluster_expanded.push(array_proxy(info, array_info, name)?);
            } else {
                for (field_num, field) in expand_svd_cluster(cluster, name)?.iter().enumerate() {
                    cluster_expanded.push(RegisterBlockField {
                        field: field.clone(),
                        description: info.description.as_ref().unwrap_or(&info.name).into(),
                        offset: info.address_offset + field_num as u32 * array_info.dim_increment,
                        size: cluster_size,
                    });
                }
            }
        }
    }

    Ok(cluster_expanded)
}

/// If svd register arrays can't be converted to rust arrays (non sequential addresses, non
/// numeral indexes, or not containing all elements from 0 to size) they will be expanded
fn expand_register(
    register: &Register,
    defs: &RegisterProperties,
    name: Option<&str>,
    config: &Config,
) -> Result<Vec<RegisterBlockField>> {
    let mut register_expanded = vec![];

    let register_size = register
        .properties
        .size
        .or(defs.size)
        .ok_or_else(|| anyhow!("Register {} has no `size` field", register.name))?;

    match register {
        Register::Single(info) => register_expanded.push(RegisterBlockField {
            field: convert_svd_register(register, name, config.ignore_groups)
                .with_context(|| "syn error occured")?,
            description: info.description.clone().unwrap_or_default(),
            offset: info.address_offset,
            size: register_size,
        }),
        Register::Array(info, array_info) => {
            let sequential_addresses = register_size == array_info.dim_increment * BITS_PER_BYTE;

            // if dimIndex exists, test if it is a sequence of numbers from 0 to dim
            let sequential_indexes = array_info.dim_index.as_ref().map_or(true, |dim_index| {
                dim_index
                    .iter()
                    .map(|element| element.parse::<u32>())
                    .eq((0..array_info.dim).map(Ok))
            });

            let array_convertible = sequential_indexes && sequential_addresses;

            if array_convertible {
                register_expanded.push(RegisterBlockField {
                    field: convert_svd_register(register, name, config.ignore_groups)?,
                    description: info.description.clone().unwrap_or_default(),
                    offset: info.address_offset,
                    size: register_size * array_info.dim,
                });
            } else {
                for (field_num, field) in expand_svd_register(register, name, config.ignore_groups)?
                    .iter()
                    .enumerate()
                {
                    register_expanded.push(RegisterBlockField {
                        field: field.clone(),
                        description: info.description.clone().unwrap_or_default(),
                        offset: info.address_offset + field_num as u32 * array_info.dim_increment,
                        size: register_size,
                    });
                }
            }
        }
    }

    Ok(register_expanded)
}

/// Render a Cluster Block into `TokenStream`
fn cluster_block(
    c: &Cluster,
    defaults: &RegisterProperties,
    p: &Peripheral,
    all_peripherals: &[Peripheral],
    config: &Config,
) -> Result<TokenStream> {
    let mut mod_items = TokenStream::new();

    // name_sc needs to take into account array type.
    let description =
        util::escape_brackets(util::respace(c.description.as_ref().unwrap_or(&c.name)).as_ref());

    // Generate the register block.
    let mod_name = util::replace_suffix(
        match c {
            Cluster::Single(info) => &info.name,
            Cluster::Array(info, _ai) => &info.name,
        },
        "",
    );
    let name_sc = Ident::new(&mod_name.to_sanitized_snake_case(), Span::call_site());

    let defaults = c.default_register_properties.derive_from(defaults);

    let reg_block = register_or_cluster_block(&c.children, &defaults, Some(&mod_name), config)?;

    // Generate definition for each of the registers.
    let registers = util::only_registers(&c.children);
    for reg in &registers {
        match register::render(reg, &registers, p, all_peripherals, &defaults, config) {
            Ok(rendered_reg) => mod_items.extend(rendered_reg),
            Err(e) => {
                let res: Result<TokenStream> = Err(e);
                return handle_reg_error(
                    "Error generating register definition for a register cluster",
                    *reg,
                    res,
                );
            }
        };
    }

    // Generate the sub-cluster blocks.
    let clusters = util::only_clusters(&c.children);
    for c in &clusters {
        mod_items.extend(cluster_block(c, &defaults, p, all_peripherals, config)?);
    }

    Ok(quote! {
        #reg_block

        ///Register block
        #[doc = #description]
        pub mod #name_sc {
            #mod_items
        }
    })
}

/// Takes a svd::Register which may be a register array, and turn in into
/// a list of syn::Field where the register arrays have been expanded.
fn expand_svd_register(
    register: &Register,
    name: Option<&str>,
    ignore_group: bool,
) -> Result<Vec<syn::Field>> {
    let mut out = vec![];

    match register {
        Register::Single(_info) => out.push(convert_svd_register(register, name, ignore_group)?),
        Register::Array(info, array_info) => {
            let indices = array_info
                .dim_index
                .as_ref()
                .map(|v| Cow::from(&**v))
                .unwrap_or_else(|| {
                    Cow::from(
                        (0..array_info.dim)
                            .map(|i| i.to_string())
                            .collect::<Vec<_>>(),
                    )
                });

            let ty_name = util::replace_suffix(&info.fullname(ignore_group), "");

            for (idx, _i) in indices.iter().zip(0..) {
                let nb_name = util::replace_suffix(&info.fullname(ignore_group), idx);

                let ty = name_to_wrapped_ty(&ty_name, name)?;

                out.push(new_syn_field(&nb_name.to_sanitized_snake_case(), ty));
            }
        }
    }
    Ok(out)
}

/// Convert a parsed `Register` into its `Field` equivalent
fn convert_svd_register(
    register: &Register,
    name: Option<&str>,
    ignore_group: bool,
) -> Result<syn::Field> {
    Ok(match register {
        Register::Single(info) => {
            let info_name = info.fullname(ignore_group);
            new_syn_field(
                &info_name.to_sanitized_snake_case(),
                name_to_wrapped_ty(&info_name, name)
                    .with_context(|| format!("Error converting info name {}", info_name))?,
            )
        }
        Register::Array(info, array_info) => {
            let nb_name = util::replace_suffix(&info.fullname(ignore_group), "");
            let ty = syn::Type::Array(parse_str::<syn::TypeArray>(&format!(
                "[{};{}]",
                name_to_wrapped_ty_str(&nb_name, name),
                u64::from(array_info.dim)
            ))?);

            new_syn_field(&nb_name.to_sanitized_snake_case(), ty)
        }
    })
}

/// Return an syn::Type for an ArrayProxy.
fn array_proxy(
    info: &ClusterInfo,
    array_info: &DimElement,
    name: Option<&str>,
) -> Result<RegisterBlockField, syn::Error> {
    let ty_name = util::replace_suffix(&info.name, "");
    let tys = name_to_ty_str(&ty_name, name);

    let ap_path = parse_str::<syn::TypePath>(&format!(
        "crate::ArrayProxy<{}, {}, {}>",
        tys,
        array_info.dim,
        util::hex(array_info.dim_increment as u64)
    ))?;

    Ok(RegisterBlockField {
        field: new_syn_field(&ty_name.to_sanitized_snake_case(), ap_path.into()),
        description: info.description.as_ref().unwrap_or(&info.name).into(),
        offset: info.address_offset,
        size: 0,
    })
}

/// Takes a svd::Cluster which may contain a register array, and turn in into
/// a list of syn::Field where the register arrays have been expanded.
fn expand_svd_cluster(
    cluster: &Cluster,
    name: Option<&str>,
) -> Result<Vec<syn::Field>, syn::Error> {
    let mut out = vec![];

    match &cluster {
        Cluster::Single(_info) => out.push(convert_svd_cluster(cluster, name)?),
        Cluster::Array(info, array_info) => {
            let indices = array_info
                .dim_index
                .as_ref()
                .map(|v| Cow::from(&**v))
                .unwrap_or_else(|| {
                    Cow::from(
                        (0..array_info.dim)
                            .map(|i| i.to_string())
                            .collect::<Vec<_>>(),
                    )
                });

            let ty_name = util::replace_suffix(&info.name, "");

            for (idx, _i) in indices.iter().zip(0..) {
                let nb_name = util::replace_suffix(&info.name, idx);

                let ty = name_to_ty(&ty_name, name)?;

                out.push(new_syn_field(&nb_name.to_sanitized_snake_case(), ty));
            }
        }
    }
    Ok(out)
}

/// Convert a parsed `Cluster` into its `Field` equivalent
fn convert_svd_cluster(cluster: &Cluster, name: Option<&str>) -> Result<syn::Field, syn::Error> {
    Ok(match cluster {
        Cluster::Single(info) => {
            let ty_name = util::replace_suffix(&info.name, "");
            let ty = name_to_ty(&ty_name, name)?;
            new_syn_field(&info.name.to_sanitized_snake_case(), ty)
        }
        Cluster::Array(info, array_info) => {
            let ty_name = util::replace_suffix(&info.name, "");

            let ty = syn::Type::Array(parse_str::<syn::TypeArray>(&format!(
                "[{};{}]",
                name_to_ty_str(&ty_name, name),
                u64::from(array_info.dim)
            ))?);

            new_syn_field(&ty_name.to_sanitized_snake_case(), ty)
        }
    })
}

fn new_syn_field(ident: &str, ty: syn::Type) -> syn::Field {
    let span = Span::call_site();
    syn::Field {
        ident: Some(Ident::new(ident, span)),
        vis: syn::Visibility::Public(syn::VisPublic {
            pub_token: Token![pub](span),
        }),
        attrs: vec![],
        colon_token: Some(Token![:](span)),
        ty,
    }
}

fn name_to_ty_str<'a, 'b>(name: &'a str, ns: Option<&'b str>) -> Cow<'a, str> {
    if let Some(ns) = ns {
        Cow::Owned(
            String::from("self::")
                + &ns.to_sanitized_snake_case()
                + "::"
                + &name.to_sanitized_upper_case(),
        )
    } else {
        name.to_sanitized_upper_case()
    }
}

fn name_to_ty(name: &str, ns: Option<&str>) -> Result<syn::Type, syn::Error> {
    let ident = name_to_ty_str(name, ns);
    Ok(syn::Type::Path(parse_str::<syn::TypePath>(&ident)?))
}

fn name_to_wrapped_ty_str(name: &str, ns: Option<&str>) -> String {
    if let Some(ns) = ns {
        format!(
            "crate::Reg<self::{}::{}::{}_SPEC>",
            &ns.to_sanitized_snake_case(),
            &name.to_sanitized_snake_case(),
            &name.to_sanitized_upper_case(),
        )
    } else {
        format!(
            "crate::Reg<{}::{}_SPEC>",
            &name.to_sanitized_snake_case(),
            &name.to_sanitized_upper_case(),
        )
    }
}

fn name_to_wrapped_ty(name: &str, ns: Option<&str>) -> Result<syn::Type> {
    let ident = name_to_wrapped_ty_str(name, ns);
    match parse_str::<syn::TypePath>(&ident) {
        Ok(path) => Ok(syn::Type::Path(path)),
        Err(e) => {
            let mut res = Err(e.into());
            res = res.with_context(|| {
                format!("Determining syn::TypePath from ident \"{}\" failed", ident)
            });
            res
        }
    }
}