misc: Use python f-strings for string formatting
This patch has been generated by applying flynt to the gem5 repo (ext has been excluded) JIRA: https://gem5.atlassian.net/browse/GEM5-831 Change-Id: I0935db6223d5426b99515959bde78e374cbadb04 Signed-off-by: Giacomo Travaglini <giacomo.travaglini@arm.com> Reviewed-on: https://gem5-review.googlesource.com/c/public/gem5/+/68957 Maintainer: Bobby Bruce <bbruce@ucdavis.edu> Tested-by: kokoro <noreply+kokoro@google.com> Reviewed-by: Bobby Bruce <bbruce@ucdavis.edu>
This commit is contained in:
@@ -387,7 +387,7 @@ class ArmBoard(ArmSystem, AbstractBoard, KernelDiskWorkload):
|
||||
"norandmaps",
|
||||
"root={root_value}",
|
||||
"rw",
|
||||
"mem=%s" % self.get_memory().get_size(),
|
||||
f"mem={self.get_memory().get_size()}",
|
||||
]
|
||||
|
||||
@overrides(SimObject)
|
||||
|
||||
@@ -293,7 +293,7 @@ class LupvBoard(AbstractSystemBoard, KernelDiskWorkload):
|
||||
root.appendCompatible(["luplab,lupv"])
|
||||
|
||||
for mem_range in self.mem_ranges:
|
||||
node = FdtNode("memory@%x" % int(mem_range.start))
|
||||
node = FdtNode(f"memory@{int(mem_range.start):x}")
|
||||
node.append(FdtPropertyStrings("device_type", ["memory"]))
|
||||
node.append(
|
||||
FdtPropertyWords(
|
||||
|
||||
@@ -248,7 +248,7 @@ class RiscvBoard(AbstractSystemBoard, KernelDiskWorkload):
|
||||
root.appendCompatible(["riscv-virtio"])
|
||||
|
||||
for mem_range in self.mem_ranges:
|
||||
node = FdtNode("memory@%x" % int(mem_range.start))
|
||||
node = FdtNode(f"memory@{int(mem_range.start):x}")
|
||||
node.append(FdtPropertyStrings("device_type", ["memory"]))
|
||||
node.append(
|
||||
FdtPropertyWords(
|
||||
|
||||
@@ -321,7 +321,7 @@ class RISCVMatchedBoard(
|
||||
root.appendCompatible(["riscv-virtio"])
|
||||
|
||||
for mem_range in self.mem_ranges:
|
||||
node = FdtNode("memory@%x" % int(mem_range.start))
|
||||
node = FdtNode(f"memory@{int(mem_range.start):x}")
|
||||
node.append(FdtPropertyStrings("device_type", ["memory"]))
|
||||
node.append(
|
||||
FdtPropertyWords(
|
||||
|
||||
@@ -108,7 +108,7 @@ def _get_resources_json_at_path(path: str, use_caching: bool = True) -> Dict:
|
||||
# Note the timeout is 120 so the `_download` function is given time to run
|
||||
# its Truncated Exponential Backoff algorithm
|
||||
# (maximum of roughly 1 minute). Typically this code will run quickly.
|
||||
with FileLock("{}.lock".format(download_path), timeout=120):
|
||||
with FileLock(f"{download_path}.lock", timeout=120):
|
||||
|
||||
# The resources.json file can change at any time, but to avoid
|
||||
# excessive retrieval we cache a version locally and use it for up to
|
||||
@@ -212,9 +212,7 @@ def _get_resources(
|
||||
# after a check that the name is unique.
|
||||
if resource["name"] in to_return.keys():
|
||||
raise Exception(
|
||||
"Error: Duplicate resource with name '{}'.".format(
|
||||
resource["name"]
|
||||
)
|
||||
f"Error: Duplicate resource with name '{resource['name']}'."
|
||||
)
|
||||
to_return[resource["name"]] = resource
|
||||
elif resource["type"] == "group":
|
||||
@@ -229,9 +227,7 @@ def _get_resources(
|
||||
# the resources.json file. The resources names need to be
|
||||
# unique keyes.
|
||||
raise Exception(
|
||||
"Error: Duplicate resources with names: {}.".format(
|
||||
str(intersection)
|
||||
)
|
||||
f"Error: Duplicate resources with names: {str(intersection)}."
|
||||
)
|
||||
to_return.update(new_map)
|
||||
|
||||
@@ -390,9 +386,7 @@ def get_resources_json_obj(resource_name: str) -> Dict:
|
||||
|
||||
if resource_name not in resource_map:
|
||||
raise Exception(
|
||||
"Error: Resource with name '{}' does not exist".format(
|
||||
resource_name
|
||||
)
|
||||
f"Error: Resource with name '{resource_name}' does not exist"
|
||||
)
|
||||
|
||||
return resource_map[resource_name]
|
||||
@@ -435,7 +429,7 @@ def get_resource(
|
||||
# same resources at once. The timeout here is somewhat arbitarily put at 15
|
||||
# minutes.Most resources should be downloaded and decompressed in this
|
||||
# timeframe, even on the most constrained of systems.
|
||||
with FileLock("{}.lock".format(to_path), timeout=900):
|
||||
with FileLock(f"{to_path}.lock", timeout=900):
|
||||
|
||||
resource_json = get_resources_json_obj(resource_name)
|
||||
|
||||
@@ -506,13 +500,11 @@ def get_resource(
|
||||
url = resource_json["url"].format(url_base=_get_url_base())
|
||||
|
||||
_download(url=url, download_to=download_dest)
|
||||
print("Finished downloading resource '{}'.".format(resource_name))
|
||||
print(f"Finished downloading resource '{resource_name}'.")
|
||||
|
||||
if run_unzip:
|
||||
print(
|
||||
"Decompressing resource '{}' ('{}')...".format(
|
||||
resource_name, download_dest
|
||||
)
|
||||
f"Decompressing resource '{resource_name}' ('{download_dest}')..."
|
||||
)
|
||||
unzip_to = download_dest[: -len(zip_extension)]
|
||||
with gzip.open(download_dest, "rb") as f:
|
||||
@@ -520,9 +512,7 @@ def get_resource(
|
||||
shutil.copyfileobj(f, o)
|
||||
os.remove(download_dest)
|
||||
download_dest = unzip_to
|
||||
print(
|
||||
"Finished decompressing resource '{}'.".format(resource_name)
|
||||
)
|
||||
print(f"Finished decompressing resource '{resource_name}'.")
|
||||
|
||||
if run_tar_extract:
|
||||
print(
|
||||
|
||||
@@ -97,5 +97,5 @@ class ExitEvent(Enum):
|
||||
# This is for the gups generator exit event
|
||||
return ExitEvent.EXIT
|
||||
raise NotImplementedError(
|
||||
"Exit event '{}' not implemented".format(exit_string)
|
||||
f"Exit event '{exit_string}' not implemented"
|
||||
)
|
||||
|
||||
@@ -47,7 +47,7 @@ class FileLock(object):
|
||||
"If timeout is not None, then delay must not be None."
|
||||
)
|
||||
self.is_locked = False
|
||||
self.lockfile = os.path.join(os.getcwd(), "%s.lock" % file_name)
|
||||
self.lockfile = os.path.join(os.getcwd(), f"{file_name}.lock")
|
||||
self.file_name = file_name
|
||||
self.timeout = timeout
|
||||
self.delay = delay
|
||||
@@ -83,7 +83,7 @@ class FileLock(object):
|
||||
)
|
||||
if (time.time() - start_time) >= self.timeout:
|
||||
raise FileLockException(
|
||||
"Timeout occured. {}".format(solution_message)
|
||||
f"Timeout occured. {solution_message}"
|
||||
)
|
||||
time.sleep(self.delay)
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ class gem5Context(context.BaseContext):
|
||||
try:
|
||||
ctx = _concrete_contexts[method]
|
||||
except KeyError:
|
||||
raise ValueError("cannot find context for %r" % method) from None
|
||||
raise ValueError(f"cannot find context for {method!r}") from None
|
||||
ctx._check_available()
|
||||
return ctx
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ def _get_exception_str(msg: str):
|
||||
# Otherwise we assume the `requires` is being called by a class, in
|
||||
# which case we label the exception message with the class name.
|
||||
name = inspect.stack()[2].frame.f_locals["self"].__class__.__name__
|
||||
return "[{}] {}".format(name, msg)
|
||||
return f"[{name}] {msg}"
|
||||
|
||||
|
||||
def requires(
|
||||
|
||||
@@ -50,7 +50,7 @@ class CodeImporter(object):
|
||||
|
||||
def add_module(self, abspath, modpath, code):
|
||||
if modpath in self.modules:
|
||||
raise AttributeError("%s already found in importer" % modpath)
|
||||
raise AttributeError(f"{modpath} already found in importer")
|
||||
|
||||
self.modules[modpath] = (abspath, code)
|
||||
|
||||
|
||||
@@ -152,7 +152,7 @@ class MetaSimObject(type):
|
||||
# and only allow "private" attributes to be passed to the base
|
||||
# __new__ (starting with underscore).
|
||||
def __new__(mcls, name, bases, dict):
|
||||
assert name not in allClasses, "SimObject %s already present" % name
|
||||
assert name not in allClasses, f"SimObject {name} already present"
|
||||
|
||||
# Copy "private" attributes, functions, and classes to the
|
||||
# official dict. Everything else goes in _init_dict to be
|
||||
@@ -252,7 +252,7 @@ class MetaSimObject(type):
|
||||
if "cxx_class" not in cls._value_dict:
|
||||
cls._value_dict["cxx_class"] = cls._value_dict["type"]
|
||||
|
||||
cls._value_dict["cxx_type"] = "%s *" % cls._value_dict["cxx_class"]
|
||||
cls._value_dict["cxx_type"] = f"{cls._value_dict['cxx_class']} *"
|
||||
|
||||
if "cxx_header" not in cls._value_dict:
|
||||
global noCxxHeader
|
||||
@@ -295,8 +295,7 @@ class MetaSimObject(type):
|
||||
def _set_keyword(cls, keyword, val, kwtype):
|
||||
if not isinstance(val, kwtype):
|
||||
raise TypeError(
|
||||
"keyword %s has bad type %s (expecting %s)"
|
||||
% (keyword, type(val), kwtype)
|
||||
f"keyword {keyword} has bad type {type(val)} (expecting {kwtype})"
|
||||
)
|
||||
if isinstance(val, FunctionType):
|
||||
val = classmethod(val)
|
||||
@@ -316,11 +315,8 @@ class MetaSimObject(type):
|
||||
hr_value = value
|
||||
value = param.convert(value)
|
||||
except Exception as e:
|
||||
msg = "%s\nError setting param %s.%s to %s\n" % (
|
||||
e,
|
||||
cls.__name__,
|
||||
name,
|
||||
value,
|
||||
msg = (
|
||||
f"{e}\nError setting param {cls.__name__}.{name} to {value}\n"
|
||||
)
|
||||
e.args = (msg,)
|
||||
raise
|
||||
@@ -372,9 +368,7 @@ class MetaSimObject(type):
|
||||
for k, v in cls._value_dict.items():
|
||||
if v == value:
|
||||
return k, v
|
||||
raise RuntimeError(
|
||||
"Cannot find parameter {} in parameter list".format(value)
|
||||
)
|
||||
raise RuntimeError(f"Cannot find parameter {value} in parameter list")
|
||||
|
||||
# Set attribute (called on foo.attr = value when foo is an
|
||||
# instance of class cls).
|
||||
@@ -411,9 +405,7 @@ class MetaSimObject(type):
|
||||
return
|
||||
|
||||
# no valid assignment... raise exception
|
||||
raise AttributeError(
|
||||
"Class %s has no parameter '%s'" % (cls.__name__, attr)
|
||||
)
|
||||
raise AttributeError(f"Class {cls.__name__} has no parameter '{attr}'")
|
||||
|
||||
def __getattr__(cls, attr):
|
||||
if attr == "cxx_class_path":
|
||||
@@ -438,7 +430,7 @@ class MetaSimObject(type):
|
||||
return getattr(cls.getCCClass(), attr)
|
||||
except AttributeError:
|
||||
raise AttributeError(
|
||||
"object '%s' has no attribute '%s'" % (cls.__name__, attr)
|
||||
f"object '{cls.__name__}' has no attribute '{attr}'"
|
||||
)
|
||||
|
||||
def __str__(cls):
|
||||
@@ -672,10 +664,10 @@ class SimObject(object, metaclass=MetaSimObject):
|
||||
ex_str = values.example_str()
|
||||
ptype = None
|
||||
if isinstance(values, VectorParamDesc):
|
||||
type_str = "Vector_%s" % values.ptype_str
|
||||
type_str = f"Vector_{values.ptype_str}"
|
||||
ptype = values
|
||||
else:
|
||||
type_str = "%s" % values.ptype_str
|
||||
type_str = f"{values.ptype_str}"
|
||||
ptype = values.ptype
|
||||
|
||||
if (
|
||||
@@ -842,9 +834,8 @@ class SimObject(object, metaclass=MetaSimObject):
|
||||
if self._ccObject and hasattr(self._ccObject, attr):
|
||||
return getattr(self._ccObject, attr)
|
||||
|
||||
err_string = "object '%s' has no attribute '%s'" % (
|
||||
self.__class__.__name__,
|
||||
attr,
|
||||
err_string = (
|
||||
f"object '{self.__class__.__name__}' has no attribute '{attr}'"
|
||||
)
|
||||
|
||||
if not self._ccObject:
|
||||
@@ -915,7 +906,7 @@ class SimObject(object, metaclass=MetaSimObject):
|
||||
|
||||
# no valid assignment... raise exception
|
||||
raise AttributeError(
|
||||
"Class %s has no parameter %s" % (self.__class__.__name__, attr)
|
||||
f"Class {self.__class__.__name__} has no parameter {attr}"
|
||||
)
|
||||
|
||||
# this hack allows tacking a '[0]' onto parameters that may or may
|
||||
@@ -923,7 +914,7 @@ class SimObject(object, metaclass=MetaSimObject):
|
||||
def __getitem__(self, key):
|
||||
if key == 0:
|
||||
return self
|
||||
raise IndexError("Non-zero index '%s' to SimObject" % key)
|
||||
raise IndexError(f"Non-zero index '{key}' to SimObject")
|
||||
|
||||
# this hack allows us to iterate over a SimObject that may
|
||||
# not be a vector, so we can call a loop over it and get just one
|
||||
@@ -1000,7 +991,7 @@ class SimObject(object, metaclass=MetaSimObject):
|
||||
|
||||
def path(self):
|
||||
if not self._parent:
|
||||
return "<orphan %s>" % self.__class__
|
||||
return f"<orphan {self.__class__}>"
|
||||
elif isinstance(self._parent, MetaSimObject):
|
||||
return str(self.__class__)
|
||||
|
||||
@@ -1096,8 +1087,7 @@ class SimObject(object, metaclass=MetaSimObject):
|
||||
value = value.unproxy(self)
|
||||
except:
|
||||
print(
|
||||
"Error in unproxying param '%s' of %s"
|
||||
% (param, self.path())
|
||||
f"Error in unproxying param '{param}' of {self.path()}"
|
||||
)
|
||||
raise
|
||||
setattr(self, param, value)
|
||||
@@ -1117,7 +1107,7 @@ class SimObject(object, metaclass=MetaSimObject):
|
||||
instanceDict[self.path()] = self
|
||||
|
||||
if hasattr(self, "type"):
|
||||
print("type=%s" % self.type, file=ini_file)
|
||||
print(f"type={self.type}", file=ini_file)
|
||||
|
||||
if len(self._children.keys()):
|
||||
print(
|
||||
@@ -1133,14 +1123,14 @@ class SimObject(object, metaclass=MetaSimObject):
|
||||
value = self._values.get(param)
|
||||
if value != None:
|
||||
print(
|
||||
"%s=%s" % (param, self._values[param].ini_str()),
|
||||
f"{param}={self._values[param].ini_str()}",
|
||||
file=ini_file,
|
||||
)
|
||||
|
||||
for port_name in sorted(self._ports.keys()):
|
||||
port = self._port_refs.get(port_name, None)
|
||||
if port != None:
|
||||
print("%s=%s" % (port_name, port.ini_str()), file=ini_file)
|
||||
print(f"{port_name}={port.ini_str()}", file=ini_file)
|
||||
|
||||
print(file=ini_file) # blank line between objects
|
||||
|
||||
@@ -1186,7 +1176,7 @@ class SimObject(object, metaclass=MetaSimObject):
|
||||
# Ensure that m5.internal.params is available.
|
||||
import m5.internal.params
|
||||
|
||||
cc_params_struct = getattr(m5.internal.params, "%sParams" % self.type)
|
||||
cc_params_struct = getattr(m5.internal.params, f"{self.type}Params")
|
||||
cc_params = cc_params_struct()
|
||||
cc_params.name = str(self)
|
||||
|
||||
@@ -1249,7 +1239,7 @@ class SimObject(object, metaclass=MetaSimObject):
|
||||
self._ccObject = params.create()
|
||||
elif self._ccObject == -1:
|
||||
raise RuntimeError(
|
||||
"%s: Cycle found in configuration hierarchy." % self.path()
|
||||
f"{self.path()}: Cycle found in configuration hierarchy."
|
||||
)
|
||||
return self._ccObject
|
||||
|
||||
|
||||
@@ -40,13 +40,13 @@ def help():
|
||||
lambda kv: isinstance(kv[1], SimpleFlag) and not kv[1].isFormat,
|
||||
sorted_flags,
|
||||
):
|
||||
print(" %s: %s" % (name, flag.desc))
|
||||
print(f" {name}: {flag.desc}")
|
||||
print()
|
||||
print("Compound Flags:")
|
||||
for name, flag in filter(
|
||||
lambda kv: isinstance(kv[1], CompoundFlag), sorted_flags
|
||||
):
|
||||
print(" %s: %s" % (name, flag.desc))
|
||||
print(f" {name}: {flag.desc}")
|
||||
# The list of kids for flag "All" is too long, so it is not printed
|
||||
if name != "All":
|
||||
printList([c.name for c in flag.kids()], indent=8)
|
||||
@@ -58,7 +58,7 @@ def help():
|
||||
lambda kv: isinstance(kv[1], SimpleFlag) and kv[1].isFormat,
|
||||
sorted_flags,
|
||||
):
|
||||
print(" %s: %s" % (name, flag.desc))
|
||||
print(f" {name}: {flag.desc}")
|
||||
print()
|
||||
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ class EventWrapper(Event):
|
||||
|
||||
if not callable(func):
|
||||
raise RuntimeError(
|
||||
"Can't wrap '%s', object is not callable" % str(func)
|
||||
f"Can't wrap '{str(func)}', object is not callable"
|
||||
)
|
||||
|
||||
self._func = func
|
||||
@@ -65,7 +65,7 @@ class EventWrapper(Event):
|
||||
self._func()
|
||||
|
||||
def __str__(self):
|
||||
return "EventWrapper(%s)" % (str(self._func),)
|
||||
return f"EventWrapper({str(self._func)})"
|
||||
|
||||
|
||||
class ProgressEvent(Event):
|
||||
@@ -76,7 +76,7 @@ class ProgressEvent(Event):
|
||||
self.eventq.schedule(self, m5.curTick() + self.period)
|
||||
|
||||
def __call__(self):
|
||||
print("Progress! Time now %fs" % (m5.curTick() / 1e12))
|
||||
print(f"Progress! Time now {m5.curTick() / 1000000000000.0:f}s")
|
||||
self.eventq.schedule(self, m5.curTick() + self.period)
|
||||
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ class FdtProperty(object):
|
||||
"""Init with name"""
|
||||
self.name = name
|
||||
if not FdtProperty.__validate_dt_name(self.name):
|
||||
raise Exception("Invalid name '%s'" % self.name)
|
||||
raise Exception(f"Invalid name '{self.name}'")
|
||||
|
||||
def get_name(self):
|
||||
"""Get property name"""
|
||||
@@ -60,7 +60,7 @@ class FdtProperty(object):
|
||||
|
||||
def __str__(self):
|
||||
"""String representation"""
|
||||
return "Property(%s)" % self.name
|
||||
return f"Property({self.name})"
|
||||
|
||||
def dts_represent(self, depth=0):
|
||||
"""Get dts string representation"""
|
||||
@@ -78,7 +78,7 @@ class FdtProperty(object):
|
||||
|
||||
def json_represent(self, depth=0):
|
||||
"""Ouput JSON"""
|
||||
return "%s: null" % json.dumps(self.name)
|
||||
return f"{json.dumps(self.name)}: null"
|
||||
|
||||
def to_raw(self):
|
||||
"""Return RAW value representation"""
|
||||
@@ -219,7 +219,7 @@ class FdtPropertyStrings(FdtProperty):
|
||||
|
||||
def json_represent(self, depth=0):
|
||||
"""Ouput JSON"""
|
||||
result = '%s: ["strings", ' % json.dumps(self.name)
|
||||
result = f'{json.dumps(self.name)}: ["strings", '
|
||||
result += ", ".join([json.dumps(stri) for stri in self.strings])
|
||||
result += "]"
|
||||
return result
|
||||
@@ -230,7 +230,7 @@ class FdtPropertyStrings(FdtProperty):
|
||||
|
||||
def __str__(self):
|
||||
"""String representation"""
|
||||
return "Property(%s,Strings:%s)" % (self.name, self.strings)
|
||||
return f"Property({self.name},Strings:{self.strings})"
|
||||
|
||||
def __getitem__(self, index):
|
||||
"""Get strings, returns a string"""
|
||||
@@ -291,7 +291,7 @@ class FdtPropertyWords(FdtProperty):
|
||||
INDENT * depth
|
||||
+ self.name
|
||||
+ " = <"
|
||||
+ " ".join(["0x%08x" % word for word in self.words])
|
||||
+ " ".join([f"0x{word:08x}" for word in self.words])
|
||||
+ ">;"
|
||||
)
|
||||
|
||||
@@ -310,8 +310,8 @@ class FdtPropertyWords(FdtProperty):
|
||||
|
||||
def json_represent(self, depth=0):
|
||||
"""Ouput JSON"""
|
||||
result = '%s: ["words", "' % json.dumps(self.name)
|
||||
result += '", "'.join(["0x%08x" % word for word in self.words])
|
||||
result = f'{json.dumps(self.name)}: ["words", "'
|
||||
result += '", "'.join([f"0x{word:08x}" for word in self.words])
|
||||
result += '"]'
|
||||
return result
|
||||
|
||||
@@ -321,7 +321,7 @@ class FdtPropertyWords(FdtProperty):
|
||||
|
||||
def __str__(self):
|
||||
"""String representation"""
|
||||
return "Property(%s,Words:%s)" % (self.name, self.words)
|
||||
return f"Property({self.name},Words:{self.words})"
|
||||
|
||||
def __getitem__(self, index):
|
||||
"""Get words, returns a word integer"""
|
||||
@@ -376,7 +376,7 @@ class FdtPropertyBytes(FdtProperty):
|
||||
+ self.name
|
||||
+ " = ["
|
||||
+ " ".join(
|
||||
["%02x" % (byte & int("ffffffff", 16)) for byte in self.bytes]
|
||||
[f"{byte & int('ffffffff', 16):02x}" for byte in self.bytes]
|
||||
)
|
||||
+ "];"
|
||||
)
|
||||
@@ -397,8 +397,8 @@ class FdtPropertyBytes(FdtProperty):
|
||||
|
||||
def json_represent(self, depth=0):
|
||||
"""Ouput JSON"""
|
||||
result = '%s: ["bytes", "' % json.dumps(self.name)
|
||||
result += '", "'.join(["%02x" % byte for byte in self.bytes])
|
||||
result = f'{json.dumps(self.name)}: ["bytes", "'
|
||||
result += '", "'.join([f"{byte:02x}" for byte in self.bytes])
|
||||
result += '"]'
|
||||
return result
|
||||
|
||||
@@ -408,7 +408,7 @@ class FdtPropertyBytes(FdtProperty):
|
||||
|
||||
def __str__(self):
|
||||
"""String representation"""
|
||||
return "Property(%s,Bytes:%s)" % (self.name, self.bytes)
|
||||
return f"Property({self.name},Bytes:{self.bytes})"
|
||||
|
||||
def __getitem__(self, index):
|
||||
"""Get bytes, returns a byte"""
|
||||
@@ -471,7 +471,7 @@ class FdtNode(object):
|
||||
self.subdata = []
|
||||
self.parent = None
|
||||
if not FdtNode.__validate_dt_name(self.name):
|
||||
raise Exception("Invalid name '%s'" % self.name)
|
||||
raise Exception(f"Invalid name '{self.name}'")
|
||||
|
||||
def get_name(self):
|
||||
"""Get property name"""
|
||||
@@ -504,7 +504,7 @@ class FdtNode(object):
|
||||
|
||||
def __str__(self):
|
||||
"""String representation"""
|
||||
return "Node(%s)" % self.name
|
||||
return f"Node({self.name})"
|
||||
|
||||
def dts_represent(self, depth=0):
|
||||
"""Get dts string representation"""
|
||||
@@ -579,7 +579,7 @@ class FdtNode(object):
|
||||
].get_name() != subnode.get_name() and self.__check_name_duplicate(
|
||||
subnode.get_name()
|
||||
):
|
||||
raise Exception("%s : %s subnode already exists" % (self, subnode))
|
||||
raise Exception(f"{self} : {subnode} subnode already exists")
|
||||
if not isinstance(subnode, (FdtNode, FdtProperty, FdtNop)):
|
||||
raise Exception("Invalid object type")
|
||||
self.subdata[index] = subnode
|
||||
@@ -635,7 +635,7 @@ class FdtNode(object):
|
||||
def append(self, subnode):
|
||||
"""Append subnode, same as add_subnode"""
|
||||
if self.__check_name_duplicate(subnode.get_name()):
|
||||
raise Exception("%s : %s subnode already exists" % (self, subnode))
|
||||
raise Exception(f"{self} : {subnode} subnode already exists")
|
||||
if not isinstance(subnode, (FdtNode, FdtProperty, FdtNop)):
|
||||
raise Exception("Invalid object type")
|
||||
self.subdata.append(subnode)
|
||||
@@ -647,7 +647,7 @@ class FdtNode(object):
|
||||
def insert(self, index, subnode):
|
||||
"""Insert subnode before index, must not be a duplicate name"""
|
||||
if self.__check_name_duplicate(subnode.get_name()):
|
||||
raise Exception("%s : %s subnode already exists" % (self, subnode))
|
||||
raise Exception(f"{self} : {subnode} subnode already exists")
|
||||
if not isinstance(subnode, (FdtNode, FdtProperty, FdtNop)):
|
||||
raise Exception("Invalid object type")
|
||||
self.subdata.insert(index, subnode)
|
||||
@@ -778,7 +778,7 @@ class Fdt(object):
|
||||
)
|
||||
if self.header["version"] >= 2:
|
||||
result += (
|
||||
"// boot_cpuid_phys:\t0x%x\n" % self.header["boot_cpuid_phys"]
|
||||
f"// boot_cpuid_phys:\t0x{self.header['boot_cpuid_phys']:x}\n"
|
||||
)
|
||||
result += "\n"
|
||||
if self.reserve_entries is not None:
|
||||
@@ -914,7 +914,7 @@ def _add_json_to_fdtnode(node, subjson):
|
||||
_add_json_to_fdtnode(subnode, value)
|
||||
elif isinstance(value, list):
|
||||
if len(value) < 2:
|
||||
raise Exception("Invalid list for %s" % key)
|
||||
raise Exception(f"Invalid list for {key}")
|
||||
if value[0] == "words":
|
||||
words = [int(word, 16) for word in value[1:]]
|
||||
node.append(FdtPropertyWords(key, words))
|
||||
@@ -924,11 +924,11 @@ def _add_json_to_fdtnode(node, subjson):
|
||||
elif value[0] == "strings":
|
||||
node.append(FdtPropertyStrings(key, [s for s in value[1:]]))
|
||||
else:
|
||||
raise Exception("Invalid list for %s" % key)
|
||||
raise Exception(f"Invalid list for {key}")
|
||||
elif value is None:
|
||||
node.append(FdtProperty(key))
|
||||
else:
|
||||
raise Exception("Invalid value for %s" % key)
|
||||
raise Exception(f"Invalid value for {key}")
|
||||
|
||||
|
||||
def FdtJsonParse(buf):
|
||||
|
||||
@@ -50,4 +50,4 @@ except ImportError:
|
||||
if in_gem5:
|
||||
for name, module in inspect.getmembers(_m5):
|
||||
if name.startswith("param_") or name.startswith("enum_"):
|
||||
exec("from _m5.%s import *" % name)
|
||||
exec(f"from _m5.{name} import *")
|
||||
|
||||
@@ -399,14 +399,14 @@ def main():
|
||||
done = True
|
||||
print("Build information:")
|
||||
print()
|
||||
print("gem5 version %s" % defines.gem5Version)
|
||||
print("compiled %s" % defines.compileDate)
|
||||
print(f"gem5 version {defines.gem5Version}")
|
||||
print(f"compiled {defines.compileDate}")
|
||||
print("build options:")
|
||||
keys = list(defines.buildEnv.keys())
|
||||
keys.sort()
|
||||
for key in keys:
|
||||
val = defines.buildEnv[key]
|
||||
print(" %s = %s" % (key, val))
|
||||
print(f" {key} = {val}")
|
||||
print()
|
||||
|
||||
if options.copyright:
|
||||
@@ -470,11 +470,11 @@ def main():
|
||||
print(brief_copyright)
|
||||
print()
|
||||
|
||||
print("gem5 version %s" % _m5.core.gem5Version)
|
||||
print("gem5 compiled %s" % _m5.core.compileDate)
|
||||
print(f"gem5 version {_m5.core.gem5Version}")
|
||||
print(f"gem5 compiled {_m5.core.compileDate}")
|
||||
|
||||
print(
|
||||
"gem5 started %s" % datetime.datetime.now().strftime("%b %e %Y %X")
|
||||
f"gem5 started {datetime.datetime.now().strftime('%b %e %Y %X')}"
|
||||
)
|
||||
print(
|
||||
"gem5 executing on %s, pid %d"
|
||||
@@ -490,7 +490,7 @@ def main():
|
||||
# check to make sure we can find the listed script
|
||||
if not options.c and (not arguments or not os.path.isfile(arguments[0])):
|
||||
if arguments and not os.path.isfile(arguments[0]):
|
||||
print("Script %s not found" % arguments[0])
|
||||
print(f"Script {arguments[0]} not found")
|
||||
|
||||
options.usage(2)
|
||||
|
||||
@@ -514,7 +514,7 @@ def main():
|
||||
elif options.listener_mode == "on":
|
||||
pass
|
||||
else:
|
||||
panic("Unhandled listener mode: %s" % options.listener_mode)
|
||||
panic(f"Unhandled listener mode: {options.listener_mode}")
|
||||
|
||||
if not options.allow_remote_connections:
|
||||
m5.listenersLoopbackOnly()
|
||||
@@ -534,7 +534,7 @@ def main():
|
||||
off = True
|
||||
|
||||
if flag not in debug.flags:
|
||||
print("invalid debug flag '%s'" % flag, file=sys.stderr)
|
||||
print(f"invalid debug flag '{flag}'", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if off:
|
||||
|
||||
@@ -26,4 +26,4 @@
|
||||
|
||||
for module in __spec__.loader_state:
|
||||
if module.startswith("m5.objects."):
|
||||
exec("from %s import *" % module)
|
||||
exec(f"from {module} import *")
|
||||
|
||||
@@ -92,8 +92,8 @@ class OptionParser(dict):
|
||||
"""add a boolean option called --name and --no-name.
|
||||
Display help depending on which is the default"""
|
||||
|
||||
tname = "--%s" % name
|
||||
fname = "--no-%s" % name
|
||||
tname = f"--{name}"
|
||||
fname = f"--no-{name}"
|
||||
dest = name.replace("-", "_")
|
||||
if default:
|
||||
thelp = optparse.SUPPRESS_HELP
|
||||
|
||||
@@ -135,8 +135,8 @@ class ParamValue(object, metaclass=MetaParamValue):
|
||||
# src into lvalue dest (of the param's C++ type)
|
||||
@classmethod
|
||||
def cxx_ini_parse(cls, code, src, dest, ret):
|
||||
code("// Unhandled param type: %s" % cls.__name__)
|
||||
code("%s false;" % ret)
|
||||
code(f"// Unhandled param type: {cls.__name__}")
|
||||
code(f"{ret} false;")
|
||||
|
||||
# allows us to blithely call unproxy() on things without checking
|
||||
# if they're really proxies or not
|
||||
@@ -176,7 +176,7 @@ class ParamDesc(object):
|
||||
del kwargs["default"]
|
||||
|
||||
if kwargs:
|
||||
raise TypeError("extra unknown kwargs %s" % kwargs)
|
||||
raise TypeError(f"extra unknown kwargs {kwargs}")
|
||||
|
||||
if not hasattr(self, "desc"):
|
||||
raise TypeError("desc attribute missing")
|
||||
@@ -191,7 +191,7 @@ class ParamDesc(object):
|
||||
return ptype
|
||||
|
||||
raise AttributeError(
|
||||
"'%s' object has no attribute '%s'" % (type(self).__name__, attr)
|
||||
f"'{type(self).__name__}' object has no attribute '{attr}'"
|
||||
)
|
||||
|
||||
def example_str(self):
|
||||
@@ -247,7 +247,7 @@ class ParamDesc(object):
|
||||
class VectorParamValue(list, metaclass=MetaParamValue):
|
||||
def __setattr__(self, attr, value):
|
||||
raise AttributeError(
|
||||
"Not allowed to set %s on '%s'" % (attr, type(self).__name__)
|
||||
f"Not allowed to set {attr} on '{type(self).__name__}'"
|
||||
)
|
||||
|
||||
def config_value(self):
|
||||
@@ -316,7 +316,7 @@ class SimObjectVector(VectorParamValue):
|
||||
val = self[key]
|
||||
if value.has_parent():
|
||||
warn(
|
||||
"SimObject %s already has a parent" % value.get_name()
|
||||
f"SimObject {value.get_name()} already has a parent"
|
||||
+ " that is being overwritten by a SimObjectVector"
|
||||
)
|
||||
value.set_parent(val.get_parent(), val._name)
|
||||
@@ -327,7 +327,7 @@ class SimObjectVector(VectorParamValue):
|
||||
# allow it to be specified on the command line.
|
||||
def enumerateParams(self, flags_dict={}, cmd_line_str="", access_str=""):
|
||||
if hasattr(self, "_paramEnumed"):
|
||||
print("Cycle detected enumerating params at %s?!" % (cmd_line_str))
|
||||
print(f"Cycle detected enumerating params at {cmd_line_str}?!")
|
||||
else:
|
||||
x = 0
|
||||
for vals in self:
|
||||
@@ -469,8 +469,8 @@ class String(ParamValue, str):
|
||||
|
||||
@classmethod
|
||||
def cxx_ini_parse(self, code, src, dest, ret):
|
||||
code("%s = %s;" % (dest, src))
|
||||
code("%s true;" % ret)
|
||||
code(f"{dest} = {src};")
|
||||
code(f"{ret} true;")
|
||||
|
||||
def getValue(self):
|
||||
return self
|
||||
@@ -571,7 +571,7 @@ class NumericParamValue(ParamValue):
|
||||
# the dest type.
|
||||
@classmethod
|
||||
def cxx_ini_parse(self, code, src, dest, ret):
|
||||
code("%s to_number(%s, %s);" % (ret, src, dest))
|
||||
code(f"{ret} to_number({src}, {dest});")
|
||||
|
||||
|
||||
# Metaclass for bounds-checked integer parameters. See CheckedInt.
|
||||
@@ -621,8 +621,7 @@ class CheckedInt(NumericParamValue, metaclass=CheckedIntType):
|
||||
self.value = int(value)
|
||||
else:
|
||||
raise TypeError(
|
||||
"Can't convert object of type %s to CheckedInt"
|
||||
% type(value).__name__
|
||||
f"Can't convert object of type {type(value).__name__} to CheckedInt"
|
||||
)
|
||||
self._check()
|
||||
|
||||
@@ -751,10 +750,10 @@ class Cycles(CheckedInt):
|
||||
@classmethod
|
||||
def cxx_ini_parse(cls, code, src, dest, ret):
|
||||
code("uint64_t _temp;")
|
||||
code("bool _ret = to_number(%s, _temp);" % src)
|
||||
code(f"bool _ret = to_number({src}, _temp);")
|
||||
code("if (_ret)")
|
||||
code(" %s = Cycles(_temp);" % dest)
|
||||
code("%s _ret;" % ret)
|
||||
code(f" {dest} = Cycles(_temp);")
|
||||
code(f"{ret} _ret;")
|
||||
|
||||
|
||||
class Float(ParamValue, float):
|
||||
@@ -766,8 +765,7 @@ class Float(ParamValue, float):
|
||||
self.value = float(value)
|
||||
else:
|
||||
raise TypeError(
|
||||
"Can't convert object of type %s to Float"
|
||||
% type(value).__name__
|
||||
f"Can't convert object of type {type(value).__name__} to Float"
|
||||
)
|
||||
|
||||
def __call__(self, value):
|
||||
@@ -786,7 +784,7 @@ class Float(ParamValue, float):
|
||||
|
||||
@classmethod
|
||||
def cxx_ini_parse(self, code, src, dest, ret):
|
||||
code("%s (std::istringstream(%s) >> %s).eof();" % (ret, src, dest))
|
||||
code(f"{ret} (std::istringstream({src}) >> {dest}).eof();")
|
||||
|
||||
|
||||
class MemorySize(CheckedInt):
|
||||
@@ -851,7 +849,7 @@ class Addr(CheckedInt):
|
||||
val = convert.toMemorySize(value)
|
||||
except TypeError:
|
||||
val = int(value)
|
||||
return "0x%x" % int(val)
|
||||
return f"0x{int(val):x}"
|
||||
|
||||
|
||||
class PcCountPair(ParamValue):
|
||||
@@ -961,11 +959,11 @@ class AddrRange(ParamValue):
|
||||
raise TypeError("Too many arguments specified")
|
||||
|
||||
if kwargs:
|
||||
raise TypeError("Too many keywords: %s" % list(kwargs.keys()))
|
||||
raise TypeError(f"Too many keywords: {list(kwargs.keys())}")
|
||||
|
||||
def __str__(self):
|
||||
if len(self.masks) == 0:
|
||||
return "%s:%s" % (self.start, self.end)
|
||||
return f"{self.start}:{self.end}"
|
||||
else:
|
||||
return "%s:%s:%s:%s" % (
|
||||
self.start,
|
||||
@@ -1084,7 +1082,7 @@ class Bool(ParamValue):
|
||||
|
||||
@classmethod
|
||||
def cxx_ini_parse(cls, code, src, dest, ret):
|
||||
code("%s to_bool(%s, %s);" % (ret, src, dest))
|
||||
code(f"{ret} to_bool({src}, {dest});")
|
||||
|
||||
|
||||
def IncEthernetAddr(addr, val=1):
|
||||
@@ -1097,7 +1095,7 @@ def IncEthernetAddr(addr, val=1):
|
||||
break
|
||||
bytes[i - 1] += val
|
||||
assert bytes[0] <= 255
|
||||
return ":".join(map(lambda x: "%02x" % x, bytes))
|
||||
return ":".join(map(lambda x: f"{x:02x}", bytes))
|
||||
|
||||
|
||||
_NextEthernetAddr = "00:90:00:00:00:01"
|
||||
@@ -1130,11 +1128,11 @@ class EthernetAddr(ParamValue):
|
||||
|
||||
bytes = value.split(":")
|
||||
if len(bytes) != 6:
|
||||
raise TypeError("invalid ethernet address %s" % value)
|
||||
raise TypeError(f"invalid ethernet address {value}")
|
||||
|
||||
for byte in bytes:
|
||||
if not 0 <= int(byte, base=16) <= 0xFF:
|
||||
raise TypeError("invalid ethernet address %s" % value)
|
||||
raise TypeError(f"invalid ethernet address {value}")
|
||||
|
||||
self.value = value
|
||||
|
||||
@@ -1160,8 +1158,8 @@ class EthernetAddr(ParamValue):
|
||||
|
||||
@classmethod
|
||||
def cxx_ini_parse(self, code, src, dest, ret):
|
||||
code("%s = networking::EthAddr(%s);" % (dest, src))
|
||||
code("%s true;" % ret)
|
||||
code(f"{dest} = networking::EthAddr({src});")
|
||||
code(f"{ret} true;")
|
||||
|
||||
|
||||
# When initializing an IpAddress, pass in an existing IpAddress, a string of
|
||||
@@ -1236,7 +1234,7 @@ class IpNetmask(IpAddress):
|
||||
elif elseVal:
|
||||
setattr(self, key, elseVal)
|
||||
else:
|
||||
raise TypeError("No value set for %s" % key)
|
||||
raise TypeError(f"No value set for {key}")
|
||||
|
||||
if len(args) == 0:
|
||||
handle_kwarg(self, kwargs, "ip")
|
||||
@@ -1261,7 +1259,7 @@ class IpNetmask(IpAddress):
|
||||
raise TypeError("Too many arguments specified")
|
||||
|
||||
if kwargs:
|
||||
raise TypeError("Too many keywords: %s" % list(kwargs.keys()))
|
||||
raise TypeError(f"Too many keywords: {list(kwargs.keys())}")
|
||||
|
||||
self.verify()
|
||||
|
||||
@@ -1312,7 +1310,7 @@ class IpWithPort(IpAddress):
|
||||
elif elseVal:
|
||||
setattr(self, key, elseVal)
|
||||
else:
|
||||
raise TypeError("No value set for %s" % key)
|
||||
raise TypeError(f"No value set for {key}")
|
||||
|
||||
if len(args) == 0:
|
||||
handle_kwarg(self, kwargs, "ip")
|
||||
@@ -1337,7 +1335,7 @@ class IpWithPort(IpAddress):
|
||||
raise TypeError("Too many arguments specified")
|
||||
|
||||
if kwargs:
|
||||
raise TypeError("Too many keywords: %s" % list(kwargs.keys()))
|
||||
raise TypeError(f"Too many keywords: {list(kwargs.keys())}")
|
||||
|
||||
self.verify()
|
||||
|
||||
@@ -1408,7 +1406,7 @@ def parse_time(value):
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
raise ValueError("Could not parse '%s' as a time" % value)
|
||||
raise ValueError(f"Could not parse '{value}' as a time")
|
||||
|
||||
|
||||
class Time(ParamValue):
|
||||
@@ -1501,9 +1499,9 @@ class MetaEnum(MetaParamValue):
|
||||
)
|
||||
|
||||
if cls.is_class:
|
||||
cls.cxx_type = "%s" % name
|
||||
cls.cxx_type = f"{name}"
|
||||
else:
|
||||
cls.cxx_type = "enums::%s" % name
|
||||
cls.cxx_type = f"enums::{name}"
|
||||
|
||||
super().__init__(name, bases, init_dict)
|
||||
|
||||
@@ -1527,8 +1525,7 @@ class Enum(ParamValue, metaclass=MetaEnum):
|
||||
def __init__(self, value):
|
||||
if value not in self.map:
|
||||
raise TypeError(
|
||||
"Enum param got bad value '%s' (not in %s)"
|
||||
% (value, self.vals)
|
||||
f"Enum param got bad value '{value}' (not in {self.vals})"
|
||||
)
|
||||
self.value = value
|
||||
|
||||
@@ -1547,20 +1544,17 @@ class Enum(ParamValue, metaclass=MetaEnum):
|
||||
code('} else if (%s == "%s") {' % (src, elem_name))
|
||||
code.indent()
|
||||
name = cls.__name__ if cls.enum_name is None else cls.enum_name
|
||||
code(
|
||||
"%s = %s::%s;"
|
||||
% (dest, name if cls.is_class else "enums", elem_name)
|
||||
)
|
||||
code("%s true;" % ret)
|
||||
code(f"{dest} = {name if cls.is_class else 'enums'}::{elem_name};")
|
||||
code(f"{ret} true;")
|
||||
code.dedent()
|
||||
code("} else {")
|
||||
code(" %s false;" % ret)
|
||||
code(f" {ret} false;")
|
||||
code("}")
|
||||
|
||||
def getValue(self):
|
||||
import m5.internal.params
|
||||
|
||||
e = getattr(m5.internal.params, "enum_%s" % self.__class__.__name__)
|
||||
e = getattr(m5.internal.params, f"enum_{self.__class__.__name__}")
|
||||
return e(self.map[self.value])
|
||||
|
||||
def __str__(self):
|
||||
@@ -1648,7 +1642,7 @@ class Latency(TickParamValue):
|
||||
return self
|
||||
if attr == "frequency":
|
||||
return Frequency(self)
|
||||
raise AttributeError("Latency object has no attribute '%s'" % attr)
|
||||
raise AttributeError(f"Latency object has no attribute '{attr}'")
|
||||
|
||||
def getValue(self):
|
||||
if self.ticks or self.value == 0:
|
||||
@@ -1691,7 +1685,7 @@ class Frequency(TickParamValue):
|
||||
return self
|
||||
if attr in ("latency", "period"):
|
||||
return Latency(self)
|
||||
raise AttributeError("Frequency object has no attribute '%s'" % attr)
|
||||
raise AttributeError(f"Frequency object has no attribute '{attr}'")
|
||||
|
||||
# convert latency to ticks
|
||||
def getValue(self):
|
||||
@@ -1730,14 +1724,14 @@ class Clock(TickParamValue):
|
||||
return value
|
||||
|
||||
def __str__(self):
|
||||
return "%s" % Latency(self)
|
||||
return f"{Latency(self)}"
|
||||
|
||||
def __getattr__(self, attr):
|
||||
if attr == "frequency":
|
||||
return Frequency(self)
|
||||
if attr in ("latency", "period"):
|
||||
return Latency(self)
|
||||
raise AttributeError("Frequency object has no attribute '%s'" % attr)
|
||||
raise AttributeError(f"Frequency object has no attribute '{attr}'")
|
||||
|
||||
def getValue(self):
|
||||
return self.period.getValue()
|
||||
@@ -1821,10 +1815,10 @@ class Temperature(ParamValue):
|
||||
@classmethod
|
||||
def cxx_ini_parse(self, code, src, dest, ret):
|
||||
code("double _temp;")
|
||||
code("bool _ret = to_number(%s, _temp);" % src)
|
||||
code(f"bool _ret = to_number({src}, _temp);")
|
||||
code("if (_ret)")
|
||||
code(" %s = Temperature(_temp);" % dest)
|
||||
code("%s _ret;" % ret)
|
||||
code(f" {dest} = Temperature(_temp);")
|
||||
code(f"{ret} _ret;")
|
||||
|
||||
|
||||
class NetworkBandwidth(float, ParamValue):
|
||||
@@ -1853,10 +1847,10 @@ class NetworkBandwidth(float, ParamValue):
|
||||
return float(value)
|
||||
|
||||
def ini_str(self):
|
||||
return "%f" % self.getValue()
|
||||
return f"{self.getValue():f}"
|
||||
|
||||
def config_value(self):
|
||||
return "%f" % self.getValue()
|
||||
return f"{self.getValue():f}"
|
||||
|
||||
@classmethod
|
||||
def cxx_ini_predecls(cls, code):
|
||||
@@ -1864,7 +1858,7 @@ class NetworkBandwidth(float, ParamValue):
|
||||
|
||||
@classmethod
|
||||
def cxx_ini_parse(self, code, src, dest, ret):
|
||||
code("%s (std::istringstream(%s) >> %s).eof();" % (ret, src, dest))
|
||||
code(f"{ret} (std::istringstream({src}) >> {dest}).eof();")
|
||||
|
||||
|
||||
class MemoryBandwidth(float, ParamValue):
|
||||
@@ -1892,10 +1886,10 @@ class MemoryBandwidth(float, ParamValue):
|
||||
return float(value)
|
||||
|
||||
def ini_str(self):
|
||||
return "%f" % self.getValue()
|
||||
return f"{self.getValue():f}"
|
||||
|
||||
def config_value(self):
|
||||
return "%f" % self.getValue()
|
||||
return f"{self.getValue():f}"
|
||||
|
||||
@classmethod
|
||||
def cxx_ini_predecls(cls, code):
|
||||
@@ -1903,7 +1897,7 @@ class MemoryBandwidth(float, ParamValue):
|
||||
|
||||
@classmethod
|
||||
def cxx_ini_parse(self, code, src, dest, ret):
|
||||
code("%s (std::istringstream(%s) >> %s).eof();" % (ret, src, dest))
|
||||
code(f"{ret} (std::istringstream({src}) >> {dest}).eof();")
|
||||
|
||||
|
||||
#
|
||||
@@ -1991,7 +1985,7 @@ class PortRef(object):
|
||||
self.index = -1 # always -1 for non-vector ports
|
||||
|
||||
def __str__(self):
|
||||
return "%s.%s" % (self.simobj, self.name)
|
||||
return f"{self.simobj}.{self.name}"
|
||||
|
||||
def __len__(self):
|
||||
# Return the number of connected ports, i.e. 0 is we have no
|
||||
@@ -2015,8 +2009,7 @@ class PortRef(object):
|
||||
# shorthand for proxies
|
||||
return self.peer.simobj
|
||||
raise AttributeError(
|
||||
"'%s' object has no attribute '%s'"
|
||||
% (self.__class__.__name__, attr)
|
||||
f"'{self.__class__.__name__}' object has no attribute '{attr}'"
|
||||
)
|
||||
|
||||
# Full connection is symmetric (both ways). Called via
|
||||
@@ -2041,8 +2034,7 @@ class PortRef(object):
|
||||
return
|
||||
elif not isinstance(other, PortRef):
|
||||
raise TypeError(
|
||||
"assigning non-port reference '%s' to port '%s'"
|
||||
% (other, self)
|
||||
f"assigning non-port reference '{other}' to port '{self}'"
|
||||
)
|
||||
|
||||
if not Port.is_compat(self, other):
|
||||
@@ -2068,8 +2060,7 @@ class PortRef(object):
|
||||
|
||||
if not isinstance(new_1, PortRef) or not isinstance(new_2, PortRef):
|
||||
raise TypeError(
|
||||
"Splicing non-port references '%s','%s' to port '%s'"
|
||||
% (new_1, new_2, self)
|
||||
f"Splicing non-port references '{new_1}','{new_2}' to port '{self}'"
|
||||
)
|
||||
|
||||
old_peer = self.peer
|
||||
@@ -2118,8 +2109,7 @@ class PortRef(object):
|
||||
realPeer = self.peer.unproxy(self.simobj)
|
||||
except:
|
||||
print(
|
||||
"Error in unproxying port '%s' of %s"
|
||||
% (self.name, self.simobj.path())
|
||||
f"Error in unproxying port '{self.name}' of {self.simobj.path()}"
|
||||
)
|
||||
raise
|
||||
self.connect(realPeer)
|
||||
@@ -2163,7 +2153,7 @@ class VectorPortRef(object):
|
||||
self.elements = []
|
||||
|
||||
def __str__(self):
|
||||
return "%s.%s[:]" % (self.simobj, self.name)
|
||||
return f"{self.simobj}.{self.name}[:]"
|
||||
|
||||
def __len__(self):
|
||||
# Return the number of connected peers, corresponding the the
|
||||
@@ -2390,12 +2380,8 @@ class DeprecatedParam(object):
|
||||
simobj_name: str, the name of the SimObject type
|
||||
"""
|
||||
if not self.message:
|
||||
self.message = "See {} for more information".format(simobj_name)
|
||||
warn(
|
||||
"{}.{} is deprecated. {}".format(
|
||||
instance_name, self._oldName, self.message
|
||||
)
|
||||
)
|
||||
self.message = f"See {simobj_name} for more information"
|
||||
warn(f"{instance_name}.{self._oldName} is deprecated. {self.message}")
|
||||
|
||||
|
||||
baseEnums = allEnums.copy()
|
||||
|
||||
@@ -63,7 +63,7 @@ class BaseProxy(object):
|
||||
def __setattr__(self, attr, value):
|
||||
if not attr.startswith("_"):
|
||||
raise AttributeError(
|
||||
"cannot set attribute '%s' on proxy object" % attr
|
||||
f"cannot set attribute '{attr}' on proxy object"
|
||||
)
|
||||
super().__setattr__(attr, value)
|
||||
|
||||
@@ -234,7 +234,7 @@ class AttrProxy(BaseProxy):
|
||||
p = self._attr
|
||||
for m in self._modifiers:
|
||||
if isinstance(m, str):
|
||||
p += ".%s" % m
|
||||
p += f".{m}"
|
||||
elif isinstance(m, int):
|
||||
p += "[%d]" % m
|
||||
else:
|
||||
|
||||
@@ -358,36 +358,35 @@ def switchCpus(system, cpuList, verbose=True):
|
||||
memory_mode_name = new_cpus[0].memory_mode()
|
||||
for old_cpu, new_cpu in cpuList:
|
||||
if not isinstance(old_cpu, objects.BaseCPU):
|
||||
raise TypeError("%s is not of type BaseCPU" % old_cpu)
|
||||
raise TypeError(f"{old_cpu} is not of type BaseCPU")
|
||||
if not isinstance(new_cpu, objects.BaseCPU):
|
||||
raise TypeError("%s is not of type BaseCPU" % new_cpu)
|
||||
raise TypeError(f"{new_cpu} is not of type BaseCPU")
|
||||
if new_cpu in old_cpu_set:
|
||||
raise RuntimeError(
|
||||
"New CPU (%s) is in the list of old CPUs." % (old_cpu,)
|
||||
f"New CPU ({old_cpu}) is in the list of old CPUs."
|
||||
)
|
||||
if not new_cpu.switchedOut():
|
||||
raise RuntimeError("New CPU (%s) is already active." % (new_cpu,))
|
||||
raise RuntimeError(f"New CPU ({new_cpu}) is already active.")
|
||||
if not new_cpu.support_take_over():
|
||||
raise RuntimeError(
|
||||
"New CPU (%s) does not support CPU handover." % (old_cpu,)
|
||||
f"New CPU ({old_cpu}) does not support CPU handover."
|
||||
)
|
||||
if new_cpu.memory_mode() != memory_mode_name:
|
||||
raise RuntimeError(
|
||||
"%s and %s require different memory modes."
|
||||
% (new_cpu, new_cpus[0])
|
||||
f"{new_cpu} and {new_cpus[0]} require different memory modes."
|
||||
)
|
||||
if old_cpu.switchedOut():
|
||||
raise RuntimeError("Old CPU (%s) is inactive." % (new_cpu,))
|
||||
raise RuntimeError(f"Old CPU ({new_cpu}) is inactive.")
|
||||
if not old_cpu.support_take_over():
|
||||
raise RuntimeError(
|
||||
"Old CPU (%s) does not support CPU handover." % (old_cpu,)
|
||||
f"Old CPU ({old_cpu}) does not support CPU handover."
|
||||
)
|
||||
|
||||
MemoryMode = params.allEnums["MemoryMode"]
|
||||
try:
|
||||
memory_mode = MemoryMode(memory_mode_name).getValue()
|
||||
except KeyError:
|
||||
raise RuntimeError("Invalid memory mode (%s)" % memory_mode_name)
|
||||
raise RuntimeError(f"Invalid memory mode ({memory_mode_name})")
|
||||
|
||||
drain()
|
||||
|
||||
|
||||
@@ -102,26 +102,21 @@ def _url_factory(schemes, enable=True):
|
||||
# values into proper Python types.
|
||||
def parse_value(key, values):
|
||||
if len(values) == 0 or (len(values) == 1 and not values[0]):
|
||||
fatal(
|
||||
"%s: '%s' doesn't have a value." % (url.geturl(), key)
|
||||
)
|
||||
fatal(f"{url.geturl()}: '{key}' doesn't have a value.")
|
||||
elif len(values) > 1:
|
||||
fatal(
|
||||
"%s: '%s' has multiple values." % (url.geturl(), key)
|
||||
)
|
||||
fatal(f"{url.geturl()}: '{key}' has multiple values.")
|
||||
else:
|
||||
try:
|
||||
return key, literal_eval(values[0])
|
||||
except ValueError:
|
||||
fatal(
|
||||
"%s: %s isn't a valid Python literal"
|
||||
% (url.geturl(), values[0])
|
||||
f"{url.geturl()}: {values[0]} isn't a valid Python literal"
|
||||
)
|
||||
|
||||
kwargs = dict([parse_value(k, v) for k, v in qs.items()])
|
||||
|
||||
try:
|
||||
return func("%s%s" % (url.netloc, url.path), **kwargs)
|
||||
return func(f"{url.netloc}{url.path}", **kwargs)
|
||||
except TypeError:
|
||||
fatal("Illegal stat visitor parameter specified")
|
||||
|
||||
@@ -227,10 +222,10 @@ def addStatVisitor(url):
|
||||
try:
|
||||
factory = factories[parsed.scheme]
|
||||
except KeyError:
|
||||
fatal("Illegal stat file type '%s' specified." % parsed.scheme)
|
||||
fatal(f"Illegal stat file type '{parsed.scheme}' specified.")
|
||||
|
||||
if factory is None:
|
||||
fatal("Stat type '%s' disabled at compile time" % parsed.scheme)
|
||||
fatal(f"Stat type '{parsed.scheme}' disabled at compile time")
|
||||
|
||||
outputList.append(factory(parsed))
|
||||
|
||||
@@ -242,12 +237,12 @@ def printStatVisitorTypes():
|
||||
|
||||
def print_doc(doc):
|
||||
for line in doc.splitlines():
|
||||
print("| %s" % line)
|
||||
print(f"| {line}")
|
||||
print()
|
||||
|
||||
enabled_visitors = [x for x in all_factories if x[2]]
|
||||
for factory, schemes, _ in enabled_visitors:
|
||||
print("%s:" % ", ".join(filter(lambda x: x is not None, schemes)))
|
||||
print(f"{', '.join(filter(lambda x: x is not None, schemes))}:")
|
||||
|
||||
# Try to extract the factory doc string
|
||||
print_doc(inspect.getdoc(factory))
|
||||
@@ -283,7 +278,7 @@ def _bindStatHierarchy(root):
|
||||
_bind_obj(name, obj[0])
|
||||
else:
|
||||
for idx, obj in enumerate(obj):
|
||||
_bind_obj("{}{}".format(name, idx), obj)
|
||||
_bind_obj(f"{name}{idx}", obj)
|
||||
else:
|
||||
# We need this check because not all obj.getCCObject() is an
|
||||
# instance of Stat::Group. For example, sc_core::sc_module, the C++
|
||||
|
||||
@@ -48,7 +48,7 @@ def setGlobalFrequency(ticksPerSecond):
|
||||
tps = round(convert.anyToFrequency(ticksPerSecond))
|
||||
else:
|
||||
raise TypeError(
|
||||
"wrong type '%s' for ticksPerSecond" % type(ticksPerSecond)
|
||||
f"wrong type '{type(ticksPerSecond)}' for ticksPerSecond"
|
||||
)
|
||||
_m5.core.setClockFrequency(int(tps))
|
||||
|
||||
@@ -61,7 +61,7 @@ def fromSeconds(value):
|
||||
import _m5.core
|
||||
|
||||
if not isinstance(value, float):
|
||||
raise TypeError("can't convert '%s' to type tick" % type(value))
|
||||
raise TypeError(f"can't convert '{type(value)}' to type tick")
|
||||
|
||||
# once someone needs to convert to seconds, the global frequency
|
||||
# had better be fixed
|
||||
|
||||
@@ -203,7 +203,7 @@ def printList(items, indent=4):
|
||||
line = " " * indent
|
||||
|
||||
if i < len(items) - 1:
|
||||
line += "%s, " % item
|
||||
line += f"{item}, "
|
||||
else:
|
||||
line += item
|
||||
print(line)
|
||||
|
||||
@@ -99,7 +99,7 @@ binary_prefixes = {
|
||||
|
||||
def assertStr(value):
|
||||
if not isinstance(value, str):
|
||||
raise TypeError("wrong type '%s' should be str" % type(value))
|
||||
raise TypeError(f"wrong type '{type(value)}' should be str")
|
||||
|
||||
|
||||
def _split_suffix(value, suffixes):
|
||||
@@ -141,9 +141,7 @@ def toNum(value, target_type, units, prefixes, converter):
|
||||
try:
|
||||
return converter(val)
|
||||
except ValueError:
|
||||
raise ValueError(
|
||||
"cannot convert '%s' to %s" % (value, target_type)
|
||||
)
|
||||
raise ValueError(f"cannot convert '{value}' to {target_type}")
|
||||
|
||||
# Units can be None, the empty string, or a list/tuple. Convert
|
||||
# to a tuple for consistent handling.
|
||||
@@ -198,7 +196,7 @@ def toBool(value):
|
||||
return True
|
||||
if value in ("false", "f", "no", "n", "0"):
|
||||
return False
|
||||
raise ValueError("cannot convert '%s' to bool" % value)
|
||||
raise ValueError(f"cannot convert '{value}' to bool")
|
||||
|
||||
|
||||
def toFrequency(value):
|
||||
@@ -265,15 +263,15 @@ def toMemorySize(value):
|
||||
|
||||
def toIpAddress(value):
|
||||
if not isinstance(value, str):
|
||||
raise TypeError("wrong type '%s' should be str" % type(value))
|
||||
raise TypeError(f"wrong type '{type(value)}' should be str")
|
||||
|
||||
bytes = value.split(".")
|
||||
if len(bytes) != 4:
|
||||
raise ValueError("invalid ip address %s" % value)
|
||||
raise ValueError(f"invalid ip address {value}")
|
||||
|
||||
for byte in bytes:
|
||||
if not 0 <= int(byte) <= 0xFF:
|
||||
raise ValueError("invalid ip address %s" % value)
|
||||
raise ValueError(f"invalid ip address {value}")
|
||||
|
||||
return (
|
||||
(int(bytes[0]) << 24)
|
||||
@@ -285,14 +283,14 @@ def toIpAddress(value):
|
||||
|
||||
def toIpNetmask(value):
|
||||
if not isinstance(value, str):
|
||||
raise TypeError("wrong type '%s' should be str" % type(value))
|
||||
raise TypeError(f"wrong type '{type(value)}' should be str")
|
||||
|
||||
(ip, netmask) = value.split("/")
|
||||
ip = toIpAddress(ip)
|
||||
netmaskParts = netmask.split(".")
|
||||
if len(netmaskParts) == 1:
|
||||
if not 0 <= int(netmask) <= 32:
|
||||
raise ValueError("invalid netmask %s" % netmask)
|
||||
raise ValueError(f"invalid netmask {netmask}")
|
||||
return (ip, int(netmask))
|
||||
elif len(netmaskParts) == 4:
|
||||
netmaskNum = toIpAddress(netmask)
|
||||
@@ -303,19 +301,19 @@ def toIpNetmask(value):
|
||||
testVal |= 1 << (31 - i)
|
||||
if testVal == netmaskNum:
|
||||
return (ip, i + 1)
|
||||
raise ValueError("invalid netmask %s" % netmask)
|
||||
raise ValueError(f"invalid netmask {netmask}")
|
||||
else:
|
||||
raise ValueError("invalid netmask %s" % netmask)
|
||||
raise ValueError(f"invalid netmask {netmask}")
|
||||
|
||||
|
||||
def toIpWithPort(value):
|
||||
if not isinstance(value, str):
|
||||
raise TypeError("wrong type '%s' should be str" % type(value))
|
||||
raise TypeError(f"wrong type '{type(value)}' should be str")
|
||||
|
||||
(ip, port) = value.split(":")
|
||||
ip = toIpAddress(ip)
|
||||
if not 0 <= int(port) <= 0xFFFF:
|
||||
raise ValueError("invalid port %s" % port)
|
||||
raise ValueError(f"invalid port {port}")
|
||||
return (ip, int(port))
|
||||
|
||||
|
||||
|
||||
@@ -284,7 +284,7 @@ def dot_gen_colour(simNode, isPort=False):
|
||||
|
||||
|
||||
def dot_rgb_to_html(r, g, b):
|
||||
return "#%.2x%.2x%.2x" % (int(r), int(g), int(b))
|
||||
return f"#{int(r):02x}{int(g):02x}{int(b):02x}"
|
||||
|
||||
|
||||
# We need to create all of the clock domains. We abuse the alpha channel to get
|
||||
|
||||
@@ -46,7 +46,7 @@ except:
|
||||
|
||||
|
||||
def _dot_rgb_to_html(r, g, b):
|
||||
return "#%.2x%.2x%.2x" % (r, g, b)
|
||||
return f"#{r:02x}{g:02x}{b:02x}"
|
||||
|
||||
|
||||
def _dot_create_router_node(full_path, label):
|
||||
|
||||
@@ -88,12 +88,9 @@ class PyBindMethod(PyBindExport):
|
||||
def get_arg_decl(arg):
|
||||
if isinstance(arg, tuple):
|
||||
name, default = arg
|
||||
return 'py::arg("%s") = %s' % (
|
||||
name,
|
||||
self._conv_arg(default),
|
||||
)
|
||||
return f'py::arg("{name}") = {self._conv_arg(default)}'
|
||||
else:
|
||||
return 'py::arg("%s")' % arg
|
||||
return f'py::arg("{arg}")'
|
||||
|
||||
arguments.extend(list([get_arg_decl(a) for a in self.args]))
|
||||
code("." + self.method_def + "(" + ", ".join(arguments) + ")")
|
||||
|
||||
Reference in New Issue
Block a user