blob: 73bdd0c6cb66cbea04512107261b16c2a3b95829 [file] [log] [blame]
lowRISC Contributors802543a2019-08-31 12:12:56 +01001#!/usr/bin/env python3
2# Copyright lowRISC contributors.
3# Licensed under the Apache License, Version 2.0, see LICENSE for details.
4# SPDX-License-Identifier: Apache-2.0
5r"""Command-line tool to validate and convert register hjson
6
7"""
8import argparse
9import logging as log
lowRISC Contributors802543a2019-08-31 12:12:56 +010010import re
11import sys
Michael Schaffner9af30532022-01-13 20:25:55 -080012from pathlib import Path
lowRISC Contributors802543a2019-08-31 12:12:56 +010013
Srikrishna Iyerd8aca092022-02-02 11:17:44 -080014from reggen import (gen_cheader, gen_dv, gen_fpv, gen_html, gen_json, gen_rtl,
15 gen_rust, gen_sec_cm_testplan, gen_selfdoc, version)
Michael Schaffner9af30532022-01-13 20:25:55 -080016from reggen.countermeasure import CounterMeasure
Srikrishna Iyerd8aca092022-02-02 11:17:44 -080017from reggen.ip_block import IpBlock
lowRISC Contributors802543a2019-08-31 12:12:56 +010018
Philipp Wagner14a3fee2019-11-21 10:07:02 +000019DESC = """regtool, generate register info from Hjson source"""
lowRISC Contributors802543a2019-08-31 12:12:56 +010020
21USAGE = '''
22 regtool [options]
23 regtool [options] <input>
24 regtool (-h | --help)
25 regtool (-V | --version)
26'''
27
28
29def main():
lowRISC Contributors802543a2019-08-31 12:12:56 +010030 verbose = 0
31
32 parser = argparse.ArgumentParser(
33 prog="regtool",
34 formatter_class=argparse.RawDescriptionHelpFormatter,
35 usage=USAGE,
36 description=DESC)
Eunchan Kim6ec3b892019-10-01 15:02:56 -070037 parser.add_argument('input',
38 nargs='?',
39 metavar='file',
40 type=argparse.FileType('r'),
41 default=sys.stdin,
Philipp Wagner14a3fee2019-11-21 10:07:02 +000042 help='input file in Hjson type')
Eunchan Kim6ec3b892019-10-01 15:02:56 -070043 parser.add_argument('-d',
44 action='store_true',
45 help='Output register documentation (html)')
46 parser.add_argument('--cdefines',
47 '-D',
48 action='store_true',
49 help='Output C defines header')
Chia-Chi Tenga0387902021-08-10 10:39:22 -060050 parser.add_argument('--rust',
51 '-R',
52 action='store_true',
53 help='Output Rust constants')
Eunchan Kim6ec3b892019-10-01 15:02:56 -070054 parser.add_argument('--doc',
55 action='store_true',
56 help='Output source file documentation (gfm)')
57 parser.add_argument('-j',
58 action='store_true',
59 help='Output as formatted JSON')
lowRISC Contributors802543a2019-08-31 12:12:56 +010060 parser.add_argument('-c', action='store_true', help='Output as JSON')
Eunchan Kim6ec3b892019-10-01 15:02:56 -070061 parser.add_argument('-r',
62 action='store_true',
63 help='Output as SystemVerilog RTL')
Srikrishna Iyerd8aca092022-02-02 11:17:44 -080064 parser.add_argument('--sec-cm-testplan',
65 action='store_true',
66 help='Generate security countermeasures testplan.')
Eunchan Kim6ec3b892019-10-01 15:02:56 -070067 parser.add_argument('-s',
68 action='store_true',
69 help='Output as UVM Register class')
Cindy Chen0bad7832019-11-07 11:25:00 -080070 parser.add_argument('-f',
71 action='store_true',
72 help='Output as FPV CSR rw assertion module')
Eunchan Kim0bd75662020-04-24 10:21:18 -070073 parser.add_argument('--outdir',
74 '-t',
75 help='Target directory for generated RTL; '
76 'tool uses ../rtl if blank.')
Cindy Chene16009b2021-11-01 19:35:51 -070077 parser.add_argument('--dv-base-names',
Cindy Chenc8389ed2021-11-04 10:53:07 -070078 nargs="+",
Cindy Chene16009b2021-11-01 19:35:51 -070079 help='Names or prefix for the DV register classes from which '
Srikrishna Iyerd2341c22021-01-11 22:31:18 -080080 'the register models are derived.')
Eunchan Kim6ec3b892019-10-01 15:02:56 -070081 parser.add_argument('--outfile',
82 '-o',
83 type=argparse.FileType('w'),
84 default=sys.stdout,
85 help='Target filename for json, html, gfm.')
86 parser.add_argument('--verbose',
87 '-v',
88 action='store_true',
89 help='Verbose and run validate twice')
90 parser.add_argument('--param',
91 '-p',
92 type=str,
Eunchan Kim276af5e2019-10-01 17:02:46 -070093 default="",
Eunchan Kim6ec3b892019-10-01 15:02:56 -070094 help='''Change the Parameter values.
95 Only integer value is supported.
96 You can add multiple param arguments.
97
98 Format: ParamA=ValA;ParamB=ValB
99 ''')
100 parser.add_argument('--version',
101 '-V',
102 action='store_true',
103 help='Show version')
104 parser.add_argument('--novalidate',
105 action='store_true',
106 help='Skip validate, just output json')
lowRISC Contributors802543a2019-08-31 12:12:56 +0100107
108 args = parser.parse_args()
109
110 if args.version:
111 version.show_and_exit(__file__, ["Hjson", "Mako"])
112
113 verbose = args.verbose
lowRISC Contributors802543a2019-08-31 12:12:56 +0100114 if (verbose):
115 log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG)
116 else:
117 log.basicConfig(format="%(levelname)s: %(message)s")
118
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000119 # Entries are triples of the form (arg, (format, dirspec)).
120 #
121 # arg is the name of the argument that selects the format. format is the
122 # name of the format. dirspec is None if the output is a single file; if
123 # the output needs a directory, it is a default path relative to the source
124 # file (used when --outdir is not given).
Weicai Yang53b0d4d2020-11-30 15:28:33 -0800125 arg_to_format = [('j', ('json', None)), ('c', ('compact', None)),
126 ('d', ('html', None)), ('doc', ('doc', None)),
127 ('r', ('rtl', 'rtl')), ('s', ('dv', 'dv')),
Chia-Chi Tenga0387902021-08-10 10:39:22 -0600128 ('f', ('fpv', 'fpv/vip')), ('cdefines', ('cdh', None)),
Srikrishna Iyerd8aca092022-02-02 11:17:44 -0800129 ('sec_cm_testplan', ('sec_cm_testplan', 'data')),
Chia-Chi Tenga0387902021-08-10 10:39:22 -0600130 ('rust', ('rs', None))]
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000131 format = None
132 dirspec = None
133 for arg_name, spec in arg_to_format:
134 if getattr(args, arg_name):
135 if format is not None:
136 log.error('Multiple output formats specified on '
Weicai Yang53b0d4d2020-11-30 15:28:33 -0800137 'command line ({} and {}).'.format(format, spec[0]))
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000138 sys.exit(1)
139 format, dirspec = spec
140 if format is None:
141 format = 'hjson'
lowRISC Contributors802543a2019-08-31 12:12:56 +0100142
143 infile = args.input
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000144
145 # Split parameters into key=value pairs.
146 raw_params = args.param.split(';') if args.param else []
147 params = []
148 for idx, raw_param in enumerate(raw_params):
149 tokens = raw_param.split('=')
150 if len(tokens) != 2:
151 raise ValueError('Entry {} in list of parameter defaults to '
152 'apply is {!r}, which is not of the form '
Srikrishna Iyerd8aca092022-02-02 11:17:44 -0800153 'param=value.'.format(idx, raw_param))
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000154 params.append((tokens[0], tokens[1]))
Eunchan Kim6ec3b892019-10-01 15:02:56 -0700155
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000156 # Define either outfile or outdir (but not both), depending on the output
157 # format.
158 outfile = None
159 outdir = None
160 if dirspec is None:
161 if args.outdir is not None:
162 log.error('The {} format expects an output file, '
Weicai Yang53b0d4d2020-11-30 15:28:33 -0800163 'not an output directory.'.format(format))
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000164 sys.exit(1)
165
166 outfile = args.outfile
lowRISC Contributors802543a2019-08-31 12:12:56 +0100167 else:
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000168 if args.outfile is not sys.stdout:
169 log.error('The {} format expects an output directory, '
Weicai Yang53b0d4d2020-11-30 15:28:33 -0800170 'not an output file.'.format(format))
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000171 sys.exit(1)
172
173 if args.outdir is not None:
174 outdir = args.outdir
175 elif infile is not sys.stdin:
Michael Schaffner9af30532022-01-13 20:25:55 -0800176 outdir = str(Path(infile.name).parents[1].joinpath(dirspec))
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000177 else:
178 # We're using sys.stdin, so can't infer an output directory name
Weicai Yang53b0d4d2020-11-30 15:28:33 -0800179 log.error(
180 'The {} format writes to an output directory, which '
181 'cannot be inferred automatically if the input comes '
182 'from stdin. Use --outdir to specify it manually.'.format(
183 format))
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000184 sys.exit(1)
lowRISC Contributors802543a2019-08-31 12:12:56 +0100185
186 if format == 'doc':
187 with outfile:
188 gen_selfdoc.document(outfile)
189 exit(0)
190
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000191 srcfull = infile.read()
192
Rupert Swarbricka9fdc612020-11-10 16:28:58 +0000193 try:
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000194 obj = IpBlock.from_text(srcfull, params, infile.name)
195 except ValueError as err:
196 log.error(str(err))
197 exit(1)
lowRISC Contributors802543a2019-08-31 12:12:56 +0100198
Michael Schaffner9af30532022-01-13 20:25:55 -0800199 # If this block has countermeasures, we grep for RTL annotations in all
200 # .sv implementation files and check whether they match up with what is
201 # defined inside the Hjson.
Srikrishna Iyera5566a42022-02-16 14:54:08 -0800202 # Skip this check when generating DV code - its not needed.
203 if format != 'dv':
Olof Kindgrenf999d552022-03-10 10:34:05 +0000204 sv_files = Path(infile.name).parent.joinpath('..').joinpath('rtl').glob('*.sv')
Srikrishna Iyerc71e12d2022-02-15 09:56:36 -0800205 rtl_names = CounterMeasure.search_rtl_files(sv_files)
206 obj.check_cm_annotations(rtl_names, infile.name)
Michael Schaffner9af30532022-01-13 20:25:55 -0800207
lowRISC Contributors802543a2019-08-31 12:12:56 +0100208 if args.novalidate:
209 with outfile:
210 gen_json.gen_json(obj, outfile, format)
211 outfile.write('\n')
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000212 else:
lowRISC Contributors802543a2019-08-31 12:12:56 +0100213 if format == 'rtl':
Rupert Swarbrick6880e212021-02-10 16:10:00 +0000214 return gen_rtl.gen_rtl(obj, outdir)
Srikrishna Iyerd8aca092022-02-02 11:17:44 -0800215 if format == 'sec_cm_testplan':
216 return gen_sec_cm_testplan.gen_sec_cm_testplan(obj, outdir)
lowRISC Contributors802543a2019-08-31 12:12:56 +0100217 if format == 'dv':
Cindy Chene16009b2021-11-01 19:35:51 -0700218 return gen_dv.gen_dv(obj, args.dv_base_names, outdir)
Cindy Chen0bad7832019-11-07 11:25:00 -0800219 if format == 'fpv':
Rupert Swarbrick6880e212021-02-10 16:10:00 +0000220 return gen_fpv.gen_fpv(obj, outdir)
lowRISC Contributors802543a2019-08-31 12:12:56 +0100221 src_lic = None
222 src_copy = ''
223 found_spdx = None
224 found_lunder = None
225 copy = re.compile(r'.*(copyright.*)|(.*\(c\).*)', re.IGNORECASE)
226 spdx = re.compile(r'.*(SPDX-License-Identifier:.+)')
227 lunder = re.compile(r'.*(Licensed under.+)', re.IGNORECASE)
228 for line in srcfull.splitlines():
229 mat = copy.match(line)
Eunchan Kim0bd75662020-04-24 10:21:18 -0700230 if mat is not None:
lowRISC Contributors802543a2019-08-31 12:12:56 +0100231 src_copy += mat.group(1)
232 mat = spdx.match(line)
Eunchan Kim0bd75662020-04-24 10:21:18 -0700233 if mat is not None:
lowRISC Contributors802543a2019-08-31 12:12:56 +0100234 found_spdx = mat.group(1)
235 mat = lunder.match(line)
Eunchan Kim0bd75662020-04-24 10:21:18 -0700236 if mat is not None:
lowRISC Contributors802543a2019-08-31 12:12:56 +0100237 found_lunder = mat.group(1)
238 if found_lunder:
239 src_lic = found_lunder
240 if found_spdx:
241 src_lic += '\n' + found_spdx
242
243 with outfile:
244 if format == 'html':
Rupert Swarbrick6880e212021-02-10 16:10:00 +0000245 return gen_html.gen_html(obj, outfile)
lowRISC Contributors802543a2019-08-31 12:12:56 +0100246 elif format == 'cdh':
Srikrishna Iyerd8aca092022-02-02 11:17:44 -0800247 return gen_cheader.gen_cdefines(obj, outfile, src_lic,
248 src_copy)
Chia-Chi Tenga0387902021-08-10 10:39:22 -0600249 elif format == 'rs':
250 return gen_rust.gen_rust(obj, outfile, src_lic, src_copy)
lowRISC Contributors802543a2019-08-31 12:12:56 +0100251 else:
Rupert Swarbrick6880e212021-02-10 16:10:00 +0000252 return gen_json.gen_json(obj, outfile, format)
lowRISC Contributors802543a2019-08-31 12:12:56 +0100253
254 outfile.write('\n')
255
256
257if __name__ == '__main__':
Rupert Swarbrick6880e212021-02-10 16:10:00 +0000258 sys.exit(main())