Skip to content

Commit

Permalink
use more f-strings for formatting strings VUnit#747
Browse files Browse the repository at this point in the history
  • Loading branch information
eine authored Oct 8, 2021
2 parents 5756e55 + 7ad7b4e commit 37bc89c
Show file tree
Hide file tree
Showing 8 changed files with 145 additions and 175 deletions.
17 changes: 5 additions & 12 deletions vunit/parsing/tokenizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def add(self, kind, regex, func=None):

def finalize(self):
self._regex = re.compile(
"|".join("(?P<%s>%s)" % spec for spec in self._regexs),
"|".join(f"(?P<{spec[0]!s}>{spec[1]!s})" for spec in self._regexs),
re.VERBOSE | re.MULTILINE,
)

Expand Down Expand Up @@ -159,11 +159,8 @@ def expect(self, *kinds):
"""
token = self.pop()
if token.kind not in kinds:
if len(kinds) == 1:
expected = str(kinds[0])
else:
expected = "any of [%s]" % ", ".join(str(kind) for kind in kinds)
raise LocationException.error("Expected %s got %s" % (expected, token.kind), token.location)
expected = str(kinds[0]) if len(kinds) == 1 else f"any of [{', '.join(str(kind) for kind in kinds)}]"
raise LocationException.error(f"Expected {expected!s} got {token.kind!s}", token.location)
return token

def slice(self, start, end):
Expand All @@ -188,7 +185,7 @@ def describe_location(location, first=True):
return retval

if not file_exists(file_name):
retval += "Unknown location in %s" % file_name
retval += f"Unknown location in {file_name!s}"
return retval

contents = read_file(file_name)
Expand All @@ -203,11 +200,7 @@ def describe_location(location, first=True):
lstart = count
lend = lstart + len(line)
if lstart <= start <= lend:
retval += "%s %s line %i:\n" % (
prefix,
simplify_path(file_name),
lineno + 1,
)
retval += f"{prefix!s} {simplify_path(file_name)!s} line {lineno + 1:d}:\n"
retval += line + "\n"
retval += (" " * (start - lstart)) + ("~" * (min(lend - 1, end) - start + 1))
return retval
Expand Down
50 changes: 23 additions & 27 deletions vunit/sim_if/activehdl.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,9 +110,9 @@ def _std_str(vhdl_standard):
Convert standard to format of Active-HDL command line flag
"""
if vhdl_standard <= VHDL.STD_2008:
return "-%s" % vhdl_standard
return f"-{vhdl_standard!s}"

raise ValueError("Invalid VHDL standard %s" % vhdl_standard)
raise ValueError(f"Invalid VHDL standard {vhdl_standard!s}")

def compile_vhdl_file_command(self, source_file):
"""
Expand Down Expand Up @@ -144,9 +144,9 @@ def compile_verilog_file_command(self, source_file):
for library in self._libraries:
args += ["-l", library.name]
for include_dir in source_file.include_dirs:
args += ["+incdir+%s" % include_dir]
args += [f"+incdir+{include_dir!s}"]
for key, value in source_file.defines.items():
args += ["+define+%s=%s" % (key, value)]
args += [f"+define+{key!s}={value!s}"]
return args

def create_library(self, library_name, path, mapped_libraries=None):
Expand Down Expand Up @@ -186,7 +186,7 @@ def _create_library_cfg(self):
return

with Path(self._library_cfg).open("w", encoding="utf-8") as ofile:
ofile.write('$INCLUDE = "%s"\n' % str(Path(self._prefix).parent / "vlib" / "library.cfg"))
ofile.write(f'$INCLUDE = "{str(Path(self._prefix).parent / "vlib" / "library.cfg")}"\n')

_library_re = re.compile(r'([a-zA-Z_]+)\s=\s"(.*)"')

Expand Down Expand Up @@ -224,12 +224,12 @@ def _create_load_function(self, config, output_path):
Create the vunit_load TCL function that runs the vsim command and loads the design
"""
set_generic_str = "\n ".join(
("set vunit_generic_%s {%s}" % (name, value) for name, value in config.generics.items())
(f"set vunit_generic_{name!s} {{{value!s}}}" for name, value in config.generics.items())
)
set_generic_name_str = " ".join(
("-g/%s/%s=${vunit_generic_%s}" % (config.entity_name, name, name) for name in config.generics)
(f"-g/{config.entity_name!s}/{name!s}=${{vunit_generic_{name!s}}}" for name in config.generics)
)
pli_str = " ".join('-pli "%s"' % fix_path(name) for name in config.sim_options.get("pli", []))
pli_str = " ".join(f'-pli "{fix_path(name)}"' for name in config.sim_options.get("pli", []))

vsim_flags = [
pli_str,
Expand All @@ -245,7 +245,7 @@ def _create_load_function(self, config, output_path):
if config.sim_options.get("enable_coverage", False):
coverage_file_path = str(Path(output_path) / "coverage.acdb")
self._coverage_files.add(coverage_file_path)
vsim_flags += ["-acdb_file {%s}" % fix_path(coverage_file_path)]
vsim_flags += [f"-acdb_file {{{fix_path(coverage_file_path)!s}}}"]

vsim_flags += [self._vsim_extra_args(config)]

Expand All @@ -257,29 +257,25 @@ def _create_load_function(self, config, output_path):

vhdl_assert_stop_level_mapping = dict(warning=1, error=2, failure=3)

tcl = """
tcl = f"""
proc vunit_load {{}} {{
{set_generic_str}
set vsim_failed [catch {{
vsim {vsim_flags}
vsim {' '.join(vsim_flags)}
}}]
if {{${{vsim_failed}}}} {{
return true
}}
global breakassertlevel
set breakassertlevel {breaklevel}
set breakassertlevel {{{vhdl_assert_stop_level_mapping[config.vhdl_assert_stop_level]}}}
global builtinbreakassertlevel
set builtinbreakassertlevel $breakassertlevel
return false
}}
""".format(
set_generic_str=set_generic_str,
vsim_flags=" ".join(vsim_flags),
breaklevel=vhdl_assert_stop_level_mapping[config.vhdl_assert_stop_level],
)
"""

return tcl

Expand Down Expand Up @@ -314,14 +310,14 @@ def merge_coverage(self, file_name, args=None):

for coverage_file in self._coverage_files:
if file_exists(coverage_file):
merge_command += " -i {%s}" % fix_path(coverage_file)
merge_command += f" -i {{{fix_path(coverage_file)!s}}}"
else:
LOGGER.warning("Missing coverage file: %s", coverage_file)

if args is not None:
merge_command += " " + " ".join("{%s}" % arg for arg in args)
merge_command += " " + " ".join(f"{{{arg!s}}}" for arg in args)

merge_command += " -o {%s}" % fix_path(file_name) + "\n"
merge_command += f" -o {{{fix_path(file_name)!s}}}\n"

merge_script_name = str(Path(self._output_path) / "acdb_merge.tcl")
with Path(merge_script_name).open("w", encoding="utf-8") as fptr:
Expand All @@ -330,10 +326,10 @@ def merge_coverage(self, file_name, args=None):
vcover_cmd = [
str(Path(self._prefix) / "vsimsa"),
"-tcl",
"%s" % fix_path(merge_script_name),
str(fix_path(merge_script_name)),
]

print("Merging coverage files into %s..." % file_name)
print(f"Merging coverage files into {file_name!s}...")
vcover_merge_process = Process(vcover_cmd, env=self.get_env())
vcover_merge_process.consume_output()
print("Done merging coverage files")
Expand All @@ -354,7 +350,7 @@ def _create_batch_script(common_file_name, load_only=False):
Create tcl script to run in batch mode
"""
batch_do = ""
batch_do += 'source "%s"\n' % fix_path(common_file_name)
batch_do += f'source "{fix_path(common_file_name)!s}"\n'
batch_do += "set failed [vunit_load]\n"
batch_do += "if {$failed} {quit -code 1}\n"
if not load_only:
Expand All @@ -369,18 +365,18 @@ def _create_gui_script(self, common_file_name, config):
"""

tcl = ""
tcl += 'source "%s"\n' % fix_path(common_file_name)
tcl += f'source "{fix_path(common_file_name)!s}"\n'
tcl += "workspace create workspace\n"
tcl += "design create -a design .\n"

for library in self._libraries:
tcl += "vmap %s %s\n" % (library.name, fix_path(library.directory))
tcl += f"vmap {library.name!s} {fix_path(library.directory)!s}\n"

tcl += "vunit_load\n"

init_file = config.sim_options.get(self.name + ".init_file.gui", None)
if init_file is not None:
tcl += 'source "%s"\n' % fix_path(str(Path(init_file).resolve()))
tcl += f'source "{fix_path(str(Path(init_file).resolve()))!s}"\n'

tcl += 'puts "VUnit help: Design already loaded. Use run -all to run the test."\n'

Expand All @@ -391,7 +387,7 @@ def _run_batch_file(self, batch_file_name, gui, cwd):
Run a test bench in batch by invoking a new vsim process from the command line
"""

todo = '@do -tcl ""%s""' % fix_path(batch_file_name)
todo = f'@do -tcl ""{fix_path(batch_file_name)!s}""'
if not gui:
todo = "@onerror {quit -code 1};" + todo

Expand Down
4 changes: 3 additions & 1 deletion vunit/sim_if/cds_file.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,5 +49,7 @@ def write(self, file_name):
"""
Write cds file to file named 'file_name'
"""
contents = "\n".join(self._other_lines + ['define %s "%s"' % item for item in sorted(self.items())]) + "\n"
contents = (
"\n".join(self._other_lines + [f'define {item[0]!s} "{item[1]!s}"' for item in sorted(self.items())]) + "\n"
)
write_file(file_name, contents)
4 changes: 2 additions & 2 deletions vunit/sim_if/factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def check_sim_option(self, name, value):
known_options = sorted(list(self._sim_options.keys()))

if name not in self._sim_options:
raise ValueError("Unknown sim_option %r, expected one of %r" % (name, known_options))
raise ValueError(f"Unknown sim_option {name!r}, expected one of {known_options!r}")

self._sim_options[name].validate(value)

Expand All @@ -90,7 +90,7 @@ def check_compile_option_name(self, name):
"""
known_options = sorted(list(self._compile_options.keys()))
if name not in known_options:
raise ValueError("Unknown compile_option %r, expected one of %r" % (name, known_options))
raise ValueError(f"Unknown compile_option {name!r}, expected one of {known_options!r}")

def check_compile_option(self, name, value):
"""
Expand Down
Loading

0 comments on commit 37bc89c

Please sign in to comment.