forked from esl-epfl/x-heep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsv2v_in_place.py
executable file
·275 lines (246 loc) · 8.23 KB
/
sv2v_in_place.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
#!/usr/bin/env python3
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
# pylint: disable=logging-format-interpolation,logging-not-lazy, super-init-not-called
# pylint: disable=raise-missing-from, unused-argument, consider-merging-isinstance
# pylint: disable=redefined-builtin, global-statement, subprocess-run-check, consider-using-sys-exit
import argparse
import logging
import os
import re
import shlex
import shutil
import subprocess
import tempfile
from typing import List, Pattern, Tuple
def read_file_list(path: str) -> List[str]:
"""Read in a list of paths from a file, one per line."""
ret = []
with open(path) as handle:
for line in handle:
ret.append(line.strip())
return ret
def transform_one(
sv2v: str,
defines: List[str],
incdirs: List[str],
pkg_paths: List[str],
sv_path: str,
dst_path: str,
) -> None:
"""Run sv2v to edit a file in place"""
defines_args = ["--define=" + d for d in defines]
incdirs_args = ["--incdir=" + d for d in incdirs]
paths = pkg_paths + ([] if sv_path in pkg_paths else [sv_path])
cmd = (
[
sv2v,
# Pass --exclude=assert to tell sv2v not to strip out assertions.
# Since the whole point of this flow is to prove assertions, we
# need to leave them unscathed!
"--exclude=assert",
"--verbose",
]
+ defines_args
+ incdirs_args
+ paths
)
logging.info("Running sv2v on {}".format(sv_path))
logging.debug("Command: {}".format(cmd))
with open(dst_path, "w") as dst_file:
proc = subprocess.run(cmd, stdout=dst_file)
if proc.returncode != 0:
cmd_str = " ".join([shlex.quote(a) for a in cmd])
raise RuntimeError(
"Failed to run sv2v on {}. "
"Exit code: {}. Full command: {}".format(
sv_path, proc.returncode, cmd_str
)
)
def parse_define_if(arg: str) -> Tuple[Pattern[str], str]:
"""Handle a --define-if argument"""
parts = arg.rsplit(":", 1)
if len(parts) != 2:
msg = (
"The --define-if argument {!r} contains no colon. The correct "
'syntax is "--define-if regex:define".'.format(arg)
)
raise argparse.ArgumentTypeError(msg)
re_str, define = parts
try:
return (re.compile(re_str), define)
except re.error as err:
raise argparse.ArgumentTypeError(
"The regex for the --define-if "
"argument ({!r}) is malformed: {}.".format(re_str, err)
)
def parse_define(arg: str) -> str:
splitted = arg.split("=")
# check if env var is set
os_value = os.environ.get(splitted[0])
return_arg = splitted[0]
if os_value is not None:
return_arg += f"={os_value}"
elif len(splitted) > 1:
# default value
return_arg += f"={splitted[1]}"
return return_arg
def transform(
sv2v: str,
defines: List[str],
defines_if: List[Tuple[Pattern[str], str]],
incdirs: List[str],
pkg_paths: List[str],
sv_paths: List[str],
) -> None:
"""Run sv2v to transform a list of files in-place"""
with tempfile.TemporaryDirectory() as tmpdir:
# First write each file to a file in a temporary directory, then copy
# everything back. We have to do it like this because otherwise we
# might trash a file that needs to be included by a later one.
dst_paths = []
for idx, src_path in enumerate(sv_paths):
dst_path = os.path.join(tmpdir, str(idx))
extra_file_defines = []
for regex, define in defines_if:
if regex.search(src_path):
extra_file_defines.append(define)
transform_one(
sv2v,
defines + extra_file_defines,
incdirs,
pkg_paths,
src_path,
dst_path,
)
dst_paths.append(dst_path)
# Now copy everything back, overwriting the original code
for dst_path, src_path in zip(dst_paths, sv_paths):
shutil.copy(dst_path, src_path)
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument(
"file_list", help=("File containing a list of " "paths on which to work.")
)
parser.add_argument(
"--verbose",
"-v",
action="store_true",
help="Log messages about what we're doing.",
)
parser.add_argument(
"--define",
"-D",
action="append",
dest="defines",
type=parse_define,
default=[],
help="Add a preprocessor define.",
)
parser.add_argument(
"--define-if",
action="append",
dest="defines_if",
type=parse_define_if,
default=[],
help=(
"Add a preprocessor define which applies to "
"specific files. For example "
"--define-if=foo:bar would define `bar on any "
"files whose paths contained a match for the "
'regex "foo".'
),
)
parser.add_argument(
"--incdir",
"-I",
action="append",
dest="incdirs",
default=[],
help="Add an include dir for the preprocessor.",
)
parser.add_argument(
"--incdir-list",
help=(
"Specify a file containing a list of include "
"directories (which are appended to any defined "
"through the --incdir argument)."
),
)
parser.add_argument(
"--sv2v",
default="sv2v",
help=("Specify the name or path of the sv2v binary. " "Defaults to 'sv2v'."),
)
parser.add_argument(
"--merge",
"-m",
action="store_true",
help="Merge before pass through sv2v",
)
args = parser.parse_args()
if args.verbose:
logging.basicConfig(level=logging.INFO)
try:
logging.info("Reading file list from {!r}.".format(args.file_list))
paths = read_file_list(args.file_list)
except IOError:
logging.error("Failed to read file list from {!r}".format(args.file_list))
return 1
if args.incdir_list is not None:
try:
logging.info("Reading incdir list from {!r}.".format(args.incdir_list))
args.incdirs += read_file_list(args.incdir_list)
except IOError:
logging.error("Failed to read incdir list from {!r}".format(args.file_list))
return 1
# Find all .sv or .svh files, splitting out paths ending in "pkg.sv"
# specially. We treat these as packages, which are included in each sv2v
# conversion.
sv_paths = []
svh_paths = []
pkg_paths = []
v_paths = []
for path in paths:
if os.path.splitext(path)[1] == ".sv":
sv_paths.append(path)
if os.path.splitext(path)[1] == ".v":
v_paths.append(path)
if os.path.splitext(path)[1] == ".svh":
svh_paths.append(path)
if path.endswith("pkg.sv"):
pkg_paths.append(path)
logging.info(
"Running sv2v in-place on {} files ({} packages).".format(
len(sv_paths), len(pkg_paths)
)
)
print("PATHS", sv_paths)
if args.merge:
with open('design.sv', 'w') as outfile:
for fname in sv_paths:
with open(fname) as infile:
for line in infile:
outfile.write(line)
for fname in v_paths:
with open(fname) as infile:
for line in infile:
outfile.write(line)
sv_paths = ['design.sv']
try:
transform(
args.sv2v, args.defines, args.defines_if, args.incdirs, pkg_paths, sv_paths
)
except RuntimeError as err:
logging.error(err)
return 1
# Empty out any remaining .svh files: they should have been included by
# this point (sv2v includes a preprocessor).
logging.info("Splatting contents of {} .svh files.".format(len(svh_paths)))
for path in svh_paths:
with open(path, "w"):
pass
return 0
if __name__ == "__main__":
exit(main())