blob: 8b7ee7feedc4941540bf35928c8d13ec5c1bb7d4 [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
12from pathlib import PurePath
13
Rupert Swarbrick588819e2021-02-10 16:27:53 +000014from reggen import (gen_cheader, gen_dv, gen_fpv, gen_html,
Chia-Chi Tenga0387902021-08-10 10:39:22 -060015 gen_json, gen_rtl, gen_rust, gen_selfdoc, version)
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +000016from reggen.ip_block import IpBlock
lowRISC Contributors802543a2019-08-31 12:12:56 +010017
Philipp Wagner14a3fee2019-11-21 10:07:02 +000018DESC = """regtool, generate register info from Hjson source"""
lowRISC Contributors802543a2019-08-31 12:12:56 +010019
20USAGE = '''
21 regtool [options]
22 regtool [options] <input>
23 regtool (-h | --help)
24 regtool (-V | --version)
25'''
26
27
28def main():
lowRISC Contributors802543a2019-08-31 12:12:56 +010029 verbose = 0
30
31 parser = argparse.ArgumentParser(
32 prog="regtool",
33 formatter_class=argparse.RawDescriptionHelpFormatter,
34 usage=USAGE,
35 description=DESC)
Eunchan Kim6ec3b892019-10-01 15:02:56 -070036 parser.add_argument('input',
37 nargs='?',
38 metavar='file',
39 type=argparse.FileType('r'),
40 default=sys.stdin,
Philipp Wagner14a3fee2019-11-21 10:07:02 +000041 help='input file in Hjson type')
Eunchan Kim6ec3b892019-10-01 15:02:56 -070042 parser.add_argument('-d',
43 action='store_true',
44 help='Output register documentation (html)')
45 parser.add_argument('--cdefines',
46 '-D',
47 action='store_true',
48 help='Output C defines header')
Chia-Chi Tenga0387902021-08-10 10:39:22 -060049 parser.add_argument('--rust',
50 '-R',
51 action='store_true',
52 help='Output Rust constants')
Eunchan Kim6ec3b892019-10-01 15:02:56 -070053 parser.add_argument('--doc',
54 action='store_true',
55 help='Output source file documentation (gfm)')
56 parser.add_argument('-j',
57 action='store_true',
58 help='Output as formatted JSON')
lowRISC Contributors802543a2019-08-31 12:12:56 +010059 parser.add_argument('-c', action='store_true', help='Output as JSON')
Eunchan Kim6ec3b892019-10-01 15:02:56 -070060 parser.add_argument('-r',
61 action='store_true',
62 help='Output as SystemVerilog RTL')
63 parser.add_argument('-s',
64 action='store_true',
65 help='Output as UVM Register class')
Cindy Chen0bad7832019-11-07 11:25:00 -080066 parser.add_argument('-f',
67 action='store_true',
68 help='Output as FPV CSR rw assertion module')
Eunchan Kim0bd75662020-04-24 10:21:18 -070069 parser.add_argument('--outdir',
70 '-t',
71 help='Target directory for generated RTL; '
72 'tool uses ../rtl if blank.')
Srikrishna Iyerd2341c22021-01-11 22:31:18 -080073 parser.add_argument('--dv-base-prefix',
74 default='dv_base',
75 help='Prefix for the DV register classes from which '
76 'the register models are derived.')
Eunchan Kim6ec3b892019-10-01 15:02:56 -070077 parser.add_argument('--outfile',
78 '-o',
79 type=argparse.FileType('w'),
80 default=sys.stdout,
81 help='Target filename for json, html, gfm.')
82 parser.add_argument('--verbose',
83 '-v',
84 action='store_true',
85 help='Verbose and run validate twice')
86 parser.add_argument('--param',
87 '-p',
88 type=str,
Eunchan Kim276af5e2019-10-01 17:02:46 -070089 default="",
Eunchan Kim6ec3b892019-10-01 15:02:56 -070090 help='''Change the Parameter values.
91 Only integer value is supported.
92 You can add multiple param arguments.
93
94 Format: ParamA=ValA;ParamB=ValB
95 ''')
96 parser.add_argument('--version',
97 '-V',
98 action='store_true',
99 help='Show version')
100 parser.add_argument('--novalidate',
101 action='store_true',
102 help='Skip validate, just output json')
lowRISC Contributors802543a2019-08-31 12:12:56 +0100103
104 args = parser.parse_args()
105
106 if args.version:
107 version.show_and_exit(__file__, ["Hjson", "Mako"])
108
109 verbose = args.verbose
lowRISC Contributors802543a2019-08-31 12:12:56 +0100110 if (verbose):
111 log.basicConfig(format="%(levelname)s: %(message)s", level=log.DEBUG)
112 else:
113 log.basicConfig(format="%(levelname)s: %(message)s")
114
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000115 # Entries are triples of the form (arg, (format, dirspec)).
116 #
117 # arg is the name of the argument that selects the format. format is the
118 # name of the format. dirspec is None if the output is a single file; if
119 # the output needs a directory, it is a default path relative to the source
120 # file (used when --outdir is not given).
Weicai Yang53b0d4d2020-11-30 15:28:33 -0800121 arg_to_format = [('j', ('json', None)), ('c', ('compact', None)),
122 ('d', ('html', None)), ('doc', ('doc', None)),
123 ('r', ('rtl', 'rtl')), ('s', ('dv', 'dv')),
Chia-Chi Tenga0387902021-08-10 10:39:22 -0600124 ('f', ('fpv', 'fpv/vip')), ('cdefines', ('cdh', None)),
125 ('rust', ('rs', None))]
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000126 format = None
127 dirspec = None
128 for arg_name, spec in arg_to_format:
129 if getattr(args, arg_name):
130 if format is not None:
131 log.error('Multiple output formats specified on '
Weicai Yang53b0d4d2020-11-30 15:28:33 -0800132 'command line ({} and {}).'.format(format, spec[0]))
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000133 sys.exit(1)
134 format, dirspec = spec
135 if format is None:
136 format = 'hjson'
lowRISC Contributors802543a2019-08-31 12:12:56 +0100137
138 infile = args.input
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000139
140 # Split parameters into key=value pairs.
141 raw_params = args.param.split(';') if args.param else []
142 params = []
143 for idx, raw_param in enumerate(raw_params):
144 tokens = raw_param.split('=')
145 if len(tokens) != 2:
146 raise ValueError('Entry {} in list of parameter defaults to '
147 'apply is {!r}, which is not of the form '
148 'param=value.'
149 .format(idx, raw_param))
150 params.append((tokens[0], tokens[1]))
Eunchan Kim6ec3b892019-10-01 15:02:56 -0700151
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000152 # Define either outfile or outdir (but not both), depending on the output
153 # format.
154 outfile = None
155 outdir = None
156 if dirspec is None:
157 if args.outdir is not None:
158 log.error('The {} format expects an output file, '
Weicai Yang53b0d4d2020-11-30 15:28:33 -0800159 'not an output directory.'.format(format))
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000160 sys.exit(1)
161
162 outfile = args.outfile
lowRISC Contributors802543a2019-08-31 12:12:56 +0100163 else:
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000164 if args.outfile is not sys.stdout:
165 log.error('The {} format expects an output directory, '
Weicai Yang53b0d4d2020-11-30 15:28:33 -0800166 'not an output file.'.format(format))
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000167 sys.exit(1)
168
169 if args.outdir is not None:
170 outdir = args.outdir
171 elif infile is not sys.stdin:
172 outdir = str(PurePath(infile.name).parents[1].joinpath(dirspec))
173 else:
174 # We're using sys.stdin, so can't infer an output directory name
Weicai Yang53b0d4d2020-11-30 15:28:33 -0800175 log.error(
176 'The {} format writes to an output directory, which '
177 'cannot be inferred automatically if the input comes '
178 'from stdin. Use --outdir to specify it manually.'.format(
179 format))
Rupert Swarbrick586b93f2020-11-10 16:25:39 +0000180 sys.exit(1)
lowRISC Contributors802543a2019-08-31 12:12:56 +0100181
182 if format == 'doc':
183 with outfile:
184 gen_selfdoc.document(outfile)
185 exit(0)
186
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000187 srcfull = infile.read()
188
Rupert Swarbricka9fdc612020-11-10 16:28:58 +0000189 try:
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000190 obj = IpBlock.from_text(srcfull, params, infile.name)
191 except ValueError as err:
192 log.error(str(err))
193 exit(1)
lowRISC Contributors802543a2019-08-31 12:12:56 +0100194
195 if args.novalidate:
196 with outfile:
197 gen_json.gen_json(obj, outfile, format)
198 outfile.write('\n')
Rupert Swarbrick269bb3d2021-02-23 15:41:56 +0000199 else:
lowRISC Contributors802543a2019-08-31 12:12:56 +0100200 if format == 'rtl':
Rupert Swarbrick6880e212021-02-10 16:10:00 +0000201 return gen_rtl.gen_rtl(obj, outdir)
lowRISC Contributors802543a2019-08-31 12:12:56 +0100202 if format == 'dv':
Rupert Swarbrick6880e212021-02-10 16:10:00 +0000203 return gen_dv.gen_dv(obj, args.dv_base_prefix, outdir)
Cindy Chen0bad7832019-11-07 11:25:00 -0800204 if format == 'fpv':
Rupert Swarbrick6880e212021-02-10 16:10:00 +0000205 return gen_fpv.gen_fpv(obj, outdir)
lowRISC Contributors802543a2019-08-31 12:12:56 +0100206 src_lic = None
207 src_copy = ''
208 found_spdx = None
209 found_lunder = None
210 copy = re.compile(r'.*(copyright.*)|(.*\(c\).*)', re.IGNORECASE)
211 spdx = re.compile(r'.*(SPDX-License-Identifier:.+)')
212 lunder = re.compile(r'.*(Licensed under.+)', re.IGNORECASE)
213 for line in srcfull.splitlines():
214 mat = copy.match(line)
Eunchan Kim0bd75662020-04-24 10:21:18 -0700215 if mat is not None:
lowRISC Contributors802543a2019-08-31 12:12:56 +0100216 src_copy += mat.group(1)
217 mat = spdx.match(line)
Eunchan Kim0bd75662020-04-24 10:21:18 -0700218 if mat is not None:
lowRISC Contributors802543a2019-08-31 12:12:56 +0100219 found_spdx = mat.group(1)
220 mat = lunder.match(line)
Eunchan Kim0bd75662020-04-24 10:21:18 -0700221 if mat is not None:
lowRISC Contributors802543a2019-08-31 12:12:56 +0100222 found_lunder = mat.group(1)
223 if found_lunder:
224 src_lic = found_lunder
225 if found_spdx:
226 src_lic += '\n' + found_spdx
227
228 with outfile:
229 if format == 'html':
Rupert Swarbrick6880e212021-02-10 16:10:00 +0000230 return gen_html.gen_html(obj, outfile)
lowRISC Contributors802543a2019-08-31 12:12:56 +0100231 elif format == 'cdh':
Rupert Swarbrick6880e212021-02-10 16:10:00 +0000232 return gen_cheader.gen_cdefines(obj, outfile, src_lic, src_copy)
Chia-Chi Tenga0387902021-08-10 10:39:22 -0600233 elif format == 'rs':
234 return gen_rust.gen_rust(obj, outfile, src_lic, src_copy)
lowRISC Contributors802543a2019-08-31 12:12:56 +0100235 else:
Rupert Swarbrick6880e212021-02-10 16:10:00 +0000236 return gen_json.gen_json(obj, outfile, format)
lowRISC Contributors802543a2019-08-31 12:12:56 +0100237
238 outfile.write('\n')
239
240
241if __name__ == '__main__':
Rupert Swarbrick6880e212021-02-10 16:10:00 +0000242 sys.exit(main())