forked from thanks4opensource/regbits
-
Notifications
You must be signed in to change notification settings - Fork 0
/
svd2regbits.py
executable file
·1710 lines (1526 loc) · 69.2 KB
/
svd2regbits.py
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
#!/usr/bin/env python3
# regbits: C++ templates for type-safe bit manipulation
# Copyright (C) 2020, 2021 Mark R. Rubin
#
# This file is part of regbits.
#
# The regbits program is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation, either version 3 of
# the License, or (at your option) any later version.
#
# The regbits program is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# (LICENSE.txt) along with the regbits program. If not, see
# <https://www.gnu.org/licenses/gpl.html>
#!/usr/bin/env python3
import argparse
import pprint # DEBUG
import os
import re
import sys
#
# Constants
#
VERSION = (0, 1, 4)
FIX_BAD_CHARS = {
i : i
if chr(i) in
'0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'
else None
for i in range(256) }
#
# Boilerplates
#
COPYRIGHT = '''%s %d.%d.%d
Copyright 2020 Mark R. Rubin aka "thanks4opensource"''' \
% (os.path.basename(sys.argv[0]), *VERSION)
HEADER = '''// Created by svd2regbits.py, version {ver}
// using Python XML module: {xml_lib}
//
// Source file: {svd_file}
// Device name: {mcu}
// SVD version: {svd_vers}
// description: {svd_desc}
#ifndef {upper}_HXX
#define {upper}_HXX
#include <stdint.h>
#include <regbits.hxx>
#if REGBITS_MAJOR_VERSION != 1
#error REGBITS_MAJOR_VERSION != 1
#endif
#if REGBITS_MINOR_VERSION < 1
#error REGBITS_MAJOR_VERSION == 1 but REGBITS_MINOR_VERSION < 1
#endif
#define {upper}_MAJOR_VERSION {maj}
#define {upper}_MINOR_VERSION {min}
#define {upper}_MICRO_VERSION {mcr}
namespace {lower} {{
using namespace regbits;
'''
PERIPH_DEFINE_0 = '\n\n\n'
PERIPH_DEFINE_1 = "#define {upper}_PERIPH(TYPE, PERIPH, BASE) \\\n"
PERIPH_DEFINE_2 = " static volatile TYPE* const \\\n"
PERIPH_DEFINE_3 = " PERIPH = reinterpret_cast<volatile TYPE*>(BASE)\n\n"
PERIPH_DEFINE = PERIPH_DEFINE_0 \
+ PERIPH_DEFINE_1 \
+ PERIPH_DEFINE_2 \
+ PERIPH_DEFINE_3
PERIPH_UNDEF = "\n#undef {upper}_PERIPH\n"
ARM_NVIC_HEADER = '''
enum class NvicIrqn {
''' + " // ARM IRQs\n"
ARM_IRQS = (
('Reset' , -15),
('NMI' , -14),
('HardFault' , -13),
('MemManage' , -12),
('BusFault' , -11),
('UsageFault' , -10),
('Reserved1' , -9),
('Reserved2' , -8),
('Reserved3' , -7),
('Reserved4' , -6),
('SVCall' , -5),
('Debug' , -4),
('Reserved5' , -3),
('PendSV' , -2),
('SysTick' , -1),
)
ARM_IRQ_NAMES = [irq[0] for irq in ARM_IRQS]
ARM_NVIC_FOOTER = '''}; // enum NvicIrqn
'''
FOOTER = '''
}} // namespace {mcu}
#endif // #ifndef {upper}_HXX
'''
#
# Utils
#
def import_xml_lib(lib, fail_ok=False):
global ET
LIBS = ('xml', 'lxml', 'defusedxml', 'BeautifulSoup')
if lib == 'auto':
for lib in LIBS:
if import_xml_lib(lib, fail_ok=True):
return lib
sys.stderr.write("Failed to import any of %s\n" % LIBS)
return None
try:
if lib == 'xml':
import xml.etree.ElementTree as ET
elif lib == 'lxml':
import lxml.etree as ET
elif lib == 'defusedxml':
import defusedxml.cElementTree as ET
elif lib == 'BeautifulSoup':
import BeautifulSoup as ET
else:
raise ImportError("Unknown xml parsing library \"%s\"" % lib)
except ImportError as error:
if fail_ok:
return False
else:
sys.stderr.write("Import of %s lib failed: %s\n" % (lib, error))
sys.exit(1)
return lib
def get_enumerated_values(register, field):
while True:
if field is None:
return None
values = field.find('enumeratedValues')
derived_from = field.get('derivedFrom')
if not derived_from:
return values
if '.' in derived_from:
sys.stderr.write( "Current version can't handle "
"<field><name>%s</name> "
"<enumeratedValues derivedFrom=\"%s\" /> "
"from different field/register/peripheral\n"
% (find_text(field, 'name'),
derived_from ) )
return values
field = register.find("./fields/field/[name='%s']" % derived_from)
def derived_from_by_name(root, node, element_type, child_name):
# if root is None or node is None:
# return None
child = node.find(child_name )
dfrm = node.get ('derivedFrom')
while child is None and dfrm is not None and node is not None:
node = root.find("./%s/[name='%s']" % (element_type, dfrm))
if node is not None:
dfrm = node.get ('derivedFrom')
child = node.find(child_name )
return child
def derived_from_stop_tag(root, element, element_type, stop_tag):
while True:
dfrm_name = element.get('derivedFrom')
if not dfrm_name:
return element
if any([child.tag == stop_tag for child in element.iterfind('*')]):
sys.stderr.write( "Element %s of %s has derivedFrom=\"%s\" "
"but one of %s is in %s. Current converter "
"can't handle modified \"derivedFrom\", only "
"unmodified clones.\n"
% (find_text(element, 'name') ,
root.tag ,
dfrm_name ,
[e.tag for e in element.iterfind('*')],
str(clone_tags) ) )
# go all the way to most-derived element
# return element
dfrm = root.find("%s/[name='%s']" % (element_type, dfrm_name))
if dfrm is None:
sys.stderr.write( "Can't find %s, <derivedFrom> of %s\n"
% (dfrm_name, find_text(element, 'name')))
return element
else:
element = dfrm
def find_text(xml, name):
found = xml.find(name)
if found is None:
return ''
text = found.text
if text is None:
return ''
else:
return text
def fixname(name):
if not name:
return name
if name[0] in '0123456789':
name = '_' + name
if name.lower() in ('alignas',
'alignof',
'and',
'and_eq',
'asm',
'atomic_cancel',
'atomic_commit',
'atomic_noexcept',
'auto',
'bitand',
'bitor',
'bits', # regbits
'bool',
'break',
'case',
'catch',
'char',
'char8',
'char16',
'char32',
'char64',
'char8_t',
'char16_t',
'char32_t',
'char64_t',
'class',
'compl',
'concept',
'const',
'consteval',
'constexpr',
'constinit',
'const_cast',
'continue',
'co_await',
'co_return',
'co_yield',
'decltype',
'default',
'delete',
'do',
'double',
'dynamic_cast',
'else',
'enum',
'explicit',
'export',
'extern',
'false',
'float',
'for',
'friend',
'goto',
'if',
'inline',
'int',
'int8_t',
'int16_t',
'int32_t',
'int64_t',
'long',
'mutable',
'mskd', # regbits
'namespace',
'new',
'noexcept',
'not',
'not_eq',
'nullptr',
'operator',
'or',
'or_eq',
'pos', # regbits
'private',
'protected',
'public',
'reflexpr',
'reg', # regbits
'register',
'reinterpret_cast',
'requires',
'return',
'short',
'signed',
'sizeof',
'static',
'static_assert',
'static_cast',
'struct',
'switch',
'synchronized',
'template',
'this',
'thread_local',
'throw',
'true',
'try',
'typedef',
'typeid',
'typename',
'uchar',
'uchar_t',
'uchar8_t',
'uchar16_t',
'uchar32_t',
'uchar64_t',
'union',
'unsigned',
'using',
'uint',
'uint8_t',
'uint16_t',
'uint32_t',
'uint64_t',
'virtual',
'void',
'volatile',
'wchar',
'wchar_t',
'wchar8_t',
'wchar16_t',
'wchar32_t',
'wchar64_t',
'wuchar',
'wuchar_t',
'wuchar8_t',
'wuchar16_t',
'wuchar32_t',
'wuchar64_t',
'while',
'xor',
'xor_eq'): name = '_' + name
name = name.translate(FIX_BAD_CHARS)
return name
def remove_name_dim(name):
name = name.replace('[%s]', '')
name = name.replace( '%s' , '')
return name
def snakecase(name):
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', name)
def camelcase(text):
# Can't use .title() because messes up already camelcased strings
text = snakecase(text) # so will keep already camelcased
# Don't remove underscore before digit(s): Replace '_' before digit(s)
# with '__' so camelcasing will leave one '_'
text = re.sub('(_[0-9])', '_\\1', text)
cced = ''.join([ s[0].upper() + s[1:].lower()
if len(s) > 1
else s.upper()
if len(s) > 0
else '_'
for s
in text.split('_') ])
return cced
def get_struct_name(element):
name = find_text(element, 'headerStructName')
if not name:
name = find_text(element, 'name')
return camelcase(fixname(remove_name_dim(name)))
def despace(text):
return " " .join(text.split())
def linebreak(outfile ,
indent ,
text ,
extra_indent =0 , # for field descriptions
first_indent =True, # for interrupt descriptions
strip_whitespace=True, # SVD descriptions indented to <xxx>
pad_first =None): # <field> description alignment
spaces = " " * indent
extra = ''
width = hxx_width - (indent + 3) # "// "
first = True
if strip_whitespace and not opts.newlines:
text = " ".join(text.split())
if pad_first:
space = text.find(" ")
text = "%s %s" % (text[:space].ljust(pad_first), text[space:])
if opts.newlines:
extra_indent -= 2
if extra_indent < 0: extra_indent = 0
for line in text.split('\n'):
if first and not first_indent:
saved = spaces
spaces = ''
if not line:
outfile.write("%s//\n" % spaces)
while line:
line = line.strip()
split = len(line)
space = -1
while split > width:
space = line[:split].rfind(" ")
if space is -1:
break
split = space
outfile.write("%s// %s%s\n" % (spaces, extra, line[:split]))
if extra == '':
extra = " " * extra_indent
width -= extra_indent
line = line[split:].strip()
if first:
if not first_indent: spaces = saved
first = False
def print_rbar(outfile, indent, rbar):
if not rbar:
return
spaces = " " * indent
if indent + len(rbar) <= hxx_width:
outfile.write('%s%s\n' % (spaces, rbar))
else:
lines = rbar.split(',')
outfile.write('%s%s,\n' % (spaces, lines[0].strip()))
# len('REGBITS_ARRAY_RANGE(') == 20
spaces = " " * (indent + 20)
for line in lines[1:-1]:
outfile.write('%s%s,\n' % (spaces, line.strip()))
outfile.write('%s%s\n' % (spaces, lines[-1].strip()))
def parse_int(text):
if not text:
return 0
try:
if len(text) == 1: return int(text )
elif text[1] in 'Xx': return int(text, 16)
else: return int(text )
except ValueError as error:
sys.stderr.write("Can't parse number \"%s\": %s\n" % (text, error))
return 0
def expand_dim_index(dim_index, location):
dims = []
toks = dim_index.split(',')
for tok in toks:
if '-' in tok:
try:
(beg, end) = map(int, tok.split('-'))
except:
sys.stderr.write( "Can't parse \"%s\" in "
"dimIndex \"%s\" %s"
% (tok, dim_index, location))
for num in range(beg, end + 1):
dims.append(num)
else:
dims.append(tok)
return dims
def indent(outfile, indent, text):
outfile.write("%s%s" % (" " * indent, text))
def print_element(outfile, element, indentation):
if element is not None:
indent(outfile,
indentation,
"%s: %s\n" % (element.tag, despace(element.text)))
def do_padding(outfile ,
periph_in_svd ,
periph_size ,
register_name ,
register_size ,
register_offset,
padding_number ,
indentation ):
bad_address = None
if register_size == 16 and register_offset & 0x1:
bad_address = register_offset
register_offset &= ~0x1
elif register_size == 32 and register_offset & 0x3 != 0:
bad_address = register_offset
register_offset &= ~0x3
elif register_size == 64 and register_offset & 0x7 != 0:
bad_address = register_offset
register_offset &= ~0x7
if bad_address:
sys.stderr.write( "Register %s in peripheral %s, size %d "
"bits at unaligned addressOffset %d==0x%x -- "
"changed to %d==0x%x\n"
% (register_name ,
periph_in_svd ,
register_size ,
bad_address ,
bad_address ,
register_offset,
register_offset) )
needed = register_offset - periph_size
if needed < 0:
sys.stderr.write( "Peripheral %s size already %d==0x%x, "
"register %s addressOffset %d==0x%x\n"
% (periph_in_svd ,
periph_size ,
periph_size ,
register_name ,
register_offset,
register_offset) )
return (periph_size, padding_number)
elif needed > 0:
outfile.write( "\n%sprivate: uint8_t padding_%d"
% (" " * indentation, padding_number))
padding_number += 1
if needed > 1:
outfile.write('[%d]; public:\n\n' % needed)
else:
outfile.write('; public:\n\n')
return (register_offset, padding_number)
def register_finish(ancestors, struct_name, struct_bytes, datatype, array_size):
if array_size > 1:
msk = opts.align[1] - 1
if struct_bytes == 1: struct_bytes = 1
elif struct_bytes == 2: struct_bytes = 2
else : struct_bytes = (struct_bytes + msk) & ~msk;
if datatype.startswith('uint'):
declaration = "%s_%s[%d];" % (datatype.ljust(12) ,
struct_name.lower(),
array_size )
else:
declaration = "%s _%s[%d];" % (datatype ,
struct_name.lower(),
array_size )
regbits_array_range = "REGBITS_ARRAY_RANGE(%s::%s, %s, %s, " \
"%s, _%s, %s)" \
% (ancestors ,
struct_name ,
struct_name.upper(),
struct_name.lower(),
datatype ,
struct_name.lower(),
array_size )
total_size = ((struct_bytes * array_size) + 0x3) & ~0x3
return ((declaration, regbits_array_range), total_size)
else:
msk = opts.align[0] - 1
if struct_bytes == 1: struct_bytes = 1
elif struct_bytes == 2: struct_bytes = 2
else : struct_bytes = (struct_bytes + msk) & ~msk;
regbits_array_range = None
if datatype.startswith('uint'):
declaration = "%s%s;" % (datatype.ljust(12) ,struct_name.lower())
else:
declaration = "%s %s;" % (datatype, struct_name.lower())
return ((declaration, regbits_array_range), struct_bytes)
def pod_instead(outfile ,
periph_struct ,
register_struct,
register_size ,
array_size ):
if register_size not in (8, 16, 32, 64):
sys.stdout.write( "WARNING: Cannot handle register size %d in "
"peripheral=%s register=%s -- skipping\n"
% (register_size, periph_struct, register_object))
return
pass
return register_finish(periph_struct ,
register_struct ,
register_size // 8 ,
'uint%d_t' % register_size,
array_size )
def do_register(outfile ,
indentation ,
periph_struct,
register ,
register_name,
register_size,
array_size ):
register_struct = camelcase(register_name)
register_object = register_name.lower()
register_type = register_object + '_t'
register_desc = find_text(register, 'description')
if 'reg' in opts.debug:
sys.stdout.write( "periph %s with %s, %s, %s %d,%d \"%s\"\n"
% (periph_struct ,
register_struct,
register_object,
register_type ,
register_size ,
array_size ,
register_desc ) )
fields = register.find('fields')
if 'reg' in opts.debug:
sys.stdout.write( "%d fields\n"
% (-1 if fields is None else len(fields)))
if fields is None or len(fields) == 0:
return pod_instead(outfile ,
periph_struct ,
register_struct, # register_object,
register_size ,
array_size )
poses = {}
offss = {}
descs = {}
bitss = {}
mskds = {}
valus = {}
for field in fields.findall('field'):
name = snakecase(find_text(field, 'name')).upper()
if not name:
sys.stderr.write( "Field with missing name in peripheral "
"%s, register %s -- skipping\n"
% (periph_struct, register_name) )
continue
dim = parse_int(find_text(field, 'dim' ))
dim_incr = parse_int(find_text(field, 'dimIncrement'))
dim_index = find_text(field, 'dimIndex' )
if dim_incr <= 0: dim_incr = 1
if '%' in name:
name = name.replace('%S', '%s') # upper() made uppercase
if not dim:
dim = 1 # for safety, shouldn't happen
if dim_index:
msg = "in peripheral %s, register %s, field %s" \
% (periph_struct, register_struct, name)
dims = expand_dim_index(dim_index, msg)
else:
dims = tuple(range(0, dim * dim_incr, dim_incr))
names = []
begs_wids = []
for (ndx, dim) in enumerate(dims):
names .append(fixname(name % dim))
begs_wids.append((ndx * dim_incr, dim_incr))
else:
names = (fixname(name),)
begin = None
width = None
bit_range = field.find('bitRange' )
bit_offset = field.find('bitOffset')
bit_width = field.find('bitWidth' )
msb = field.find('msb' )
lsb = field.find('lsb' )
if bit_range is not None:
(lft, rgt) = map(int, bit_range.text[1:-1].split(':'))
begin = rgt
width = 1 + lft - rgt
elif not None in (bit_offset, bit_width):
begin = int(bit_offset.text)
width = int(bit_width .text)
elif not None in (msb, lsb):
begin = int(lsb.text)
width = int(msb.text) - begin + 1
if None in (begin, width):
sys.stderr.write( "peripheral %s, register %s, field %s: "
"No bitRange or bitOffset+bitWidth -- "
"skipping\n"
% (periph_struct, register_struct, name) )
continue
begs_wids = ((begin, width),)
description = find_text(field, 'description')
for (name, (begin, width)) in zip(names, begs_wids):
# safety: have seen duplicate plain (not "%"/dim) names
if name in poses:
suffix = 1
orig = name
while name in poses:
name = orig + str(suffix)
suffix += 1
offss.setdefault(begin, [])
offss[begin].append(name)
poses[name ] = (begin, width)
descs[name ] = description
if width == 1:
bitss[begin] = name
else:
mskds[begin] = name
valus[name] = []
values = get_enumerated_values(register, field)
if values is not None:
if not begin in mskds: # enumeratedValues for single bit fields
mskds[begin] = name
for value in values.findall('enumeratedValue'):
base = fixname(snakecase(find_text(value, 'name'))).upper()
if not base:
sys.stderr.write( "Peripheral %s, register %s: "
"<enueratedValue> without <name> "
"-- skipping\n"
% (periph_struct, register_name) )
continue
valu = find_text(value, 'value')
if not value:
sys.stderr.write( "Peripheral %s, register %s: "
"<enueratedValue> \"%s\" without "
"<value> -- skipping\n"
% (periph_struct, register_name, base))
continue
desc = find_text(value, 'description')
if base == "MASK": base = "MASK_MASK" # dupe of uint32_t
if valu: valu = valu.lower() # "X" and "b"
else: valu = '0'
if valu.startswith('#'): valu = '0b' + valu[1:]
if valu.startswith('0b') and 'x' in valu:
# both versions of "don't care" bits
# for self-documentation: not really needed,
# (could just use zeros) and certainly
# no need for all possible permutations
valus[name].append((valu.replace('x', '0'),
base + '_0' ,
desc ))
valus[name].append((valu.replace('x', '1'),
base + '_1' ,
desc ))
else:
valus[name].append((valu, base, desc))
if 'reg' in opts.debug:
sys.stdout.write('poses:\n'); pprint.pprint(poses)
sys.stdout.write('offss:\n'); pprint.pprint(offss)
sys.stdout.write('descs:\n'); pprint.pprint(descs)
sys.stdout.write('bitss:\n'); pprint.pprint(bitss)
sys.stdout.write('mskds:\n'); pprint.pprint(mskds)
sys.stdout.write('valus:\n'); pprint.pprint(valus)
# maybe make uintN_t instead of struct with poses,bitss,mskds, etc
if len(offss) == 1 \
and 0 in offss \
and len (offss[0]) == 1 \
and poses[offss[0][0]][1] == register_size \
and not values :
return pod_instead(outfile ,
periph_struct ,
register_struct, # register_object,
register_size ,
array_size )
# wait until now because pod gets with definition
outfile.write('\n')
if register_desc:
linebreak(outfile, indentation, register_desc)
indent(outfile, indentation, 'struct %s {\n' % register_struct)
max_width = max([len(name) for name in poses.keys()])
had_offset_desc = False
for offs in sorted(offss.keys()):
for name in offss[offs]:
if descs[name] is not None:
name_desc = "%s %s" % (name, descs[name])
linebreak(outfile ,
indentation + 4 ,
name_desc ,
extra_indent=max_width + 4,
pad_first=max_width )
had_offset_desc = True
if had_offset_desc: outfile.write('\n')
indent(outfile ,
indentation + 4 ,
"using pos_t = Pos<uint%d_t, %s>;\n"
% (register_size, register_struct) )
indent(outfile, indentation + 4, "static constexpr pos_t")
first = True
for offs in sorted(offss.keys()):
for name in offss[offs]:
if first:
outfile.write('\n')
first = False
else:
outfile.write(',\n')
name += '_POS'
indent(outfile ,
indentation + 4 ,
"%-16s = pos_t(%2d)"
% (name.rjust(max_width + 4), offs))
outfile.write(';\n')
if bitss:
max_width = max([len(name) for name in bitss.values()])
ndx = 0
first = True
for offs in sorted(offss.keys()):
for bit_name in offss[offs]:
if bit_name not in bitss.values():
continue
if first:
outfile.write('\n')
indent(outfile ,
indentation ,
" using "
"bits_t = Bits<uint%d_t, %s>;\n"
% (register_size, register_struct))
indent(outfile ,
indentation + 4 ,
"static constexpr bits_t\n")
first = False
else:
outfile.write(',\n')
pos_name = bit_name + '_POS'
indent(outfile ,
indentation + 4 ,
"%s = bits_t(1, %s)"
% (bit_name.ljust(16) ,
pos_name.rjust(max_width + 4)))
ndx += 1
if not first: outfile.write(';\n')
if mskds:
max_width = max([len(item[1]) for item in mskds.items()])
enums = [] # mskd_ts with less than max_mskd values (explicit each)
rangs = [] # " " more (use REGBITS_MSKD_RANGE)
outfile.write('\n')
first = True
for offs in sorted(offss.keys()):
for name in offss[offs]:
(begin, width) = poses[name]
if begin in mskds and width > 1 or valus[name]:
if first:
indent(outfile ,
indentation + 4 ,
"static const uint%d_t\n" % register_size)
first = False
else:
outfile.write(',\n')
indent(outfile ,
indentation + 4 ,
"%s_MASK = 0x%08x"
% (name.rjust(max_width), (1 << width) - 1))
if width < opts.max_mskd or valus[name]:
enums.append(name)
else:
rangs.append(name)
if not first:
outfile.write(';\n')
outfile.write('\n')
indent(outfile ,
indentation + 4 ,
"using mskd_t = Mskd<uint%d_t, %s>;\n"
% (register_size, register_struct) )
indent(outfile ,
indentation + 4 ,
"using shft_t = Shft<uint%d_t, %s>;\n"
% (register_size, register_struct) )
if enums:
outfile.write('\n')
first = True
mskd_valus = set()
valu_pad = max([ max([len(val[0]) for val in vals])
if vals
else 0
for vals
in valus.values() ])
valu_pad = max(valu_pad, opts.max_mskd + 2)
max_name = 0
for valu in valus:
mskd_len = len(valu)
if valus[valu]:
mskd_len += max([len(val[1]) for val in valus[valu]])
if mskd_len > max_name: max_name = mskd_len
for offs in sorted(offss.keys()):
for mskd_name in offss[offs]:
if not mskd_name in enums:
continue
pos_name = mskd_name + '_POS'
for valu in valus[mskd_name]:
if first:
indent(outfile ,
indentation + 4 ,
"static constexpr mskd_t\n")
first = False
else:
outfile.write(',\n')
if valu[2]:
linebreak(outfile ,
indentation + 4,
valu[2] )
mskd_valu = '%s_%s' % (mskd_name, valu[1])
if mskd_valu in mskd_valus:
plain = mskd_valu
undupe = 1
while mskd_valu in mskd_valus:
mskd_valu = '%s_%d' % (plain, undupe)
undupe += 1
mskd_valus.add(mskd_valu)
indent(outfile ,
indentation + 4 ,
"%s = mskd_t(%s_MASK, %2s, %s)"
% (mskd_valu.ljust(max_name + 1),
mskd_name.rjust(max_width ),
valu[0] .ljust(valu_pad ),
pos_name .rjust(max_width + 4)))
if valus[mskd_name]:
continue # had "enumeratedValues" in SVD
# else generate numeric names for all field values
for enum in range(1 << poses[mskd_name][1]):
if first:
indent(outfile ,
indentation + 4 ,
"static constexpr mskd_t\n")
first = False
else:
outfile.write(',\n')
indent(outfile ,
indentation + 4 ,
"%s = mskd_t(%s_MASK, %s, %s)"
% ( ('%s_%02d' % (mskd_name, enum))
.ljust(max_name + 1) ,
mskd_name.rjust(max_width ),
('0x%x' % enum).ljust(valu_pad),
pos_name.rjust(max_width + 4 )))
if not first:
outfile.write(';\n')
if rangs:
outfile.write('\n')
for offs in sorted(offss.keys()):
for mskd_name in offss[offs]:
if not mskd_name in rangs:
continue
constexpr = mskd_name.upper()