-
Notifications
You must be signed in to change notification settings - Fork 163
Expand file tree
/
Copy pathperipheral.rs
More file actions
1450 lines (1333 loc) · 52 KB
/
peripheral.rs
File metadata and controls
1450 lines (1333 loc) · 52 KB
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
use regex::Regex;
use std::borrow::Cow;
use std::cmp::Ordering;
use std::fmt;
use svd_parser::expand::{
derive_cluster, derive_peripheral, derive_register, BlockPath, Index, RegisterPath,
};
use syn::LitInt;
use crate::config::Config;
use crate::svd::{
self, Cluster, ClusterInfo, MaybeArray, Peripheral, Register, RegisterCluster, RegisterInfo,
};
use log::{debug, trace, warn};
use proc_macro2::{Delimiter, Group, Ident, Punct, Spacing, Span, TokenStream};
use quote::{quote, ToTokens};
use syn::{punctuated::Punctuated, Token};
use crate::util::{
self, ident, name_to_ty, path_segment, type_path, unsuffixed, zst_type, DimSuffix, FullName,
BITS_PER_BYTE,
};
use anyhow::{anyhow, bail, Context, Result};
use crate::generate::register;
mod accessor;
use accessor::*;
pub fn render(p_original: &Peripheral, index: &Index, config: &Config) -> Result<TokenStream> {
let mut out = TokenStream::new();
let mut p = p_original.clone();
let mut path = None;
let dpath = p.derived_from.take();
if let Some(dpath) = dpath {
path = derive_peripheral(&mut p, &dpath, index)?;
}
let name = util::name_of(&p, config.ignore_groups);
let span = Span::call_site();
let p_ty = ident(&name, config, "peripheral", span);
let name_str = p_ty.to_string();
let address = util::hex(p.base_address + config.base_address_shift);
let doc = util::escape_special_chars(p.description.as_ref().unwrap_or(&name));
let doc = util::respace(&doc);
let doc = quote! { #[doc = #doc] };
let mod_ty = ident(&name, config, "peripheral_mod", span);
let (derive_regs, base, path) = if let Some(path) = path {
(
true,
ident(&path.peripheral, config, "peripheral_mod", span),
path,
)
} else {
(false, mod_ty.clone(), BlockPath::new(&p.name))
};
let mut feature_attribute = TokenStream::new();
let feature_format = config.ident_formats.get("peripheral_feature").unwrap();
if config.feature_group && p.group_name.is_some() {
let feature_name = feature_format.apply(p.group_name.as_ref().unwrap());
feature_attribute.extend(quote! { #[cfg(feature = #feature_name)] });
};
let phtml = config.settings.html_url.as_ref().map(|url| {
let doc = format!("See peripheral [structure]({url}#{})", &path.peripheral);
quote!(#[doc = ""] #doc)
});
let per_to_tokens = |out: &mut TokenStream,
feature_attribute: &TokenStream,
doc: &TokenStream,
p_ty: &Ident,
name_str: &str,
doc_alias: Option<TokenStream>,
address: LitInt| {
let pspec = ident(name_str, config, "peripheral_spec", Span::call_site());
out.extend(quote! {
#doc
#phtml
#doc_alias
#feature_attribute
pub type #p_ty = crate::Periph<#pspec>;
#feature_attribute
pub struct #pspec;
#feature_attribute
impl crate::PeripheralSpec for #pspec {
type RB = #base::RegisterBlock;
const ADDRESS: usize = #address;
const NAME: &'static str = #name_str;
}
});
};
match &p {
Peripheral::Array(p, dim) => {
let mut feature_names = Vec::with_capacity(dim.dim as _);
for pi in svd::peripheral::expand(p, dim) {
let name = &pi.name;
let doc = util::escape_special_chars(pi.description.as_ref().unwrap_or(&pi.name));
let doc = util::respace(&doc);
let doc = quote! { #[doc = #doc] };
let p_ty = ident(name, config, "peripheral", span);
let name_str = p_ty.to_string();
let doc_alias = (&name_str != name).then(|| quote!(#[doc(alias = #name)]));
let address = util::hex(pi.base_address + config.base_address_shift);
let p_feature = feature_format.apply(name);
feature_names.push(p_feature.to_string());
let mut feature_attribute_n = feature_attribute.clone();
if config.feature_peripheral {
feature_attribute_n.extend(quote! { #[cfg(feature = #p_feature)] })
};
// Insert the peripherals structure
per_to_tokens(
&mut out,
&feature_attribute_n,
&doc,
&p_ty,
&name_str,
doc_alias,
address,
);
}
let feature_any_attribute = quote! {#[cfg(any(#(feature = #feature_names),*))]};
// 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
#feature_any_attribute
pub use self::#base as #mod_ty;
});
return Ok(out);
}
}
Peripheral::Single(_) => {
let p_feature = feature_format.apply(&name);
if config.feature_peripheral {
feature_attribute.extend(quote! { #[cfg(feature = #p_feature)] })
};
// Insert the peripheral structure
per_to_tokens(
&mut out,
&feature_attribute,
&doc,
&p_ty,
&name_str,
None,
address,
);
// 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
#feature_attribute
pub use self::#base as #mod_ty;
});
return Ok(out);
}
}
}
// Build up an alternate erc list by expanding any derived registers/clusters
// erc: *E*ither *R*egister or *C*luster
let mut ercs = p.registers.take().unwrap_or_default();
// No `struct RegisterBlock` can be generated
if ercs.is_empty() {
// Drop the definition of the peripheral
return Ok(TokenStream::new());
}
debug!("Checking derivation information");
let derive_infos = check_erc_derive_infos(&mut ercs, &path, index, config)?;
let zipped = ercs.iter_mut().zip(derive_infos.iter());
for (mut erc, derive_info) in zipped {
if let RegisterCluster::Register(register) = &mut erc {
if let DeriveInfo::Implicit(rpath) = derive_info {
debug!(
"register {} implicitly derives from {}",
register.name, rpath.name
);
}
}
}
debug!("Pushing cluster & register information into output");
// Push all cluster & register related information into the peripheral module
let mod_items = render_ercs(&mut ercs, &derive_infos, &path, index, config)?;
// Push any register or cluster blocks into the output
debug!(
"Pushing {} register or cluster blocks into output",
ercs.len()
);
let reg_block = register_or_cluster_block(
&ercs,
&BlockPath::new(&p.name),
&derive_infos,
None,
"e! { #[doc = "Register block"] },
None,
config,
)?;
out.extend(quote! {
#doc
#feature_attribute
pub mod #mod_ty
});
let mut out_items = TokenStream::new();
out_items.extend(reg_block);
out_items.extend(mod_items);
let out_group = Group::new(Delimiter::Brace, out_items);
out.extend(quote! { #out_group });
p.registers = Some(ercs);
Ok(out)
}
/// An enum describing the derivation status of an erc, which allows for disjoint arrays to be
/// implicitly derived from a common type.
#[derive(Default, Debug, PartialEq)]
enum DeriveInfo {
#[default]
Root,
Explicit(RegisterPath),
Implicit(RegisterPath),
Cluster, // don't do anything different for clusters
}
impl fmt::Display for DeriveInfo {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
#[derive(Clone, Debug)]
struct RegisterBlockField {
syn_field: syn::Field,
offset: u32,
size: u32,
accessors: Vec<AccessType>,
}
#[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 size(&self) -> u32 {
self.end - self.offset
}
fn shortest_ident(&self) -> Option<String> {
let mut idents: Vec<_> = self
.rbfs
.iter()
.filter_map(|f| f.syn_field.ident.as_ref().map(ToString::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.syn_field.ident.as_ref().map(ToString::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.div_ceil(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) => {
if new_region.size() == 0 {
// add ArrayProxy
self.regions.insert(idx, new_region);
} else {
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 {new_ident:?}",
r.ident
);
r.ident = new_ident;
});
Ok(())
}
}
fn make_comment(size: u32, offset: u32, description: &str) -> String {
let desc = util::escape_special_chars(description);
let desc = util::respace(&desc);
if size > 32 {
let end = offset + size / 8;
format!("0x{offset:02x}..0x{end:02x} - {desc}")
} else {
format!("0x{offset:02x} - {desc}")
}
}
fn register_or_cluster_block(
ercs: &[RegisterCluster],
path: &BlockPath,
derive_infos: &[DeriveInfo],
name: Option<&str>,
doc: &TokenStream,
size: Option<u32>,
config: &Config,
) -> Result<TokenStream> {
let mut rbfs = TokenStream::new();
let mut accessors = TokenStream::new();
let ercs_expanded = expand(ercs, path, derive_infos, 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 ®ion.rbfs {
if is_region_a_union {
reg_block_field.accessors[0]
.clone()
.raw()
.to_tokens(&mut accessors);
} else {
reg_block_field.syn_field.to_tokens(&mut region_rbfs);
Punct::new(',', Spacing::Alone).to_tokens(&mut region_rbfs);
reg_block_field.accessors[0].to_tokens(&mut accessors);
}
for a in ®_block_field.accessors[1..] {
a.to_tokens(&mut accessors);
}
}
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;
}
if let Some(size) = size {
let pad = size
.checked_sub(last_end)
.ok_or_else(|| anyhow!("Incorrect block size"))?;
if pad > 0 {
let name = Ident::new("_reserved_end", span);
let pad = util::hex(pad as u64);
rbfs.extend(quote! {
#name : [u8; #pad],
});
}
}
let derive_debug = config.impl_debug.then(|| {
if let Some(feature_name) = &config.impl_debug_feature {
quote!(#[cfg_attr(feature = #feature_name, derive(Debug))])
} else {
quote!(#[derive(Debug)])
}
});
let mut doc_alias = None;
let block_ty = if let Some(name) = name {
let ty = ident(name, config, "cluster", span);
if ty != name {
doc_alias = Some(quote!(#[doc(alias = #name)]));
}
ty
} else {
Ident::new("RegisterBlock", span)
};
let accessors = (!accessors.is_empty()).then(|| {
quote! {
impl #block_ty {
#accessors
}
}
});
Ok(quote! {
#[repr(C)]
#derive_debug
#doc
#doc_alias
pub struct #block_ty {
#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],
path: &BlockPath,
derive_infos: &[DeriveInfo],
config: &Config,
) -> Result<Vec<RegisterBlockField>> {
let mut ercs_expanded = vec![];
debug!("Expanding registers or clusters into Register Block Fields");
let zipped = ercs.iter().zip(derive_infos.iter());
for (erc, derive_info) in zipped {
match &erc {
RegisterCluster::Register(register) => {
let reg_name = ®ister.name;
let expanded_reg = expand_register(register, path, derive_info, config)
.with_context(|| format!("can't expand register '{reg_name}'"))?;
trace!("Register: {reg_name}");
ercs_expanded.extend(expanded_reg);
}
RegisterCluster::Cluster(cluster) => {
let cluster_name = &cluster.name;
let expanded_cluster = expand_cluster(cluster, path, config)
.with_context(|| format!("can't expand cluster '{cluster_name}'"))?;
trace!("Cluster: {cluster_name}");
ercs_expanded.extend(expanded_cluster);
}
};
}
ercs_expanded.sort_by_key(|x| x.offset);
Ok(ercs_expanded)
}
/// Searches types using regex to find disjoint arrays which should implicitly derive from
/// another register. Returns a vector of `DeriveInfo` which should be `zip`ped with ercs when rendering.
fn check_erc_derive_infos(
ercs: &mut [RegisterCluster],
path: &BlockPath,
index: &Index,
config: &Config,
) -> Result<Vec<DeriveInfo>> {
let mut ercs_type_info: Vec<(String, Option<Regex>, &RegisterCluster, &mut DeriveInfo)> =
vec![];
let mut derive_infos: Vec<DeriveInfo> = vec![];
// fill the array so we can slice it (without implementing clone)
for _i in 0..ercs.len() {
derive_infos.push(DeriveInfo::default());
}
let derive_infos_slice = &mut derive_infos[0..ercs.len()];
let zipped = ercs.iter_mut().zip(derive_infos_slice.iter_mut());
for (mut erc, derive_info) in zipped {
match &mut erc {
RegisterCluster::Register(register) => {
let info_name = register.fullname(config.ignore_groups).to_string();
let explicit_rpath = match &mut register.derived_from.clone() {
Some(dpath) => {
let (_, root) = find_root(dpath, path, index)?;
Some(root)
}
None => None,
};
match register {
Register::Single(_) => {
let ty_name = info_name.clone();
*derive_info = match explicit_rpath {
None => {
match compare_this_against_prev(
register,
&ty_name,
path,
index,
&ercs_type_info,
)? {
Some(root) => {
// make sure the matched register isn't already deriving from this register
if ty_name == root.name {
DeriveInfo::Root
} else {
DeriveInfo::Implicit(root)
}
}
None => DeriveInfo::Root,
}
}
Some(rpath) => DeriveInfo::Explicit(rpath),
};
ercs_type_info.push((ty_name, None, erc, derive_info));
}
Register::Array(..) => {
// Only match integer indeces when searching for disjoint arrays
let re_string = info_name.expand_dim("([0-9]+|%s)");
let re = Regex::new(format!("^{re_string}$").as_str()).map_err(|_| {
anyhow!("Error creating regex for register {}", register.name)
})?;
let ty_name = info_name.clone(); // keep suffix for regex matching
*derive_info = match explicit_rpath {
None => {
match compare_this_against_prev(
register,
&ty_name,
path,
index,
&ercs_type_info,
)? {
Some(root) => DeriveInfo::Implicit(root),
None => compare_prev_against_this(
register,
&ty_name,
&re,
path,
index,
&mut ercs_type_info,
)?,
}
}
Some(rpath) => DeriveInfo::Explicit(rpath),
};
ercs_type_info.push((ty_name, Some(re), erc, derive_info));
}
};
}
RegisterCluster::Cluster(cluster) => {
*derive_info = DeriveInfo::Cluster;
ercs_type_info.push((cluster.name.clone(), None, erc, derive_info));
}
};
}
Ok(derive_infos)
}
fn find_root(
dpath: &str,
path: &BlockPath,
index: &Index,
) -> Result<(MaybeArray<RegisterInfo>, RegisterPath)> {
let (dblock, dname) = RegisterPath::parse_str(dpath);
let rdpath;
let reg_path;
let d = (if let Some(dblock) = dblock {
reg_path = dblock.new_register(dname);
rdpath = dblock;
index.registers.get(®_path)
} else {
reg_path = path.new_register(dname);
rdpath = path.clone();
index.registers.get(®_path)
})
.ok_or_else(|| anyhow!("register {} not found", dpath))?;
match d.derived_from.as_ref() {
Some(dp) => find_root(dp, &rdpath, index),
None => Ok(((*d).clone(), reg_path)),
}
}
/// Compare the given type name against previous regexs, then inspect fields
fn compare_this_against_prev(
reg: &MaybeArray<RegisterInfo>,
ty_name: &str,
path: &BlockPath,
index: &Index,
ercs_type_info: &Vec<(String, Option<Regex>, &RegisterCluster, &mut DeriveInfo)>,
) -> Result<Option<RegisterPath>> {
for prev in ercs_type_info {
let (prev_name, prev_regex, prev_erc, _prev_derive_info) = prev;
if let RegisterCluster::Register(_) = prev_erc {
if let Some(prev_re) = prev_regex {
if prev_re.is_match(ty_name) {
let (source_reg, rpath) = find_root(prev_name, path, index)?;
if is_derivable(&source_reg, reg) {
return Ok(Some(rpath));
}
}
}
}
}
Ok(None)
}
/// Compare previous type names against the given regex, then inspect fields
fn compare_prev_against_this(
reg: &MaybeArray<RegisterInfo>,
ty_name: &str,
re: ®ex::Regex,
path: &BlockPath,
index: &Index,
ercs_type_info: &mut Vec<(String, Option<Regex>, &RegisterCluster, &mut DeriveInfo)>,
) -> Result<DeriveInfo> {
let mut my_derive_info = DeriveInfo::Root;
// Check this type regex against previous names
for prev in ercs_type_info {
let (prev_name, _prev_regex, prev_erc, prev_derive_info) = prev;
if let RegisterCluster::Register(prev_reg) = prev_erc {
if let Register::Array(..) = prev_reg {
// Arrays are covered with compare_this_against_prev
continue;
}
if re.is_match(prev_name) {
let loop_derive_info = match prev_derive_info {
DeriveInfo::Root => {
// Get the RegisterPath for reg
let (_, implicit_rpath) = find_root(ty_name, path, index)?;
if is_derivable(prev_reg, reg) {
**prev_derive_info = DeriveInfo::Implicit(implicit_rpath);
}
DeriveInfo::Root
}
DeriveInfo::Explicit(rpath) => {
let (source_reg, implicit_rpath) = find_root(&rpath.name, path, index)?;
if is_derivable(&source_reg, reg) {
DeriveInfo::Implicit(implicit_rpath)
} else {
DeriveInfo::Root
}
}
DeriveInfo::Implicit(rpath) => {
let (source_reg, _) = find_root(&rpath.name, path, index)?;
if is_derivable(&source_reg, reg) {
DeriveInfo::Implicit(rpath.clone())
} else {
DeriveInfo::Root
}
}
DeriveInfo::Cluster => {
return Err(anyhow!("register {} represented as cluster", prev_reg.name))
}
};
if let DeriveInfo::Root = my_derive_info {
if my_derive_info != loop_derive_info {
my_derive_info = loop_derive_info;
}
}
}
if let DeriveInfo::Implicit(my_rpath) = &my_derive_info {
match prev_derive_info {
DeriveInfo::Implicit(their_rpath) => {
if their_rpath.name == ty_name {
(_, *their_rpath) = find_root(&my_rpath.name, path, index)?;
}
}
DeriveInfo::Explicit(their_rpath) => {
if their_rpath.name == ty_name {
(_, *their_rpath) = find_root(&my_rpath.name, path, index)?;
}
}
_ => {}
}
}
}
}
Ok(my_derive_info)
}
fn is_derivable(
source_reg: &MaybeArray<RegisterInfo>,
target_reg: &MaybeArray<RegisterInfo>,
) -> bool {
(source_reg.properties == target_reg.properties) && (source_reg.fields == target_reg.fields)
}
/// 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, path: &BlockPath, config: &Config) -> Result<u32> {
match cluster {
Cluster::Single(info) => cluster_info_size_in_bits(info, path, 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, path, 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, path: &BlockPath, 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, path, &DeriveInfo::Root, 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, path, config)?
}
};
size = size.max(end);
}
Ok(size)
}
/// Render a given cluster (and any children) into `RegisterBlockField`s
fn expand_cluster(
cluster: &Cluster,
path: &BlockPath,
config: &Config,
) -> Result<Vec<RegisterBlockField>> {
let mut cluster_expanded = vec![];
let cluster_size = cluster_info_size_in_bits(cluster, path, config)
.with_context(|| format!("Can't calculate cluster {} size", cluster.name))?;
let description = cluster
.description
.as_ref()
.unwrap_or(&cluster.name)
.to_string();
let ty_name = if cluster.is_single() {
Cow::Borrowed(cluster.name.as_str())
} else {
cluster.name.remove_dim()
};
let span = Span::call_site();
let ty = name_to_ty(ident(&ty_name, config, "cluster", span));
match cluster {
Cluster::Single(info) => {
let doc = make_comment(cluster_size, info.address_offset, &description);
let name: Ident = ident(&info.name, config, "cluster_accessor", span);
let syn_field = new_syn_field(name.clone(), ty.clone());
let accessor = Accessor::Reg(RegAccessor {
doc,
name,
ty,
offset: info.address_offset,
})
.raw_if(false);
cluster_expanded.push(RegisterBlockField {
syn_field,
offset: info.address_offset,
size: cluster_size,
accessors: vec![accessor],
})
}
Cluster::Array(info, array_info) => {
let ends_with_index = info.name.ends_with("[%s]") || info.name.ends_with("%s");
let increment_bits = array_info.dim_increment * BITS_PER_BYTE;
if cluster_size > increment_bits {
let cname = &cluster.name;
return Err(anyhow!("Cluster {cname} has size {cluster_size} bits that is more then array increment {increment_bits} bits"));
}
let cluster_size = if config.max_cluster_size {
increment_bits
} else {
cluster_size
};
let sequential_addresses = (array_info.dim == 1) || (cluster_size == increment_bits);