-
Notifications
You must be signed in to change notification settings - Fork 790
/
regtool.py
executable file
·320 lines (292 loc) · 12.1 KB
/
regtool.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
#!/usr/bin/env python3
# Copyright lowRISC contributors (OpenTitan project).
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
r"""Command-line tool to validate and convert register hjson
"""
import argparse
import logging as log
import re
import sys
from pathlib import Path
from reggen import (
gen_cfg_md, gen_cheader, gen_dv, gen_fpv, gen_md, gen_html, gen_json, gen_rtl,
gen_rust, gen_sec_cm_testplan, gen_selfdoc, gen_tock, version,
)
from reggen.ip_block import IpBlock
import version_file
DESC = """regtool, generate register info from Hjson source"""
USAGE = '''
regtool [options]
regtool [options] <input>
regtool (-h | --help)
regtool (-V | --version)
'''
def main():
verbose = 0
parser = argparse.ArgumentParser(
prog="regtool",
formatter_class=argparse.RawDescriptionHelpFormatter,
usage=USAGE,
description=DESC)
parser.add_argument('input',
nargs='?',
metavar='file',
type=argparse.FileType('r'),
default=sys.stdin,
help='input file in Hjson type')
parser.add_argument('-d',
action='store_true',
help='Output register documentation (markdown)')
parser.add_argument('-a',
'--alias',
type=Path,
default=None,
help='Alias register file in Hjson type')
parser.add_argument('-S',
'--scrub',
default=False,
action='store_true',
help='Scrub alias register definition')
parser.add_argument('--cdefines',
'-D',
action='store_true',
help='Output C defines header')
parser.add_argument('--rust',
'-R',
action='store_true',
help='Output Rust constants')
parser.add_argument('--tock',
action='store_true',
help='Output Tock constants')
parser.add_argument('--interfaces',
action='store_true',
help='Output interfaces documentation (markdown)')
parser.add_argument('--doc-html-old',
action='store_true',
help='Output html documentation (depreciated)')
parser.add_argument('--doc',
action='store_true',
help='Output source file documentation (markdown)')
parser.add_argument('-j',
action='store_true',
help='Output as formatted JSON')
parser.add_argument('-c', action='store_true', help='Output as JSON')
parser.add_argument('-r',
action='store_true',
help='Output as SystemVerilog RTL')
parser.add_argument('--sec-cm-testplan',
action='store_true',
help='Generate security countermeasures testplan.')
parser.add_argument('-s',
action='store_true',
help='Output as UVM Register class')
parser.add_argument('-f',
action='store_true',
help='Output as FPV CSR rw assertion module')
parser.add_argument('--outdir',
'-t',
help='Target directory for generated RTL; '
'tool uses ../rtl if blank.')
parser.add_argument(
'--dv-base-names',
nargs="+",
help='Names or prefix for the DV register classes from which '
'the register models are derived.')
parser.add_argument('--outfile',
'-o',
type=argparse.FileType('w'),
default=sys.stdout,
help='Target filename for json, html, gfm.')
parser.add_argument('--verbose',
'-v',
action='store_true',
help='Verbose and run validate twice')
parser.add_argument('--quiet',
'-q',
action='store_true',
help='Log only errors, not warnings')
parser.add_argument('--param',
'-p',
type=str,
default="",
help='''Change the Parameter values.
Only integer value is supported.
You can add multiple param arguments.
Format: ParamA=ValA;ParamB=ValB
''')
parser.add_argument('--version',
'-V',
action='store_true',
help='Show version')
parser.add_argument('--novalidate',
action='store_true',
help='Skip validate, just output json')
parser.add_argument('--node',
'-n',
type=str,
default="",
help='''Regblock node to generate.
By default, generate for all nodes.
''')
parser.add_argument(
'--version-stamp',
type=str,
default=None,
help=
'If version stamping, the location of workspace version stamp file.')
args = parser.parse_args()
if args.version:
version.show_and_exit(__file__, ["Hjson", "Mako"])
verbose = args.verbose
if verbose:
log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG)
elif args.quiet:
log.basicConfig(format="%(levelname)s: %(message)s", level=log.ERROR)
else:
log.basicConfig(format="%(levelname)s: %(message)s")
# Entries are triples of the form (arg, (fmt, dirspec)).
#
# arg is the name of the argument that selects the format. fmt is the
# name of the format. dirspec is None if the output is a single file; if
# the output needs a directory, it is a default path relative to the source
# file (used when --outdir is not given).
arg_to_format = [('j', ('json', None)), ('c', ('compact', None)),
('d', ('registers', None)), ('doc', ('doc', None)),
('r', ('rtl', 'rtl')), ('s', ('dv', 'dv')),
('f', ('fpv', 'fpv/vip')), ('cdefines', ('cdh', None)),
('sec_cm_testplan', ('sec_cm_testplan', 'data')),
('rust', ('rs', None)), ('tock', ('trs', None)),
('interfaces', ('interfaces', None)),
('doc_html_old', ('doc_html_old', None))]
fmt = None
dirspec = None
for arg_name, spec in arg_to_format:
if getattr(args, arg_name):
if fmt is not None:
log.error('Multiple output formats specified on '
'command line ({} and {}).'.format(fmt, spec[0]))
sys.exit(1)
fmt, dirspec = spec
if fmt is None:
fmt = 'hjson'
infile = args.input
# Split parameters into key=value pairs.
raw_params = args.param.split(';') if args.param else []
params = []
for idx, raw_param in enumerate(raw_params):
tokens = raw_param.split('=')
if len(tokens) != 2:
raise ValueError('Entry {} in list of parameter defaults to '
'apply is {!r}, which is not of the form '
'param=value.'.format(idx, raw_param))
params.append((tokens[0], tokens[1]))
# Define either outfile or outdir (but not both), depending on the output
# format.
outfile = None
outdir = None
if dirspec is None:
if args.outdir is not None:
log.error('The {} format expects an output file, '
'not an output directory.'.format(fmt))
sys.exit(1)
outfile = args.outfile
else:
if args.outfile is not sys.stdout:
log.error('The {} format expects an output directory, '
'not an output file.'.format(fmt))
sys.exit(1)
if args.outdir is not None:
outdir = args.outdir
elif infile is not sys.stdin:
outdir = str(Path(infile.name).parents[1].joinpath(dirspec))
else:
# We're using sys.stdin, so can't infer an output directory name
log.error(
'The {} format writes to an output directory, which '
'cannot be inferred automatically if the input comes '
'from stdin. Use --outdir to specify it manually.'.format(
fmt))
sys.exit(1)
# Extract version stamp from file
version_stamp = version_file.VersionInformation(args.version_stamp)
if fmt == 'doc':
with outfile:
gen_selfdoc.document(outfile)
exit(0)
srcfull = infile.read()
try:
obj = IpBlock.from_text(srcfull, params, infile.name, args.node)
except ValueError as err:
log.error(str(err))
exit(1)
# Parse and validate alias register definitions (this ensures that the
# structure of the original register node and the alias register file is
# identical).
if args.alias is not None:
try:
obj.alias_from_path(args.scrub, args.alias)
except ValueError as err:
log.error(str(err))
exit(1)
else:
if args.scrub:
raise ValueError('The --scrub argument is only meaningful in '
'combination with the --alias argument')
if args.novalidate:
with outfile:
gen_json.gen_json(obj, outfile, fmt)
outfile.write('\n')
else:
if fmt == 'rtl':
return gen_rtl.gen_rtl(obj, outdir)
if fmt == 'sec_cm_testplan':
return gen_sec_cm_testplan.gen_sec_cm_testplan(obj, outdir)
if fmt == 'dv':
return gen_dv.gen_dv(obj, args.dv_base_names, outdir)
if fmt == 'fpv':
return gen_fpv.gen_fpv(obj, outdir)
src_lic = None
src_copy = ''
found_spdx = None
found_lunder = None
copy = re.compile(r'.*(copyright.*)|(.*\(c\).*)', re.IGNORECASE)
spdx = re.compile(r'.*(SPDX-License-Identifier:.+)')
lunder = re.compile(r'.*(Licensed under.+)', re.IGNORECASE)
for line in srcfull.splitlines():
mat = copy.match(line)
if mat is not None:
src_copy += mat.group(1)
mat = spdx.match(line)
if mat is not None:
found_spdx = mat.group(1)
mat = lunder.match(line)
if mat is not None:
found_lunder = mat.group(1)
if found_lunder:
src_lic = found_lunder
if found_spdx:
src_lic += '\n' + found_spdx
with outfile:
if fmt == 'registers':
return gen_md.gen_md(obj, outfile)
elif fmt == 'interfaces':
# Assumes the registers will be in a file called `registers.md`
# and within the same location as the output's destination.
# Exposing this as an option would nice to do.
return gen_cfg_md.gen_cfg_md(obj, outfile, "registers.md")
elif fmt == 'doc_html_old':
return gen_html.gen_html(obj, outfile)
elif fmt == 'cdh':
return gen_cheader.gen_cdefines(obj, outfile, src_lic,
src_copy)
elif fmt == 'rs':
return gen_rust.gen_rust(obj, outfile, src_lic, src_copy)
elif fmt == 'trs':
return gen_tock.gen_tock(obj, outfile, infile.name, src_lic,
src_copy, version_stamp)
else:
return gen_json.gen_json(obj, outfile, fmt)
outfile.write('\n')
if __name__ == '__main__':
sys.exit(main())