misc,python: Run pre-commit run --all-files

Applies the `pyupgrade` hook to all files in the repo.

Change-Id: I9879c634a65c5fcaa9567c63bc5977ff97d5d3bf
This commit is contained in:
Bobby R. Bruce
2023-10-09 13:40:03 -07:00
parent 83af4525ce
commit 298119e402
188 changed files with 741 additions and 779 deletions

View File

@@ -46,7 +46,7 @@ import os
import re
class lookup(object):
class lookup:
def __init__(self, formatter, frame, *args, **kwargs):
self.frame = frame
self.formatter = formatter
@@ -106,7 +106,7 @@ class code_formatter_meta(type):
"""
def __init__(cls, name, bases, dct):
super(code_formatter_meta, cls).__init__(name, bases, dct)
super().__init__(name, bases, dct)
if "pattern" in dct:
pat = cls.pattern
else:
@@ -125,7 +125,7 @@ class code_formatter_meta(type):
cls.pattern = re.compile(pat, re.VERBOSE | re.DOTALL | re.MULTILINE)
class code_formatter(object, metaclass=code_formatter_meta):
class code_formatter(metaclass=code_formatter_meta):
delim = r"$"
ident = r"[_A-z]\w*"
pos = r"[0-9]+"
@@ -272,7 +272,7 @@ class code_formatter(object, metaclass=code_formatter_meta):
# check for a lone identifier
if ident:
indent = match.group("indent") # must be spaces
lone = "%s" % (l[ident],)
lone = f"{l[ident]}"
def indent_lines(gen):
for line in gen:
@@ -284,7 +284,7 @@ class code_formatter(object, metaclass=code_formatter_meta):
# check for an identifier, braced or not
ident = match.group("ident") or match.group("b_ident")
if ident is not None:
return "%s" % (l[ident],)
return f"{l[ident]}"
# check for a positional parameter, braced or not
pos = match.group("pos") or match.group("b_pos")
@@ -295,13 +295,13 @@ class code_formatter(object, metaclass=code_formatter_meta):
"Positional parameter #%d not found in pattern" % pos,
code_formatter.pattern,
)
return "%s" % (args[int(pos)],)
return f"{args[int(pos)]}"
# check for a double braced expression
eval_expr = match.group("eval")
if eval_expr is not None:
result = eval(eval_expr, {}, l)
return "%s" % (result,)
return f"{result}"
# check for an escaped delimiter
if match.group("escaped") is not None:

View File

@@ -66,7 +66,7 @@ code = code_formatter()
wrapper_name = enum.wrapper_name
wrapper = "struct" if enum.wrapper_is_struct else "namespace"
name = enum.__name__ if enum.enum_name is None else enum.enum_name
idem_macro = "__ENUM__%s__%s__" % (wrapper_name, name)
idem_macro = f"__ENUM__{wrapper_name}__{name}__"
code(
"""\

View File

@@ -36,7 +36,7 @@ class ParseError(Exception):
self.token = token
class Grammar(object):
class Grammar:
def setupLexerFactory(self, **kwargs):
if "module" in kwargs:
raise AttributeError("module is an illegal attribute")
@@ -92,7 +92,7 @@ class Grammar(object):
return self.current_lexer.lineno
raise AttributeError(
"'%s' object has no attribute '%s'" % (type(self), attr)
f"'{type(self)}' object has no attribute '{attr}'"
)
def parse_string(self, data, source="<string>", debug=None, tracking=0):
@@ -118,7 +118,7 @@ class Grammar(object):
def parse_file(self, f, **kwargs):
if isinstance(f, str):
source = f
f = open(f, "r")
f = open(f)
elif isinstance(f, file):
source = f.name
else:
@@ -137,7 +137,7 @@ class Grammar(object):
t.value,
)
else:
msg = "Syntax error at end of %s" % (self.current_source,)
msg = f"Syntax error at end of {self.current_source}"
raise ParseError(msg, t)
def t_error(self, t):

View File

@@ -56,7 +56,7 @@ for source in args.files:
# `README.md = "..."` which is not valid as `md` is not a property of
# `README`.
src = os.path.basename(source).replace(".", "_")
with open(source, "r") as f:
with open(source) as f:
data = "".join(f)
code("${src} = ${{repr(data)}}")

View File

@@ -74,7 +74,7 @@ if "LC_CTYPE" in os.environ:
_, cpp, python, modpath, abspath = sys.argv
with open(python, "r") as f:
with open(python) as f:
src = f.read()
compiled = compile(src, python, "exec")

View File

@@ -81,7 +81,7 @@ except:
warned_about_nested_templates = False
class CxxClass(object):
class CxxClass:
def __init__(self, sig, template_params=[]):
# Split the signature into its constituent parts. This could
# potentially be done with regular expressions, but

View File

@@ -42,7 +42,7 @@ import sys
from textwrap import TextWrapper
class ObjectList(object):
class ObjectList:
"""Creates a list of objects that are sub-classes of a given class."""
def _is_obj_class(self, cls):
@@ -86,7 +86,7 @@ class ObjectList(object):
print(line)
if self._aliases:
print("\Aliases:")
print(r"\Aliases:")
for alias, target in list(self._aliases.items()):
print(f"\t{alias} => {target}")
@@ -127,14 +127,14 @@ class CPUList(ObjectList):
# We can't use the normal inspect.isclass because the ParamFactory
# and ProxyFactory classes have a tendency to confuse it.
try:
return super(CPUList, self)._is_obj_class(cls) and not issubclass(
return super()._is_obj_class(cls) and not issubclass(
cls, m5.objects.CheckerCPU
)
except (TypeError, AttributeError):
return False
def _add_objects(self):
super(CPUList, self)._add_objects()
super()._add_objects()
from importlib import import_module

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jason Power
# All rights reserved.
#

View File

@@ -153,8 +153,8 @@ def findCptDir(options, cptdir, testsys):
# Assumes that the checkpoint dir names are formatted as follows:
dirs = listdir(cptdir)
expr = re.compile(
"cpt\.simpoint_(\d+)_inst_(\d+)"
+ "_weight_([\d\.e\-]+)_interval_(\d+)_warmup_(\d+)"
r"cpt\.simpoint_(\d+)_inst_(\d+)"
+ r"_weight_([\d\.e\-]+)_interval_(\d+)_warmup_(\d+)"
)
cpts = []
for dir in dirs:
@@ -190,7 +190,7 @@ def findCptDir(options, cptdir, testsys):
else:
dirs = listdir(cptdir)
expr = re.compile("cpt\.([0-9]+)")
expr = re.compile(r"cpt\.([0-9]+)")
cpts = []
for dir in dirs:
match = expr.match(dir)
@@ -325,7 +325,7 @@ def parseSimpointAnalysisFile(options, testsys):
line = simpoint_file.readline()
if not line:
break
m = re.match("(\d+)\s+(\d+)", line)
m = re.match(r"(\d+)\s+(\d+)", line)
if m:
interval = int(m.group(1))
else:
@@ -334,7 +334,7 @@ def parseSimpointAnalysisFile(options, testsys):
line = weight_file.readline()
if not line:
fatal("not enough lines in simpoint weight file!")
m = re.match("([0-9\.e\-]+)\s+(\d+)", line)
m = re.match(r"([0-9\.e\-]+)\s+(\d+)", line)
if m:
weight = float(m.group(1))
else:

View File

@@ -30,7 +30,7 @@ config_path = os.path.dirname(os.path.abspath(__file__))
config_root = os.path.dirname(config_path)
class PathSearchFunc(object):
class PathSearchFunc:
_sys_paths = None
environment_variable = "M5_PATH"
@@ -58,7 +58,7 @@ class PathSearchFunc(object):
paths = list(filter(os.path.isdir, paths))
if not paths:
raise IOError(
raise OSError(
"Can't find system files directory, "
"check your {} environment variable".format(
self.environment_variable
@@ -72,7 +72,7 @@ class PathSearchFunc(object):
try:
return next(p for p in paths if os.path.exists(p))
except StopIteration:
raise IOError(
raise OSError(
f"Can't find file '{filepath}' on {self.environment_variable}."
)

View File

@@ -71,7 +71,7 @@ def copyfiles(srcdir, dstdir):
os.symlink(".", outlink)
class Benchmark(object):
class Benchmark:
def __init__(self, isa, os, input_set):
if not hasattr(self.__class__, "name"):
self.name = self.__class__.__name__
@@ -877,7 +877,7 @@ class vortex(Benchmark):
else:
raise AttributeError(f"unknown ISA {isa}")
super(vortex, self).__init__(isa, os, input_set)
super().__init__(isa, os, input_set)
def test(self, isa, os):
self.args = [f"{self.endian}.raw"]

View File

@@ -94,7 +94,7 @@ def get_processes(args):
process.gid = os.getgid()
if args.env:
with open(args.env, "r") as f:
with open(args.env) as f:
process.env = [line.rstrip() for line in f]
if len(pargs) > idx:

View File

@@ -185,7 +185,7 @@ itt = 150 * 1000
def create_trace(filename, max_addr, burst_size, itt):
try:
proto_out = gzip.open(filename, "wb")
except IOError:
except OSError:
print("Failed to open ", filename, " for writing")
exit(-1)

View File

@@ -699,7 +699,7 @@ if os.path.isdir(executable):
executable = find_file(benchmark_path, args.cmd)
if args.env:
with open(args.env, "r") as f:
with open(args.env) as f:
env = [line.rstrip() for line in f]
else:
env = [

View File

@@ -171,9 +171,10 @@ def create(args):
system.workload = workload_class(object_file, system)
if args.with_pmu:
enabled_pmu_events = set(
(*args.pmu_dump_stats_on, *args.pmu_reset_stats_on)
)
enabled_pmu_events = {
*args.pmu_dump_stats_on,
*args.pmu_reset_stats_on,
}
exit_sim_on_control = bool(
enabled_pmu_events & set(pmu_control_events.keys())
)

View File

@@ -462,7 +462,7 @@ class SimpleSystem(BaseSimpleSystem):
"""
def __init__(self, caches, mem_size, platform=None, **kwargs):
super(SimpleSystem, self).__init__(mem_size, platform, **kwargs)
super().__init__(mem_size, platform, **kwargs)
self.membus = MemBus()
# CPUs->PIO
@@ -501,7 +501,7 @@ class ArmRubySystem(BaseSimpleSystem):
"""
def __init__(self, mem_size, platform=None, **kwargs):
super(ArmRubySystem, self).__init__(mem_size, platform, **kwargs)
super().__init__(mem_size, platform, **kwargs)
self._dma_ports = []
self._mem_ports = []

View File

@@ -47,7 +47,7 @@ import fs_bigLITTLE as bL
class CpuPowerOn(MathExprPowerModel):
def __init__(self, cpu_path, **kwargs):
super(CpuPowerOn, self).__init__(**kwargs)
super().__init__(**kwargs)
# 2A per IPC, 3pA per cache miss
# and then convert to Watt
self.dyn = (
@@ -64,7 +64,7 @@ class CpuPowerOff(MathExprPowerModel):
class CpuPowerModel(PowerModel):
def __init__(self, cpu_path, **kwargs):
super(CpuPowerModel, self).__init__(**kwargs)
super().__init__(**kwargs)
self.pm = [
CpuPowerOn(cpu_path), # ON
CpuPowerOff(), # CLK_GATED
@@ -75,7 +75,7 @@ class CpuPowerModel(PowerModel):
class L2PowerOn(MathExprPowerModel):
def __init__(self, l2_path, **kwargs):
super(L2PowerOn, self).__init__(**kwargs)
super().__init__(**kwargs)
# Example to report l2 Cache overallAccesses
# The estimated power is converted to Watt and will vary based
# on the size of the cache
@@ -90,7 +90,7 @@ class L2PowerOff(MathExprPowerModel):
class L2PowerModel(PowerModel):
def __init__(self, l2_path, **kwargs):
super(L2PowerModel, self).__init__(**kwargs)
super().__init__(**kwargs)
# Choose a power model for every power state
self.pm = [
L2PowerOn(l2_path), # ON

View File

@@ -49,7 +49,7 @@ class ArmBaremetal(ArmFsWorkload):
dtb_addr = 0
def __init__(self, obj, system, **kwargs):
super(ArmBaremetal, self).__init__(**kwargs)
super().__init__(**kwargs)
self.object_file = obj
@@ -76,7 +76,7 @@ class ArmTrustedFirmware(ArmFsWorkload):
dtb_addr = 0
def __init__(self, obj, system, **kwargs):
super(ArmTrustedFirmware, self).__init__(**kwargs)
super().__init__(**kwargs)
self.extras = [binary("bl1.bin"), binary("fip.bin")]
self.extras_addrs = [

View File

@@ -175,7 +175,7 @@ board = X86Board(
command = (
"cd /home/gem5/parsec-benchmark;".format(args.benchmark)
f"cd /home/gem5/parsec-benchmark;"
+ "source env.sh;"
+ f"parsecmgmt -a run -p {args.benchmark} -c gcc-hooks -i {args.size} -n 2;"
+ "sleep 5;"
@@ -236,7 +236,7 @@ print("Done with the simulation")
print()
print("Performance statistics:")
print("Simulated time in ROI: " + ((str(simulator.get_roi_ticks()[0]))))
print("Simulated time in ROI: " + (str(simulator.get_roi_ticks()[0])))
print(
"Ran a total of", simulator.get_current_tick() / 1e12, "simulated seconds"
)

View File

@@ -37,7 +37,7 @@ from network import Network
class DisjointSimple(SimpleNetwork):
def __init__(self, ruby_system):
super(DisjointSimple, self).__init__()
super().__init__()
self.netifs = []
self.routers = []
@@ -73,7 +73,7 @@ class DisjointSimple(SimpleNetwork):
class DisjointGarnet(GarnetNetwork):
def __init__(self, ruby_system):
super(DisjointGarnet, self).__init__()
super().__init__()
self.netifs = []
self.ruby_system = ruby_system

View File

@@ -47,7 +47,7 @@ class Disjoint_VIPER(RubySystem):
if buildEnv["PROTOCOL"] != "GPU_VIPER":
fatal("This ruby config only supports the GPU_VIPER protocol")
super(Disjoint_VIPER, self).__init__()
super().__init__()
def create(self, options, system, piobus, dma_devices):
# Disjoint network topology

View File

@@ -184,7 +184,7 @@ def connectGPU(system, args):
elif args.gpu_device == "Vega10":
system.pc.south_bridge.gpu.DeviceID = 0x6863
else:
panic("Unknown GPU device: {}".format(args.gpu_device))
panic(f"Unknown GPU device: {args.gpu_device}")
# Use the gem5 default of 0x280 OR'd with 0x10 which tells Linux there is
# a PCI capabilities list to travse.

View File

@@ -140,7 +140,7 @@ for name, parser in list(param_parsers.items()):
setattr(m5.params.__dict__[name], "parse_ini", classmethod(parser))
class PortConnection(object):
class PortConnection:
"""This class is similar to m5.params.PortRef but with just enough
information for ConfigManager"""
@@ -151,7 +151,7 @@ class PortConnection(object):
@classmethod
def from_string(cls, str):
m = re.match("(.*)\.([^.\[]+)(\[(\d+)\])?", str)
m = re.match(r"(.*)\.([^.\[]+)(\[(\d+)\])?", str)
object_name, port_name, whole_index, index = m.groups()
if index is not None:
index = int(index)
@@ -178,7 +178,7 @@ def to_list(v):
return [v]
class ConfigManager(object):
class ConfigManager:
"""Manager for parsing a Root configuration from a config file"""
def __init__(self, config):
@@ -296,7 +296,7 @@ class ConfigManager(object):
def parse_port_name(self, port):
"""Parse the name of a port"""
m = re.match("(.*)\.([^.\[]+)(\[(\d+)\])?", port)
m = re.match(r"(.*)\.([^.\[]+)(\[(\d+)\])?", port)
peer, peer_port, whole_index, index = m.groups()
if index is not None:
index = int(index)
@@ -415,7 +415,7 @@ class ConfigManager(object):
self.bind_ports(connections)
class ConfigFile(object):
class ConfigFile:
def get_flags(self):
return set()
@@ -444,7 +444,7 @@ class ConfigFile(object):
pass
def get_port_peers(self, object_name, port_name):
"""Get the list of connected port names (in the string form
r"""Get the list of connected port names (in the string form
object.port(\[index\])?) of the port object_name.port_name"""
pass
@@ -507,7 +507,7 @@ class ConfigJsonFile(ConfigFile):
self.find_all_objects(elem)
def load(self, config_file):
root = json.load(open(config_file, "r"))
root = json.load(open(config_file))
self.object_dicts = {}
self.find_all_objects(root)

View File

@@ -48,7 +48,7 @@ from common import SysPaths
class ArmSstSystem(ArmSystem):
def __init__(self, cpu_clock_rate, **kwargs):
super(ArmSstSystem, self).__init__(**kwargs)
super().__init__(**kwargs)
self.voltage_domain = VoltageDomain(voltage="1.0V")
self.clk_domain = SrcClockDomain(

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jason Power
# All rights reserved.
#
@@ -55,7 +54,7 @@ class L1Cache(Cache):
tgts_per_mshr = 20
def __init__(self, options=None):
super(L1Cache, self).__init__()
super().__init__()
pass
def connectBus(self, bus):
@@ -79,7 +78,7 @@ class L1ICache(L1Cache):
)
def __init__(self, opts=None):
super(L1ICache, self).__init__(opts)
super().__init__(opts)
if not opts or not opts.l1i_size:
return
self.size = opts.l1i_size
@@ -100,7 +99,7 @@ class L1DCache(L1Cache):
)
def __init__(self, opts=None):
super(L1DCache, self).__init__(opts)
super().__init__(opts)
if not opts or not opts.l1d_size:
return
self.size = opts.l1d_size
@@ -125,7 +124,7 @@ class L2Cache(Cache):
SimpleOpts.add_option("--l2_size", help=f"L2 cache size. Default: {size}")
def __init__(self, opts=None):
super(L2Cache, self).__init__()
super().__init__()
if not opts or not opts.l2_size:
return
self.size = opts.l2_size

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jason Power
# All rights reserved.
#

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Jason Lowe-Power
# All rights reserved.
#

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Jason Lowe-Power
# All rights reserved.
#

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Jason Lowe-Power
# All rights reserved.
#

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Jason Lowe-Power
# All rights reserved.
#

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Jason Power
# All rights reserved.
#
@@ -48,7 +47,7 @@ class MyCacheSystem(RubySystem):
if buildEnv["PROTOCOL"] != "MSI":
fatal("This system assumes MSI from learning gem5!")
super(MyCacheSystem, self).__init__()
super().__init__()
def setup(self, system, cpus, mem_ctrls):
"""Set up the Ruby cache subsystem. Note: This can't be done in the
@@ -121,7 +120,7 @@ class L1Cache(L1Cache_Controller):
"""CPUs are needed to grab the clock domain and system is needed for
the cache block size.
"""
super(L1Cache, self).__init__()
super().__init__()
self.version = self.versionCount()
# This is the cache memory object that stores the cache data and tags
@@ -184,7 +183,7 @@ class DirController(Directory_Controller):
"""ranges are the memory ranges assigned to this controller."""
if len(mem_ctrls) > 1:
panic("This cache system can only be connected to one mem ctrl")
super(DirController, self).__init__()
super().__init__()
self.version = self.versionCount()
self.addr_ranges = ranges
self.ruby_system = ruby_system
@@ -216,7 +215,7 @@ class MyNetwork(SimpleNetwork):
"""A simple point-to-point network. This doesn't not use garnet."""
def __init__(self, ruby_system):
super(MyNetwork, self).__init__()
super().__init__()
self.netifs = []
self.ruby_system = ruby_system

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jason Power
# All rights reserved.
#
@@ -50,7 +49,7 @@ class MyCacheSystem(RubySystem):
if buildEnv["PROTOCOL"] != "MI_example":
fatal("This system assumes MI_example!")
super(MyCacheSystem, self).__init__()
super().__init__()
def setup(self, system, cpus, mem_ctrls):
"""Set up the Ruby cache subsystem. Note: This can't be done in the
@@ -119,7 +118,7 @@ class L1Cache(L1Cache_Controller):
"""CPUs are needed to grab the clock domain and system is needed for
the cache block size.
"""
super(L1Cache, self).__init__()
super().__init__()
self.version = self.versionCount()
# This is the cache memory object that stores the cache data and tags
@@ -173,7 +172,7 @@ class DirController(Directory_Controller):
"""ranges are the memory ranges assigned to this controller."""
if len(mem_ctrls) > 1:
panic("This cache system can only be connected to one mem ctrl")
super(DirController, self).__init__()
super().__init__()
self.version = self.versionCount()
self.addr_ranges = ranges
self.ruby_system = ruby_system
@@ -202,7 +201,7 @@ class MyNetwork(SimpleNetwork):
"""A simple point-to-point network. This doesn't not use garnet."""
def __init__(self, ruby_system):
super(MyNetwork, self).__init__()
super().__init__()
self.netifs = []
self.ruby_system = ruby_system

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jason Power
# All rights reserved.
#

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2015 Jason Power
# All rights reserved.
#

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Jason Power
# All rights reserved.
#
@@ -48,7 +47,7 @@ class TestCacheSystem(RubySystem):
if buildEnv["PROTOCOL"] != "MSI":
fatal("This system assumes MSI from learning gem5!")
super(TestCacheSystem, self).__init__()
super().__init__()
def setup(self, system, tester, mem_ctrls):
"""Set up the Ruby cache subsystem. Note: This can't be done in the

View File

@@ -116,7 +116,7 @@ class CHI_Node(SubSystem):
router_list = None
def __init__(self, ruby_system):
super(CHI_Node, self).__init__()
super().__init__()
self._ruby_system = ruby_system
self._network = ruby_system.network
@@ -201,7 +201,7 @@ class CHI_Cache_Controller(Cache_Controller):
"""
def __init__(self, ruby_system):
super(CHI_Cache_Controller, self).__init__(
super().__init__(
version=Versions.getVersion(Cache_Controller),
ruby_system=ruby_system,
mandatoryQueue=MessageBuffer(),
@@ -228,7 +228,7 @@ class CHI_L1Controller(CHI_Cache_Controller):
"""
def __init__(self, ruby_system, sequencer, cache, prefetcher):
super(CHI_L1Controller, self).__init__(ruby_system)
super().__init__(ruby_system)
self.sequencer = sequencer
self.cache = cache
self.use_prefetcher = False
@@ -265,7 +265,7 @@ class CHI_L2Controller(CHI_Cache_Controller):
"""
def __init__(self, ruby_system, cache, prefetcher):
super(CHI_L2Controller, self).__init__(ruby_system)
super().__init__(ruby_system)
self.sequencer = NULL
self.cache = cache
self.use_prefetcher = False
@@ -301,7 +301,7 @@ class CHI_HNFController(CHI_Cache_Controller):
"""
def __init__(self, ruby_system, cache, prefetcher, addr_ranges):
super(CHI_HNFController, self).__init__(ruby_system)
super().__init__(ruby_system)
self.sequencer = NULL
self.cache = cache
self.use_prefetcher = False
@@ -340,7 +340,7 @@ class CHI_MNController(MiscNode_Controller):
def __init__(
self, ruby_system, addr_range, l1d_caches, early_nonsync_comp
):
super(CHI_MNController, self).__init__(
super().__init__(
version=Versions.getVersion(MiscNode_Controller),
ruby_system=ruby_system,
mandatoryQueue=MessageBuffer(),
@@ -371,7 +371,7 @@ class CHI_DMAController(CHI_Cache_Controller):
"""
def __init__(self, ruby_system, sequencer):
super(CHI_DMAController, self).__init__(ruby_system)
super().__init__(ruby_system)
self.sequencer = sequencer
class DummyCache(RubyCache):
@@ -463,7 +463,7 @@ class CHI_RNF(CHI_Node):
l1Iprefetcher_type=None,
l1Dprefetcher_type=None,
):
super(CHI_RNF, self).__init__(ruby_system)
super().__init__(ruby_system)
self._block_size_bits = int(math.log(cache_line_size, 2))
@@ -606,7 +606,7 @@ class CHI_HNF(CHI_Node):
# The CHI controller can be a child of this object or another if
# 'parent' if specified
def __init__(self, hnf_idx, ruby_system, llcache_type, parent):
super(CHI_HNF, self).__init__(ruby_system)
super().__init__(ruby_system)
addr_ranges, intlvHighBit = self.getAddrRanges(hnf_idx)
# All ranges should have the same interleaving
@@ -644,7 +644,7 @@ class CHI_MN(CHI_Node):
# The CHI controller can be a child of this object or another if
# 'parent' if specified
def __init__(self, ruby_system, l1d_caches, early_nonsync_comp=False):
super(CHI_MN, self).__init__(ruby_system)
super().__init__(ruby_system)
# MiscNode has internal address range starting at 0
addr_range = AddrRange(0, size="1kB")
@@ -675,7 +675,7 @@ class CHI_SNF_Base(CHI_Node):
# The CHI controller can be a child of this object or another if
# 'parent' if specified
def __init__(self, ruby_system, parent):
super(CHI_SNF_Base, self).__init__(ruby_system)
super().__init__(ruby_system)
self._cntrl = Memory_Controller(
version=Versions.getVersion(Memory_Controller),
@@ -722,7 +722,7 @@ class CHI_SNF_BootMem(CHI_SNF_Base):
"""
def __init__(self, ruby_system, parent, bootmem):
super(CHI_SNF_BootMem, self).__init__(ruby_system, parent)
super().__init__(ruby_system, parent)
self._cntrl.memory_out_port = bootmem.port
self._cntrl.addr_ranges = self.getMemRange(bootmem)
@@ -733,7 +733,7 @@ class CHI_SNF_MainMem(CHI_SNF_Base):
"""
def __init__(self, ruby_system, parent, mem_ctrl=None):
super(CHI_SNF_MainMem, self).__init__(ruby_system, parent)
super().__init__(ruby_system, parent)
if mem_ctrl:
self._cntrl.memory_out_port = mem_ctrl.port
self._cntrl.addr_ranges = self.getMemRange(mem_ctrl)
@@ -748,7 +748,7 @@ class CHI_RNI_Base(CHI_Node):
# The CHI controller can be a child of this object or another if
# 'parent' if specified
def __init__(self, ruby_system, parent):
super(CHI_RNI_Base, self).__init__(ruby_system)
super().__init__(ruby_system)
self._sequencer = RubySequencer(
version=Versions.getSeqId(),
@@ -777,7 +777,7 @@ class CHI_RNI_DMA(CHI_RNI_Base):
"""
def __init__(self, ruby_system, dma_port, parent):
super(CHI_RNI_DMA, self).__init__(ruby_system, parent)
super().__init__(ruby_system, parent)
assert dma_port != None
self._sequencer.in_ports = dma_port
@@ -788,5 +788,5 @@ class CHI_RNI_IO(CHI_RNI_Base):
"""
def __init__(self, ruby_system, parent):
super(CHI_RNI_IO, self).__init__(ruby_system, parent)
super().__init__(ruby_system, parent)
ruby_system._io_port = self._sequencer

View File

@@ -27,7 +27,7 @@
import m5
class BaseTopology(object):
class BaseTopology:
description = "BaseTopology"
def __init__(self):

View File

@@ -105,7 +105,7 @@ class UninitializedConfigException(Exception):
pass
class TagRegex(object):
class TagRegex:
def __init__(self, include, regex):
self.include = include
self.regex = re.compile(regex)
@@ -115,7 +115,7 @@ class TagRegex(object):
return "%10s: %s" % (type_, self.regex.pattern)
class _Config(object):
class _Config:
_initialized = False
__shared_dict = {}
@@ -185,8 +185,8 @@ class _Config(object):
return (getattr(self._defaults, attr),)
def __getattr__(self, attr):
if attr in dir(super(_Config, self)):
return getattr(super(_Config, self), attr)
if attr in dir(super()):
return getattr(super(), attr)
elif not self._initialized:
raise UninitializedConfigException(
"Cannot directly access elements from the config before it is"
@@ -434,7 +434,7 @@ def define_post_processors(config):
)
class Argument(object):
class Argument:
"""
Class represents a cli argument/flag for a argparse parser.
@@ -651,7 +651,7 @@ def define_common_args(config):
common_args = AttrDict({arg.name: arg for arg in common_args})
class ArgParser(object, metaclass=abc.ABCMeta):
class ArgParser(metaclass=abc.ABCMeta):
class ExtendAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
items = getattr(namespace, self.dest, [])
@@ -679,7 +679,7 @@ class CommandParser(ArgParser):
def __init__(self):
parser = argparse.ArgumentParser()
super(CommandParser, self).__init__(parser)
super().__init__(parser)
self.subparser = self.add_subparsers(dest="command")
@@ -691,7 +691,7 @@ class RunParser(ArgParser):
def __init__(self, subparser):
parser = subparser.add_parser("run", help="""Run Tests.""")
super(RunParser, self).__init__(parser)
super().__init__(parser)
common_args.uid.add_to(parser)
common_args.skip_build.add_to(parser)
@@ -718,7 +718,7 @@ class ListParser(ArgParser):
parser = subparser.add_parser(
"list", help="""List and query test metadata."""
)
super(ListParser, self).__init__(parser)
super().__init__(parser)
Argument(
"--suites",
@@ -777,7 +777,7 @@ class ListParser(ArgParser):
class RerunParser(ArgParser):
def __init__(self, subparser):
parser = subparser.add_parser("rerun", help="""Rerun failed tests.""")
super(RerunParser, self).__init__(parser)
super().__init__(parser)
common_args.skip_build.add_to(parser)
common_args.directories.add_to(parser)

View File

@@ -34,14 +34,14 @@ from typing import Optional
class SkipException(Exception):
def __init__(self, fixture, testitem):
self.msg = 'Fixture "%s" raised SkipException for "%s".' % (
self.msg = 'Fixture "{}" raised SkipException for "{}".'.format(
fixture.name,
testitem.name,
)
super(SkipException, self).__init__(self.msg)
super().__init__(self.msg)
class Fixture(object):
class Fixture:
"""
Base Class for a test Fixture.
@@ -60,7 +60,7 @@ class Fixture(object):
collector = helper.InstanceCollector()
def __new__(klass, *args, **kwargs):
obj = super(Fixture, klass).__new__(klass)
obj = super().__new__(klass)
Fixture.collector.collect(obj)
return obj

View File

@@ -48,7 +48,7 @@ from queue import Queue, Empty
from testlib.configuration import constants
class _TestStreamManager(object):
class _TestStreamManager:
def __init__(self):
self._writers = {}
@@ -75,7 +75,7 @@ class _TestStreamManager(object):
self._writers.clear()
class _TestStreams(object):
class _TestStreams:
def __init__(self, stdout, stderr):
helper.mkdir_p(os.path.dirname(stdout))
helper.mkdir_p(os.path.dirname(stderr))
@@ -87,7 +87,7 @@ class _TestStreams(object):
self.stderr.close()
class ResultHandler(object):
class ResultHandler:
"""
Log handler which listens for test results and output saving data as
it is reported.
@@ -184,7 +184,7 @@ class ResultHandler(object):
# TODO Change from a handler to an internal post processor so it can be used
# to reprint results
class SummaryHandler(object):
class SummaryHandler:
"""
A log handler which listens to the log for test results
and reports the aggregate results when closed.
@@ -255,7 +255,7 @@ class SummaryHandler(object):
string = (
" Results:"
+ string
+ " in {:.2} seconds ".format(self._timer.active_time())
+ f" in {self._timer.active_time():.2} seconds "
)
string += " "
return terminal.insert_separator(
@@ -263,7 +263,7 @@ class SummaryHandler(object):
)
class TerminalHandler(object):
class TerminalHandler:
color = terminal.get_termcap()
verbosity_mapping = {
log.LogLevel.Warn: color.Yellow,
@@ -339,7 +339,7 @@ class TerminalHandler(object):
)
def _colorize(self, message, level, bold=False):
return "%s%s%s%s" % (
return "{}{}{}{}".format(
self.color.Bold if bold else "",
self.verbosity_mapping.get(level, ""),
message,
@@ -355,7 +355,7 @@ class TerminalHandler(object):
pass
class MultiprocessingHandlerWrapper(object):
class MultiprocessingHandlerWrapper:
"""
A handler class which forwards log records to subhandlers, enabling
logging across multiprocessing python processes.

View File

@@ -56,7 +56,7 @@ import threading
import time
class TimedWaitPID(object):
class TimedWaitPID:
"""Utility to monkey-patch os.waitpid() with os.wait4().
This allows process usage time to be obtained directly from the OS
@@ -73,7 +73,7 @@ class TimedWaitPID(object):
TimeRecord = namedtuple("_TimeRecord", "user_time system_time")
class Wrapper(object):
class Wrapper:
def __init__(self):
self._time_for_pid = {}
self._access_lock = threading.Lock()
@@ -93,7 +93,7 @@ class TimedWaitPID(object):
def get_time_for_pid(self, pid):
with self._access_lock:
if pid not in self._time_for_pid:
raise Exception("No resource usage for pid {}".format(pid))
raise Exception(f"No resource usage for pid {pid}")
time_for_pid = self._time_for_pid[pid]
del self._time_for_pid[pid]
return time_for_pid
@@ -346,8 +346,8 @@ class OrderedSet(MutableSet):
def __repr__(self):
if not self:
return "%s()" % (self.__class__.__name__,)
return "%s(%r)" % (self.__class__.__name__, list(self))
return f"{self.__class__.__name__}()"
return f"{self.__class__.__name__}({list(self)!r})"
def __eq__(self, other):
if isinstance(other, OrderedSet):
@@ -386,7 +386,7 @@ class FrozenSetException(Exception):
pass
class AttrDict(object):
class AttrDict:
"""Object which exposes its own internal dictionary through attributes."""
def __init__(self, dict_={}):
@@ -417,7 +417,7 @@ class FrozenAttrDict(AttrDict):
__initialized = False
def __init__(self, dict_={}):
super(FrozenAttrDict, self).__init__(dict_)
super().__init__(dict_)
self.__initialized = True
def __setattr__(self, attr, val):
@@ -426,7 +426,7 @@ class FrozenAttrDict(AttrDict):
"Cannot modify an attribute in a FozenAttrDict"
)
else:
super(FrozenAttrDict, self).__setattr__(attr, val)
super().__setattr__(attr, val)
def update(self, items):
if self.__initialized:
@@ -434,10 +434,10 @@ class FrozenAttrDict(AttrDict):
"Cannot modify an attribute in a FozenAttrDict"
)
else:
super(FrozenAttrDict, self).update(items)
super().update(items)
class InstanceCollector(object):
class InstanceCollector:
"""
A class used to simplify collecting of Classes.
@@ -475,7 +475,7 @@ def append_dictlist(dict_, key, value):
def _filter_file(fname, filters):
with open(fname, "r") as file_:
with open(fname) as file_:
for line in file_:
for regex in filters:
if re.match(regex, line):
@@ -529,7 +529,7 @@ def diff_out_file(ref_file, out_file, logger, ignore_regexes=tuple()):
except OSError:
# Likely signals that diff does not exist on this system. fallback
# to difflib
with open(out_file, "r") as outf, open(ref_file, "r") as reff:
with open(out_file) as outf, open(ref_file) as reff:
diff = difflib.unified_diff(
iter(reff.readline, ""),
iter(outf.readline, ""),

View File

@@ -110,7 +110,7 @@ def path_as_modulename(filepath):
def path_as_suitename(filepath):
return os.path.split(os.path.dirname(os.path.abspath((filepath))))[-1]
return os.path.split(os.path.dirname(os.path.abspath(filepath)))[-1]
def _assert_files_in_same_dir(files):
@@ -121,7 +121,7 @@ def _assert_files_in_same_dir(files):
assert os.path.dirname(f) == directory
class Loader(object):
class Loader:
"""
Class for discovering tests.

View File

@@ -57,7 +57,7 @@ class RecordTypeCounterMetaclass(type):
RecordTypeCounterMetaclass.counter += 1
class Record(object, metaclass=RecordTypeCounterMetaclass):
class Record(metaclass=RecordTypeCounterMetaclass):
"""
A generic object that is passed to the :class:`Log` and its handlers.
@@ -70,9 +70,7 @@ class Record(object, metaclass=RecordTypeCounterMetaclass):
def __getitem__(self, item):
if item not in self.data:
raise KeyError(
"%s not in record %s" % (item, self.__class__.__name__)
)
raise KeyError(f"{item} not in record {self.__class__.__name__}")
return self.data[item]
def __str__(self):
@@ -132,7 +130,7 @@ class LibraryMessage(Record):
pass
class Log(object):
class Log:
_result_typemap = {
wrappers.LoadedLibrary.__name__: LibraryResult,
wrappers.LoadedSuite.__name__: SuiteResult,

View File

@@ -141,7 +141,7 @@ def filter_with_config_tags(loaded_library):
filters = list(itertools.chain(final_tags, tags))
string = "Filtering suites with tags as follows:\n"
filter_string = "\t\n".join((str(f) for f in filters))
filter_string = "\t\n".join(str(f) for f in filters)
log.test_log.trace(string + filter_string)
return filter_with_tags(loaded_library, filters)
@@ -307,11 +307,11 @@ def run_schedule(test_schedule, log_handler):
log.test_log.message(terminal.separator())
log.test_log.message(
"Running Tests from {} suites".format(len(test_schedule.suites)),
f"Running Tests from {len(test_schedule.suites)} suites",
bold=True,
)
log.test_log.message(
"Results will be stored in {}".format(configuration.config.result_path)
f"Results will be stored in {configuration.config.result_path}"
)
log.test_log.message(terminal.separator())

View File

@@ -32,7 +32,7 @@ import testlib.log as log
# TODO Refactor print logic out of this so the objects
# created are separate from print logic.
class QueryRunner(object):
class QueryRunner:
def __init__(self, test_schedule):
self.schedule = test_schedule

View File

@@ -189,7 +189,7 @@ class InternalSavedResults:
return pickle.load(f)
class XMLElement(object):
class XMLElement:
def write(self, file_):
self.begin(file_)
self.end(file_)
@@ -219,15 +219,13 @@ class XMLElement(object):
file_.write("</%s>" % self.name)
class XMLAttribute(object):
class XMLAttribute:
def __init__(self, name, value):
self.name = name
self.value = value
def write(self, file_):
file_.write(
"%s=%s" % (self.name, xml.sax.saxutils.quoteattr(self.value))
)
file_.write(f"{self.name}={xml.sax.saxutils.quoteattr(self.value)}")
class JUnitTestSuites(XMLElement):
@@ -328,10 +326,10 @@ class LargeFileElement(XMLElement):
def body(self, file_):
try:
with open(self.filename, "r") as f:
with open(self.filename) as f:
for line in f:
file_.write(xml.sax.saxutils.escape(line))
except IOError:
except OSError:
# TODO Better error logic, this is sometimes O.K.
# if there was no stdout/stderr captured for the test
#

View File

@@ -75,7 +75,7 @@ def compute_aggregate_result(iterable):
return Result(Result.Passed)
class TestParameters(object):
class TestParameters:
def __init__(self, test, suite):
self.test = test
self.suite = suite
@@ -188,10 +188,10 @@ class BrokenFixtureException(Exception):
'Exception raised building "%s" raised SkipException'
' for "%s".' % (trace, fixture.name, testitem.name)
)
super(BrokenFixtureException, self).__init__(self.msg)
super().__init__(self.msg)
class FixtureBuilder(object):
class FixtureBuilder:
def __init__(self, fixtures):
self.fixtures = fixtures
self.built_fixtures = []
@@ -211,7 +211,7 @@ class FixtureBuilder(object):
"Exception raised while setting up fixture for %s"
% testitem.uid
)
log.test_log.warn("%s\n%s" % (exc, msg))
log.test_log.warn(f"{exc}\n{msg}")
raise BrokenFixtureException(
fixture, testitem, traceback.format_exc()
@@ -232,4 +232,4 @@ class FixtureBuilder(object):
"Exception raised while tearing down fixture for %s"
% testitem.uid
)
log.test_log.warn("%s\n%s" % (exc, msg))
log.test_log.warn(f"{exc}\n{msg}")

View File

@@ -31,7 +31,7 @@ import testlib.helper as helper
import testlib.runner as runner_mod
class TestSuite(object):
class TestSuite:
"""
An object grouping a collection of tests. It provides tags which enable
filtering during list and run selection. All tests held in the suite must
@@ -54,7 +54,7 @@ class TestSuite(object):
tags = set()
def __new__(klass, *args, **kwargs):
obj = super(TestSuite, klass).__new__(klass)
obj = super().__new__(klass)
TestSuite.collector.collect(obj)
return obj

View File

@@ -86,7 +86,7 @@ except:
cap_string = null_cap_string
class ColorStrings(object):
class ColorStrings:
def __init__(self, cap_string):
for i, c in enumerate(color_names):
setattr(self, c, cap_string("setaf", i))
@@ -123,7 +123,7 @@ def terminal_size():
),
)
return w, h
except IOError:
except OSError:
# It's possible that in sandboxed environments the above ioctl is not
# allowed (e.g., some jenkins setups)
return 80, 24

View File

@@ -30,7 +30,7 @@ import testlib.helper as helper
import testlib.runner as runner_mod
class TestCase(object):
class TestCase:
"""
Base class for all tests.
@@ -47,7 +47,7 @@ class TestCase(object):
collector = helper.InstanceCollector()
def __new__(cls, *args, **kwargs):
obj = super(TestCase, cls).__new__(cls)
obj = super().__new__(cls)
TestCase.collector.collect(obj)
return obj

View File

@@ -32,7 +32,7 @@ import itertools
import testlib.configuration as configuration
class UID(object):
class UID:
sep = ":"
type_idx, path_idx = range(2)

View File

@@ -75,7 +75,7 @@ class LibraryMetadata:
self.status = status
class LoadedTestable(object):
class LoadedTestable:
"""
Base class for loaded test items.

View File

@@ -88,7 +88,7 @@ def TempFileSpawn(scons_env):
# Generate a string of the form:
# common/path/prefix/src1, src2 -> tgt1, tgt2
# to print while building.
class Transform(object):
class Transform:
# all specific color settings should be here and nowhere else
tool_color = termcap.Normal
pfx_color = termcap.Yellow

View File

@@ -53,7 +53,7 @@ def ConfigFile(env):
# operands are the name of the variable and a Value node containing the
# value of the variable.
def build_config_file(target, source, env):
(variable, value) = [s.get_contents().decode("utf-8") for s in source]
(variable, value) = (s.get_contents().decode("utf-8") for s in source)
with open(str(target[0].abspath), "w") as f:
print("#define", variable, value, file=f)
return None

View File

@@ -80,17 +80,17 @@ def CheckLinkFlag(context, flag, autoadd=True, set_for_shared=True):
def CheckMember(context, include, decl, member, include_quotes="<>"):
context.Message(f"Checking for member {member} in {decl}...")
text = """
#include %(header)s
int main(){
%(decl)s test;
(void)test.%(member)s;
#include {header}
int main(){{
{decl} test;
(void)test.{member};
return 0;
};
""" % {
"header": include_quotes[0] + include + include_quotes[1],
"decl": decl,
"member": member,
}
}};
""".format(
header=include_quotes[0] + include + include_quotes[1],
decl=decl,
member=member,
)
ret = context.TryCompile(text, extension=".cc")
context.Result(ret)

View File

@@ -45,32 +45,30 @@ from gem5_python_paths import extra_python_paths
def EnvDefaults(env):
# initialize the toolchain related env with host environment
use_vars = set(
[
"AS",
"AR",
"CC",
"CXX",
"HOME",
"CPATH",
"LD_LIBRARY_PATH",
"LIBRARY_PATH",
"PATH",
"PKG_CONFIG_PATH",
"PROTOC",
"PYTHONPATH",
"RANLIB",
"TERM", # for clang reports errors in color
"PYTHON_CONFIG", # gem5 specific build env
"CCFLAGS_EXTRA", # gem5 specific build env
"GEM5PY_CCFLAGS_EXTRA", # gem5 specific build env
"GEM5PY_LINKFLAGS_EXTRA", # gem5 specific build env
"LINKFLAGS_EXTRA", # gem5 specific build env
"LANG", # for work with non-ascii directory path
"LC_CTYPE", # for work with non-ascii directory path
"DISPLAY", # for gui program, ex kconfig guiconfig
]
)
use_vars = {
"AS",
"AR",
"CC",
"CXX",
"HOME",
"CPATH",
"LD_LIBRARY_PATH",
"LIBRARY_PATH",
"PATH",
"PKG_CONFIG_PATH",
"PROTOC",
"PYTHONPATH",
"RANLIB",
"TERM", # for clang reports errors in color
"PYTHON_CONFIG", # gem5 specific build env
"CCFLAGS_EXTRA", # gem5 specific build env
"GEM5PY_CCFLAGS_EXTRA", # gem5 specific build env
"GEM5PY_LINKFLAGS_EXTRA", # gem5 specific build env
"LINKFLAGS_EXTRA", # gem5 specific build env
"LANG", # for work with non-ascii directory path
"LC_CTYPE", # for work with non-ascii directory path
"DISPLAY", # for gui program, ex kconfig guiconfig
}
use_prefixes = [
"ASAN_", # address sanitizer symbolizer path and settings

View File

@@ -126,7 +126,7 @@ def resolve_tags(env, tags):
return tags
class SourceFilter(object):
class SourceFilter:
factories = {}
def __init__(self, predicate):
@@ -209,11 +209,11 @@ class SourceMeta(type):
particular type."""
def __init__(cls, name, bases, dict):
super(SourceMeta, cls).__init__(name, bases, dict)
super().__init__(name, bases, dict)
cls.all = SourceList()
class SourceItem(object, metaclass=SourceMeta):
class SourceItem(metaclass=SourceMeta):
"""Base object that encapsulates the notion of a source component for
gem5. This specifies a set of tags which help group components into groups
based on arbitrary properties."""

View File

@@ -100,7 +100,7 @@ def compareVersions(v1, v2):
return v
elif isinstance(v, str):
return list(
map(lambda x: int(re.match("\d+", x).group()), v.split("."))
map(lambda x: int(re.match(r"\d+", x).group()), v.split("."))
)
else:
raise TypeError()

View File

@@ -38,7 +38,6 @@
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import print_function
# Check for recent-enough Python and SCons versions.
try:

View File

@@ -43,7 +43,7 @@ from m5.objects.Gic import ArmInterruptPin, ArmPPI
from m5.util.fdthelper import *
class ProbeEvent(object):
class ProbeEvent:
def __init__(self, pmu, _eventId, obj, *listOfNames):
self.obj = obj
self.names = listOfNames
@@ -58,7 +58,7 @@ class ProbeEvent(object):
)
class SoftwareIncrement(object):
class SoftwareIncrement:
def __init__(self, pmu, _eventId):
self.eventId = _eventId
self.pmu = pmu

View File

@@ -61,7 +61,7 @@ debug = False
labelRE = re.compile(r"(?<!%)%\(([^\)]+)\)[sd]")
class Template(object):
class Template:
def __init__(self, parser, t):
self.parser = parser
self.template = t
@@ -95,12 +95,10 @@ class Template(object):
l for l in labelRE.findall(template) if l in d.snippets
]
snippets = dict(
[
(s, self.parser.mungeSnippet(d.snippets[s]))
for s in snippetLabels
]
)
snippets = {
s: self.parser.mungeSnippet(d.snippets[s])
for s in snippetLabels
}
myDict.update(snippets)
@@ -199,7 +197,7 @@ class Template(object):
# definition.
class Format(object):
class Format:
def __init__(self, id, params, code):
self.id = id
self.params = params
@@ -242,7 +240,7 @@ class Format(object):
# Special null format to catch an implicit-format instruction
# definition outside of any format block.
class NoFormat(object):
class NoFormat:
def __init__(self):
self.defaultInst = ""
@@ -265,7 +263,7 @@ class NoFormat(object):
# to allow explicit default clauses to override default default clauses.
class GenCode(object):
class GenCode:
# Constructor.
def __init__(
self,
@@ -355,7 +353,7 @@ def substBitOps(code):
if here < 0:
sys.exit("Didn't find '('!")
exprStart = here + 1
newExpr = r"bits(%s, %s, %s)" % (
newExpr = r"bits({}, {}, {})".format(
code[exprStart : exprEnd + 1],
match.group(1),
match.group(2),
@@ -413,7 +411,7 @@ instFlagRE = re.compile(r"Is.*")
opClassRE = re.compile(r".*Op|No_OpClass")
class InstObjParams(object):
class InstObjParams:
def __init__(
self, parser, mnem, class_name, base_class="", snippets={}, opt_args=[]
):
@@ -559,7 +557,7 @@ class ISAParser(Grammar):
self.fileNameStack = Stack()
symbols = ("makeList", "re")
self.exportContext = dict([(s, eval(s)) for s in symbols])
self.exportContext = {s: eval(s) for s in symbols}
self.exportContext.update(
{
"overrideInOperand": overrideInOperand,
@@ -594,7 +592,7 @@ class ISAParser(Grammar):
# Change the file suffix of a base filename:
# (e.g.) decoder.cc -> decoder-g.cc.inc for 'global' outputs
def suffixize(self, s, sec):
extn = re.compile("(\.[^\.]+)$") # isolate extension
extn = re.compile(r"(\.[^\.]+)$") # isolate extension
if self.namespace:
return extn.sub(r"-ns\1.inc", s) # insert some text on either side
else:
@@ -686,7 +684,7 @@ class ISAParser(Grammar):
# is guaranteed to have been written for parse to complete
f.write(f'#include "{fn}"\n')
extn = re.compile("(\.[^\.]+)$")
extn = re.compile(r"(\.[^\.]+)$")
# instruction constructors
splits = self.splits[self.get_file("decoder")]
@@ -1564,9 +1562,9 @@ StaticInstPtr
operandsREString = r"""
(?<!\w|:) # neg. lookbehind assertion: prevent partial matches
((%s)(?:_(%s))?) # match: operand with optional '_' then suffix
(({})(?:_({}))?) # match: operand with optional '_' then suffix
(?!\w) # neg. lookahead assertion: prevent partial matches
""" % (
""".format(
"|".join(operands),
"|".join(extensions),
)
@@ -1578,7 +1576,7 @@ StaticInstPtr
# Same as operandsREString, but extension is mandatory, and only two
# groups are returned (base and ext, not full name as above).
# Used for subtituting '_' for '.' to make C++ identifiers.
operandsWithExtREString = r"(?<!\w)(%s)_(%s)(?!\w)" % (
operandsWithExtREString = r"(?<!\w)({})_({})(?!\w)".format(
"|".join(operands),
"|".join(extensions),
)
@@ -1630,7 +1628,7 @@ StaticInstPtr
fname = matchobj.group("filename")
full_fname = os.path.normpath(os.path.join(dirname, fname))
contents = '##newfile "%s"\n%s\n##endfile\n' % (
contents = '##newfile "{}"\n{}\n##endfile\n'.format(
full_fname,
self.read_and_flatten(full_fname),
)
@@ -1642,7 +1640,7 @@ StaticInstPtr
current_dir = os.path.dirname(filename)
try:
contents = open(filename).read()
except IOError:
except OSError:
error(f'Error including file "{filename}"')
self.fileNameStack.push(LineTracker(filename))

View File

@@ -41,7 +41,7 @@ from .util import assignRE, commentRE, stringRE
from .util import error
class OperandList(object):
class OperandList:
"""Find all the operands in the given code block. Returns an operand
descriptor list (instance of class OperandList)."""

View File

@@ -46,7 +46,7 @@ def overrideInOperand(func):
overrideInOperand.overrides = dict()
class OperandDesc(object):
class OperandDesc:
def __init__(
self, base_cls, dflt_ext, reg_spec, flags=None, sort_pri=None
):
@@ -111,7 +111,7 @@ class OperandDesc(object):
self.attrs["base_name"] = name
class Operand(object):
class Operand:
"""Base class for operand descriptors. An instance of this class
(or actually a class derived from this one) represents a specific
operand for a code block (e.g, "Rc.sq" as a dest). Intermediate

View File

@@ -156,7 +156,7 @@ def backtrace(filename_stack):
#
class LineTracker(object):
class LineTracker:
def __init__(self, filename, lineno=1):
self.filename = filename
self.lineno = lineno

View File

@@ -88,18 +88,18 @@ class Rom(MicroContainer):
##########################################################################
class Label(object):
class Label:
def __init__(self):
self.extern = False
self.name = ""
class Block(object):
class Block:
def __init__(self):
self.statements = []
class Statement(object):
class Statement:
def __init__(self):
self.is_microop = False
self.is_directive = False
@@ -570,7 +570,7 @@ def p_error(t):
error(0, "unknown syntax error", True)
class MicroAssembler(object):
class MicroAssembler:
def __init__(self, macro_type, microops, rom=None, rom_macroop_type=None):
self.lexer = lex.lex()
self.parser = yacc.yacc(write_tables=False)

View File

@@ -27,17 +27,17 @@
from micro_asm import MicroAssembler, CombinationalMacroop, RomMacroop, Rom
class Bah(object):
class Bah:
def __init__(self):
self.mnemonic = "bah"
class Bah_Tweaked(object):
class Bah_Tweaked:
def __init__(self):
self.mnemonic = "bah_tweaked"
class Hoop(object):
class Hoop:
def __init__(self, first_param, second_param):
self.mnemonic = f"hoop_{first_param}_{second_param}"
@@ -45,7 +45,7 @@ class Hoop(object):
return f"{self.mnemonic}"
class Dah(object):
class Dah:
def __init__(self):
self.mnemonic = "dah"

View File

@@ -293,8 +293,7 @@ class BaseCPU(ClockedObject):
# Generate nodes from the BaseCPU children (hence under the root node,
# and don't add them as subnode). Please note: this is mainly needed
# for the ISA class, to generate the PMU entry in the DTB.
for child_node in self.recurseDeviceTree(state):
yield child_node
yield from self.recurseDeviceTree(state)
def __init__(self, **kwargs):
super().__init__(**kwargs)

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Jason Lowe-Power
# All rights reserved.
#

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Jason Lowe-Power
# All rights reserved.
#

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Jason Lowe-Power
# All rights reserved.
#

View File

@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2017 Jason Lowe-Power
# All rights reserved.
#

View File

@@ -47,7 +47,7 @@ class DRAMSys(AbstractMemory):
add_citation(
DRAMSys,
"""@inproceedings{Steiner:2020:dramsys4,
r"""@inproceedings{Steiner:2020:dramsys4,
author = {Lukas Steiner and
Matthias Jung and
Felipe S. Prado and

View File

@@ -45,7 +45,7 @@ from m5.objects.IndexingPolicies import *
from m5.objects.ReplacementPolicies import *
class HWPProbeEvent(object):
class HWPProbeEvent:
def __init__(self, prefetcher, obj, *listOfNames):
self.obj = obj
self.prefetcher = prefetcher

View File

@@ -41,7 +41,7 @@ class DeferEnqueueingStatementAST(StatementAST):
self.statements = statements
def __repr__(self):
return "[DeferEnqueueingStatementAst: %s %s %s]" % (
return "[DeferEnqueueingStatementAst: {} {} {}]".format(
self.queue_name,
self.type_ast.ident,
self.statements,

View File

@@ -49,7 +49,7 @@ class EnqueueStatementAST(StatementAST):
self.statements = statements
def __repr__(self):
return "[EnqueueStatementAst: %s %s %s]" % (
return "[EnqueueStatementAst: {} {} {}]".format(
self.queue_name,
self.type_ast.ident,
self.statements,

View File

@@ -47,7 +47,7 @@ class EnumDeclAST(DeclAST):
ident = f"{parent}_{self.type_ast.ident}"
else:
ident = self.type_ast.ident
s = set((f"{ident}.hh", f"{ident}.cc"))
s = {f"{ident}.hh", f"{ident}.cc"}
return s
def generate(self):

View File

@@ -42,15 +42,13 @@ class MachineAST(DeclAST):
return f"[Machine: {self.ident!r}]"
def files(self, parent=None):
s = set(
(
f"{self.ident}_Controller.cc",
f"{self.ident}_Controller.hh",
f"{self.ident}_Controller.py",
f"{self.ident}_Transitions.cc",
f"{self.ident}_Wakeup.cc",
)
)
s = {
f"{self.ident}_Controller.cc",
f"{self.ident}_Controller.hh",
f"{self.ident}_Controller.py",
f"{self.ident}_Transitions.cc",
f"{self.ident}_Wakeup.cc",
}
s |= self.decls.files(self.ident)
return s

View File

@@ -77,7 +77,7 @@ class MemberMethodCallExprAST(MethodCallExprAST):
self.obj_expr_ast = obj_expr_ast
def __repr__(self):
return "[MethodCallExpr: %r%r %r]" % (
return "[MethodCallExpr: {!r}{!r} {!r}]".format(
self.proc_name,
self.obj_expr_ast,
self.expr_ast_vec,

View File

@@ -109,8 +109,8 @@ class InfixOperatorExprAST(ExprAST):
if output == None:
self.error(
"Type mismatch: operands ({0}, {1}) for operator "
"'{2}' failed to match with the expected types".format(
"Type mismatch: operands ({}, {}) for operator "
"'{}' failed to match with the expected types".format(
ltype, rtype, self.op
)
)

View File

@@ -40,11 +40,13 @@ class PeekStatementAST(StatementAST):
self.method = method
def __repr__(self):
return "[PeekStatementAST: %r queue_name: %r type: %r %r]" % (
self.method,
self.queue_name,
self.type_ast,
self.statements,
return (
"[PeekStatementAST: {!r} queue_name: {!r} type: {!r} {!r}]".format(
self.method,
self.queue_name,
self.type_ast,
self.statements,
)
)
def generate(self, code, return_type, **kwargs):

View File

@@ -46,7 +46,7 @@ class StateDeclAST(DeclAST):
ident = f"{parent}_{self.type_ast.ident}"
else:
ident = self.type_ast.ident
s = set((f"{ident}.hh", f"{ident}.cc"))
s = {f"{ident}.hh", f"{ident}.cc"}
return s
def generate(self):

View File

@@ -47,7 +47,7 @@ class TypeDeclAST(DeclAST):
ident = f"{parent}_{self.type_ast.ident}"
else:
ident = self.type_ast.ident
return set((f"{ident}.hh", f"{ident}.cc"))
return {f"{ident}.hh", f"{ident}.cc"}
def generate(self):
ident = str(self.type_ast)

View File

@@ -86,7 +86,7 @@ class SLICC(Grammar):
self.symtab.writeHTMLFiles(html_path)
def files(self):
f = set(["Types.hh"])
f = {"Types.hh"}
f |= self.decl_list.files()
@@ -284,7 +284,7 @@ class SLICC(Grammar):
def p_decl__protocol(self, p):
"decl : PROTOCOL STRING SEMI"
if self.protocol:
msg = "Protocol can only be set once! Error at %s:%s\n" % (
msg = "Protocol can only be set once! Error at {}:{}\n".format(
self.current_source,
self.current_line,
)

View File

@@ -973,8 +973,7 @@ $c_ident::regStats()
# check if Events/States have profiling qualifiers flags for
# inTransLatHist and outTransLatHist stats.
ev_ident_list = [
"%s_Event_%s" % (ident, ev.ident)
for ev in self.event_stats_out_trans
f"{ident}_Event_{ev.ident}" for ev in self.event_stats_out_trans
]
ev_ident_str = "{" + ",".join(ev_ident_list) + "}"
code(
@@ -983,8 +982,7 @@ $c_ident::regStats()
"""
)
ev_ident_list = [
"%s_Event_%s" % (ident, ev.ident)
for ev in self.event_stats_in_trans
f"{ident}_Event_{ev.ident}" for ev in self.event_stats_in_trans
]
ev_ident_str = "{" + ",".join(ev_ident_list) + "}"
code(
@@ -994,13 +992,13 @@ $c_ident::regStats()
)
kv_ident_list = []
for ev in self.event_stats_in_trans:
key_ident = "%s_Event_%s" % (ident, ev.ident)
key_ident = f"{ident}_Event_{ev.ident}"
val_ident_lst = [
"%s_State_%s" % (ident, trans.state.ident)
f"{ident}_State_{trans.state.ident}"
for trans in self.transitions_per_ev[ev]
]
val_ident_str = "{" + ",".join(val_ident_lst) + "}"
kv_ident_list.append("{%s, %s}" % (key_ident, val_ident_str))
kv_ident_list.append(f"{{{key_ident}, {val_ident_str}}}")
key_ident_str = "{" + ",".join(kv_ident_list) + "}"
code(
"""
@@ -1734,7 +1732,7 @@ ${ident}_Controller::doTransitionWorker(${ident}_Event event,
cases = OrderedDict()
for trans in self.transitions:
case_string = "%s_State_%s, %s_Event_%s" % (
case_string = "{}_State_{}, {}_Event_{}".format(
self.ident,
trans.state.ident,
self.ident,
@@ -1778,10 +1776,10 @@ if (!{key.code}.areNSlotsAvailable({val}, clockEdge()))
# Check all of the request_types for resource constraints
for request_type in request_types:
val = """
if (!checkResourceAvailable(%s_RequestType_%s, addr)) {
if (!checkResourceAvailable({}_RequestType_{}, addr)) {{
return TransitionResult_ResourceStall;
}
""" % (
}}
""".format(
self.ident,
request_type.ident,
)

View File

@@ -43,7 +43,7 @@ def makeDir(path):
os.makedirs(path, exist_ok=True)
class SymbolTable(object):
class SymbolTable:
def __init__(self, slicc):
self.slicc = slicc

View File

@@ -72,7 +72,7 @@ class Transition(Symbol):
self.resources[var] = str(num)
def __repr__(self):
return "[Transition: (%r, %r) -> %r, %r]" % (
return "[Transition: ({!r}, {!r}) -> {!r}, {!r}]".format(
self.state,
self.event,
self.nextState,

View File

@@ -28,7 +28,7 @@ import os
import sys
class PairContainer(object):
class PairContainer:
def __init__(self, pairs=None):
self.pairs = {}
if pairs:
@@ -47,7 +47,7 @@ class PairContainer(object):
return self.pairs.get(item, failobj)
class Location(object):
class Location:
def __init__(self, filename, lineno, no_warning=False):
if not isinstance(filename, str):
raise AttributeError(

View File

@@ -91,7 +91,7 @@ class LupvBoard(AbstractSystemBoard, KernelDiskWorkload):
cache_hierarchy: AbstractCacheHierarchy,
) -> None:
if cache_hierarchy.is_ruby():
raise EnvironmentError("RiscvBoard is not compatible with Ruby")
raise OSError("RiscvBoard is not compatible with Ruby")
if processor.get_isa() != ISA.RISCV:
raise Exception(

View File

@@ -66,7 +66,7 @@ class AbstractNode(Cache_Controller):
# TODO: I don't love that we have to pass in the cache line size.
# However, we need some way to set the index bits
def __init__(self, network: RubyNetwork, cache_line_size: int):
super(AbstractNode, self).__init__()
super().__init__()
# Note: Need to call versionCount method on *this* class, not the
# potentially derived class

View File

@@ -54,7 +54,7 @@ class AbstractProcessor(SubSystem):
if cores:
# In the stdlib we assume the system processor conforms to a single
# ISA target.
assert len(set(core.get_isa() for core in cores)) == 1
assert len({core.get_isa() for core in cores}) == 1
self.cores = cores
self._isa = cores[0].get_isa()
else:

View File

@@ -62,7 +62,7 @@ def get_cpu_type_from_str(input: str) -> CPUTypes:
if input.lower() == cpu_type.value:
return cpu_type
valid_cpu_types_list_str = str()
valid_cpu_types_list_str = ""
for cpu_type_str in get_cpu_types_str_set():
valid_cpu_types_list_str += f"{os.linesep}{cpu_type_str}"

View File

@@ -63,7 +63,7 @@ class SwitchableProcessor(AbstractProcessor):
# In the stdlib we assume the system processor conforms to a single
# ISA target.
assert len(set(core.get_isa() for core in self._current_cores)) == 1
assert len({core.get_isa() for core in self._current_cores}) == 1
super().__init__(isa=self._current_cores[0].get_isa())
for name, core_list in self._switchable_cores.items():
@@ -113,8 +113,7 @@ class SwitchableProcessor(AbstractProcessor):
def _all_cores(self):
for core_list in self._switchable_cores.values():
for core in core_list:
yield core
yield from core_list
def switch_to_processor(self, switchable_core_key: str):
# Run various checks.

View File

@@ -80,7 +80,7 @@ def get_isa_from_str(input: str) -> ISA:
if input.lower() == isa.value:
return isa
valid_isas_str_list = str()
valid_isas_str_list = ""
for isa_str in get_isas_str_set():
valid_isas_str_list += f"{os.linesep}{isa_str}"

View File

@@ -41,7 +41,7 @@ def getFileContent(file_path: Path) -> Dict:
:return: The content of the file
"""
if file_path.exists():
with open(file_path, "r") as file:
with open(file_path) as file:
return json.load(file)
else:
raise Exception(f"File not found at {file_path}")

View File

@@ -686,8 +686,7 @@ class SuiteResource(AbstractResource):
:yields: A generator that iterates over the workloads in the suite.
"""
for workload in self._workloads.keys():
yield workload
yield from self._workloads.keys()
def __len__(self):
"""

View File

@@ -48,8 +48,7 @@ def warn_default_decorator(gen: Generator, type: str, effect: str):
f"No behavior was set by the user for {type}."
f" Default behavior is {effect}."
)
for value in gen(*args, **kw_args):
yield value
yield from gen(*args, **kw_args)
return wrapped_generator

View File

@@ -32,7 +32,7 @@ class FileLockException(Exception):
pass
class FileLock(object):
class FileLock:
"""A file locking mechanism that has context-manager support so
you can use it in a with statement. This should be relatively cross
compatible as it doesn't rely on msvcrt or fcntl for the locking.

View File

@@ -42,7 +42,7 @@ class ByteCodeLoader(importlib.abc.Loader):
# Simple importer that allows python to import data from a dict of
# code objects. The keys are the module path, and the items are the
# filename and bytecode of the file.
class CodeImporter(object):
class CodeImporter:
def __init__(self):
self.modules = {}
override_var = os.environ.get("M5_OVERRIDE_PY_SOURCE", "false")
@@ -61,7 +61,7 @@ class CodeImporter(object):
abspath, code = self.modules[fullname]
if self.override and os.path.exists(abspath):
src = open(abspath, "r").read()
src = open(abspath).read()
code = compile(src, abspath, "exec")
is_package = os.path.basename(abspath) == "__init__.py"

View File

@@ -521,7 +521,7 @@ def cxxMethod(*args, **kwargs):
# This class holds information about each simobject parameter
# that should be displayed on the command line for use in the
# configuration system.
class ParamInfo(object):
class ParamInfo:
def __init__(self, type, desc, type_str, example, default_val, access_str):
self.type = type
self.desc = desc
@@ -546,7 +546,7 @@ class SimObjectCliWrapperException(Exception):
super().__init__(message)
class SimObjectCliWrapper(object):
class SimObjectCliWrapper:
"""
Wrapper class to restrict operations that may be done
from the command line on SimObjects.
@@ -609,7 +609,7 @@ class SimObjectCliWrapper(object):
# The SimObject class is the root of the special hierarchy. Most of
# the code in this class deals with the configuration hierarchy itself
# (parent/child node relationships).
class SimObject(object, metaclass=MetaSimObject):
class SimObject(metaclass=MetaSimObject):
# Specify metaclass. Any class inheriting from SimObject will
# get this metaclass.
type = "SimObject"
@@ -874,7 +874,7 @@ class SimObject(object, metaclass=MetaSimObject):
hr_value = value
value = param.convert(value)
except Exception as e:
msg = "%s\nError setting param %s.%s to %s\n" % (
msg = "{}\nError setting param {}.{} to {}\n".format(
e,
self.__class__.__name__,
attr,
@@ -1253,8 +1253,7 @@ class SimObject(object, metaclass=MetaSimObject):
# it based on the key (name) to ensure the order is the same
# on all hosts
for name, child in sorted(self._children.items()):
for obj in child.descendants():
yield obj
yield from child.descendants()
# Call C++ to create C++ object corresponding to this object
def createCCObject(self):
@@ -1287,8 +1286,7 @@ class SimObject(object, metaclass=MetaSimObject):
def recurseDeviceTree(self, state):
for child in self._children.values():
for item in child: # For looping over SimObjectVectors
for dt in item.generateDeviceTree(state):
yield dt
yield from item.generateDeviceTree(state)
# On a separate method otherwise certain buggy Python versions
# would fail with: SyntaxError: unqualified exec is not allowed

View File

@@ -113,7 +113,7 @@ gem5_citations = """@article{Binkert:2011:gem5,
Mohammad Alian and
Rico Amslinger and
Matteo Andreozzi and
Adri{\`{a}} Armejach and
Adri{\\`{a}} Armejach and
Nils Asmussen and
Srikant Bharadwaj and
Gabe Black and

Some files were not shown because too many files have changed in this diff Show More