From e73655d038cdfa68964109044e33c9a6e7d85ac9 Mon Sep 17 00:00:00 2001 From: Giacomo Travaglini Date: Wed, 15 Mar 2023 13:34:46 +0000 Subject: [PATCH] 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 Reviewed-on: https://gem5-review.googlesource.com/c/public/gem5/+/68957 Maintainer: Bobby Bruce Tested-by: kokoro Reviewed-by: Bobby Bruce --- configs/common/CacheConfig.py | 6 +- configs/common/FileSystemConfig.py | 10 +- configs/common/GPUTLBConfig.py | 4 +- configs/common/ObjectList.py | 12 +- configs/common/Options.py | 3 +- configs/common/Simulation.py | 18 +-- configs/common/SysPaths.py | 4 +- configs/common/cpu2000.py | 39 +++--- configs/deprecated/example/fs.py | 6 +- configs/deprecated/example/se.py | 3 +- configs/example/apu_se.py | 18 +-- configs/example/arm/baremetal.py | 4 +- configs/example/arm/fs_bigLITTLE.py | 6 +- configs/example/arm/fs_power.py | 2 +- configs/example/arm/ruby_fs.py | 12 +- configs/example/arm/starter_fs.py | 12 +- .../gem5_library/x86-gapbs-benchmarks.py | 8 +- .../gem5_library/x86-npb-benchmarks.py | 2 +- .../gem5_library/x86-parsec-benchmarks.py | 5 +- .../x86-spec-cpu2006-benchmarks.py | 4 +- .../x86-spec-cpu2017-benchmarks.py | 4 +- configs/example/gpufs/DisjointNetwork.py | 8 +- configs/example/gpufs/hip_cookbook.py | 10 +- configs/example/gpufs/hip_rodinia.py | 10 +- configs/example/gpufs/hip_samples.py | 10 +- configs/example/gpufs/runfs.py | 2 +- configs/example/gpufs/vega10_kvm.py | 10 +- configs/example/hsaTopology.py | 72 +++++----- configs/example/lupv/run_lupv.py | 4 +- configs/example/memcheck.py | 2 +- configs/example/memtest.py | 5 +- configs/example/read_config.py | 10 +- configs/example/riscv/fs_linux.py | 2 +- configs/example/sst/riscv_fs.py | 2 +- configs/learning_gem5/part1/caches.py | 8 +- configs/learning_gem5/part3/ruby_test.py | 4 +- configs/learning_gem5/part3/simple_ruby.py | 4 +- configs/ruby/CHI.py | 2 +- configs/ruby/CHI_config.py | 2 +- configs/ruby/Ruby.py | 12 +- configs/topologies/CustomMesh.py | 12 +- .../gem5_scons/builders/switching_headers.py | 2 +- site_scons/gem5_scons/configure.py | 10 +- site_scons/site_tools/git.py | 2 +- src/arch/arm/ArmSystem.py | 2 +- src/arch/arm/fastmodel/FastModel.py | 4 +- src/arch/arm/fastmodel/arm_fast_model.py | 12 +- src/arch/isa_parser/isa_parser.py | 81 ++++++----- src/arch/isa_parser/operand_list.py | 3 +- src/arch/isa_parser/operand_types.py | 22 +-- src/arch/micro_asm.py | 34 ++--- src/arch/micro_asm_test.py | 4 +- src/arch/x86/bios/IntelMP.py | 3 +- src/arch/x86/isa/insts/__init__.py | 2 +- .../x86/isa/insts/general_purpose/__init__.py | 2 +- .../general_purpose/arithmetic/__init__.py | 2 +- .../compare_and_test/__init__.py | 2 +- .../control_transfer/__init__.py | 2 +- .../data_conversion/__init__.py | 2 +- .../general_purpose/data_transfer/__init__.py | 2 +- .../insts/general_purpose/flags/__init__.py | 2 +- .../general_purpose/input_output/__init__.py | 2 +- .../rotate_and_shift/__init__.py | 2 +- .../insts/general_purpose/string/__init__.py | 2 +- src/arch/x86/isa/insts/simd128/__init__.py | 2 +- .../insts/simd128/floating_point/__init__.py | 2 +- .../floating_point/arithmetic/__init__.py | 2 +- .../floating_point/compare/__init__.py | 2 +- .../data_conversion/__init__.py | 2 +- .../data_reordering/__init__.py | 2 +- .../floating_point/data_transfer/__init__.py | 2 +- .../floating_point/logical/__init__.py | 2 +- .../x86/isa/insts/simd128/integer/__init__.py | 2 +- .../simd128/integer/arithmetic/__init__.py | 2 +- .../insts/simd128/integer/compare/__init__.py | 2 +- .../integer/data_conversion/__init__.py | 2 +- .../integer/data_reordering/__init__.py | 2 +- .../simd128/integer/data_transfer/__init__.py | 2 +- .../insts/simd128/integer/logical/__init__.py | 2 +- .../save_and_restore_state/__init__.py | 2 +- .../insts/simd128/integer/shift/__init__.py | 2 +- src/arch/x86/isa/insts/simd64/__init__.py | 2 +- .../insts/simd64/floating_point/__init__.py | 2 +- .../floating_point/arithmetic/__init__.py | 2 +- .../simd64/floating_point/compare/__init__.py | 2 +- .../x86/isa/insts/simd64/integer/__init__.py | 2 +- .../simd64/integer/arithmetic/__init__.py | 2 +- .../insts/simd64/integer/compare/__init__.py | 2 +- .../integer/data_reordering/__init__.py | 2 +- .../simd64/integer/data_transfer/__init__.py | 2 +- .../insts/simd64/integer/logical/__init__.py | 2 +- .../insts/simd64/integer/shift/__init__.py | 2 +- src/arch/x86/isa/insts/system/__init__.py | 2 +- src/arch/x86/isa/insts/x87/__init__.py | 2 +- .../x86/isa/insts/x87/arithmetic/__init__.py | 2 +- .../insts/x87/compare_and_test/__init__.py | 2 +- .../x86/isa/insts/x87/control/__init__.py | 2 +- .../data_transfer_and_conversion/__init__.py | 2 +- .../isa/insts/x87/load_constants/__init__.py | 2 +- .../insts/x87/stack_management/__init__.py | 2 +- .../x87/transcendental_functions/__init__.py | 2 +- src/cpu/BaseCPU.py | 8 +- src/cpu/testers/traffic_gen/BaseTrafficGen.py | 2 +- src/dev/Device.py | 2 +- src/dev/arm/GenericTimer.py | 2 +- src/dev/arm/RealView.py | 6 +- src/dev/arm/SMMUv3.py | 2 +- src/dev/arm/css/MHU.py | 2 +- src/mem/slicc/ast/ActionDeclAST.py | 2 +- src/mem/slicc/ast/AssignStatementAST.py | 2 +- .../slicc/ast/CheckAllocateStatementAST.py | 2 +- src/mem/slicc/ast/CheckProbeStatementAST.py | 2 +- src/mem/slicc/ast/DeclListAST.py | 2 +- src/mem/slicc/ast/EnumDeclAST.py | 8 +- src/mem/slicc/ast/EnumExprAST.py | 2 +- src/mem/slicc/ast/ExprStatementAST.py | 2 +- src/mem/slicc/ast/FormalParamAST.py | 12 +- src/mem/slicc/ast/FuncCallExprAST.py | 16 +-- src/mem/slicc/ast/FuncDeclAST.py | 6 +- src/mem/slicc/ast/IfStatementAST.py | 2 +- src/mem/slicc/ast/InPortDeclAST.py | 2 +- src/mem/slicc/ast/IsValidPtrExprAST.py | 2 +- src/mem/slicc/ast/LiteralExprAST.py | 4 +- src/mem/slicc/ast/LocalVariableAST.py | 8 +- src/mem/slicc/ast/MachineAST.py | 14 +- src/mem/slicc/ast/MemberExprAST.py | 5 +- src/mem/slicc/ast/MethodCallExprAST.py | 8 +- src/mem/slicc/ast/NewExprAST.py | 2 +- src/mem/slicc/ast/ObjDeclAST.py | 11 +- src/mem/slicc/ast/OperatorExprAST.py | 6 +- src/mem/slicc/ast/OutPortDeclAST.py | 2 +- src/mem/slicc/ast/PairAST.py | 2 +- src/mem/slicc/ast/PairListAST.py | 2 +- src/mem/slicc/ast/ReturnStatementAST.py | 2 +- src/mem/slicc/ast/StallAndWaitStatementAST.py | 2 +- src/mem/slicc/ast/StateDeclAST.py | 10 +- src/mem/slicc/ast/StatementListAST.py | 2 +- src/mem/slicc/ast/StaticCastAST.py | 2 +- src/mem/slicc/ast/TransitionDeclAST.py | 9 +- src/mem/slicc/ast/TypeDeclAST.py | 6 +- src/mem/slicc/ast/TypeFieldEnumAST.py | 4 +- src/mem/slicc/ast/TypeFieldStateAST.py | 4 +- src/mem/slicc/ast/VarExprAST.py | 2 +- src/mem/slicc/ast/WakeupPortStatementAST.py | 2 +- src/mem/slicc/main.py | 2 +- src/mem/slicc/parser.py | 2 +- src/mem/slicc/symbols/Action.py | 2 +- src/mem/slicc/symbols/Event.py | 2 +- src/mem/slicc/symbols/Func.py | 9 +- src/mem/slicc/symbols/RequestType.py | 2 +- src/mem/slicc/symbols/State.py | 2 +- src/mem/slicc/symbols/StateMachine.py | 117 ++++++++-------- src/mem/slicc/symbols/Symbol.py | 2 +- src/mem/slicc/symbols/SymbolTable.py | 6 +- src/mem/slicc/symbols/Transition.py | 2 +- src/mem/slicc/symbols/Type.py | 22 +-- src/mem/slicc/symbols/Var.py | 2 +- src/mem/slicc/util.py | 10 +- .../gem5/components/boards/arm_board.py | 2 +- .../boards/experimental/lupv_board.py | 2 +- .../gem5/components/boards/riscv_board.py | 2 +- .../riscvmatched/riscvmatched_board.py | 2 +- src/python/gem5/resources/downloader.py | 26 ++-- src/python/gem5/simulate/exit_event.py | 2 +- src/python/gem5/utils/filelock.py | 4 +- .../gem5/utils/multiprocessing/context.py | 2 +- src/python/gem5/utils/requires.py | 2 +- src/python/importer.py | 2 +- src/python/m5/SimObject.py | 52 +++---- src/python/m5/debug.py | 6 +- src/python/m5/event.py | 6 +- src/python/m5/ext/pyfdt/pyfdt.py | 44 +++--- src/python/m5/internal/params.py | 2 +- src/python/m5/main.py | 18 +-- src/python/m5/objects/__init__.py | 2 +- src/python/m5/options.py | 4 +- src/python/m5/params.py | 130 ++++++++---------- src/python/m5/proxy.py | 4 +- src/python/m5/simulate.py | 19 ++- src/python/m5/stats/__init__.py | 23 ++-- src/python/m5/ticks.py | 4 +- src/python/m5/util/__init__.py | 2 +- src/python/m5/util/convert.py | 26 ++-- src/python/m5/util/dot_writer.py | 2 +- src/python/m5/util/dot_writer_ruby.py | 2 +- src/python/m5/util/pybind.py | 7 +- src/systemc/tests/tlm/endian_conv/testall.py | 19 +-- src/systemc/tests/verify.py | 14 +- tests/configs/dram-lowp.py | 2 +- tests/gem5/arm-boot-tests/test_linux_boot.py | 4 +- tests/gem5/configs/arm_boot_exit_run.py | 4 +- tests/gem5/configs/boot_kvm_fork_run.py | 4 +- tests/gem5/configs/boot_kvm_switch_exit.py | 4 +- tests/gem5/configs/checkpoint.py | 4 +- tests/gem5/configs/parsec_disk_run.py | 16 +-- tests/gem5/configs/riscv_boot_exit_run.py | 2 +- tests/gem5/configs/switcheroo.py | 4 +- tests/gem5/configs/x86_boot_exit_run.py | 4 +- tests/gem5/cpu_tests/test.py | 4 +- tests/gem5/fixture.py | 6 +- .../gem5/kvm-fork-tests/test_kvm_fork_run.py | 4 +- .../kvm-switch-tests/test_kvm_cpu_switch.py | 4 +- .../run_replacement_policy_test.py | 4 +- .../gem5/riscv-boot-tests/test_linux_boot.py | 4 +- tests/gem5/suite.py | 4 +- tests/gem5/traffic_gen/simple_traffic_run.py | 4 +- tests/gem5/verifier.py | 3 +- tests/gem5/x86-boot-tests/test_linux_boot.py | 4 +- tests/run.py | 6 +- util/checkpoint-tester.py | 4 +- util/cpt_upgrader.py | 31 ++--- util/cpt_upgraders/arm-hdlcd-upgrade.py | 2 +- util/cpt_upgraders/etherswitch.py | 2 +- util/cpt_upgraders/isa-is-simobject.py | 2 +- util/cpt_upgraders/process-fdmap-rename.py | 4 +- util/decode_inst_dep_trace.py | 20 +-- util/decode_packet_trace.py | 11 +- util/find_copyrights.py | 12 +- .../artifact/gem5art/artifact/_artifactdb.py | 2 +- .../artifact/gem5art/artifact/artifact.py | 10 +- util/gem5art/run/gem5art/run.py | 6 +- util/gem5art/run/tests/test_run.py | 2 +- util/gem5img.py | 18 +-- util/gen_arm_fs_files.py | 22 +-- util/git-pre-commit.py | 6 +- util/maint/list_changes.py | 4 +- util/maint/show_changes_by_file.py | 10 +- util/minorview/model.py | 12 +- util/minorview/point.py | 4 +- util/o3-pipeview.py | 4 +- util/on-chip-network-power-area.py | 12 +- util/oprofile-top.py | 4 +- util/plot_dram/PlotPowerStates.py | 2 +- util/plot_dram/dram_sweep_plot.py | 2 +- util/plot_dram/lowp_dram_sweep_plot.py | 2 +- util/streamline/m5stats2streamline.py | 13 +- util/style.py | 5 +- util/style/region.py | 16 +-- util/style/repo.py | 10 +- util/style/sort_includes.py | 4 +- util/style/verifiers.py | 4 +- util/update-copyright.py | 2 +- 242 files changed, 814 insertions(+), 1002 deletions(-) diff --git a/configs/common/CacheConfig.py b/configs/common/CacheConfig.py index 63ffe6765c..7a191570e3 100644 --- a/configs/common/CacheConfig.py +++ b/configs/common/CacheConfig.py @@ -60,15 +60,15 @@ def _get_hwp(hwp_option): def _get_cache_opts(level, options): opts = {} - size_attr = "{}_size".format(level) + size_attr = f"{level}_size" if hasattr(options, size_attr): opts["size"] = getattr(options, size_attr) - assoc_attr = "{}_assoc".format(level) + assoc_attr = f"{level}_assoc" if hasattr(options, assoc_attr): opts["assoc"] = getattr(options, assoc_attr) - prefetcher_attr = "{}_hwp_type".format(level) + prefetcher_attr = f"{level}_hwp_type" if hasattr(options, prefetcher_attr): opts["prefetcher"] = _get_hwp(getattr(options, prefetcher_attr)) diff --git a/configs/common/FileSystemConfig.py b/configs/common/FileSystemConfig.py index 066eb9a811..9c6647c861 100644 --- a/configs/common/FileSystemConfig.py +++ b/configs/common/FileSystemConfig.py @@ -51,7 +51,7 @@ from shutil import rmtree, copyfile def hex_mask(terms): dec_mask = reduce(operator.or_, [2**i for i in terms], 0) - return "%08x" % dec_mask + return f"{dec_mask:08x}" def file_append(path, contents): @@ -252,13 +252,13 @@ def _redirect_paths(options): # Redirect filesystem syscalls from src to the first matching dests redirect_paths = [ RedirectPath( - app_path="/proc", host_paths=["%s/fs/proc" % m5.options.outdir] + app_path="/proc", host_paths=[f"{m5.options.outdir}/fs/proc"] ), RedirectPath( - app_path="/sys", host_paths=["%s/fs/sys" % m5.options.outdir] + app_path="/sys", host_paths=[f"{m5.options.outdir}/fs/sys"] ), RedirectPath( - app_path="/tmp", host_paths=["%s/fs/tmp" % m5.options.outdir] + app_path="/tmp", host_paths=[f"{m5.options.outdir}/fs/tmp"] ), ] @@ -275,7 +275,7 @@ def _redirect_paths(options): if chroot: redirect_paths.append( RedirectPath( - app_path="/", host_paths=["%s" % os.path.expanduser(chroot)] + app_path="/", host_paths=[f"{os.path.expanduser(chroot)}"] ) ) diff --git a/configs/common/GPUTLBConfig.py b/configs/common/GPUTLBConfig.py index b70d6c5516..e59cd00da4 100644 --- a/configs/common/GPUTLBConfig.py +++ b/configs/common/GPUTLBConfig.py @@ -204,8 +204,8 @@ def config_tlb_hierarchy( # add the different TLB levels to the system # Modify here if you want to make the TLB hierarchy a child of # the shader. - exec("system.%s = TLB_array" % system_TLB_name) - exec("system.%s = Coalescer_array" % system_Coalescer_name) + exec(f"system.{system_TLB_name} = TLB_array") + exec(f"system.{system_Coalescer_name} = Coalescer_array") # =========================================================== # Specify the TLB hierarchy (i.e., port connections) diff --git a/configs/common/ObjectList.py b/configs/common/ObjectList.py index ce529677e7..4b862db9e8 100644 --- a/configs/common/ObjectList.py +++ b/configs/common/ObjectList.py @@ -65,22 +65,18 @@ class ObjectList(object): sub_cls = self._sub_classes[real_name] return sub_cls except KeyError: - print( - "{} is not a valid sub-class of {}.".format( - name, self.base_cls - ) - ) + print(f"{name} is not a valid sub-class of {self.base_cls}.") raise def print(self): """Print a list of available sub-classes and aliases.""" - print("Available {} classes:".format(self.base_cls)) + print(f"Available {self.base_cls} classes:") doc_wrapper = TextWrapper( initial_indent="\t\t", subsequent_indent="\t\t" ) for name, cls in list(self._sub_classes.items()): - print("\t{}".format(name)) + print(f"\t{name}") # Try to extract the class documentation from the class help # string. @@ -92,7 +88,7 @@ class ObjectList(object): if self._aliases: print("\Aliases:") for alias, target in list(self._aliases.items()): - print("\t{} => {}".format(alias, target)) + print(f"\t{alias} => {target}") def get_names(self): """Return a list of valid sub-class names and aliases.""" diff --git a/configs/common/Options.py b/configs/common/Options.py index 5585a75b80..8344d9fd44 100644 --- a/configs/common/Options.py +++ b/configs/common/Options.py @@ -834,8 +834,7 @@ def addFSOptions(parser): action="store", type=str, dest="benchmark", - help="Specify the benchmark to run. Available benchmarks: %s" - % DefinedBenchmarks, + help=f"Specify the benchmark to run. Available benchmarks: {DefinedBenchmarks}", ) # Metafile options diff --git a/configs/common/Simulation.py b/configs/common/Simulation.py index 731b3fcaa5..4377b65e64 100644 --- a/configs/common/Simulation.py +++ b/configs/common/Simulation.py @@ -71,7 +71,7 @@ def setCPUClass(options): TmpClass, test_mem_mode = getCPUClass(options.cpu_type) CPUClass = None if TmpClass.require_caches() and not options.caches and not options.ruby: - fatal("%s must be used with caches" % options.cpu_type) + fatal(f"{options.cpu_type} must be used with caches") if options.checkpoint_restore != None: if options.restore_with_cpu != options.cpu_type: @@ -144,7 +144,7 @@ def findCptDir(options, cptdir, testsys): fatal("Unable to find simpoint") inst += int(testsys.cpu[0].workload[0].simpoint) - checkpoint_dir = joinpath(cptdir, "cpt.%s.%s" % (options.bench, inst)) + checkpoint_dir = joinpath(cptdir, f"cpt.{options.bench}.{inst}") if not exists(checkpoint_dir): fatal("Unable to find checkpoint directory %s", checkpoint_dir) @@ -204,7 +204,7 @@ def findCptDir(options, cptdir, testsys): fatal("Checkpoint %d not found", cpt_num) cpt_starttick = int(cpts[cpt_num - 1]) - checkpoint_dir = joinpath(cptdir, "cpt.%s" % cpts[cpt_num - 1]) + checkpoint_dir = joinpath(cptdir, f"cpt.{cpts[cpt_num - 1]}") return cpt_starttick, checkpoint_dir @@ -220,7 +220,7 @@ def scriptCheckpoints(options, maxtick, cptdir): print("Creating checkpoint at inst:%d" % (checkpoint_inst)) exit_event = m5.simulate() exit_cause = exit_event.getCause() - print("exit cause = %s" % exit_cause) + print(f"exit cause = {exit_cause}") # skip checkpoint instructions should they exist while exit_cause == "checkpoint": @@ -549,10 +549,10 @@ def run(options, root, testsys, cpu_class): if options.repeat_switch: switch_class = getCPUClass(options.cpu_type)[0] if switch_class.require_caches() and not options.caches: - print("%s: Must be used with caches" % str(switch_class)) + print(f"{str(switch_class)}: Must be used with caches") sys.exit(1) if not switch_class.support_take_over(): - print("%s: CPU switching not supported" % str(switch_class)) + print(f"{str(switch_class)}: CPU switching not supported") sys.exit(1) repeat_switch_cpus = [ @@ -740,9 +740,9 @@ def run(options, root, testsys, cpu_class): ) exit_event = m5.simulate() else: - print("Switch at curTick count:%s" % str(10000)) + print(f"Switch at curTick count:{str(10000)}") exit_event = m5.simulate(10000) - print("Switched CPUS @ tick %s" % (m5.curTick())) + print(f"Switched CPUS @ tick {m5.curTick()}") m5.switchCpus(testsys, switch_cpu_list) @@ -757,7 +757,7 @@ def run(options, root, testsys, cpu_class): exit_event = m5.simulate() else: exit_event = m5.simulate(options.standard_switch) - print("Switching CPUS @ tick %s" % (m5.curTick())) + print(f"Switching CPUS @ tick {m5.curTick()}") print( "Simulation ends instruction count:%d" % (testsys.switch_cpus_1[0].max_insts_any_thread) diff --git a/configs/common/SysPaths.py b/configs/common/SysPaths.py index 7c0f5bf59b..60375c30c5 100644 --- a/configs/common/SysPaths.py +++ b/configs/common/SysPaths.py @@ -73,9 +73,7 @@ class PathSearchFunc(object): return next(p for p in paths if os.path.exists(p)) except StopIteration: raise IOError( - "Can't find file '{}' on {}.".format( - filepath, self.environment_variable - ) + f"Can't find file '{filepath}' on {self.environment_variable}." ) diff --git a/configs/common/cpu2000.py b/configs/common/cpu2000.py index 3b1b390618..06f927cbcf 100644 --- a/configs/common/cpu2000.py +++ b/configs/common/cpu2000.py @@ -83,7 +83,7 @@ class Benchmark(object): self.args = [] if not hasattr(self.__class__, "output"): - self.output = "%s.out" % self.name + self.output = f"{self.name}.out" if not hasattr(self.__class__, "simpoint"): self.simpoint = None @@ -92,13 +92,12 @@ class Benchmark(object): func = getattr(self.__class__, input_set) except AttributeError: raise AttributeError( - "The benchmark %s does not have the %s input set" - % (self.name, input_set) + f"The benchmark {self.name} does not have the {input_set} input set" ) executable = joinpath(spec_dist, "binaries", isa, os, self.binary) if not isfile(executable): - raise AttributeError("%s not found" % executable) + raise AttributeError(f"{executable} not found") self.executable = executable # root of tree for input & output data files @@ -112,7 +111,7 @@ class Benchmark(object): self.input_set = input_set if not isdir(inputs_dir): - raise AttributeError("%s not found" % inputs_dir) + raise AttributeError(f"{inputs_dir} not found") self.inputs_dir = [inputs_dir] if isdir(all_dir): @@ -121,12 +120,12 @@ class Benchmark(object): self.outputs_dir = outputs_dir if not hasattr(self.__class__, "stdin"): - self.stdin = joinpath(inputs_dir, "%s.in" % self.name) + self.stdin = joinpath(inputs_dir, f"{self.name}.in") if not isfile(self.stdin): self.stdin = None if not hasattr(self.__class__, "stdout"): - self.stdout = joinpath(outputs_dir, "%s.out" % self.name) + self.stdout = joinpath(outputs_dir, f"{self.name}.out") if not isfile(self.stdout): self.stdout = None @@ -387,9 +386,9 @@ class mesa(Benchmark): "-frames", frames, "-meshfile", - "%s.in" % self.name, + f"{self.name}.in", "-ppmfile", - "%s.ppm" % self.name, + f"{self.name}.ppm", ] def test(self, isa, os): @@ -876,34 +875,34 @@ class vortex(Benchmark): elif isa == "sparc" or isa == "sparc32": self.endian = "bendian" else: - raise AttributeError("unknown ISA %s" % isa) + raise AttributeError(f"unknown ISA {isa}") super(vortex, self).__init__(isa, os, input_set) def test(self, isa, os): - self.args = ["%s.raw" % self.endian] + self.args = [f"{self.endian}.raw"] self.output = "vortex.out" def train(self, isa, os): - self.args = ["%s.raw" % self.endian] + self.args = [f"{self.endian}.raw"] self.output = "vortex.out" def smred(self, isa, os): - self.args = ["%s.raw" % self.endian] + self.args = [f"{self.endian}.raw"] self.output = "vortex.out" def mdred(self, isa, os): - self.args = ["%s.raw" % self.endian] + self.args = [f"{self.endian}.raw"] self.output = "vortex.out" def lgred(self, isa, os): - self.args = ["%s.raw" % self.endian] + self.args = [f"{self.endian}.raw"] self.output = "vortex.out" class vortex1(vortex): def ref(self, isa, os): - self.args = ["%s1.raw" % self.endian] + self.args = [f"{self.endian}1.raw"] self.output = "vortex1.out" self.simpoint = 271 * 100e6 @@ -911,14 +910,14 @@ class vortex1(vortex): class vortex2(vortex): def ref(self, isa, os): self.simpoint = 1024 * 100e6 - self.args = ["%s2.raw" % self.endian] + self.args = [f"{self.endian}2.raw"] self.output = "vortex2.out" class vortex3(vortex): def ref(self, isa, os): self.simpoint = 564 * 100e6 - self.args = ["%s3.raw" % self.endian] + self.args = [f"{self.endian}3.raw"] self.output = "vortex3.out" @@ -1031,8 +1030,8 @@ if __name__ == "__main__": for bench in all: for input_set in "ref", "test", "train": - print("class: %s" % bench.__name__) + print(f"class: {bench.__name__}") x = bench("x86", "linux", input_set) - print("%s: %s" % (x, input_set)) + print(f"{x}: {input_set}") pprint(x.makeProcessArgs()) print() diff --git a/configs/deprecated/example/fs.py b/configs/deprecated/example/fs.py index 59c35925fc..c50e3ac4cc 100644 --- a/configs/deprecated/example/fs.py +++ b/configs/deprecated/example/fs.py @@ -347,8 +347,8 @@ if args.benchmark: try: bm = Benchmarks[args.benchmark] except KeyError: - print("Error benchmark %s has not been defined." % args.benchmark) - print("Valid benchmarks are: %s" % DefinedBenchmarks) + print(f"Error benchmark {args.benchmark} has not been defined.") + print(f"Valid benchmarks are: {DefinedBenchmarks}") sys.exit(1) else: if args.dual: @@ -433,7 +433,7 @@ if buildEnv["USE_ARM_ISA"] and not args.bare_metal and not args.dtb_filename: if hasattr(root, sysname): sys = getattr(root, sysname) sys.workload.dtb_filename = os.path.join( - m5.options.outdir, "%s.dtb" % sysname + m5.options.outdir, f"{sysname}.dtb" ) sys.generateDtb(sys.workload.dtb_filename) diff --git a/configs/deprecated/example/se.py b/configs/deprecated/example/se.py index 4732839874..8d6735903f 100644 --- a/configs/deprecated/example/se.py +++ b/configs/deprecated/example/se.py @@ -159,8 +159,7 @@ if args.bench: multiprocesses.append(workload.makeProcess()) except: print( - "Unable to find workload for %s: %s" - % (get_runtime_isa().name(), app), + f"Unable to find workload for {get_runtime_isa().name()}: {app}", file=sys.stderr, ) sys.exit(1) diff --git a/configs/example/apu_se.py b/configs/example/apu_se.py index c2b97fd82e..287135fd62 100644 --- a/configs/example/apu_se.py +++ b/configs/example/apu_se.py @@ -683,7 +683,7 @@ def find_path(base_list, rel_path, test): full_path = os.path.join(base, rel_path) if test(full_path): return full_path - fatal("%s not found in %s" % (rel_path, base_list)) + fatal(f"{rel_path} not found in {base_list}") def find_file(base_list, rel_path): @@ -717,7 +717,7 @@ else: "/usr/lib/x86_64-linux-gnu", ] ), - "HOME=%s" % os.getenv("HOME", "/"), + f"HOME={os.getenv('HOME', '/')}", # Disable the VM fault handler signal creation for dGPUs also # forces the use of DefaultSignals instead of driver-controlled # InteruptSignals throughout the runtime. DefaultSignals poll @@ -922,14 +922,10 @@ else: redirect_paths = [ RedirectPath( - app_path="/proc", host_paths=["%s/fs/proc" % m5.options.outdir] - ), - RedirectPath( - app_path="/sys", host_paths=["%s/fs/sys" % m5.options.outdir] - ), - RedirectPath( - app_path="/tmp", host_paths=["%s/fs/tmp" % m5.options.outdir] + app_path="/proc", host_paths=[f"{m5.options.outdir}/fs/proc"] ), + RedirectPath(app_path="/sys", host_paths=[f"{m5.options.outdir}/fs/sys"]), + RedirectPath(app_path="/tmp", host_paths=[f"{m5.options.outdir}/fs/tmp"]), ] system.redirect_paths = redirect_paths @@ -981,7 +977,7 @@ exit_event = m5.simulate(maxtick) if args.fast_forward: if exit_event.getCause() == "a thread reached the max instruction count": m5.switchCpus(system, switch_cpu_list) - print("Switched CPUS @ tick %s" % (m5.curTick())) + print(f"Switched CPUS @ tick {m5.curTick()}") m5.stats.reset() exit_event = m5.simulate(maxtick - m5.curTick()) elif args.fast_forward_pseudo_op: @@ -992,7 +988,7 @@ elif args.fast_forward_pseudo_op: print("Dumping stats...") m5.stats.dump() m5.switchCpus(system, switch_cpu_list) - print("Switched CPUS @ tick %s" % (m5.curTick())) + print(f"Switched CPUS @ tick {m5.curTick()}") m5.stats.reset() # This lets us switch back and forth without keeping a counter switch_cpu_list = [(x[1], x[0]) for x in switch_cpu_list] diff --git a/configs/example/arm/baremetal.py b/configs/example/arm/baremetal.py index fc630e5299..0072c1d629 100644 --- a/configs/example/arm/baremetal.py +++ b/configs/example/arm/baremetal.py @@ -77,7 +77,7 @@ def create(args): """Create and configure the system object.""" if args.readfile and not os.path.isfile(args.readfile): - print("Error: Bootscript %s does not exist" % args.readfile) + print(f"Error: Bootscript {args.readfile} does not exist") sys.exit(1) object_file = args.kernel if args.kernel else "" @@ -149,7 +149,7 @@ def create(args): def run(args): cptdir = m5.options.outdir if args.checkpoint: - print("Checkpoint directory: %s" % cptdir) + print(f"Checkpoint directory: {cptdir}") while True: event = m5.simulate() diff --git a/configs/example/arm/fs_bigLITTLE.py b/configs/example/arm/fs_bigLITTLE.py index 060c51ec3c..401eb0c9e7 100644 --- a/configs/example/arm/fs_bigLITTLE.py +++ b/configs/example/arm/fs_bigLITTLE.py @@ -331,10 +331,10 @@ def build(options): "lpj=19988480", "norandmaps", "loglevel=8", - "mem=%s" % options.mem_size, - "root=%s" % options.root, + f"mem={options.mem_size}", + f"root={options.root}", "rw", - "init=%s" % options.kernel_init, + f"init={options.kernel_init}", "vmalloc=768MB", ] diff --git a/configs/example/arm/fs_power.py b/configs/example/arm/fs_power.py index 95d2182508..671cf63f2f 100644 --- a/configs/example/arm/fs_power.py +++ b/configs/example/arm/fs_power.py @@ -79,7 +79,7 @@ class L2PowerOn(MathExprPowerModel): # Example to report l2 Cache overallAccesses # The estimated power is converted to Watt and will vary based # on the size of the cache - self.dyn = "{}.overallAccesses * 0.000018000".format(l2_path) + self.dyn = f"{l2_path}.overallAccesses * 0.000018000" self.st = "(voltage * 3)/10" diff --git a/configs/example/arm/ruby_fs.py b/configs/example/arm/ruby_fs.py index fd36319363..67a8a6e0b3 100644 --- a/configs/example/arm/ruby_fs.py +++ b/configs/example/arm/ruby_fs.py @@ -100,7 +100,7 @@ def create(args): """Create and configure the system object.""" if args.script and not os.path.isfile(args.script): - print("Error: Bootscript %s does not exist" % args.script) + print(f"Error: Bootscript {args.script} does not exist") sys.exit(1) cpu_class = cpu_types[args.cpu] @@ -171,11 +171,11 @@ def create(args): # memory layout. "norandmaps", # Tell Linux where to find the root disk image. - "root=%s" % args.root_device, + f"root={args.root_device}", # Mount the root disk read-write by default. "rw", # Tell Linux about the amount of physical memory present. - "mem=%s" % args.mem_size, + f"mem={args.mem_size}", ] system.workload.command_line = " ".join(kernel_cmd) @@ -185,7 +185,7 @@ def create(args): def run(args): cptdir = m5.options.outdir if args.checkpoint: - print("Checkpoint directory: %s" % cptdir) + print(f"Checkpoint directory: {cptdir}") while True: event = m5.simulate() @@ -221,9 +221,7 @@ def main(): "--root-device", type=str, default=default_root_device, - help="OS device name for root partition (default: {})".format( - default_root_device - ), + help=f"OS device name for root partition (default: {default_root_device})", ) parser.add_argument( "--script", type=str, default="", help="Linux bootscript" diff --git a/configs/example/arm/starter_fs.py b/configs/example/arm/starter_fs.py index 7d7ab71768..48cbbdb3e6 100644 --- a/configs/example/arm/starter_fs.py +++ b/configs/example/arm/starter_fs.py @@ -88,7 +88,7 @@ def create(args): """Create and configure the system object.""" if args.script and not os.path.isfile(args.script): - print("Error: Bootscript %s does not exist" % args.script) + print(f"Error: Bootscript {args.script} does not exist") sys.exit(1) cpu_class = cpu_types[args.cpu][0] @@ -163,11 +163,11 @@ def create(args): # memory layout. "norandmaps", # Tell Linux where to find the root disk image. - "root=%s" % args.root_device, + f"root={args.root_device}", # Mount the root disk read-write by default. "rw", # Tell Linux about the amount of physical memory present. - "mem=%s" % args.mem_size, + f"mem={args.mem_size}", ] system.workload.command_line = " ".join(kernel_cmd) @@ -177,7 +177,7 @@ def create(args): def run(args): cptdir = m5.options.outdir if args.checkpoint: - print("Checkpoint directory: %s" % cptdir) + print(f"Checkpoint directory: {cptdir}") while True: event = m5.simulate() @@ -219,9 +219,7 @@ def main(): "--root-device", type=str, default=default_root_device, - help="OS device name for root partition (default: {})".format( - default_root_device - ), + help=f"OS device name for root partition (default: {default_root_device})", ) parser.add_argument( "--script", type=str, default="", help="Linux bootscript" diff --git a/configs/example/gem5_library/x86-gapbs-benchmarks.py b/configs/example/gem5_library/x86-gapbs-benchmarks.py index 6ab37479f9..b85ce6e7e8 100644 --- a/configs/example/gem5_library/x86-gapbs-benchmarks.py +++ b/configs/example/gem5_library/x86-gapbs-benchmarks.py @@ -195,9 +195,9 @@ if args.synthetic == "1": ) exit(-1) - command = "./{} -g {}\n".format(args.benchmark, args.size) + command = f"./{args.benchmark} -g {args.size}\n" else: - command = "./{} -sf ../{}".format(args.benchmark, args.size) + command = f"./{args.benchmark} -sf ../{args.size}" board.set_kernel_disk_workload( # The x86 linux kernel will be automatically downloaded to the @@ -262,7 +262,9 @@ print("Done with the simulation") print() print("Performance statistics:") -print("Simulated time in ROI: %.2fs" % ((end_tick - start_tick) / 1e12)) +print( + f"Simulated time in ROI: {(end_tick - start_tick) / 1000000000000.0:.2f}s" +) print( "Ran a total of", simulator.get_current_tick() / 1e12, "simulated seconds" ) diff --git a/configs/example/gem5_library/x86-npb-benchmarks.py b/configs/example/gem5_library/x86-npb-benchmarks.py index ff363e449c..cffba5a294 100644 --- a/configs/example/gem5_library/x86-npb-benchmarks.py +++ b/configs/example/gem5_library/x86-npb-benchmarks.py @@ -195,7 +195,7 @@ board = X86Board( # properly. command = ( - "/home/gem5/NPB3.3-OMP/bin/{}.{}.x;".format(args.benchmark, args.size) + f"/home/gem5/NPB3.3-OMP/bin/{args.benchmark}.{args.size}.x;" + "sleep 5;" + "m5 exit;" ) diff --git a/configs/example/gem5_library/x86-parsec-benchmarks.py b/configs/example/gem5_library/x86-parsec-benchmarks.py index 190c0a0980..aaffec8edc 100644 --- a/configs/example/gem5_library/x86-parsec-benchmarks.py +++ b/configs/example/gem5_library/x86-parsec-benchmarks.py @@ -177,10 +177,7 @@ board = X86Board( command = ( "cd /home/gem5/parsec-benchmark;".format(args.benchmark) + "source env.sh;" - + "parsecmgmt -a run -p {} -c gcc-hooks -i {} \ - -n {};".format( - args.benchmark, args.size, "2" - ) + + f"parsecmgmt -a run -p {args.benchmark} -c gcc-hooks -i {args.size} -n 2;" + "sleep 5;" + "m5 exit;" ) diff --git a/configs/example/gem5_library/x86-spec-cpu2006-benchmarks.py b/configs/example/gem5_library/x86-spec-cpu2006-benchmarks.py index 8f39f49e2e..a681ecadcb 100644 --- a/configs/example/gem5_library/x86-spec-cpu2006-benchmarks.py +++ b/configs/example/gem5_library/x86-spec-cpu2006-benchmarks.py @@ -179,7 +179,7 @@ if not os.path.exists(args.image): print( "https://gem5art.readthedocs.io/en/latest/tutorials/spec-tutorial.html" ) - fatal("The disk-image is not found at {}".format(args.image)) + fatal(f"The disk-image is not found at {args.image}") # Setting up all the fixed system parameters here # Caches: MESI Two Level Cache Hierarchy @@ -252,7 +252,7 @@ except FileExistsError: # The runscript.sh file places `m5 exit` before and after the following command # Therefore, we only pass this command without m5 exit. -command = "{} {} {}".format(args.benchmark, args.size, output_dir) +command = f"{args.benchmark} {args.size} {output_dir}" board.set_kernel_disk_workload( # The x86 linux kernel will be automatically downloaded to the diff --git a/configs/example/gem5_library/x86-spec-cpu2017-benchmarks.py b/configs/example/gem5_library/x86-spec-cpu2017-benchmarks.py index c4af7f5dd9..531ce9413e 100644 --- a/configs/example/gem5_library/x86-spec-cpu2017-benchmarks.py +++ b/configs/example/gem5_library/x86-spec-cpu2017-benchmarks.py @@ -193,7 +193,7 @@ if not os.path.exists(args.image): print( "https://gem5art.readthedocs.io/en/latest/tutorials/spec-tutorial.html" ) - fatal("The disk-image is not found at {}".format(args.image)) + fatal(f"The disk-image is not found at {args.image}") # Setting up all the fixed system parameters here # Caches: MESI Two Level Cache Hierarchy @@ -266,7 +266,7 @@ except FileExistsError: # The runscript.sh file places `m5 exit` before and after the following command # Therefore, we only pass this command without m5 exit. -command = "{} {} {}".format(args.benchmark, args.size, output_dir) +command = f"{args.benchmark} {args.size} {output_dir}" # For enabling CustomResource, we pass an additional parameter to mount the # correct partition. diff --git a/configs/example/gpufs/DisjointNetwork.py b/configs/example/gpufs/DisjointNetwork.py index 1d7f708967..1fbd0dcb15 100644 --- a/configs/example/gpufs/DisjointNetwork.py +++ b/configs/example/gpufs/DisjointNetwork.py @@ -48,7 +48,7 @@ class DisjointSimple(SimpleNetwork): def connectCPU(self, opts, controllers): # Setup parameters for makeTopology call for CPU network - topo_module = import_module("topologies.%s" % opts.cpu_topology) + topo_module = import_module(f"topologies.{opts.cpu_topology}") topo_class = getattr(topo_module, opts.cpu_topology) _topo = topo_class(controllers) _topo.makeTopology(opts, self, SimpleIntLink, SimpleExtLink, Switch) @@ -58,7 +58,7 @@ class DisjointSimple(SimpleNetwork): def connectGPU(self, opts, controllers): # Setup parameters for makeTopology call for GPU network - topo_module = import_module("topologies.%s" % opts.gpu_topology) + topo_module = import_module(f"topologies.{opts.gpu_topology}") topo_class = getattr(topo_module, opts.gpu_topology) _topo = topo_class(controllers) _topo.makeTopology(opts, self, SimpleIntLink, SimpleExtLink, Switch) @@ -84,7 +84,7 @@ class DisjointGarnet(GarnetNetwork): def connectCPU(self, opts, controllers): # Setup parameters for makeTopology call for CPU network - topo_module = import_module("topologies.%s" % opts.cpu_topology) + topo_module = import_module(f"topologies.{opts.cpu_topology}") topo_class = getattr(topo_module, opts.cpu_topology) _topo = topo_class(controllers) _topo.makeTopology( @@ -96,7 +96,7 @@ class DisjointGarnet(GarnetNetwork): def connectGPU(self, opts, controllers): # Setup parameters for makeTopology call - topo_module = import_module("topologies.%s" % opts.gpu_topology) + topo_module = import_module(f"topologies.{opts.gpu_topology}") topo_class = getattr(topo_module, opts.gpu_topology) _topo = topo_class(controllers) _topo.makeTopology( diff --git a/configs/example/gpufs/hip_cookbook.py b/configs/example/gpufs/hip_cookbook.py index 1c22be52da..87c7547dd3 100644 --- a/configs/example/gpufs/hip_cookbook.py +++ b/configs/example/gpufs/hip_cookbook.py @@ -99,18 +99,16 @@ if __name__ == "__m5_main__": # Create temp script to run application if args.app is None: - print("No application given. Use %s -a " % sys.argv[0]) + print(f"No application given. Use {sys.argv[0]} -a ") sys.exit(1) elif args.kernel is None: - print("No kernel path given. Use %s --kernel " % sys.argv[0]) + print(f"No kernel path given. Use {sys.argv[0]} --kernel ") sys.exit(1) elif args.disk_image is None: - print("No disk path given. Use %s --disk-image " % sys.argv[0]) + print(f"No disk path given. Use {sys.argv[0]} --disk-image ") sys.exit(1) elif args.gpu_mmio_trace is None: - print( - "No MMIO trace path. Use %s --gpu-mmio-trace " % sys.argv[0] - ) + print(f"No MMIO trace path. Use {sys.argv[0]} --gpu-mmio-trace ") sys.exit(1) _, tempRunscript = tempfile.mkstemp() diff --git a/configs/example/gpufs/hip_rodinia.py b/configs/example/gpufs/hip_rodinia.py index a6c7c504c1..8ed951b55e 100644 --- a/configs/example/gpufs/hip_rodinia.py +++ b/configs/example/gpufs/hip_rodinia.py @@ -107,18 +107,16 @@ if __name__ == "__m5_main__": # Create temp script to run application if args.app is None: - print("No application given. Use %s -a " % sys.argv[0]) + print(f"No application given. Use {sys.argv[0]} -a ") sys.exit(1) elif args.kernel is None: - print("No kernel path given. Use %s --kernel " % sys.argv[0]) + print(f"No kernel path given. Use {sys.argv[0]} --kernel ") sys.exit(1) elif args.disk_image is None: - print("No disk path given. Use %s --disk-image " % sys.argv[0]) + print(f"No disk path given. Use {sys.argv[0]} --disk-image ") sys.exit(1) elif args.gpu_mmio_trace is None: - print( - "No MMIO trace path. Use %s --gpu-mmio-trace " % sys.argv[0] - ) + print(f"No MMIO trace path. Use {sys.argv[0]} --gpu-mmio-trace ") sys.exit(1) _, tempRunscript = tempfile.mkstemp() diff --git a/configs/example/gpufs/hip_samples.py b/configs/example/gpufs/hip_samples.py index 0d9263e128..ccc1719639 100644 --- a/configs/example/gpufs/hip_samples.py +++ b/configs/example/gpufs/hip_samples.py @@ -97,18 +97,16 @@ if __name__ == "__m5_main__": # Create temp script to run application if args.app is None: - print("No application given. Use %s -a " % sys.argv[0]) + print(f"No application given. Use {sys.argv[0]} -a ") sys.exit(1) elif args.kernel is None: - print("No kernel path given. Use %s --kernel " % sys.argv[0]) + print(f"No kernel path given. Use {sys.argv[0]} --kernel ") sys.exit(1) elif args.disk_image is None: - print("No disk path given. Use %s --disk-image " % sys.argv[0]) + print(f"No disk path given. Use {sys.argv[0]} --disk-image ") sys.exit(1) elif args.gpu_mmio_trace is None: - print( - "No MMIO trace path. Use %s --gpu-mmio-trace " % sys.argv[0] - ) + print(f"No MMIO trace path. Use {sys.argv[0]} --gpu-mmio-trace ") sys.exit(1) _, tempRunscript = tempfile.mkstemp() diff --git a/configs/example/gpufs/runfs.py b/configs/example/gpufs/runfs.py index 86b91034b0..4a28068a11 100644 --- a/configs/example/gpufs/runfs.py +++ b/configs/example/gpufs/runfs.py @@ -184,7 +184,7 @@ def runGpuFSSystem(args): break else: print( - "Unknown exit event: %s. Continuing..." % exit_event.getCause() + f"Unknown exit event: {exit_event.getCause()}. Continuing..." ) print( diff --git a/configs/example/gpufs/vega10_kvm.py b/configs/example/gpufs/vega10_kvm.py index 48e2d69516..54253bece5 100644 --- a/configs/example/gpufs/vega10_kvm.py +++ b/configs/example/gpufs/vega10_kvm.py @@ -82,18 +82,16 @@ if __name__ == "__m5_main__": # Create temp script to run application if args.app is None: - print("No application given. Use %s -a " % sys.argv[0]) + print(f"No application given. Use {sys.argv[0]} -a ") sys.exit(1) elif args.kernel is None: - print("No kernel path given. Use %s --kernel " % sys.argv[0]) + print(f"No kernel path given. Use {sys.argv[0]} --kernel ") sys.exit(1) elif args.disk_image is None: - print("No disk path given. Use %s --disk-image " % sys.argv[0]) + print(f"No disk path given. Use {sys.argv[0]} --disk-image ") sys.exit(1) elif args.gpu_mmio_trace is None: - print( - "No MMIO trace path. Use %s --gpu-mmio-trace " % sys.argv[0] - ) + print(f"No MMIO trace path. Use {sys.argv[0]} --gpu-mmio-trace ") sys.exit(1) elif not os.path.isfile(args.app): print("Could not find applcation", args.app) diff --git a/configs/example/hsaTopology.py b/configs/example/hsaTopology.py index 691e8c2a58..909b9ef519 100644 --- a/configs/example/hsaTopology.py +++ b/configs/example/hsaTopology.py @@ -118,11 +118,11 @@ def createVegaTopology(options): # Populate CPU node properties node_prop = ( - "cpu_cores_count %s\n" % options.num_cpus + f"cpu_cores_count {options.num_cpus}\n" + "simd_count 0\n" + "mem_banks_count 1\n" + "caches_count 0\n" - + "io_links_count %s\n" % io_links + + f"io_links_count {io_links}\n" + "cpu_core_id_base 0\n" + "simd_id_base 0\n" + "max_waves_per_simd 0\n" @@ -200,8 +200,8 @@ def createVegaTopology(options): "cpu_cores_count 0\n" + "simd_count 256\n" + "mem_banks_count 1\n" - + "caches_count %s\n" % caches - + "io_links_count %s\n" % io_links + + f"caches_count {caches}\n" + + f"io_links_count {io_links}\n" + "cpu_core_id_base 0\n" + "simd_id_base 2147487744\n" + "max_waves_per_simd 10\n" @@ -212,11 +212,11 @@ def createVegaTopology(options): + "simd_arrays_per_engine 1\n" + "cu_per_simd_array 16\n" + "simd_per_cu 4\n" - + "max_slots_scratch_cu %s\n" % cu_scratch + + f"max_slots_scratch_cu {cu_scratch}\n" + "vendor_id 4098\n" + "device_id 26720\n" + "location_id 1024\n" - + "drm_render_minor %s\n" % drm_num + + f"drm_render_minor {drm_num}\n" + "hive_id 0\n" + "num_sdma_engines 2\n" + "num_sdma_xgmi_engines 0\n" @@ -313,11 +313,11 @@ def createFijiTopology(options): # Populate CPU node properties node_prop = ( - "cpu_cores_count %s\n" % options.num_cpus + f"cpu_cores_count {options.num_cpus}\n" + "simd_count 0\n" + "mem_banks_count 1\n" + "caches_count 0\n" - + "io_links_count %s\n" % io_links + + f"io_links_count {io_links}\n" + "cpu_core_id_base 0\n" + "simd_id_base 0\n" + "max_waves_per_simd 0\n" @@ -392,33 +392,30 @@ def createFijiTopology(options): # Populate GPU node properties node_prop = ( "cpu_cores_count 0\n" - + "simd_count %s\n" - % (options.num_compute_units * options.simds_per_cu) + + f"simd_count {options.num_compute_units * options.simds_per_cu}\n" + "mem_banks_count 1\n" - + "caches_count %s\n" % caches - + "io_links_count %s\n" % io_links + + f"caches_count {caches}\n" + + f"io_links_count {io_links}\n" + "cpu_core_id_base 0\n" + "simd_id_base 2147487744\n" - + "max_waves_per_simd %s\n" % options.wfs_per_simd - + "lds_size_in_kb %s\n" % int(options.lds_size / 1024) + + f"max_waves_per_simd {options.wfs_per_simd}\n" + + f"lds_size_in_kb {int(options.lds_size / 1024)}\n" + "gds_size_in_kb 0\n" - + "wave_front_size %s\n" % options.wf_size + + f"wave_front_size {options.wf_size}\n" + "array_count 4\n" - + "simd_arrays_per_engine %s\n" % options.sa_per_complex - + "cu_per_simd_array %s\n" % options.cu_per_sa - + "simd_per_cu %s\n" % options.simds_per_cu + + f"simd_arrays_per_engine {options.sa_per_complex}\n" + + f"cu_per_simd_array {options.cu_per_sa}\n" + + f"simd_per_cu {options.simds_per_cu}\n" + "max_slots_scratch_cu 32\n" + "vendor_id 4098\n" + "device_id 29440\n" + "location_id 512\n" - + "drm_render_minor %s\n" % drm_num - + "max_engine_clk_fcompute %s\n" - % int(toFrequency(options.gpu_clock) / 1e6) + + f"drm_render_minor {drm_num}\n" + + f"max_engine_clk_fcompute {int(toFrequency(options.gpu_clock) / 1000000.0)}\n" + "local_mem_size 4294967296\n" + "fw_version 730\n" + "capability 4736\n" - + "max_engine_clk_ccompute %s\n" - % int(toFrequency(options.CPUClock) / 1e6) + + f"max_engine_clk_ccompute {int(toFrequency(options.CPUClock) / 1000000.0)}\n" ) file_append((node_dir, "properties"), node_prop) @@ -484,34 +481,31 @@ def createCarrizoTopology(options): # populate global node properties # NOTE: SIMD count triggers a valid GPU agent creation node_prop = ( - "cpu_cores_count %s\n" % options.num_cpus - + "simd_count %s\n" - % (options.num_compute_units * options.simds_per_cu) - + "mem_banks_count %s\n" % mem_banks_cnt + f"cpu_cores_count {options.num_cpus}\n" + + f"simd_count {options.num_compute_units * options.simds_per_cu}\n" + + f"mem_banks_count {mem_banks_cnt}\n" + "caches_count 0\n" + "io_links_count 0\n" + "cpu_core_id_base 16\n" + "simd_id_base 2147483648\n" - + "max_waves_per_simd %s\n" % options.wfs_per_simd - + "lds_size_in_kb %s\n" % int(options.lds_size / 1024) + + f"max_waves_per_simd {options.wfs_per_simd}\n" + + f"lds_size_in_kb {int(options.lds_size / 1024)}\n" + "gds_size_in_kb 0\n" - + "wave_front_size %s\n" % options.wf_size + + f"wave_front_size {options.wf_size}\n" + "array_count 1\n" - + "simd_arrays_per_engine %s\n" % options.sa_per_complex - + "cu_per_simd_array %s\n" % options.cu_per_sa - + "simd_per_cu %s\n" % options.simds_per_cu + + f"simd_arrays_per_engine {options.sa_per_complex}\n" + + f"cu_per_simd_array {options.cu_per_sa}\n" + + f"simd_per_cu {options.simds_per_cu}\n" + "max_slots_scratch_cu 32\n" + "vendor_id 4098\n" - + "device_id %s\n" % device_id + + f"device_id {device_id}\n" + "location_id 8\n" - + "drm_render_minor %s\n" % drm_num - + "max_engine_clk_fcompute %s\n" - % int(toFrequency(options.gpu_clock) / 1e6) + + f"drm_render_minor {drm_num}\n" + + f"max_engine_clk_fcompute {int(toFrequency(options.gpu_clock) / 1000000.0)}\n" + "local_mem_size 0\n" + "fw_version 699\n" + "capability 4738\n" - + "max_engine_clk_ccompute %s\n" - % int(toFrequency(options.CPUClock) / 1e6) + + f"max_engine_clk_ccompute {int(toFrequency(options.CPUClock) / 1000000.0)}\n" ) file_append((node_dir, "properties"), node_prop) diff --git a/configs/example/lupv/run_lupv.py b/configs/example/lupv/run_lupv.py index 0056cf8bb4..d92ea3fa3f 100644 --- a/configs/example/lupv/run_lupv.py +++ b/configs/example/lupv/run_lupv.py @@ -113,6 +113,4 @@ print("Beginning simulation!") exit_event = m5.simulate(args.max_ticks) -print( - "Exiting @ tick {} because {}.".format(m5.curTick(), exit_event.getCause()) -) +print(f"Exiting @ tick {m5.curTick()} because {exit_event.getCause()}.") diff --git a/configs/example/memcheck.py b/configs/example/memcheck.py index a50644b2b1..aee2ef74d0 100644 --- a/configs/example/memcheck.py +++ b/configs/example/memcheck.py @@ -330,7 +330,7 @@ def make_cache_level(ncaches, prototypes, level, next_cache): make_cache_level(cachespec, cache_proto, len(cachespec), None) # Connect the lowest level crossbar to the memory -last_subsys = getattr(system, "l%dsubsys0" % len(cachespec)) +last_subsys = getattr(system, f"l{len(cachespec)}subsys0") last_subsys.xbar.mem_side_ports = system.physmem.port last_subsys.xbar.point_of_coherency = True diff --git a/configs/example/memtest.py b/configs/example/memtest.py index 58d762dc60..0cbbab5b4f 100644 --- a/configs/example/memtest.py +++ b/configs/example/memtest.py @@ -211,8 +211,7 @@ else: if numtesters(cachespec, testerspec) > block_size: print( - "Error: Limited to %s testers because of false sharing" - % (block_size) + f"Error: Limited to {block_size} testers because of false sharing" ) sys.exit(1) @@ -351,7 +350,7 @@ make_cache_level(cachespec, cache_proto, len(cachespec), None) # Connect the lowest level crossbar to the last-level cache and memory # controller -last_subsys = getattr(system, "l%dsubsys0" % len(cachespec)) +last_subsys = getattr(system, f"l{len(cachespec)}subsys0") last_subsys.xbar.point_of_coherency = True if args.noncoherent_cache: system.llc = NoncoherentCache( diff --git a/configs/example/read_config.py b/configs/example/read_config.py index b52a73d1fa..40c20ef501 100644 --- a/configs/example/read_config.py +++ b/configs/example/read_config.py @@ -68,8 +68,7 @@ sim_object_classes_by_name = { def no_parser(cls, flags, param): raise Exception( - "Can't parse string: %s for parameter" - " class: %s" % (str(param), cls.__name__) + f"Can't parse string: {str(param)} for parameter class: {cls.__name__}" ) @@ -114,7 +113,7 @@ def memory_bandwidth_parser(cls, flags, param): value = 1.0 / float(param) # Convert to byte/s value = ticks.fromSeconds(value) - return cls("%fB/s" % value) + return cls(f"{value:f}B/s") # These parameters have trickier parsing from .ini files than might be @@ -201,8 +200,7 @@ class ConfigManager(object): if object_type not in sim_object_classes_by_name: raise Exception( - "No SimObject type %s is available to" - " build: %s" % (object_type, object_name) + f"No SimObject type {object_type} is available to build: {object_name}" ) object_class = sim_object_classes_by_name[object_type] @@ -479,7 +477,7 @@ class ConfigIniFile(ConfigFile): if object_name == "root": return child_name else: - return "%s.%s" % (object_name, child_name) + return f"{object_name}.{child_name}" return [(name, make_path(name)) for name in child_names] diff --git a/configs/example/riscv/fs_linux.py b/configs/example/riscv/fs_linux.py index 1a98126e92..aec126ab0d 100644 --- a/configs/example/riscv/fs_linux.py +++ b/configs/example/riscv/fs_linux.py @@ -91,7 +91,7 @@ from common import Options def generateMemNode(state, mem_range): - 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( diff --git a/configs/example/sst/riscv_fs.py b/configs/example/sst/riscv_fs.py index fb22f29190..fc8f8618c4 100644 --- a/configs/example/sst/riscv_fs.py +++ b/configs/example/sst/riscv_fs.py @@ -35,7 +35,7 @@ import argparse def generateMemNode(state, mem_range): - 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( diff --git a/configs/learning_gem5/part1/caches.py b/configs/learning_gem5/part1/caches.py index 9bb06ab2e6..3f7d26ed21 100644 --- a/configs/learning_gem5/part1/caches.py +++ b/configs/learning_gem5/part1/caches.py @@ -75,7 +75,7 @@ class L1ICache(L1Cache): size = "16kB" SimpleOpts.add_option( - "--l1i_size", help="L1 instruction cache size. Default: %s" % size + "--l1i_size", help=f"L1 instruction cache size. Default: {size}" ) def __init__(self, opts=None): @@ -96,7 +96,7 @@ class L1DCache(L1Cache): size = "64kB" SimpleOpts.add_option( - "--l1d_size", help="L1 data cache size. Default: %s" % size + "--l1d_size", help=f"L1 data cache size. Default: {size}" ) def __init__(self, opts=None): @@ -122,9 +122,7 @@ class L2Cache(Cache): mshrs = 20 tgts_per_mshr = 12 - SimpleOpts.add_option( - "--l2_size", help="L2 cache size. Default: %s" % size - ) + SimpleOpts.add_option("--l2_size", help=f"L2 cache size. Default: {size}") def __init__(self, opts=None): super(L2Cache, self).__init__() diff --git a/configs/learning_gem5/part3/ruby_test.py b/configs/learning_gem5/part3/ruby_test.py index d0cc1be613..e46f07bb0a 100644 --- a/configs/learning_gem5/part3/ruby_test.py +++ b/configs/learning_gem5/part3/ruby_test.py @@ -78,6 +78,4 @@ m5.instantiate() print("Beginning simulation!") exit_event = m5.simulate() -print( - "Exiting @ tick {} because {}".format(m5.curTick(), exit_event.getCause()) -) +print(f"Exiting @ tick {m5.curTick()} because {exit_event.getCause()}") diff --git a/configs/learning_gem5/part3/simple_ruby.py b/configs/learning_gem5/part3/simple_ruby.py index b62a7195c8..f3f84353e8 100644 --- a/configs/learning_gem5/part3/simple_ruby.py +++ b/configs/learning_gem5/part3/simple_ruby.py @@ -110,6 +110,4 @@ m5.instantiate() print("Beginning simulation!") exit_event = m5.simulate() -print( - "Exiting @ tick {} because {}".format(m5.curTick(), exit_event.getCause()) -) +print(f"Exiting @ tick {m5.curTick()} because {exit_event.getCause()}") diff --git a/configs/ruby/CHI.py b/configs/ruby/CHI.py index df97b923ae..96537e558a 100644 --- a/configs/ruby/CHI.py +++ b/configs/ruby/CHI.py @@ -280,6 +280,6 @@ def create_system( elif options.topology in ["Crossbar", "Pt2Pt"]: topology = create_topology(network_cntrls, options) else: - m5.fatal("%s not supported!" % options.topology) + m5.fatal(f"{options.topology} not supported!") return (cpu_sequencers, mem_cntrls, topology) diff --git a/configs/ruby/CHI_config.py b/configs/ruby/CHI_config.py index 6d2084bc7b..4f2580c373 100644 --- a/configs/ruby/CHI_config.py +++ b/configs/ruby/CHI_config.py @@ -428,7 +428,7 @@ class CPUSequencerWrapper: cpu.icache_port = self.inst_seq.in_ports for p in cpu._cached_ports: if str(p) != "icache_port": - exec("cpu.%s = self.data_seq.in_ports" % p) + exec(f"cpu.{p} = self.data_seq.in_ports") cpu.connectUncachedPorts( self.data_seq.in_ports, self.data_seq.interrupt_out_port ) diff --git a/configs/ruby/Ruby.py b/configs/ruby/Ruby.py index 3ca7b95140..d3c2efbb3f 100644 --- a/configs/ruby/Ruby.py +++ b/configs/ruby/Ruby.py @@ -120,8 +120,8 @@ def define_options(parser): ) protocol = buildEnv["PROTOCOL"] - exec("from . import %s" % protocol) - eval("%s.define_options(parser)" % protocol) + exec(f"from . import {protocol}") + eval(f"{protocol}.define_options(parser)") Network.define_options(parser) @@ -207,8 +207,8 @@ def create_topology(controllers, options): found in configs/topologies/BaseTopology.py This is a wrapper for the legacy topologies. """ - exec("import topologies.%s as Topo" % options.topology) - topology = eval("Topo.%s(controllers)" % options.topology) + exec(f"import topologies.{options.topology} as Topo") + topology = eval(f"Topo.{options.topology}(controllers)") return topology @@ -242,7 +242,7 @@ def create_system( cpus = system.cpu protocol = buildEnv["PROTOCOL"] - exec("from . import %s" % protocol) + exec(f"from . import {protocol}") try: (cpu_sequencers, dir_cntrls, topology) = eval( "%s.create_system(options, full_system, system, dma_ports,\ @@ -250,7 +250,7 @@ def create_system( % protocol ) except: - print("Error: could not create sytem for ruby protocol %s" % protocol) + print(f"Error: could not create sytem for ruby protocol {protocol}") raise # Create the network topology diff --git a/configs/topologies/CustomMesh.py b/configs/topologies/CustomMesh.py index 088e4b9cfe..c62b39a9c2 100644 --- a/configs/topologies/CustomMesh.py +++ b/configs/topologies/CustomMesh.py @@ -325,9 +325,7 @@ class CustomMesh(SimpleTopology): rni_io_params = check_same(type(n).NoC_Params, rni_io_params) else: fatal( - "topologies.CustomMesh: {} not supported".format( - n.__class__.__name__ - ) + f"topologies.CustomMesh: {n.__class__.__name__} not supported" ) # Create all mesh routers @@ -420,11 +418,11 @@ class CustomMesh(SimpleTopology): if pair_debug: print(c.path()) for r in c.addr_ranges: - print("%s" % r) + print(f"{r}") for p in c._pairing: print("\t" + p.path()) for r in p.addr_ranges: - print("\t%s" % r) + print(f"\t{r}") # all must be paired for c in all_cache: @@ -516,8 +514,8 @@ class CustomMesh(SimpleTopology): assert len(c._pairing) == pairing_check print(c.path()) for r in c.addr_ranges: - print("%s" % r) + print(f"{r}") for p in c._pairing: print("\t" + p.path()) for r in p.addr_ranges: - print("\t%s" % r) + print(f"\t{r}") diff --git a/site_scons/gem5_scons/builders/switching_headers.py b/site_scons/gem5_scons/builders/switching_headers.py index a56ab51c86..92bd613508 100755 --- a/site_scons/gem5_scons/builders/switching_headers.py +++ b/site_scons/gem5_scons/builders/switching_headers.py @@ -61,7 +61,7 @@ def SwitchingHeaders(env): os.path.realpath(dp), os.path.realpath(env["BUILDDIR"]) ) with open(path, "w") as hdr: - print('#include "%s/%s/%s"' % (dp, subdir, fp), file=hdr) + print(f'#include "{dp}/{subdir}/{fp}"', file=hdr) switching_header_action = MakeAction( build_switching_header, Transform("GENERATE") diff --git a/site_scons/gem5_scons/configure.py b/site_scons/gem5_scons/configure.py index 55a0d7d399..d04cdd49cb 100644 --- a/site_scons/gem5_scons/configure.py +++ b/site_scons/gem5_scons/configure.py @@ -46,7 +46,7 @@ import SCons.Util def CheckCxxFlag(context, flag, autoadd=True): - context.Message("Checking for compiler %s support... " % flag) + context.Message(f"Checking for compiler {flag} support... ") last_cxxflags = context.env["CXXFLAGS"] context.env.Append(CXXFLAGS=[flag]) pre_werror = context.env["CXXFLAGS"] @@ -60,7 +60,7 @@ def CheckCxxFlag(context, flag, autoadd=True): def CheckLinkFlag(context, flag, autoadd=True, set_for_shared=True): - context.Message("Checking for linker %s support... " % flag) + context.Message(f"Checking for linker {flag} support... ") last_linkflags = context.env["LINKFLAGS"] context.env.Append(LINKFLAGS=[flag]) pre_werror = context.env["LINKFLAGS"] @@ -78,7 +78,7 @@ def CheckLinkFlag(context, flag, autoadd=True, set_for_shared=True): # Add a custom Check function to test for structure members. def CheckMember(context, include, decl, member, include_quotes="<>"): - context.Message("Checking for member %s in %s..." % (member, decl)) + context.Message(f"Checking for member {member} in {decl}...") text = """ #include %(header)s int main(){ @@ -128,8 +128,8 @@ def CheckPkgConfig(context, pkgs, *args): assert pkgs for pkg in pkgs: - context.Message("Checking for pkg-config package %s... " % pkg) - ret = context.TryAction("pkg-config %s" % pkg)[0] + context.Message(f"Checking for pkg-config package {pkg}... ") + ret = context.TryAction(f"pkg-config {pkg}")[0] if not ret: context.Result(ret) continue diff --git a/site_scons/site_tools/git.py b/site_scons/site_tools/git.py index b47de77612..362c20b105 100644 --- a/site_scons/site_tools/git.py +++ b/site_scons/site_tools/git.py @@ -63,7 +63,7 @@ def install_style_hooks(env): ).strip("\n") ) except Exception as e: - print("Warning: Failed to find git repo directory: %s" % e) + print(f"Warning: Failed to find git repo directory: {e}") return git_hooks = gitdir.Dir("hooks") diff --git a/src/arch/arm/ArmSystem.py b/src/arch/arm/ArmSystem.py index 25cf8b2172..7367d80eec 100644 --- a/src/arch/arm/ArmSystem.py +++ b/src/arch/arm/ArmSystem.py @@ -262,7 +262,7 @@ class ArmSystem(System): # root instead of appended. def generateMemNode(mem_range): - 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( diff --git a/src/arch/arm/fastmodel/FastModel.py b/src/arch/arm/fastmodel/FastModel.py index 1ea3c5e8d7..8ba537623a 100644 --- a/src/arch/arm/fastmodel/FastModel.py +++ b/src/arch/arm/fastmodel/FastModel.py @@ -39,11 +39,11 @@ def AMBA_INITIATOR_ROLE(width): def SC_REQUEST_PORT_ROLE(port_type): - return "SC REQUEST PORT for %s" % port_type + return f"SC REQUEST PORT for {port_type}" def SC_RESPONSE_PORT_ROLE(port_type): - return "SC RESPONSE PORT for %s" % port_type + return f"SC RESPONSE PORT for {port_type}" class AmbaTargetSocket(Port): diff --git a/src/arch/arm/fastmodel/arm_fast_model.py b/src/arch/arm/fastmodel/arm_fast_model.py index 81b2cfe04b..5a38eb132b 100644 --- a/src/arch/arm/fastmodel/arm_fast_model.py +++ b/src/arch/arm/fastmodel/arm_fast_model.py @@ -64,13 +64,13 @@ def check_armlmd_license(timeout): for server in servers: if os.path.exists(server): - logging.debug("License file %s exists." % server) + logging.debug(f"License file {server} exists.") break tuple = server.split("@") if len(tuple) != 2: # Probably not a server, and we know the file doesn't exist. - logging.debug('License file "%s" does not exist.' % server) + logging.debug(f'License file "{server}" does not exist.') continue try: @@ -80,17 +80,15 @@ def check_armlmd_license(timeout): (tuple[1], int(tuple[0])), timeout=timeout ) s.close() - logging.debug("License server %s is reachable." % server) + logging.debug(f"License server {server} is reachable.") break except Exception as e: logging.debug( - "Cannot connect to license server %s (%s: %s)." - % (server, type(e).__name__, e) + f"Cannot connect to license server {server} ({type(e).__name__}: {e})." ) else: raise ConnectionError( - "Cannot connect to any of the license servers (%s)." - % ", ".join(servers) + f"Cannot connect to any of the license servers ({', '.join(servers)})." ) diff --git a/src/arch/isa_parser/isa_parser.py b/src/arch/isa_parser/isa_parser.py index 39b50f06b6..0f29840c3b 100755 --- a/src/arch/isa_parser/isa_parser.py +++ b/src/arch/isa_parser/isa_parser.py @@ -206,13 +206,11 @@ class Format(object): label = "def format " + id self.user_code = compile(fixPythonIndentation(code), label, "exec") param_list = ", ".join(params) - f = ( - """def defInst(_code, _context, %s): + f = f"""def defInst(_code, _context, {param_list}): my_locals = vars().copy() exec(_code, _context, my_locals) - return my_locals\n""" - % param_list - ) + return my_locals +""" c = compile(f, label + " wrapper", "exec") exec(c, globals()) self.func = defInst @@ -230,7 +228,7 @@ class Format(object): except Exception as exc: if debug: raise - error(lineno, 'error defining "%s": %s.' % (name, exc)) + error(lineno, f'error defining "{name}": {exc}.') for k in list(vars.keys()): if k not in ( "header_output", @@ -250,7 +248,7 @@ class NoFormat(object): def defineInst(self, parser, name, args, lineno): error( - lineno, 'instruction definition "%s" with no active format!' % name + lineno, f'instruction definition "{name}" with no active format!' ) @@ -606,7 +604,7 @@ class ISAParser(Grammar): if section == "header": file = "decoder.hh" else: - file = "%s.cc" % section + file = f"{section}.cc" filename = self.suffixize(file, section) try: return self.files[filename] @@ -652,7 +650,7 @@ class ISAParser(Grammar): ) fn = "decoder-g.hh.inc" assert fn in self.files - f.write('#include "%s"\n' % fn) + f.write(f'#include "{fn}"\n') fn = "decoder-ns.hh.inc" assert fn in self.files @@ -663,26 +661,25 @@ class ISAParser(Grammar): ) f.write("} // namespace gem5") f.write( - "\n#endif // __ARCH_%s_GENERATED_DECODER_HH__\n" - % self.isa_name.upper() + f"\n#endif // __ARCH_{self.isa_name.upper()}_GENERATED_DECODER_HH__\n" ) # decoder method - cannot be split file = "decoder.cc" with self.open(file) as f: fn = "base/compiler.hh" - f.write('#include "%s"\n' % fn) + f.write(f'#include "{fn}"\n') fn = "decoder-g.cc.inc" assert fn in self.files - f.write('#include "%s"\n' % fn) + f.write(f'#include "{fn}"\n') fn = "decoder.hh" - f.write('#include "%s"\n' % fn) + f.write(f'#include "{fn}"\n') fn = "decode-method.cc.inc" # is guaranteed to have been written for parse to complete - f.write('#include "%s"\n' % fn) + f.write(f'#include "{fn}"\n') extn = re.compile("(\.[^\.]+)$") @@ -697,10 +694,10 @@ class ISAParser(Grammar): with self.open(file) as f: fn = "decoder-g.cc.inc" assert fn in self.files - f.write('#include "%s"\n' % fn) + f.write(f'#include "{fn}"\n') fn = "decoder.hh" - f.write('#include "%s"\n' % fn) + f.write(f'#include "{fn}"\n') fn = "decoder-ns.cc.inc" assert fn in self.files @@ -708,7 +705,7 @@ class ISAParser(Grammar): print("namespace %s {" % self.namespace, file=f) if splits > 1: print("#define __SPLIT %u" % i, file=f) - print('#include "%s"' % fn, file=f) + print(f'#include "{fn}"', file=f) print("} // namespace %s" % self.namespace, file=f) print("} // namespace gem5", file=f) @@ -721,7 +718,7 @@ class ISAParser(Grammar): with self.open(file) as f: fn = "exec-g.cc.inc" assert fn in self.files - f.write('#include "%s"\n' % fn) + f.write(f'#include "{fn}"\n') f.write('#include "cpu/exec_context.hh"\n') f.write('#include "decoder.hh"\n') @@ -731,7 +728,7 @@ class ISAParser(Grammar): print("namespace %s {" % self.namespace, file=f) if splits > 1: print("#define __SPLIT %u" % i, file=f) - print('#include "%s"' % fn, file=f) + print(f'#include "{fn}"', file=f) print("} // namespace %s" % self.namespace, file=f) print("} // namespace gem5", file=f) @@ -847,7 +844,7 @@ class ISAParser(Grammar): try: t.value = int(t.value, 0) except ValueError: - error(t.lexer.lineno, 'Integer value "%s" too large' % t.value) + error(t.lexer.lineno, f'Integer value "{t.value}" too large') t.value = 0 return t @@ -902,7 +899,7 @@ class ISAParser(Grammar): # Error handler def t_error(self, t): - error(t.lexer.lineno, "illegal character '%s'" % t.value[0]) + error(t.lexer.lineno, f"illegal character '{t.value[0]}'") t.skip(1) ##################################################################### @@ -1060,7 +1057,7 @@ del wrap traceback.print_exc(file=sys.stdout) if debug: raise - error(t.lineno(1), "In global let block: %s" % exc) + error(t.lineno(1), f"In global let block: {exc}") GenCode( self, header_output=self.exportContext["header_output"], @@ -1078,7 +1075,7 @@ del wrap except Exception as exc: if debug: raise - error(t.lineno(1), "In def operand_types: %s" % exc) + error(t.lineno(1), f"In def operand_types: {exc}") # Define the mapping from operand names to operand classes and # other traits. Stored in operandNameMap. @@ -1094,7 +1091,7 @@ del wrap except Exception as exc: if debug: raise - error(t.lineno(1), "In def operands: %s" % exc) + error(t.lineno(1), f"In def operands: {exc}") self.buildOperandNameMap(user_dict, t.lexer.lineno) # A bitfield definition looks like: @@ -1105,7 +1102,7 @@ del wrap expr = "bits(machInst, %2d, %2d)" % (t[6], t[8]) if t[2] == "signed": expr = "sext<%d>(%s)" % (t[6] - t[8] + 1, expr) - hash_define = "#undef %s\n#define %s\t%s\n" % (t[4], t[4], expr) + hash_define = f"#undef {t[4]}\n#define {t[4]}\t{expr}\n" GenCode(self, header_output=hash_define).emit() # alternate form for single bit: 'def [signed] bitfield []' @@ -1114,7 +1111,7 @@ del wrap expr = "bits(machInst, %2d, %2d)" % (t[6], t[6]) if t[2] == "signed": expr = "sext<%d>(%s)" % (1, expr) - hash_define = "#undef %s\n#define %s\t%s\n" % (t[4], t[4], expr) + hash_define = f"#undef {t[4]}\n#define {t[4]}\t{expr}\n" GenCode(self, header_output=hash_define).emit() # alternate form for structure member: 'def bitfield ' @@ -1124,8 +1121,8 @@ del wrap error( t.lineno(1), "error: structure bitfields are always unsigned." ) - expr = "machInst.%s" % t[5] - hash_define = "#undef %s\n#define %s\t%s\n" % (t[4], t[4], expr) + expr = f"machInst.{t[5]}" + hash_define = f"#undef {t[4]}\n#define {t[4]}\t{expr}\n" GenCode(self, header_output=hash_define).emit() def p_id_with_dot_0(self, t): @@ -1147,7 +1144,7 @@ del wrap def p_def_template(self, t): "def_template : DEF TEMPLATE ID CODELIT SEMI" if t[3] in self.templateMap: - print("warning: template %s already defined" % t[3]) + print(f"warning: template {t[3]} already defined") self.templateMap[t[3]] = Template(self, t[4]) # An instruction format definition looks like @@ -1326,9 +1323,9 @@ StaticInstPtr "push_format_id : ID" try: self.formatStack.push(self.formatMap[t[1]]) - t[0] = ("", "// format %s" % t[1]) + t[0] = ("", f"// format {t[1]}") except KeyError: - error(t.lineno(1), 'instruction format "%s" not defined.' % t[1]) + error(t.lineno(1), f'instruction format "{t[1]}" not defined.') # Nested decode block: if the value of the current field matches # the specified constant(s), do a nested decode on some other field. @@ -1339,7 +1336,7 @@ StaticInstPtr # just wrap the decoding code from the block as a case in the # outer switch statement. codeObj.wrap_decode_block( - "\n%s\n" % "".join(case_list), "GEM5_UNREACHABLE;\n" + f"\n{''.join(case_list)}\n", "GEM5_UNREACHABLE;\n" ) codeObj.has_decode_default = case_list == ["default:"] t[0] = codeObj @@ -1349,7 +1346,7 @@ StaticInstPtr "decode_stmt : case_list COLON inst SEMI" case_list = t[1] codeObj = t[3] - codeObj.wrap_decode_block("\n%s" % "".join(case_list), "break;\n") + codeObj.wrap_decode_block(f"\n{''.join(case_list)}", "break;\n") codeObj.has_decode_default = case_list == ["default:"] t[0] = codeObj @@ -1368,7 +1365,7 @@ StaticInstPtr return "case %#x: " % lit def prep_str_lit_case_label(self, lit): - return "case %s: " % lit + return f"case {lit}: " def p_case_list_1(self, t): "case_list : INTLIT" @@ -1399,7 +1396,7 @@ StaticInstPtr args = ",".join(list(map(str, t[3]))) args = re.sub("(?m)^", "//", args) args = re.sub("^//", "", args) - comment = "\n// %s::%s(%s)\n" % (currentFormat.id, t[1], args) + comment = f"\n// {currentFormat.id}::{t[1]}({args})\n" codeObj.prepend_all(comment) t[0] = codeObj @@ -1410,10 +1407,10 @@ StaticInstPtr try: format = self.formatMap[t[1]] except KeyError: - error(t.lineno(1), 'instruction format "%s" not defined.' % t[1]) + error(t.lineno(1), f'instruction format "{t[1]}" not defined.') codeObj = format.defineInst(self, t[3], t[5], t.lexer.lineno) - comment = "\n// %s::%s(%s)\n" % (t[1], t[3], t[5]) + comment = f"\n// {t[1]}::{t[3]}({t[5]})\n" codeObj.prepend_all(comment) t[0] = codeObj @@ -1503,7 +1500,7 @@ StaticInstPtr # t.value) def p_error(self, t): if t: - error(t.lexer.lineno, "syntax error at '%s'" % t.value) + error(t.lexer.lineno, f"syntax error at '{t.value}'") else: error("unknown syntax error") @@ -1523,7 +1520,7 @@ StaticInstPtr # make sure we haven't already defined this one if id in self.formatMap: - error(lineno, "format %s redefined." % id) + error(lineno, f"format {id} redefined.") # create new object and store in global map self.formatMap[id] = Format(id, params, code) @@ -1641,7 +1638,7 @@ StaticInstPtr try: contents = open(filename).read() except IOError: - error('Error including file "%s"' % filename) + error(f'Error including file "{filename}"') self.fileNameStack.push(LineTracker(filename)) @@ -1691,7 +1688,7 @@ StaticInstPtr self._parse_isa_desc(*args, **kwargs) except ISAParserError as e: print(backtrace(self.fileNameStack)) - print("At %s:" % e.lineno) + print(f"At {e.lineno}:") print(e) sys.exit(1) diff --git a/src/arch/isa_parser/operand_list.py b/src/arch/isa_parser/operand_list.py index 8df36c711b..5741a52324 100755 --- a/src/arch/isa_parser/operand_list.py +++ b/src/arch/isa_parser/operand_list.py @@ -205,8 +205,7 @@ class SubOperandList(OperandList): op_desc = requestor_list.find_base(op_base) if not op_desc: error( - "Found operand %s which is not in the requestor list!" - % op_base + f"Found operand {op_base} which is not in the requestor list!" ) else: # See if we've already found this operand diff --git a/src/arch/isa_parser/operand_types.py b/src/arch/isa_parser/operand_types.py index 4786f88774..174a54cd4c 100755 --- a/src/arch/isa_parser/operand_types.py +++ b/src/arch/isa_parser/operand_types.py @@ -286,16 +286,16 @@ class VecRegOperand(RegOperand): else: ext = dflt_elem_ext ctype = self.parser.operandTypeMap[ext] - return "\n\t%s %s = 0;" % (ctype, elem_name) + return f"\n\t{ctype} {elem_name} = 0;" def makeDecl(self): if not self.is_dest and self.is_src: - c_decl = "\t/* Vars for %s*/" % (self.base_name) + c_decl = f"\t/* Vars for {self.base_name}*/" if hasattr(self, "active_elems"): if self.active_elems: for elem in self.active_elems: c_decl += self.makeDeclElem(elem) - return c_decl + "\t/* End vars for %s */\n" % (self.base_name) + return c_decl + f"\t/* End vars for {self.base_name} */\n" else: return "" @@ -308,12 +308,7 @@ class VecRegOperand(RegOperand): else: ext = dflt_elem_ext ctype = self.parser.operandTypeMap[ext] - c_read = "\t\t%s& %s = %s[%s];\n" % ( - ctype, - elem_name, - self.base_name, - elem_spec, - ) + c_read = f"\t\t{ctype}& {elem_name} = {self.base_name}[{elem_spec}];\n" return c_read def makeReadW(self): @@ -346,7 +341,7 @@ class VecRegOperand(RegOperand): else: ext = dflt_elem_ext ctype = self.parser.operandTypeMap[ext] - c_read = "\t\t%s = %s[%s];\n" % (elem_name, name, elem_spec) + c_read = f"\t\t{elem_name} = {name}[{elem_spec}];\n" return c_read def makeRead(self): @@ -610,10 +605,7 @@ class PCStateOperand(Operand): def makeWrite(self): if self.reg_spec: # A component of the PC state. - return "__parserAutoPCState.%s(%s);\n" % ( - self.reg_spec, - self.base_name, - ) + return f"__parserAutoPCState.{self.reg_spec}({self.base_name});\n" else: # The whole PC state itself. return f"xc->pcState({self.base_name});\n" @@ -624,7 +616,7 @@ class PCStateOperand(Operand): ctype = self.ctype # Note that initializations in the declarations are solely # to avoid 'uninitialized variable' errors from the compiler. - return "%s %s = 0;\n" % (ctype, self.base_name) + return f"{ctype} {self.base_name} = 0;\n" def isPCState(self): return 1 diff --git a/src/arch/micro_asm.py b/src/arch/micro_asm.py index 5b4378881e..1c2183c07a 100644 --- a/src/arch/micro_asm.py +++ b/src/arch/micro_asm.py @@ -56,9 +56,9 @@ class MicroContainer: self.microops.append(microop) def __str__(self): - string = "%s:\n" % self.name + string = f"{self.name}:\n" for microop in self.microops: - string += " %s\n" % microop + string += f" {microop}\n" return string @@ -72,7 +72,7 @@ class RomMacroop: self.target = target def __str__(self): - return "%s: %s\n" % (self.name, self.target) + return f"{self.name}: {self.target}\n" class Rom(MicroContainer): @@ -130,29 +130,26 @@ class Directive(Statement): def print_error(message): print() - print("*** %s" % message) + print(f"*** {message}") print() def handle_statement(parser, container, statement): if statement.is_microop: if statement.mnemonic not in parser.microops.keys(): - raise Exception( - "Unrecognized mnemonic: {}".format(statement.mnemonic) - ) + raise Exception(f"Unrecognized mnemonic: {statement.mnemonic}") parser.symbols[ "__microopClassFromInsideTheAssembler" ] = parser.microops[statement.mnemonic] try: microop = eval( - "__microopClassFromInsideTheAssembler(%s)" % statement.params, + f"__microopClassFromInsideTheAssembler({statement.params})", {}, parser.symbols, ) except: print_error( - "Error creating microop object with mnemonic %s." - % statement.mnemonic + f"Error creating microop object with mnemonic {statement.mnemonic}." ) raise try: @@ -166,16 +163,13 @@ def handle_statement(parser, container, statement): raise elif statement.is_directive: if statement.name not in container.directives.keys(): - raise Exception( - "Unrecognized directive: {}".format(statement.name) - ) + raise Exception(f"Unrecognized directive: {statement.name}") parser.symbols[ "__directiveFunctionFromInsideTheAssembler" ] = container.directives[statement.name] try: eval( - "__directiveFunctionFromInsideTheAssembler(%s)" - % statement.params, + f"__directiveFunctionFromInsideTheAssembler({statement.params})", {}, parser.symbols, ) @@ -184,9 +178,7 @@ def handle_statement(parser, container, statement): print(container.directives) raise else: - raise Exception( - "Didn't recognize the type of statement {}".format(statement) - ) + raise Exception(f"Didn't recognize the type of statement {statement}") ########################################################################## @@ -207,7 +199,7 @@ def error(lineno, string, print_traceback=False): line_str = "%d:" % lineno else: line_str = "" - sys.exit("%s %s" % (line_str, string)) + sys.exit(f"{line_str} {string}") reserved = ("DEF", "MACROOP", "ROM", "EXTERN") @@ -358,7 +350,7 @@ t_ANY_ignore = " \t\x0c" def t_ANY_error(t): - error(t.lineno, "illegal character '%s'" % t.value[0]) + error(t.lineno, f"illegal character '{t.value[0]}'") t.skip(1) @@ -570,7 +562,7 @@ def p_directive_1(t): # *token*, not a grammar symbol (hence the need to use t.value) def p_error(t): if t: - error(t.lineno, "syntax error at '%s'" % t.value) + error(t.lineno, f"syntax error at '{t.value}'") else: error(0, "unknown syntax error", True) diff --git a/src/arch/micro_asm_test.py b/src/arch/micro_asm_test.py index 85bbe6b7c9..609b8a4021 100755 --- a/src/arch/micro_asm_test.py +++ b/src/arch/micro_asm_test.py @@ -39,10 +39,10 @@ class Bah_Tweaked(object): class Hoop(object): def __init__(self, first_param, second_param): - self.mnemonic = "hoop_%s_%s" % (first_param, second_param) + self.mnemonic = f"hoop_{first_param}_{second_param}" def __str__(self): - return "%s" % self.mnemonic + return f"{self.mnemonic}" class Dah(object): diff --git a/src/arch/x86/bios/IntelMP.py b/src/arch/x86/bios/IntelMP.py index 3471f50540..a1e7e823be 100644 --- a/src/arch/x86/bios/IntelMP.py +++ b/src/arch/x86/bios/IntelMP.py @@ -81,8 +81,7 @@ class X86IntelMPConfigTable(SimObject): self.ext_entries.append(entry) else: panic( - "Don't know what type of Intel MP entry %s is." - % entry.__class__.__name__ + f"Don't know what type of Intel MP entry {entry.__class__.__name__} is." ) diff --git a/src/arch/x86/isa/insts/__init__.py b/src/arch/x86/isa/insts/__init__.py index 2d10d98647..270d405a28 100644 --- a/src/arch/x86/isa/insts/__init__.py +++ b/src/arch/x86/isa/insts/__init__.py @@ -46,5 +46,5 @@ microcode = """ # X86 microcode """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/general_purpose/__init__.py b/src/arch/x86/isa/insts/general_purpose/__init__.py index eef0150ae8..0843c231d6 100644 --- a/src/arch/x86/isa/insts/general_purpose/__init__.py +++ b/src/arch/x86/isa/insts/general_purpose/__init__.py @@ -56,5 +56,5 @@ microcode = """ # Microcode for general purpose instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/general_purpose/arithmetic/__init__.py b/src/arch/x86/isa/insts/general_purpose/arithmetic/__init__.py index 287d1de9eb..29fa42d4f5 100644 --- a/src/arch/x86/isa/insts/general_purpose/arithmetic/__init__.py +++ b/src/arch/x86/isa/insts/general_purpose/arithmetic/__init__.py @@ -41,5 +41,5 @@ categories = [ microcode = "" for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/general_purpose/compare_and_test/__init__.py b/src/arch/x86/isa/insts/general_purpose/compare_and_test/__init__.py index fc7b35f867..65ab0e8db6 100644 --- a/src/arch/x86/isa/insts/general_purpose/compare_and_test/__init__.py +++ b/src/arch/x86/isa/insts/general_purpose/compare_and_test/__init__.py @@ -44,5 +44,5 @@ categories = [ microcode = "" for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/general_purpose/control_transfer/__init__.py b/src/arch/x86/isa/insts/general_purpose/control_transfer/__init__.py index b651278990..93a437a80c 100644 --- a/src/arch/x86/isa/insts/general_purpose/control_transfer/__init__.py +++ b/src/arch/x86/isa/insts/general_purpose/control_transfer/__init__.py @@ -44,5 +44,5 @@ categories = [ microcode = "" for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/general_purpose/data_conversion/__init__.py b/src/arch/x86/isa/insts/general_purpose/data_conversion/__init__.py index e6eca02d15..613b9c8fed 100644 --- a/src/arch/x86/isa/insts/general_purpose/data_conversion/__init__.py +++ b/src/arch/x86/isa/insts/general_purpose/data_conversion/__init__.py @@ -44,5 +44,5 @@ categories = [ microcode = "" for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/general_purpose/data_transfer/__init__.py b/src/arch/x86/isa/insts/general_purpose/data_transfer/__init__.py index cef9e595b4..e53f82bfe8 100644 --- a/src/arch/x86/isa/insts/general_purpose/data_transfer/__init__.py +++ b/src/arch/x86/isa/insts/general_purpose/data_transfer/__init__.py @@ -37,5 +37,5 @@ categories = ["conditional_move", "move", "stack_operations", "xchg"] microcode = "" for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/general_purpose/flags/__init__.py b/src/arch/x86/isa/insts/general_purpose/flags/__init__.py index ef1585ab26..6005ea0d5d 100644 --- a/src/arch/x86/isa/insts/general_purpose/flags/__init__.py +++ b/src/arch/x86/isa/insts/general_purpose/flags/__init__.py @@ -37,5 +37,5 @@ categories = ["load_and_store", "push_and_pop", "set_and_clear"] microcode = "" for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/general_purpose/input_output/__init__.py b/src/arch/x86/isa/insts/general_purpose/input_output/__init__.py index 08b88dd9bd..e1ee1d6571 100644 --- a/src/arch/x86/isa/insts/general_purpose/input_output/__init__.py +++ b/src/arch/x86/isa/insts/general_purpose/input_output/__init__.py @@ -37,5 +37,5 @@ categories = ["general_io", "string_io"] microcode = "" for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/general_purpose/rotate_and_shift/__init__.py b/src/arch/x86/isa/insts/general_purpose/rotate_and_shift/__init__.py index 2675ed2429..202cf32cd2 100644 --- a/src/arch/x86/isa/insts/general_purpose/rotate_and_shift/__init__.py +++ b/src/arch/x86/isa/insts/general_purpose/rotate_and_shift/__init__.py @@ -37,5 +37,5 @@ categories = ["rotate", "shift"] microcode = "" for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/general_purpose/string/__init__.py b/src/arch/x86/isa/insts/general_purpose/string/__init__.py index 0f7e81a82c..13199ed9f3 100644 --- a/src/arch/x86/isa/insts/general_purpose/string/__init__.py +++ b/src/arch/x86/isa/insts/general_purpose/string/__init__.py @@ -43,5 +43,5 @@ categories = [ microcode = "" for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/__init__.py b/src/arch/x86/isa/insts/simd128/__init__.py index 5f0b52c50a..2e343362d3 100644 --- a/src/arch/x86/isa/insts/simd128/__init__.py +++ b/src/arch/x86/isa/insts/simd128/__init__.py @@ -39,5 +39,5 @@ microcode = """ # SSE instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/floating_point/__init__.py b/src/arch/x86/isa/insts/simd128/floating_point/__init__.py index 4becf25c29..c0f3149623 100644 --- a/src/arch/x86/isa/insts/simd128/floating_point/__init__.py +++ b/src/arch/x86/isa/insts/simd128/floating_point/__init__.py @@ -46,5 +46,5 @@ microcode = """ # SSE instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/floating_point/arithmetic/__init__.py b/src/arch/x86/isa/insts/simd128/floating_point/arithmetic/__init__.py index 08bfb09f03..d03a3c9c6f 100644 --- a/src/arch/x86/isa/insts/simd128/floating_point/arithmetic/__init__.py +++ b/src/arch/x86/isa/insts/simd128/floating_point/arithmetic/__init__.py @@ -50,5 +50,5 @@ microcode = """ # SSE instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/floating_point/compare/__init__.py b/src/arch/x86/isa/insts/simd128/floating_point/compare/__init__.py index d9f10dcedc..9b5b8fa1b9 100644 --- a/src/arch/x86/isa/insts/simd128/floating_point/compare/__init__.py +++ b/src/arch/x86/isa/insts/simd128/floating_point/compare/__init__.py @@ -43,5 +43,5 @@ microcode = """ # SSE instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/floating_point/data_conversion/__init__.py b/src/arch/x86/isa/insts/simd128/floating_point/data_conversion/__init__.py index 6661dc8120..b6ddbf1e2c 100644 --- a/src/arch/x86/isa/insts/simd128/floating_point/data_conversion/__init__.py +++ b/src/arch/x86/isa/insts/simd128/floating_point/data_conversion/__init__.py @@ -45,5 +45,5 @@ microcode = """ # SSE instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/floating_point/data_reordering/__init__.py b/src/arch/x86/isa/insts/simd128/floating_point/data_reordering/__init__.py index 2584d21ede..711a98b81b 100644 --- a/src/arch/x86/isa/insts/simd128/floating_point/data_reordering/__init__.py +++ b/src/arch/x86/isa/insts/simd128/floating_point/data_reordering/__init__.py @@ -39,5 +39,5 @@ microcode = """ # SSE instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/floating_point/data_transfer/__init__.py b/src/arch/x86/isa/insts/simd128/floating_point/data_transfer/__init__.py index d1e90960ac..3c4e21da9d 100644 --- a/src/arch/x86/isa/insts/simd128/floating_point/data_transfer/__init__.py +++ b/src/arch/x86/isa/insts/simd128/floating_point/data_transfer/__init__.py @@ -44,5 +44,5 @@ microcode = """ # SSE instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/floating_point/logical/__init__.py b/src/arch/x86/isa/insts/simd128/floating_point/logical/__init__.py index 996aa74e93..3917c8b10d 100644 --- a/src/arch/x86/isa/insts/simd128/floating_point/logical/__init__.py +++ b/src/arch/x86/isa/insts/simd128/floating_point/logical/__init__.py @@ -39,5 +39,5 @@ microcode = """ # SSE instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/integer/__init__.py b/src/arch/x86/isa/insts/simd128/integer/__init__.py index cf4491f9bf..ad8751fe45 100644 --- a/src/arch/x86/isa/insts/simd128/integer/__init__.py +++ b/src/arch/x86/isa/insts/simd128/integer/__init__.py @@ -48,5 +48,5 @@ microcode = """ # 128 bit multimedia and scientific instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/integer/arithmetic/__init__.py b/src/arch/x86/isa/insts/simd128/integer/arithmetic/__init__.py index c2de13b845..6d757c91f3 100644 --- a/src/arch/x86/isa/insts/simd128/integer/arithmetic/__init__.py +++ b/src/arch/x86/isa/insts/simd128/integer/arithmetic/__init__.py @@ -47,5 +47,5 @@ microcode = """ # 128 bit multimedia and scientific instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/integer/compare/__init__.py b/src/arch/x86/isa/insts/simd128/integer/compare/__init__.py index df0bc81b10..e69ca449e4 100644 --- a/src/arch/x86/isa/insts/simd128/integer/compare/__init__.py +++ b/src/arch/x86/isa/insts/simd128/integer/compare/__init__.py @@ -39,5 +39,5 @@ microcode = """ # 128 bit multimedia and scientific instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/integer/data_conversion/__init__.py b/src/arch/x86/isa/insts/simd128/integer/data_conversion/__init__.py index 3212cf0636..1d85906e1a 100644 --- a/src/arch/x86/isa/insts/simd128/integer/data_conversion/__init__.py +++ b/src/arch/x86/isa/insts/simd128/integer/data_conversion/__init__.py @@ -43,5 +43,5 @@ microcode = """ # 128 bit multimedia and scientific conversion instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/integer/data_reordering/__init__.py b/src/arch/x86/isa/insts/simd128/integer/data_reordering/__init__.py index 1c0d574847..6a21322891 100644 --- a/src/arch/x86/isa/insts/simd128/integer/data_reordering/__init__.py +++ b/src/arch/x86/isa/insts/simd128/integer/data_reordering/__init__.py @@ -44,5 +44,5 @@ microcode = """ # 128 bit multimedia and scientific instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/integer/data_transfer/__init__.py b/src/arch/x86/isa/insts/simd128/integer/data_transfer/__init__.py index 4117b59325..0d67e7d9ca 100644 --- a/src/arch/x86/isa/insts/simd128/integer/data_transfer/__init__.py +++ b/src/arch/x86/isa/insts/simd128/integer/data_transfer/__init__.py @@ -39,5 +39,5 @@ microcode = """ # 128 bit multimedia and scientific data transfer instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/integer/logical/__init__.py b/src/arch/x86/isa/insts/simd128/integer/logical/__init__.py index 72fc2cfd56..15e5fe32d5 100644 --- a/src/arch/x86/isa/insts/simd128/integer/logical/__init__.py +++ b/src/arch/x86/isa/insts/simd128/integer/logical/__init__.py @@ -39,5 +39,5 @@ microcode = """ # 128 bit multimedia and scientific instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/integer/save_and_restore_state/__init__.py b/src/arch/x86/isa/insts/simd128/integer/save_and_restore_state/__init__.py index ee0ee06639..e4511545dd 100644 --- a/src/arch/x86/isa/insts/simd128/integer/save_and_restore_state/__init__.py +++ b/src/arch/x86/isa/insts/simd128/integer/save_and_restore_state/__init__.py @@ -39,5 +39,5 @@ microcode = """ # 128 bit multimedia and scientific instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd128/integer/shift/__init__.py b/src/arch/x86/isa/insts/simd128/integer/shift/__init__.py index b3a35cb812..1e7cc1c700 100644 --- a/src/arch/x86/isa/insts/simd128/integer/shift/__init__.py +++ b/src/arch/x86/isa/insts/simd128/integer/shift/__init__.py @@ -43,5 +43,5 @@ microcode = """ # 128 bit multimedia and scientific instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd64/__init__.py b/src/arch/x86/isa/insts/simd64/__init__.py index 5109e99634..ac36d68cad 100644 --- a/src/arch/x86/isa/insts/simd64/__init__.py +++ b/src/arch/x86/isa/insts/simd64/__init__.py @@ -39,5 +39,5 @@ microcode = """ # 64 bit multimedia instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd64/floating_point/__init__.py b/src/arch/x86/isa/insts/simd64/floating_point/__init__.py index 1d4d70f700..a4c8278f27 100644 --- a/src/arch/x86/isa/insts/simd64/floating_point/__init__.py +++ b/src/arch/x86/isa/insts/simd64/floating_point/__init__.py @@ -39,5 +39,5 @@ microcode = """ # 64 bit multimedia instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd64/floating_point/arithmetic/__init__.py b/src/arch/x86/isa/insts/simd64/floating_point/arithmetic/__init__.py index 59cb06036f..ac8672f2d0 100644 --- a/src/arch/x86/isa/insts/simd64/floating_point/arithmetic/__init__.py +++ b/src/arch/x86/isa/insts/simd64/floating_point/arithmetic/__init__.py @@ -46,5 +46,5 @@ microcode = """ # 64 bit multimedia instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd64/floating_point/compare/__init__.py b/src/arch/x86/isa/insts/simd64/floating_point/compare/__init__.py index 1226c61f98..96601c1871 100644 --- a/src/arch/x86/isa/insts/simd64/floating_point/compare/__init__.py +++ b/src/arch/x86/isa/insts/simd64/floating_point/compare/__init__.py @@ -39,5 +39,5 @@ microcode = """ # 64 bit multimedia instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd64/integer/__init__.py b/src/arch/x86/isa/insts/simd64/integer/__init__.py index 8e5209b926..6b026f78c6 100644 --- a/src/arch/x86/isa/insts/simd64/integer/__init__.py +++ b/src/arch/x86/isa/insts/simd64/integer/__init__.py @@ -49,5 +49,5 @@ microcode = """ # 64 bit multimedia instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd64/integer/arithmetic/__init__.py b/src/arch/x86/isa/insts/simd64/integer/arithmetic/__init__.py index 4458ee80f6..cd1bd9be10 100644 --- a/src/arch/x86/isa/insts/simd64/integer/arithmetic/__init__.py +++ b/src/arch/x86/isa/insts/simd64/integer/arithmetic/__init__.py @@ -46,5 +46,5 @@ microcode = """ # 64 bit multimedia instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd64/integer/compare/__init__.py b/src/arch/x86/isa/insts/simd64/integer/compare/__init__.py index 1226c61f98..96601c1871 100644 --- a/src/arch/x86/isa/insts/simd64/integer/compare/__init__.py +++ b/src/arch/x86/isa/insts/simd64/integer/compare/__init__.py @@ -39,5 +39,5 @@ microcode = """ # 64 bit multimedia instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd64/integer/data_reordering/__init__.py b/src/arch/x86/isa/insts/simd64/integer/data_reordering/__init__.py index a3ea862ec7..df73b13d89 100644 --- a/src/arch/x86/isa/insts/simd64/integer/data_reordering/__init__.py +++ b/src/arch/x86/isa/insts/simd64/integer/data_reordering/__init__.py @@ -44,5 +44,5 @@ microcode = """ # 64 bit multimedia instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd64/integer/data_transfer/__init__.py b/src/arch/x86/isa/insts/simd64/integer/data_transfer/__init__.py index 1417770087..8bad75e90c 100644 --- a/src/arch/x86/isa/insts/simd64/integer/data_transfer/__init__.py +++ b/src/arch/x86/isa/insts/simd64/integer/data_transfer/__init__.py @@ -39,5 +39,5 @@ microcode = """ # 64 bit multimedia instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd64/integer/logical/__init__.py b/src/arch/x86/isa/insts/simd64/integer/logical/__init__.py index 385af7ecac..e3d12ed838 100644 --- a/src/arch/x86/isa/insts/simd64/integer/logical/__init__.py +++ b/src/arch/x86/isa/insts/simd64/integer/logical/__init__.py @@ -39,5 +39,5 @@ microcode = """ # 64 bit multimedia instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/simd64/integer/shift/__init__.py b/src/arch/x86/isa/insts/simd64/integer/shift/__init__.py index fd8c75fa12..def2967878 100644 --- a/src/arch/x86/isa/insts/simd64/integer/shift/__init__.py +++ b/src/arch/x86/isa/insts/simd64/integer/shift/__init__.py @@ -43,5 +43,5 @@ microcode = """ # 64 bit multimedia instructions """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/system/__init__.py b/src/arch/x86/isa/insts/system/__init__.py index e84ee3e732..67d6d62322 100644 --- a/src/arch/x86/isa/insts/system/__init__.py +++ b/src/arch/x86/isa/insts/system/__init__.py @@ -47,5 +47,5 @@ categories = [ microcode = "" for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/x87/__init__.py b/src/arch/x86/isa/insts/x87/__init__.py index 169ac7275e..369450e751 100644 --- a/src/arch/x86/isa/insts/x87/__init__.py +++ b/src/arch/x86/isa/insts/x87/__init__.py @@ -48,5 +48,5 @@ microcode = """ # X86 microcode """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/x87/arithmetic/__init__.py b/src/arch/x86/isa/insts/x87/arithmetic/__init__.py index a64665722d..082582d0cd 100644 --- a/src/arch/x86/isa/insts/x87/arithmetic/__init__.py +++ b/src/arch/x86/isa/insts/x87/arithmetic/__init__.py @@ -48,5 +48,5 @@ microcode = """ # X86 microcode """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/x87/compare_and_test/__init__.py b/src/arch/x86/isa/insts/x87/compare_and_test/__init__.py index cb4b1093fe..9ce0bc96b0 100644 --- a/src/arch/x86/isa/insts/x87/compare_and_test/__init__.py +++ b/src/arch/x86/isa/insts/x87/compare_and_test/__init__.py @@ -45,5 +45,5 @@ microcode = """ # X86 microcode """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/x87/control/__init__.py b/src/arch/x86/isa/insts/x87/control/__init__.py index 00d86f468c..9bda0269a1 100644 --- a/src/arch/x86/isa/insts/x87/control/__init__.py +++ b/src/arch/x86/isa/insts/x87/control/__init__.py @@ -46,5 +46,5 @@ microcode = """ # X86 microcode """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/x87/data_transfer_and_conversion/__init__.py b/src/arch/x86/isa/insts/x87/data_transfer_and_conversion/__init__.py index dcb581e158..cd71033cb6 100644 --- a/src/arch/x86/isa/insts/x87/data_transfer_and_conversion/__init__.py +++ b/src/arch/x86/isa/insts/x87/data_transfer_and_conversion/__init__.py @@ -46,5 +46,5 @@ microcode = """ # X86 microcode """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/x87/load_constants/__init__.py b/src/arch/x86/isa/insts/x87/load_constants/__init__.py index b89e81525f..a3e41a47f0 100644 --- a/src/arch/x86/isa/insts/x87/load_constants/__init__.py +++ b/src/arch/x86/isa/insts/x87/load_constants/__init__.py @@ -39,5 +39,5 @@ microcode = """ # X86 microcode """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/x87/stack_management/__init__.py b/src/arch/x86/isa/insts/x87/stack_management/__init__.py index ffbabaf89f..5d9e16a25a 100644 --- a/src/arch/x86/isa/insts/x87/stack_management/__init__.py +++ b/src/arch/x86/isa/insts/x87/stack_management/__init__.py @@ -39,5 +39,5 @@ microcode = """ # X86 microcode """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/arch/x86/isa/insts/x87/transcendental_functions/__init__.py b/src/arch/x86/isa/insts/x87/transcendental_functions/__init__.py index d8651fe2ae..776b588ab3 100644 --- a/src/arch/x86/isa/insts/x87/transcendental_functions/__init__.py +++ b/src/arch/x86/isa/insts/x87/transcendental_functions/__init__.py @@ -39,5 +39,5 @@ microcode = """ # X86 microcode """ for category in categories: - exec("from . import %s as cat" % category) + exec(f"from . import {category} as cat") microcode += cat.microcode diff --git a/src/cpu/BaseCPU.py b/src/cpu/BaseCPU.py index d77036a480..556af52612 100644 --- a/src/cpu/BaseCPU.py +++ b/src/cpu/BaseCPU.py @@ -172,13 +172,13 @@ class BaseCPU(ClockedObject): def connectCachedPorts(self, in_ports): for p in self._cached_ports: - exec("self.%s = in_ports" % p) + exec(f"self.{p} = in_ports") def connectUncachedPorts(self, in_ports, out_ports): for p in self._uncached_interrupt_response_ports: - exec("self.%s = out_ports" % p) + exec(f"self.{p} = out_ports") for p in self._uncached_interrupt_request_ports: - exec("self.%s = in_ports" % p) + exec(f"self.{p} = in_ports") def connectAllPorts(self, cached_in, uncached_in, uncached_out): self.connectCachedPorts(cached_in) @@ -267,7 +267,7 @@ class BaseCPU(ClockedObject): # Generate cpu nodes for i in range(int(self.numThreads)): reg = (int(self.socket_id) << 8) + int(self.cpu_id) + i - node = FdtNode("cpu@%x" % reg) + node = FdtNode(f"cpu@{reg:x}") node.append(FdtPropertyStrings("device_type", "cpu")) node.appendCompatible(["gem5,arm-cpu"]) node.append(FdtPropertyWords("reg", state.CPUAddrCells(reg))) diff --git a/src/cpu/testers/traffic_gen/BaseTrafficGen.py b/src/cpu/testers/traffic_gen/BaseTrafficGen.py index 0d9146756d..b5df83e779 100644 --- a/src/cpu/testers/traffic_gen/BaseTrafficGen.py +++ b/src/cpu/testers/traffic_gen/BaseTrafficGen.py @@ -117,7 +117,7 @@ class BaseTrafficGen(ClockedObject): def connectCachedPorts(self, in_ports): if hasattr(self, "_cached_ports") and (len(self._cached_ports) > 0): for p in self._cached_ports: - exec("self.%s = in_ports" % p) + exec(f"self.{p} = in_ports") else: self.port = in_ports diff --git a/src/dev/Device.py b/src/dev/Device.py index 5c3a4193a1..7f8428e6ff 100644 --- a/src/dev/Device.py +++ b/src/dev/Device.py @@ -55,7 +55,7 @@ class PioDevice(ClockedObject): def generateBasicPioDeviceNode( self, state, name, pio_addr, size, interrupts=None ): - node = FdtNode("%s@%x" % (name, int(pio_addr))) + node = FdtNode(f"{name}@{int(pio_addr):x}") node.append( FdtPropertyWords( "reg", state.addrCells(pio_addr) + state.sizeCells(size) diff --git a/src/dev/arm/GenericTimer.py b/src/dev/arm/GenericTimer.py index a44cd6fd7e..4b104ade92 100644 --- a/src/dev/arm/GenericTimer.py +++ b/src/dev/arm/GenericTimer.py @@ -158,7 +158,7 @@ class GenericTimerFrame(PioDevice): int_virt = Param.ArmSPI("Virtual Interrupt") def generateDeviceTree(self, state, gic): - node = FdtNode("frame@{:08x}".format(self.cnt_base.value)) + node = FdtNode(f"frame@{self.cnt_base.value:08x}") node.append(FdtPropertyWords("frame-number", self._frame_num)) ints = self.int_phys.generateFdtProperty(gic) diff --git a/src/dev/arm/RealView.py b/src/dev/arm/RealView.py index 0009842771..e71f6cee5a 100644 --- a/src/dev/arm/RealView.py +++ b/src/dev/arm/RealView.py @@ -248,7 +248,7 @@ class RealViewCtrl(BasicPioDevice): idreg = Param.UInt32(0x00000000, "ID Register, SYS_ID") def generateDeviceTree(self, state): - node = FdtNode("sysreg@%x" % int(self.pio_addr)) + node = FdtNode(f"sysreg@{int(self.pio_addr):x}") node.appendCompatible("arm,vexpress-sysreg") node.append( FdtPropertyWords( @@ -458,7 +458,7 @@ class FixedClock(SrcClockDomain): def generateDeviceTree(self, state): if len(self.clock) > 1: fatal("FixedClock configured with multiple frequencies") - node = FdtNode("clock{}".format(FixedClock._index)) + node = FdtNode(f"clock{FixedClock._index}") node.appendCompatible("fixed-clock") node.append(FdtPropertyWords("#clock-cells", 0)) node.append( @@ -743,7 +743,7 @@ class MmioSRAM(ParentMem): super().__init__(**kwargs) def generateDeviceTree(self, state): - node = FdtNode("sram@%x" % int(self.range.start)) + node = FdtNode(f"sram@{int(self.range.start):x}") node.appendCompatible(["mmio-sram"]) node.append( FdtPropertyWords( diff --git a/src/dev/arm/SMMUv3.py b/src/dev/arm/SMMUv3.py index a1992ecd63..46fad3bf68 100644 --- a/src/dev/arm/SMMUv3.py +++ b/src/dev/arm/SMMUv3.py @@ -203,7 +203,7 @@ class SMMUv3(ClockedObject): def generateDeviceTree(self, state): reg_addr = self.reg_map.start reg_size = self.reg_map.size() - node = FdtNode("smmuv3@%x" % int(reg_addr)) + node = FdtNode(f"smmuv3@{int(reg_addr):x}") node.appendCompatible("arm,smmu-v3") node.append( FdtPropertyWords( diff --git a/src/dev/arm/css/MHU.py b/src/dev/arm/css/MHU.py index 6a930f423c..a26b239332 100644 --- a/src/dev/arm/css/MHU.py +++ b/src/dev/arm/css/MHU.py @@ -103,7 +103,7 @@ class MHU(BasicPioDevice): scp = Param.Scp(Parent.any, "System Control Processor") def generateDeviceTree(self, state): - node = FdtNode("mailbox@%x" % int(self.pio_addr)) + node = FdtNode(f"mailbox@{int(self.pio_addr):x}") node.appendCompatible(["arm,mhu", "arm,primecell"]) node.append( FdtPropertyWords( diff --git a/src/mem/slicc/ast/ActionDeclAST.py b/src/mem/slicc/ast/ActionDeclAST.py index 21b6e3a2f7..ff6a4ff9d5 100644 --- a/src/mem/slicc/ast/ActionDeclAST.py +++ b/src/mem/slicc/ast/ActionDeclAST.py @@ -36,7 +36,7 @@ class ActionDeclAST(DeclAST): self.statement_list = statement_list def __repr__(self): - return "[ActionDecl: %r]" % (self.ident) + return f"[ActionDecl: {self.ident!r}]" def generate(self): resources = {} diff --git a/src/mem/slicc/ast/AssignStatementAST.py b/src/mem/slicc/ast/AssignStatementAST.py index d1f5f5105a..47d91a3413 100644 --- a/src/mem/slicc/ast/AssignStatementAST.py +++ b/src/mem/slicc/ast/AssignStatementAST.py @@ -35,7 +35,7 @@ class AssignStatementAST(StatementAST): self.rvalue = rvalue def __repr__(self): - return "[AssignStatementAST: %r := %r]" % (self.lvalue, self.rvalue) + return f"[AssignStatementAST: {self.lvalue!r} := {self.rvalue!r}]" def generate(self, code, return_type, **kwargs): lcode = self.slicc.codeFormatter() diff --git a/src/mem/slicc/ast/CheckAllocateStatementAST.py b/src/mem/slicc/ast/CheckAllocateStatementAST.py index 83325df7f0..0f3c6e47dd 100644 --- a/src/mem/slicc/ast/CheckAllocateStatementAST.py +++ b/src/mem/slicc/ast/CheckAllocateStatementAST.py @@ -34,7 +34,7 @@ class CheckAllocateStatementAST(StatementAST): self.variable = variable def __repr__(self): - return "[CheckAllocateStatementAst: %r]" % self.variable + return f"[CheckAllocateStatementAst: {self.variable!r}]" def generate(self, code, return_type, **kwargs): # FIXME - check the type of the variable diff --git a/src/mem/slicc/ast/CheckProbeStatementAST.py b/src/mem/slicc/ast/CheckProbeStatementAST.py index 4e798ed12f..10945cfc30 100644 --- a/src/mem/slicc/ast/CheckProbeStatementAST.py +++ b/src/mem/slicc/ast/CheckProbeStatementAST.py @@ -36,7 +36,7 @@ class CheckProbeStatementAST(StatementAST): self.address = address def __repr__(self): - return "[CheckProbeStatementAst: %r]" % self.in_port + return f"[CheckProbeStatementAst: {self.in_port!r}]" def generate(self, code, return_type, **kwargs): self.in_port.assertType("InPort") diff --git a/src/mem/slicc/ast/DeclListAST.py b/src/mem/slicc/ast/DeclListAST.py index a835a04a61..4d893c97d2 100644 --- a/src/mem/slicc/ast/DeclListAST.py +++ b/src/mem/slicc/ast/DeclListAST.py @@ -37,7 +37,7 @@ class DeclListAST(AST): self.decls = decls def __repr__(self): - return "[DeclListAST: %s]" % (", ".join(repr(d) for d in self.decls)) + return f"[DeclListAST: {', '.join(repr(d) for d in self.decls)}]" def files(self, parent=None): s = set() diff --git a/src/mem/slicc/ast/EnumDeclAST.py b/src/mem/slicc/ast/EnumDeclAST.py index 5ffc8bb720..9b4a6be77a 100644 --- a/src/mem/slicc/ast/EnumDeclAST.py +++ b/src/mem/slicc/ast/EnumDeclAST.py @@ -37,17 +37,17 @@ class EnumDeclAST(DeclAST): self.fields = fields def __repr__(self): - return "[EnumDecl: %s]" % (self.type_ast) + return f"[EnumDecl: {self.type_ast}]" def files(self, parent=None): if "external" in self: return set() if parent: - ident = "%s_%s" % (parent, self.type_ast.ident) + ident = f"{parent}_{self.type_ast.ident}" else: ident = self.type_ast.ident - s = set(("%s.hh" % ident, "%s.cc" % ident)) + s = set((f"{ident}.hh", f"{ident}.cc")) return s def generate(self): @@ -64,7 +64,7 @@ class EnumDeclAST(DeclAST): field.generate(t) # Add the implicit State_to_string method - FIXME, this is a bit dirty - func_id = "%s_to_string" % t.c_ident + func_id = f"{t.c_ident}_to_string" pairs = {"external": "yes"} func = Func( diff --git a/src/mem/slicc/ast/EnumExprAST.py b/src/mem/slicc/ast/EnumExprAST.py index 9f3aae33a3..b3034b5c06 100644 --- a/src/mem/slicc/ast/EnumExprAST.py +++ b/src/mem/slicc/ast/EnumExprAST.py @@ -39,7 +39,7 @@ class EnumExprAST(ExprAST): self.value = value def __repr__(self): - return "[EnumExpr: %s:%s]" % (self.type_ast, self.value) + return f"[EnumExpr: {self.type_ast}:{self.value}]" def generate(self, code, **kwargs): fix = code.nofix() diff --git a/src/mem/slicc/ast/ExprStatementAST.py b/src/mem/slicc/ast/ExprStatementAST.py index d26920c11c..9545ef3e41 100644 --- a/src/mem/slicc/ast/ExprStatementAST.py +++ b/src/mem/slicc/ast/ExprStatementAST.py @@ -37,7 +37,7 @@ class ExprStatementAST(StatementAST): self.expr = expr def __repr__(self): - return "[ExprStatementAST: %s]" % (self.expr) + return f"[ExprStatementAST: {self.expr}]" def generate(self, code, return_type, **kwargs): actual_type, rcode = self.expr.inline(True, **kwargs) diff --git a/src/mem/slicc/ast/FormalParamAST.py b/src/mem/slicc/ast/FormalParamAST.py index cd6cdc182c..8b97a81790 100644 --- a/src/mem/slicc/ast/FormalParamAST.py +++ b/src/mem/slicc/ast/FormalParamAST.py @@ -50,7 +50,7 @@ class FormalParamAST(AST): self.qualifier = qualifier def __repr__(self): - return "[FormalParamAST: %s]" % self.ident + return f"[FormalParamAST: {self.ident}]" @property def name(self): @@ -58,7 +58,7 @@ class FormalParamAST(AST): def generate(self): type = self.type_ast.type - param = "param_%s" % self.ident + param = f"param_{self.ident}" # Add to symbol table v = Var( @@ -84,10 +84,10 @@ class FormalParamAST(AST): qualifier = "CONST_REF" if qualifier == "PTR": - return type, "%s* %s" % (type.c_ident, param) + return type, f"{type.c_ident}* {param}" elif qualifier == "REF": - return type, "%s& %s" % (type.c_ident, param) + return type, f"{type.c_ident}& {param}" elif qualifier == "CONST_REF": - return type, "const %s& %s" % (type.c_ident, param) + return type, f"const {type.c_ident}& {param}" else: - self.error("Invalid qualifier for param '%s'" % self.ident) + self.error(f"Invalid qualifier for param '{self.ident}'") diff --git a/src/mem/slicc/ast/FuncCallExprAST.py b/src/mem/slicc/ast/FuncCallExprAST.py index 940e78acff..6ccca6650a 100644 --- a/src/mem/slicc/ast/FuncCallExprAST.py +++ b/src/mem/slicc/ast/FuncCallExprAST.py @@ -49,7 +49,7 @@ class FuncCallExprAST(ExprAST): self.exprs = exprs def __repr__(self): - return "[FuncCallExpr: %s %s]" % (self.proc_name, self.exprs) + return f"[FuncCallExpr: {self.proc_name} {self.exprs}]" # When calling generate for statements in a in_port, the reference to # the port must be provided as the in_port kwarg (see InPortDeclAST) @@ -69,14 +69,14 @@ class FuncCallExprAST(ExprAST): # handled differently. Hence the check whether or not # the str_list is empty. - dflag = "%s" % (self.exprs[0].name) + dflag = f"{self.exprs[0].name}" machine.addDebugFlag(dflag) - format = "%s" % (self.exprs[1].inline()) + format = f"{self.exprs[1].inline()}" format_length = len(format) str_list = [] for i in range(2, len(self.exprs)): - str_list.append("%s" % self.exprs[i].inline()) + str_list.append(f"{self.exprs[i].inline()}") if len(str_list) == 0: code( @@ -97,12 +97,12 @@ class FuncCallExprAST(ExprAST): return self.symtab.find("void", Type) if self.proc_name == "DPRINTFN": - format = "%s" % (self.exprs[0].inline()) + format = f"{self.exprs[0].inline()}" format_length = len(format) str_list = [] for i in range(1, len(self.exprs)): - str_list.append("%s" % self.exprs[i].inline()) + str_list.append(f"{self.exprs[i].inline()}") if len(str_list) == 0: code( @@ -264,11 +264,11 @@ if (!(${{cvec[0]}})) { ) elif self.proc_name == "set_cache_entry": - code("set_cache_entry(m_cache_entry_ptr, %s);" % (cvec[0])) + code(f"set_cache_entry(m_cache_entry_ptr, {cvec[0]});") elif self.proc_name == "unset_cache_entry": code("unset_cache_entry(m_cache_entry_ptr);") elif self.proc_name == "set_tbe": - code("set_tbe(m_tbe_ptr, %s);" % (cvec[0])) + code(f"set_tbe(m_tbe_ptr, {cvec[0]});") elif self.proc_name == "unset_tbe": code("unset_tbe(m_tbe_ptr);") elif self.proc_name == "stallPort": diff --git a/src/mem/slicc/ast/FuncDeclAST.py b/src/mem/slicc/ast/FuncDeclAST.py index ece27e708f..38898ff9e5 100644 --- a/src/mem/slicc/ast/FuncDeclAST.py +++ b/src/mem/slicc/ast/FuncDeclAST.py @@ -39,7 +39,7 @@ class FuncDeclAST(DeclAST): self.statements = statements def __repr__(self): - return "[FuncDecl: %s]" % self.ident + return f"[FuncDecl: {self.ident}]" def files(self, parent=None): return set() @@ -102,12 +102,12 @@ class FuncDeclAST(DeclAST): if parent is not None: if not parent.addFunc(func): - self.error("Duplicate method: %s:%s()" % (parent, self.ident)) + self.error(f"Duplicate method: {parent}:{self.ident}()") func.class_name = parent.c_ident elif machine is not None: machine.addFunc(func) func.isInternalMachineFunc = True - func.class_name = "%s_Controller" % machine + func.class_name = f"{machine}_Controller" else: self.symtab.newSymbol(func) diff --git a/src/mem/slicc/ast/IfStatementAST.py b/src/mem/slicc/ast/IfStatementAST.py index aba19d62ce..1cb50bd95f 100644 --- a/src/mem/slicc/ast/IfStatementAST.py +++ b/src/mem/slicc/ast/IfStatementAST.py @@ -41,7 +41,7 @@ class IfStatementAST(StatementAST): self.else_ = else_ def __repr__(self): - return "[IfStatement: %r%r%r]" % (self.cond, self.then, self.else_) + return f"[IfStatement: {self.cond!r}{self.then!r}{self.else_!r}]" def generate(self, code, return_type, **kwargs): cond_code = self.slicc.codeFormatter() diff --git a/src/mem/slicc/ast/InPortDeclAST.py b/src/mem/slicc/ast/InPortDeclAST.py index c8b99a4710..2cbf3bb617 100644 --- a/src/mem/slicc/ast/InPortDeclAST.py +++ b/src/mem/slicc/ast/InPortDeclAST.py @@ -53,7 +53,7 @@ class InPortDeclAST(DeclAST): self.queue_type = TypeAST(slicc, "InPort") def __repr__(self): - return "[InPortDecl: %s]" % self.ident + return f"[InPortDecl: {self.ident}]" def generate(self): symtab = self.symtab diff --git a/src/mem/slicc/ast/IsValidPtrExprAST.py b/src/mem/slicc/ast/IsValidPtrExprAST.py index ec285dcaa6..0a58361ab2 100644 --- a/src/mem/slicc/ast/IsValidPtrExprAST.py +++ b/src/mem/slicc/ast/IsValidPtrExprAST.py @@ -37,7 +37,7 @@ class IsValidPtrExprAST(ExprAST): self.flag = flag def __repr__(self): - return "[IsValidPtrExprAST: %r]" % self.variable + return f"[IsValidPtrExprAST: {self.variable!r}]" def generate(self, code, **kwargs): # Make sure the variable is valid diff --git a/src/mem/slicc/ast/LiteralExprAST.py b/src/mem/slicc/ast/LiteralExprAST.py index 973ac6a1c0..37655529d8 100644 --- a/src/mem/slicc/ast/LiteralExprAST.py +++ b/src/mem/slicc/ast/LiteralExprAST.py @@ -36,7 +36,7 @@ class LiteralExprAST(ExprAST): self.type = type def __repr__(self): - return "[Literal: %s]" % self.literal + return f"[Literal: {self.literal}]" def generate(self, code, **kwargs): fix = code.nofix() @@ -51,6 +51,6 @@ class LiteralExprAST(ExprAST): type = self.symtab.find(self.type, Type) if type is None: # Can't find the type - self.error("Internal: can't primitive type '%s'" % self.type) + self.error(f"Internal: can't primitive type '{self.type}'") return type diff --git a/src/mem/slicc/ast/LocalVariableAST.py b/src/mem/slicc/ast/LocalVariableAST.py index e08e5770a4..b4ac8f446b 100644 --- a/src/mem/slicc/ast/LocalVariableAST.py +++ b/src/mem/slicc/ast/LocalVariableAST.py @@ -39,7 +39,7 @@ class LocalVariableAST(StatementAST): self.pointer = pointer def __repr__(self): - return "[LocalVariableAST: %r %r]" % (self.type_ast, self.ident) + return f"[LocalVariableAST: {self.type_ast!r} {self.ident!r}]" @property def name(self): @@ -55,7 +55,7 @@ class LocalVariableAST(StatementAST): def generate(self, code, **kwargs): type = self.type_ast.type - ident = "%s" % self.ident + ident = f"{self.ident}" # Add to symbol table v = Var( @@ -72,7 +72,7 @@ class LocalVariableAST(StatementAST): and (type["interface"] == "AbstractCacheEntry") ) ): - code += "%s* %s" % (type.c_ident, ident) + code += f"{type.c_ident}* {ident}" else: - code += "%s %s" % (type.c_ident, ident) + code += f"{type.c_ident} {ident}" return type diff --git a/src/mem/slicc/ast/MachineAST.py b/src/mem/slicc/ast/MachineAST.py index 57526daa3c..5c76aa8173 100644 --- a/src/mem/slicc/ast/MachineAST.py +++ b/src/mem/slicc/ast/MachineAST.py @@ -39,16 +39,16 @@ class MachineAST(DeclAST): self.decls = decls def __repr__(self): - return "[Machine: %r]" % self.ident + return f"[Machine: {self.ident!r}]" def files(self, parent=None): s = set( ( - "%s_Controller.cc" % self.ident, - "%s_Controller.hh" % self.ident, - "%s_Controller.py" % self.ident, - "%s_Transitions.cc" % self.ident, - "%s_Wakeup.cc" % self.ident, + 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", ) ) @@ -83,4 +83,4 @@ class MachineAST(DeclAST): mtype = self.ident machine_type = self.symtab.find("MachineType", Type) if not machine_type.checkEnum(mtype): - self.error("Duplicate machine name: %s:%s" % (machine_type, mtype)) + self.error(f"Duplicate machine name: {machine_type}:{mtype}") diff --git a/src/mem/slicc/ast/MemberExprAST.py b/src/mem/slicc/ast/MemberExprAST.py index 292c1b7899..d45a6ac9a4 100644 --- a/src/mem/slicc/ast/MemberExprAST.py +++ b/src/mem/slicc/ast/MemberExprAST.py @@ -36,7 +36,7 @@ class MemberExprAST(ExprAST): self.field = field def __repr__(self): - return "[MemberExprAST: %r.%r]" % (self.expr_ast, self.field) + return f"[MemberExprAST: {self.expr_ast!r}.{self.field!r}]" def generate(self, code): return_type, gcode = self.expr_ast.inline(True) @@ -68,6 +68,5 @@ class MemberExprAST(ExprAST): return interface_type.data_members[self.field].type self.error( "Invalid object field: " - + "Type '%s' does not have data member %s" - % (return_type, self.field) + + f"Type '{return_type}' does not have data member {self.field}" ) diff --git a/src/mem/slicc/ast/MethodCallExprAST.py b/src/mem/slicc/ast/MethodCallExprAST.py index a4ebc67ecc..7bdf0c7dd9 100644 --- a/src/mem/slicc/ast/MethodCallExprAST.py +++ b/src/mem/slicc/ast/MethodCallExprAST.py @@ -171,9 +171,9 @@ class MemberMethodCallExprAST(MethodCallExprAST): "interface" in obj_type and (obj_type["interface"] == "AbstractCacheEntry") ): - prefix = "%s((*(%s))." % (prefix, code) + prefix = f"{prefix}((*({code}))." else: - prefix = "%s((%s)." % (prefix, code) + prefix = f"{prefix}(({code})." return obj_type, methodId, prefix @@ -186,12 +186,12 @@ class ClassMethodCallExprAST(MethodCallExprAST): self.type_ast = type_ast def __repr__(self): - return "[MethodCallExpr: %r %r]" % (self.proc_name, self.expr_ast_vec) + return f"[MethodCallExpr: {self.proc_name!r} {self.expr_ast_vec!r}]" def generate_prefix(self, paramTypes): # class method call - prefix = "(%s::" % self.type_ast + prefix = f"({self.type_ast}::" obj_type = self.type_ast.type methodId = obj_type.methodId(self.proc_name, paramTypes) diff --git a/src/mem/slicc/ast/NewExprAST.py b/src/mem/slicc/ast/NewExprAST.py index 3488070783..a9ee3ed07c 100644 --- a/src/mem/slicc/ast/NewExprAST.py +++ b/src/mem/slicc/ast/NewExprAST.py @@ -34,7 +34,7 @@ class NewExprAST(ExprAST): self.type_ast = type_ast def __repr__(self): - return "[NewExprAST: %r]" % self.type_ast + return f"[NewExprAST: {self.type_ast!r}]" @property def name(self): diff --git a/src/mem/slicc/ast/ObjDeclAST.py b/src/mem/slicc/ast/ObjDeclAST.py index 0aec0c367e..504d0d41c3 100644 --- a/src/mem/slicc/ast/ObjDeclAST.py +++ b/src/mem/slicc/ast/ObjDeclAST.py @@ -39,7 +39,7 @@ class ObjDeclAST(DeclAST): self.pointer = pointer def __repr__(self): - return "[ObjDecl: %r]" % self.ident + return f"[ObjDecl: {self.ident!r}]" def generate(self, parent=None, **kwargs): if "network" in self and not ( @@ -60,7 +60,7 @@ class ObjDeclAST(DeclAST): elif self.ident == "recycle_latency": c_code = "m_recycle_latency" else: - c_code = "(*m_%s_ptr)" % (self.ident) + c_code = f"(*m_{self.ident}_ptr)" # check type if this is a initialization init_code = "" @@ -68,8 +68,7 @@ class ObjDeclAST(DeclAST): rvalue_type, init_code = self.rvalue.inline(True) if type != rvalue_type: self.error( - "Initialization type mismatch '%s' and '%s'" - % (type, rvalue_type) + f"Initialization type mismatch '{type}' and '{rvalue_type}'" ) machine = self.symtab.state_machine @@ -89,9 +88,7 @@ class ObjDeclAST(DeclAST): if not parent.addDataMember( self.ident, type, self.pairs, init_code ): - self.error( - "Duplicate data member: %s:%s" % (parent, self.ident) - ) + self.error(f"Duplicate data member: {parent}:{self.ident}") elif machine: machine.addObject(v) diff --git a/src/mem/slicc/ast/OperatorExprAST.py b/src/mem/slicc/ast/OperatorExprAST.py index ebebfdf23d..714b553101 100644 --- a/src/mem/slicc/ast/OperatorExprAST.py +++ b/src/mem/slicc/ast/OperatorExprAST.py @@ -38,7 +38,7 @@ class InfixOperatorExprAST(ExprAST): self.right = right def __repr__(self): - return "[InfixExpr: %r %s %r]" % (self.left, self.op, self.right) + return f"[InfixExpr: {self.left!r} {self.op} {self.right!r}]" def generate(self, code, **kwargs): lcode = self.slicc.codeFormatter() @@ -83,7 +83,7 @@ class InfixOperatorExprAST(ExprAST): ("int", "Cycles", "Cycles"), ] else: - self.error("No operator matched with {0}!".format(self.op)) + self.error(f"No operator matched with {self.op}!") for expected_type in expected_types: left_input_type = self.symtab.find(expected_type[0], Type) @@ -115,7 +115,7 @@ class PrefixOperatorExprAST(ExprAST): self.operand = operand def __repr__(self): - return "[PrefixExpr: %s %r]" % (self.op, self.operand) + return f"[PrefixExpr: {self.op} {self.operand!r}]" def generate(self, code, **kwargs): opcode = self.slicc.codeFormatter() diff --git a/src/mem/slicc/ast/OutPortDeclAST.py b/src/mem/slicc/ast/OutPortDeclAST.py index 887597b797..e21a4a6fa7 100644 --- a/src/mem/slicc/ast/OutPortDeclAST.py +++ b/src/mem/slicc/ast/OutPortDeclAST.py @@ -41,7 +41,7 @@ class OutPortDeclAST(DeclAST): self.queue_type = TypeAST(slicc, "OutPort") def __repr__(self): - return "[OutPortDecl: %r]" % self.ident + return f"[OutPortDecl: {self.ident!r}]" def generate(self): code = self.slicc.codeFormatter(newlines=False) diff --git a/src/mem/slicc/ast/PairAST.py b/src/mem/slicc/ast/PairAST.py index eae776f136..526b97f189 100644 --- a/src/mem/slicc/ast/PairAST.py +++ b/src/mem/slicc/ast/PairAST.py @@ -34,4 +34,4 @@ class PairAST(AST): self.value = value def __repr__(self): - return "[%s=%s]" % (self.key, self.value) + return f"[{self.key}={self.value}]" diff --git a/src/mem/slicc/ast/PairListAST.py b/src/mem/slicc/ast/PairListAST.py index a0cf26d07f..6a8efe1a80 100644 --- a/src/mem/slicc/ast/PairListAST.py +++ b/src/mem/slicc/ast/PairListAST.py @@ -32,7 +32,7 @@ class PairListAST(AST): super().__init__(slicc) def __repr__(self): - return "[PairListAST] %r" % self.pairs + return f"[PairListAST] {self.pairs!r}" def addPair(self, pair_ast): self[pair_ast.key] = pair_ast.value diff --git a/src/mem/slicc/ast/ReturnStatementAST.py b/src/mem/slicc/ast/ReturnStatementAST.py index ca4e33dbb9..a742947b4d 100644 --- a/src/mem/slicc/ast/ReturnStatementAST.py +++ b/src/mem/slicc/ast/ReturnStatementAST.py @@ -35,7 +35,7 @@ class ReturnStatementAST(StatementAST): self.expr_ast = expr_ast def __repr__(self): - return "[ReturnStatementAST: %r]" % self.expr_ast + return f"[ReturnStatementAST: {self.expr_ast!r}]" def generate(self, code, return_type, **kwargs): actual_type, ecode = self.expr_ast.inline(True) diff --git a/src/mem/slicc/ast/StallAndWaitStatementAST.py b/src/mem/slicc/ast/StallAndWaitStatementAST.py index 37e567289e..6214fac10f 100644 --- a/src/mem/slicc/ast/StallAndWaitStatementAST.py +++ b/src/mem/slicc/ast/StallAndWaitStatementAST.py @@ -36,7 +36,7 @@ class StallAndWaitStatementAST(StatementAST): self.address = address def __repr__(self): - return "[StallAndWaitStatementAst: %r]" % self.in_port + return f"[StallAndWaitStatementAst: {self.in_port!r}]" def generate(self, code, return_type, **kwargs): self.in_port.assertType("InPort") diff --git a/src/mem/slicc/ast/StateDeclAST.py b/src/mem/slicc/ast/StateDeclAST.py index f6e5d6e39b..d190326484 100644 --- a/src/mem/slicc/ast/StateDeclAST.py +++ b/src/mem/slicc/ast/StateDeclAST.py @@ -36,17 +36,17 @@ class StateDeclAST(DeclAST): self.states = states def __repr__(self): - return "[StateDecl: %s]" % (self.type_ast) + return f"[StateDecl: {self.type_ast}]" def files(self, parent=None): if "external" in self: return set() if parent: - ident = "%s_%s" % (parent, self.type_ast.ident) + ident = f"{parent}_{self.type_ast.ident}" else: ident = self.type_ast.ident - s = set(("%s.hh" % ident, "%s.cc" % ident)) + s = set((f"{ident}.hh", f"{ident}.cc")) return s def generate(self): @@ -63,7 +63,7 @@ class StateDeclAST(DeclAST): state.generate(t) # Add the implicit State_to_string method - FIXME, this is a bit dirty - func_id = "%s_to_string" % t.c_ident + func_id = f"{t.c_ident}_to_string" pairs = {"external": "yes"} func = Func( @@ -80,7 +80,7 @@ class StateDeclAST(DeclAST): self.symtab.newSymbol(func) # Add the State_to_permission method - func_id = "%s_to_permission" % t.c_ident + func_id = f"{t.c_ident}_to_permission" pairs = {"external": "yes"} func = Func( diff --git a/src/mem/slicc/ast/StatementListAST.py b/src/mem/slicc/ast/StatementListAST.py index 82b5d20d1e..9e2bb6579a 100644 --- a/src/mem/slicc/ast/StatementListAST.py +++ b/src/mem/slicc/ast/StatementListAST.py @@ -36,7 +36,7 @@ class StatementListAST(AST): self.statements = statements def __repr__(self): - return "[StatementListAST: %r]" % self.statements + return f"[StatementListAST: {self.statements!r}]" def generate(self, code, return_type, **kwargs): for statement in self.statements: diff --git a/src/mem/slicc/ast/StaticCastAST.py b/src/mem/slicc/ast/StaticCastAST.py index 16f6b151bc..178285202b 100644 --- a/src/mem/slicc/ast/StaticCastAST.py +++ b/src/mem/slicc/ast/StaticCastAST.py @@ -36,7 +36,7 @@ class StaticCastAST(ExprAST): self.type_modifier = type_modifier def __repr__(self): - return "[StaticCastAST: %r]" % self.expr_ast + return f"[StaticCastAST: {self.expr_ast!r}]" def generate(self, code, **kwargs): actual_type, ecode = self.expr_ast.inline(True) diff --git a/src/mem/slicc/ast/TransitionDeclAST.py b/src/mem/slicc/ast/TransitionDeclAST.py index 089bb45e4e..c791ed9548 100644 --- a/src/mem/slicc/ast/TransitionDeclAST.py +++ b/src/mem/slicc/ast/TransitionDeclAST.py @@ -53,8 +53,7 @@ class TransitionDeclAST(DeclAST): for action in self.actions: if action not in machine.actions: self.error( - "Invalid action: %s is not part of machine: %s" - % (action, machine) + f"Invalid action: {action} is not part of machine: {machine}" ) for request_type in self.request_types: @@ -67,15 +66,13 @@ class TransitionDeclAST(DeclAST): for state in self.states: if state not in machine.states: self.error( - "Invalid state: %s is not part of machine: %s" - % (state, machine) + f"Invalid state: {state} is not part of machine: {machine}" ) next_state = self.next_state or state for event in self.events: if event not in machine.events: self.error( - "Invalid event: %s is not part of machine: %s" - % (event, machine) + f"Invalid event: {event} is not part of machine: {machine}" ) t = Transition( self.symtab, diff --git a/src/mem/slicc/ast/TypeDeclAST.py b/src/mem/slicc/ast/TypeDeclAST.py index e64b3d5010..d39e678477 100644 --- a/src/mem/slicc/ast/TypeDeclAST.py +++ b/src/mem/slicc/ast/TypeDeclAST.py @@ -37,17 +37,17 @@ class TypeDeclAST(DeclAST): self.field_asts = field_asts def __repr__(self): - return "[TypeDecl: %r]" % (self.type_ast) + return f"[TypeDecl: {self.type_ast!r}]" def files(self, parent=None): if "external" in self: return set() if parent: - ident = "%s_%s" % (parent, self.type_ast.ident) + ident = f"{parent}_{self.type_ast.ident}" else: ident = self.type_ast.ident - return set(("%s.hh" % ident, "%s.cc" % ident)) + return set((f"{ident}.hh", f"{ident}.cc")) def generate(self): ident = str(self.type_ast) diff --git a/src/mem/slicc/ast/TypeFieldEnumAST.py b/src/mem/slicc/ast/TypeFieldEnumAST.py index ea35e081eb..68dd0cd0fa 100644 --- a/src/mem/slicc/ast/TypeFieldEnumAST.py +++ b/src/mem/slicc/ast/TypeFieldEnumAST.py @@ -37,7 +37,7 @@ class TypeFieldEnumAST(TypeFieldAST): self.pairs_ast = pairs_ast def __repr__(self): - return "[TypeFieldEnum: %r]" % self.field_id + return f"[TypeFieldEnum: {self.field_id!r}]" def generate(self, type, **kwargs): if str(type) == "State": @@ -47,7 +47,7 @@ class TypeFieldEnumAST(TypeFieldAST): # Add enumeration if not type.addEnum(self.field_id, self.pairs_ast.pairs): - self.error("Duplicate enumeration: %s:%s" % (type, self.field_id)) + self.error(f"Duplicate enumeration: {type}:{self.field_id}") # Fill machine info machine = self.symtab.state_machine diff --git a/src/mem/slicc/ast/TypeFieldStateAST.py b/src/mem/slicc/ast/TypeFieldStateAST.py index e71b9383c3..b04a708f21 100644 --- a/src/mem/slicc/ast/TypeFieldStateAST.py +++ b/src/mem/slicc/ast/TypeFieldStateAST.py @@ -39,7 +39,7 @@ class TypeFieldStateAST(TypeFieldAST): self.pairs_ast = pairs_ast def __repr__(self): - return "[TypeFieldState: %r]" % self.field_id + return f"[TypeFieldState: {self.field_id!r}]" def generate(self, type, **kwargs): if not str(type) == "State": @@ -47,7 +47,7 @@ class TypeFieldStateAST(TypeFieldAST): # Add enumeration if not type.addEnum(self.field_id, self.pairs_ast.pairs): - self.error("Duplicate enumeration: %s:%s" % (type, self.field_id)) + self.error(f"Duplicate enumeration: {type}:{self.field_id}") # Fill machine info machine = self.symtab.state_machine diff --git a/src/mem/slicc/ast/VarExprAST.py b/src/mem/slicc/ast/VarExprAST.py index a653504f6d..3c4023e8fe 100644 --- a/src/mem/slicc/ast/VarExprAST.py +++ b/src/mem/slicc/ast/VarExprAST.py @@ -36,7 +36,7 @@ class VarExprAST(ExprAST): self._var = var def __repr__(self): - return "[VarExprAST: %r]" % self._var + return f"[VarExprAST: {self._var!r}]" @property def name(self): diff --git a/src/mem/slicc/ast/WakeupPortStatementAST.py b/src/mem/slicc/ast/WakeupPortStatementAST.py index 62e3549ceb..31a60e8715 100644 --- a/src/mem/slicc/ast/WakeupPortStatementAST.py +++ b/src/mem/slicc/ast/WakeupPortStatementAST.py @@ -43,7 +43,7 @@ class WakeupPortStatementAST(StatementAST): self.address = address def __repr__(self): - return "[WakeupPortStatementAst: %r]" % self.in_port + return f"[WakeupPortStatementAst: {self.in_port!r}]" def generate(self, code, return_type): self.in_port.assertType("InPort") diff --git a/src/mem/slicc/main.py b/src/mem/slicc/main.py index bb0f9cbf16..a3d562220a 100644 --- a/src/mem/slicc/main.py +++ b/src/mem/slicc/main.py @@ -122,7 +122,7 @@ def main(args=None): if opts.print_files: for i in sorted(slicc.files()): - print(" %s" % i) + print(f" {i}") else: output("Processing AST...") slicc.process() diff --git a/src/mem/slicc/parser.py b/src/mem/slicc/parser.py index 2d33cd30b5..155eb07f7a 100644 --- a/src/mem/slicc/parser.py +++ b/src/mem/slicc/parser.py @@ -520,7 +520,7 @@ class SLICC(Grammar): def p_typestr__multi(self, p): "typestr : typestr DOUBLE_COLON ident" - p[0] = "%s::%s" % (p[1], p[3]) + p[0] = f"{p[1]}::{p[3]}" def p_typestr__single(self, p): "typestr : ident" diff --git a/src/mem/slicc/symbols/Action.py b/src/mem/slicc/symbols/Action.py index c00482f276..c2f7d906ee 100644 --- a/src/mem/slicc/symbols/Action.py +++ b/src/mem/slicc/symbols/Action.py @@ -34,7 +34,7 @@ class Action(Symbol): self.resources = resources def __repr__(self): - return "[Action: %s]" % self.ident + return f"[Action: {self.ident}]" __all__ = ["Action"] diff --git a/src/mem/slicc/symbols/Event.py b/src/mem/slicc/symbols/Event.py index 57ab7a76e3..c2fd8d3372 100644 --- a/src/mem/slicc/symbols/Event.py +++ b/src/mem/slicc/symbols/Event.py @@ -30,7 +30,7 @@ from slicc.symbols.Symbol import Symbol class Event(Symbol): def __repr__(self): - return "[Event: %s]" % self.ident + return f"[Event: {self.ident}]" __all__ = ["Event"] diff --git a/src/mem/slicc/symbols/Func.py b/src/mem/slicc/symbols/Func.py index 4d254138e1..18de3af41f 100644 --- a/src/mem/slicc/symbols/Func.py +++ b/src/mem/slicc/symbols/Func.py @@ -67,11 +67,7 @@ class Func(Symbol): elif "return_by_pointer" in self and self.return_type != void_type: return_type += "*" - return "%s %s(%s);" % ( - return_type, - self.c_name, - ", ".join(self.param_strings), - ) + return f"{return_type} {self.c_name}({', '.join(self.param_strings)});" def writeCodeFiles(self, path, includes): return @@ -97,8 +93,7 @@ class Func(Symbol): and str(actual_type["interface"]) != str(expected_type) ): expr.error( - "Type mismatch: expected: %s actual: %s" - % (expected_type, actual_type) + f"Type mismatch: expected: {expected_type} actual: {actual_type}" ) cvec.append(param_code) type_vec.append(expected_type) diff --git a/src/mem/slicc/symbols/RequestType.py b/src/mem/slicc/symbols/RequestType.py index db822a0b17..e5a6df2e76 100644 --- a/src/mem/slicc/symbols/RequestType.py +++ b/src/mem/slicc/symbols/RequestType.py @@ -29,7 +29,7 @@ from slicc.symbols.Symbol import Symbol class RequestType(Symbol): def __repr__(self): - return "[RequestType: %s]" % self.ident + return f"[RequestType: {self.ident}]" __all__ = ["RequestType"] diff --git a/src/mem/slicc/symbols/State.py b/src/mem/slicc/symbols/State.py index 59c7c7d701..e855f1ba0f 100644 --- a/src/mem/slicc/symbols/State.py +++ b/src/mem/slicc/symbols/State.py @@ -30,7 +30,7 @@ from slicc.symbols.Symbol import Symbol class State(Symbol): def __repr__(self): - return "[State: %s]" % self.ident + return f"[State: {self.ident}]" def isWildcard(self): return False diff --git a/src/mem/slicc/symbols/StateMachine.py b/src/mem/slicc/symbols/StateMachine.py index b5af9ca8ed..4712064089 100644 --- a/src/mem/slicc/symbols/StateMachine.py +++ b/src/mem/slicc/symbols/StateMachine.py @@ -86,7 +86,7 @@ class StateMachine(Symbol): param.ident, location, param.type_ast.type, - "(*m_%s_ptr)" % param.ident, + f"(*m_{param.ident}_ptr)", {}, self, ) @@ -96,7 +96,7 @@ class StateMachine(Symbol): param.ident, location, param.type_ast.type, - "m_%s" % param.ident, + f"m_{param.ident}", {}, self, ) @@ -127,7 +127,7 @@ class StateMachine(Symbol): self.debug_flags.add("RubySlicc") def __repr__(self): - return "[StateMachine: %s]" % self.ident + return f"[StateMachine: {self.ident}]" def addState(self, state): assert self.table is None @@ -143,15 +143,13 @@ class StateMachine(Symbol): # Check for duplicate action for other in self.actions.values(): if action.ident == other.ident: - action.warning( - "Duplicate action definition: %s" % action.ident - ) - action.error("Duplicate action definition: %s" % action.ident) + action.warning(f"Duplicate action definition: {action.ident}") + action.error(f"Duplicate action definition: {action.ident}") if action.short == other.short: - other.warning("Duplicate action shorthand: %s" % other.ident) - other.warning(" shorthand = %s" % other.short) - action.warning("Duplicate action shorthand: %s" % action.ident) - action.error(" shorthand = %s" % action.short) + other.warning(f"Duplicate action shorthand: {other.ident}") + other.warning(f" shorthand = {other.short}") + action.warning(f"Duplicate action shorthand: {action.ident}") + action.error(f" shorthand = {action.short}") self.actions[action.ident] = action @@ -179,9 +177,9 @@ class StateMachine(Symbol): self.objects.append(obj) def addType(self, type): - type_ident = "%s" % type.c_ident + type_ident = f"{type.c_ident}" - if type_ident == "%s_TBE" % self.ident: + if type_ident == f"{self.ident}_TBE": if self.TBEType != None: self.error( "Multiple Transaction Buffer types in a single machine." @@ -216,14 +214,14 @@ class StateMachine(Symbol): index = (trans.state, trans.event) if index in table: - table[index].warning("Duplicate transition: %s" % table[index]) - trans.error("Duplicate transition: %s" % trans) + table[index].warning(f"Duplicate transition: {table[index]}") + trans.error(f"Duplicate transition: {trans}") table[index] = trans # Look at all actions to make sure we used them all for action in self.actions.values(): if not action.used: - error_msg = "Unused action: %s" % action.ident + error_msg = f"Unused action: {action.ident}" if "desc" in action: error_msg += ", " + action.desc action.warning(error_msg) @@ -235,7 +233,7 @@ class StateMachine(Symbol): port_to_buf_map = {} in_msg_bufs = {} for port in self.in_ports: - buf_name = "m_%s_ptr" % port.pairs["buffer_expr"].name + buf_name = f"m_{port.pairs['buffer_expr'].name}_ptr" msg_bufs.append(buf_name) port_to_buf_map[port] = msg_bufs.index(buf_name) if buf_name not in in_msg_bufs: @@ -255,8 +253,8 @@ class StateMachine(Symbol): code = self.symtab.codeFormatter() ident = self.ident - py_ident = "%s_Controller" % ident - c_ident = "%s_Controller" % self.ident + py_ident = f"{ident}_Controller" + c_ident = f"{self.ident}_Controller" code( """ @@ -292,13 +290,13 @@ class $py_ident(RubyController): ) code.dedent() - code.write(path, "%s.py" % py_ident) + code.write(path, f"{py_ident}.py") def printControllerHH(self, path): """Output the method declarations for the class declaration""" code = self.symtab.codeFormatter() ident = self.ident - c_ident = "%s_Controller" % self.ident + c_ident = f"{self.ident}_Controller" code( """ @@ -529,14 +527,14 @@ void unset_tbe(${{self.TBEType.c_ident}}*& m_tbe_ptr); """ ) - code.write(path, "%s.hh" % c_ident) + code.write(path, f"{c_ident}.hh") def printControllerCC(self, path, includes): """Output the actions for performing the actions""" code = self.symtab.codeFormatter() ident = self.ident - c_ident = "%s_Controller" % self.ident + c_ident = f"{self.ident}_Controller" # Unfortunately, clang compilers will throw a "call to function ... # that is neither visible in the template definition nor found by @@ -701,7 +699,7 @@ $c_ident::initNetQueues() vnet_dir_set = set() for var in self.config_parameters: - vid = "m_%s_ptr" % var.ident + vid = f"m_{var.ident}_ptr" if "network" in var: vtype = var.type_ast.type code("assert($vid != NULL);") @@ -742,7 +740,7 @@ $c_ident::init() for var in self.objects: vtype = var.type - vid = "m_%s_ptr" % var.ident + vid = f"m_{var.ident}_ptr" if "network" not in var: # Not a network port object if "primitive" in vtype: @@ -752,7 +750,7 @@ $c_ident::init() else: # Normal Object th = var.get("template", "") - expr = "%s = new %s%s" % (vid, vtype.c_ident, th) + expr = f"{vid} = new {vtype.c_ident}{th}" args = "" if "non_obj" not in vtype and not vtype.isEnumeration: args = var.get("constructor", "") @@ -763,7 +761,7 @@ $c_ident::init() if "default" in var: code('*$vid = ${{var["default"]}}; // Object default') elif "default" in vtype: - comment = "Type %s default" % vtype.ident + comment = f"Type {vtype.ident} default" code('*$vid = ${{vtype["default"]}}; // $comment') # Set the prefetchers @@ -787,8 +785,8 @@ $c_ident::init() # Only possible if it is not a 'z' case if not stall: - state = "%s_State_%s" % (self.ident, trans.state.ident) - event = "%s_Event_%s" % (self.ident, trans.event.ident) + state = f"{self.ident}_State_{trans.state.ident}" + event = f"{self.ident}_Event_{trans.event.ident}" code("possibleTransition($state, $event);") code.dedent() @@ -819,19 +817,19 @@ $c_ident::init() for param in self.config_parameters: if param.ident == "sequencer": assert param.pointer - seq_ident = "m_%s_ptr" % param.ident + seq_ident = f"m_{param.ident}_ptr" dma_seq_ident = "NULL" for param in self.config_parameters: if param.ident == "dma_sequencer": assert param.pointer - dma_seq_ident = "m_%s_ptr" % param.ident + dma_seq_ident = f"m_{param.ident}_ptr" coal_ident = "NULL" for param in self.config_parameters: if param.ident == "coalescer": assert param.pointer - coal_ident = "m_%s_ptr" % param.ident + coal_ident = f"m_{param.ident}_ptr" if seq_ident != "NULL": code( @@ -1276,13 +1274,13 @@ $c_ident::functionalWriteBuffers(PacketPtr& pkt) for var in self.objects: vtype = var.type if vtype.isBuffer: - vid = "m_%s_ptr" % var.ident + vid = f"m_{var.ident}_ptr" code("num_functional_writes += $vid->functionalWrite(pkt);") for var in self.config_parameters: vtype = var.type_ast.type if vtype.isBuffer: - vid = "m_%s_ptr" % var.ident + vid = f"m_{var.ident}_ptr" code("num_functional_writes += $vid->functionalWrite(pkt);") code( @@ -1303,13 +1301,13 @@ $c_ident::functionalReadBuffers(PacketPtr& pkt) for var in self.objects: vtype = var.type if vtype.isBuffer: - vid = "m_%s_ptr" % var.ident + vid = f"m_{var.ident}_ptr" code("if ($vid->functionalRead(pkt)) return true;") for var in self.config_parameters: vtype = var.type_ast.type if vtype.isBuffer: - vid = "m_%s_ptr" % var.ident + vid = f"m_{var.ident}_ptr" code("if ($vid->functionalRead(pkt)) return true;") code( @@ -1326,13 +1324,13 @@ $c_ident::functionalReadBuffers(PacketPtr& pkt, WriteMask &mask) for var in self.objects: vtype = var.type if vtype.isBuffer: - vid = "m_%s_ptr" % var.ident + vid = f"m_{var.ident}_ptr" code("if ($vid->functionalRead(pkt, mask)) read = true;") for var in self.config_parameters: vtype = var.type_ast.type if vtype.isBuffer: - vid = "m_%s_ptr" % var.ident + vid = f"m_{var.ident}_ptr" code("if ($vid->functionalRead(pkt, mask)) read = true;") code( @@ -1345,7 +1343,7 @@ $c_ident::functionalReadBuffers(PacketPtr& pkt, WriteMask &mask) """ ) - code.write(path, "%s.cc" % c_ident) + code.write(path, f"{c_ident}.cc") def printCWakeup(self, path, includes): """Output the wakeup loop for the events""" @@ -1496,7 +1494,7 @@ ${ident}_Controller::wakeup() """ ) - code.write(path, "%s_Wakeup.cc" % self.ident) + code.write(path, f"{self.ident}_Wakeup.cc") def printCSwitch(self, path): """Output switch statement for transition table""" @@ -1720,13 +1718,10 @@ ${ident}_Controller::doTransitionWorker(${ident}_Event event, case_sorter = [] res = trans.resources for key, val in res.items(): - val = """ -if (!%s.areNSlotsAvailable(%s, clockEdge())) + val = f""" +if (!{key.code}.areNSlotsAvailable({val}, clockEdge())) return TransitionResult_ResourceStall; -""" % ( - key.code, - val, - ) +""" case_sorter.append(val) # Check all of the request_types for resource constraints @@ -1811,7 +1806,7 @@ if (!checkResourceAvailable(%s_RequestType_%s, addr)) { } // namespace gem5 """ ) - code.write(path, "%s_Transitions.cc" % self.ident) + code.write(path, f"{self.ident}_Transitions.cc") # ************************** # ******* HTML Files ******* @@ -1838,19 +1833,19 @@ if (!checkResourceAvailable(%s_RequestType_%s, addr)) { # Generate action descriptions for action in self.actions.values(): - name = "%s_action_%s.html" % (self.ident, action.ident) + name = f"{self.ident}_action_{action.ident}.html" code = html.createSymbol(action, "Action") code.write(path, name) # Generate state descriptions for state in self.states.values(): - name = "%s_State_%s.html" % (self.ident, state.ident) + name = f"{self.ident}_State_{state.ident}.html" code = html.createSymbol(state, "State") code.write(path, name) # Generate event descriptions for event in self.events.values(): - name = "%s_Event_%s.html" % (self.ident, event.ident) + name = f"{self.ident}_Event_{event.ident}.html" code = html.createSymbol(event, "Event") code.write(path, name) @@ -1891,7 +1886,7 @@ if (!checkResourceAvailable(%s_RequestType_%s, addr)) { ) for event in self.events.values(): - href = "%s_Event_%s.html" % (self.ident, event.ident) + href = f"{self.ident}_Event_{event.ident}.html" ref = self.frameRef(href, "Status", href, "1", event.short) code("$ref") @@ -1904,8 +1899,8 @@ if (!checkResourceAvailable(%s_RequestType_%s, addr)) { else: color = "white" - click = "%s_table_%s.html" % (self.ident, state.ident) - over = "%s_State_%s.html" % (self.ident, state.ident) + click = f"{self.ident}_table_{state.ident}.html" + over = f"{self.ident}_State_{state.ident}.html" text = html.formatShorthand(state.short) ref = self.frameRef(click, "Table", over, "1", state.short) code( @@ -1955,7 +1950,7 @@ if (!checkResourceAvailable(%s_RequestType_%s, addr)) { code("") for action in trans.actions: - href = "%s_action_%s.html" % (self.ident, action.ident) + href = f"{self.ident}_action_{action.ident}.html" ref = self.frameRef( href, "Status", href, "1", action.short ) @@ -1963,8 +1958,8 @@ if (!checkResourceAvailable(%s_RequestType_%s, addr)) { if next != state: if trans.actions: code("/") - click = "%s_table_%s.html" % (self.ident, next.ident) - over = "%s_State_%s.html" % (self.ident, next.ident) + click = f"{self.ident}_table_{next.ident}.html" + over = f"{self.ident}_State_{next.ident}.html" ref = self.frameRef(click, "Table", over, "1", next.short) code("$ref") code("") @@ -1975,8 +1970,8 @@ if (!checkResourceAvailable(%s_RequestType_%s, addr)) { else: color = "white" - click = "%s_table_%s.html" % (self.ident, state.ident) - over = "%s_State_%s.html" % (self.ident, state.ident) + click = f"{self.ident}_table_{state.ident}.html" + over = f"{self.ident}_State_{state.ident}.html" ref = self.frameRef(click, "Table", over, "1", state.short) code( """ @@ -1993,7 +1988,7 @@ if (!checkResourceAvailable(%s_RequestType_%s, addr)) { ) for event in self.events.values(): - href = "%s_Event_%s.html" % (self.ident, event.ident) + href = f"{self.ident}_Event_{event.ident}.html" ref = self.frameRef(href, "Status", href, "1", event.short) code("$ref") code( @@ -2005,9 +2000,9 @@ if (!checkResourceAvailable(%s_RequestType_%s, addr)) { ) if active_state: - name = "%s_table_%s.html" % (self.ident, active_state.ident) + name = f"{self.ident}_table_{active_state.ident}.html" else: - name = "%s_table.html" % self.ident + name = f"{self.ident}_table.html" code.write(path, name) diff --git a/src/mem/slicc/symbols/Symbol.py b/src/mem/slicc/symbols/Symbol.py index cd8f6b9a29..74863724d2 100644 --- a/src/mem/slicc/symbols/Symbol.py +++ b/src/mem/slicc/symbols/Symbol.py @@ -64,7 +64,7 @@ class Symbol(PairContainer): self.used = False def __repr__(self): - return "[Symbol: %s]" % self.ident + return f"[Symbol: {self.ident}]" def __str__(self): return str(self.ident) diff --git a/src/mem/slicc/symbols/SymbolTable.py b/src/mem/slicc/symbols/SymbolTable.py index 4b06be5c4a..f5dfec1d68 100644 --- a/src/mem/slicc/symbols/SymbolTable.py +++ b/src/mem/slicc/symbols/SymbolTable.py @@ -38,7 +38,7 @@ def makeDir(path): ensure that it is a directory""" if os.path.exists(path): if not os.path.isdir(path): - raise AttributeError("%s exists but is not directory" % path) + raise AttributeError(f"{path} exists but is not directory") else: os.mkdir(path) @@ -124,7 +124,7 @@ class SymbolTable(object): def registerGlobalSym(self, ident, symbol): # Check for redeclaration (global frame only) if ident in self.sym_map_vec[0]: - symbol.error("Symbol '%s' redeclared in global scope." % ident) + symbol.error(f"Symbol '{ident}' redeclared in global scope.") self.sym_map_vec[0][ident] = symbol @@ -155,7 +155,7 @@ class SymbolTable(object): machines = list(self.getAllType(StateMachine)) if len(machines) > 1: - name = "%s_table.html" % machines[0].ident + name = f"{machines[0].ident}_table.html" else: name = "empty.html" diff --git a/src/mem/slicc/symbols/Transition.py b/src/mem/slicc/symbols/Transition.py index 478f28c74c..b517cf4d44 100644 --- a/src/mem/slicc/symbols/Transition.py +++ b/src/mem/slicc/symbols/Transition.py @@ -41,7 +41,7 @@ class Transition(Symbol): request_types, location, ): - ident = "%s|%s" % (state, event) + ident = f"{state}|{event}" super().__init__(table, ident, location) self.state = machine.states[state] diff --git a/src/mem/slicc/symbols/Type.py b/src/mem/slicc/symbols/Type.py index c51902667b..7010461e0c 100644 --- a/src/mem/slicc/symbols/Type.py +++ b/src/mem/slicc/symbols/Type.py @@ -73,7 +73,7 @@ class Type(Symbol): self.c_ident = self["external_name"] else: # Append with machine name - self.c_ident = "%s_%s" % (machine, ident) + self.c_ident = f"{machine}_{ident}" self.pairs.setdefault("desc", "No description avaliable") @@ -157,7 +157,7 @@ class Type(Symbol): ident, self.location, type, - "m_%s" % ident, + f"m_{ident}", pairs, None, init_code, @@ -195,7 +195,7 @@ class Type(Symbol): # Add default if "default" not in self: - self["default"] = "%s_NUM" % self.c_ident + self["default"] = f"{self.c_ident}_NUM" return True @@ -240,7 +240,7 @@ class Type(Symbol): parent = "" if "interface" in self: code('#include "mem/ruby/protocol/$0.hh"', self["interface"]) - parent = " : public %s" % self["interface"] + parent = f" : public {self['interface']}" code( """ @@ -294,7 +294,7 @@ $klass ${{self.c_ident}}$parent # ******** Full init constructor ******** if not self.isGlobal: params = [ - "const %s& local_%s" % (dm.real_c_type, dm.ident) + f"const {dm.real_c_type}& local_{dm.ident}" for dm in self.data_members.values() ] params = ", ".join(params) @@ -407,7 +407,7 @@ set${{dm.ident}}(const ${{dm.real_c_type}}& local_${{dm.ident}}) if dm.init_code: # only global structure can have init value here assert self.isGlobal - init = " = %s" % (dm.init_code) + init = f" = {dm.init_code}" if "desc" in dm: code('/** ${{dm["desc"]}} */') @@ -440,7 +440,7 @@ operator<<(::std::ostream& out, const ${{self.c_ident}}& obj) """ ) - code.write(path, "%s.hh" % self.c_ident) + code.write(path, f"{self.c_ident}.hh") def printTypeCC(self, path): code = self.symtab.codeFormatter() @@ -498,7 +498,7 @@ out << "${{dm.ident}} = " << printAddress(m_${{dm.ident}}) << " ";""" """ ) - code.write(path, "%s.cc" % self.c_ident) + code.write(path, f"{self.c_ident}.cc") def printEnumHH(self, path): code = self.symtab.codeFormatter() @@ -552,7 +552,7 @@ enum ${{self.c_ident}} { for i, (ident, enum) in enumerate(self.enums.items()): desc = enum.get("desc", "No description avaliable") if i == 0: - init = " = %s_FIRST" % self.c_ident + init = f" = {self.c_ident}_FIRST" else: init = "" code("${{self.c_ident}}_${{enum.ident}}$init, /**< $desc */") @@ -640,7 +640,7 @@ struct hash """ ) - code.write(path, "%s.hh" % self.c_ident) + code.write(path, f"{self.c_ident}.hh") def printEnumCC(self, path): code = self.symtab.codeFormatter() @@ -932,7 +932,7 @@ get${{enum.ident}}MachineID(NodeID RubyNode) ) # Write the file - code.write(path, "%s.cc" % self.c_ident) + code.write(path, f"{self.c_ident}.cc") __all__ = ["Type"] diff --git a/src/mem/slicc/symbols/Var.py b/src/mem/slicc/symbols/Var.py index 3b8a538a23..cafdb17ff3 100644 --- a/src/mem/slicc/symbols/Var.py +++ b/src/mem/slicc/symbols/Var.py @@ -39,7 +39,7 @@ class Var(Symbol): self.code = code def __repr__(self): - return "[Var id: %s]" % (self.ident) + return f"[Var id: {self.ident}]" def writeCodeFiles(self, path, includes): pass diff --git a/src/mem/slicc/util.py b/src/mem/slicc/util.py index 07b5ba6ab2..3bb4131a01 100644 --- a/src/mem/slicc/util.py +++ b/src/mem/slicc/util.py @@ -51,11 +51,11 @@ class Location(object): def __init__(self, filename, lineno, no_warning=False): if not isinstance(filename, str): raise AttributeError( - "filename must be a string, found {}".format(type(filename)) + f"filename must be a string, found {type(filename)}" ) if not isinstance(lineno, int): raise AttributeError( - "filename must be an integer, found {}".format(type(lineno)) + f"filename must be an integer, found {type(lineno)}" ) self.filename = filename self.lineno = lineno @@ -70,13 +70,13 @@ class Location(object): if args: message = message % args # raise Exception, "%s: Warning: %s" % (self, message) - print("%s: Warning: %s" % (self, message), file=sys.stderr) + print(f"{self}: Warning: {message}", file=sys.stderr) def error(self, message, *args): if args: message = message % args - raise Exception("{}: Error: {}".format(self, message)) - sys.exit("\n%s: Error: %s" % (self, message)) + raise Exception(f"{self}: Error: {message}") + sys.exit(f"\n{self}: Error: {message}") __all__ = ["PairContainer", "Location"] diff --git a/src/python/gem5/components/boards/arm_board.py b/src/python/gem5/components/boards/arm_board.py index 7936c0c25e..10e2c0eb82 100644 --- a/src/python/gem5/components/boards/arm_board.py +++ b/src/python/gem5/components/boards/arm_board.py @@ -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) diff --git a/src/python/gem5/components/boards/experimental/lupv_board.py b/src/python/gem5/components/boards/experimental/lupv_board.py index 5624712ca8..ad130b7273 100644 --- a/src/python/gem5/components/boards/experimental/lupv_board.py +++ b/src/python/gem5/components/boards/experimental/lupv_board.py @@ -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( diff --git a/src/python/gem5/components/boards/riscv_board.py b/src/python/gem5/components/boards/riscv_board.py index 15ec57af69..25f1fac562 100644 --- a/src/python/gem5/components/boards/riscv_board.py +++ b/src/python/gem5/components/boards/riscv_board.py @@ -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( diff --git a/src/python/gem5/prebuilt/riscvmatched/riscvmatched_board.py b/src/python/gem5/prebuilt/riscvmatched/riscvmatched_board.py index 4148c0a061..ae483cc401 100644 --- a/src/python/gem5/prebuilt/riscvmatched/riscvmatched_board.py +++ b/src/python/gem5/prebuilt/riscvmatched/riscvmatched_board.py @@ -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( diff --git a/src/python/gem5/resources/downloader.py b/src/python/gem5/resources/downloader.py index 24b8970cc0..16b0147b74 100644 --- a/src/python/gem5/resources/downloader.py +++ b/src/python/gem5/resources/downloader.py @@ -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( diff --git a/src/python/gem5/simulate/exit_event.py b/src/python/gem5/simulate/exit_event.py index 1e14fdd11a..605fb6e556 100644 --- a/src/python/gem5/simulate/exit_event.py +++ b/src/python/gem5/simulate/exit_event.py @@ -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" ) diff --git a/src/python/gem5/utils/filelock.py b/src/python/gem5/utils/filelock.py index a6798e9f53..6fb4e3e1d1 100644 --- a/src/python/gem5/utils/filelock.py +++ b/src/python/gem5/utils/filelock.py @@ -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) diff --git a/src/python/gem5/utils/multiprocessing/context.py b/src/python/gem5/utils/multiprocessing/context.py index 2108bc624c..87917d1bfb 100644 --- a/src/python/gem5/utils/multiprocessing/context.py +++ b/src/python/gem5/utils/multiprocessing/context.py @@ -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 diff --git a/src/python/gem5/utils/requires.py b/src/python/gem5/utils/requires.py index 30a8ef4a8b..9d271aafa2 100644 --- a/src/python/gem5/utils/requires.py +++ b/src/python/gem5/utils/requires.py @@ -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( diff --git a/src/python/importer.py b/src/python/importer.py index 3d3ee7c068..d3bdd593ef 100644 --- a/src/python/importer.py +++ b/src/python/importer.py @@ -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) diff --git a/src/python/m5/SimObject.py b/src/python/m5/SimObject.py index 354a8288cd..08105d8833 100644 --- a/src/python/m5/SimObject.py +++ b/src/python/m5/SimObject.py @@ -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 "" % self.__class__ + return f"" 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 diff --git a/src/python/m5/debug.py b/src/python/m5/debug.py index 70af2e0f3a..09a032aa50 100644 --- a/src/python/m5/debug.py +++ b/src/python/m5/debug.py @@ -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() diff --git a/src/python/m5/event.py b/src/python/m5/event.py index 707d65d63d..7c3f9a7c42 100644 --- a/src/python/m5/event.py +++ b/src/python/m5/event.py @@ -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) diff --git a/src/python/m5/ext/pyfdt/pyfdt.py b/src/python/m5/ext/pyfdt/pyfdt.py index 191a57740d..499af7588a 100644 --- a/src/python/m5/ext/pyfdt/pyfdt.py +++ b/src/python/m5/ext/pyfdt/pyfdt.py @@ -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): diff --git a/src/python/m5/internal/params.py b/src/python/m5/internal/params.py index 8225d0b059..bd6cbb7d80 100644 --- a/src/python/m5/internal/params.py +++ b/src/python/m5/internal/params.py @@ -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 *") diff --git a/src/python/m5/main.py b/src/python/m5/main.py index 458e143a53..d8c9951f6d 100644 --- a/src/python/m5/main.py +++ b/src/python/m5/main.py @@ -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: diff --git a/src/python/m5/objects/__init__.py b/src/python/m5/objects/__init__.py index b6672331f4..788babf620 100644 --- a/src/python/m5/objects/__init__.py +++ b/src/python/m5/objects/__init__.py @@ -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 *") diff --git a/src/python/m5/options.py b/src/python/m5/options.py index 08638c65a7..ed0dcddc97 100644 --- a/src/python/m5/options.py +++ b/src/python/m5/options.py @@ -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 diff --git a/src/python/m5/params.py b/src/python/m5/params.py index 92e913b2f0..e9047a85d4 100644 --- a/src/python/m5/params.py +++ b/src/python/m5/params.py @@ -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() diff --git a/src/python/m5/proxy.py b/src/python/m5/proxy.py index 16aa0c4505..78862346b4 100644 --- a/src/python/m5/proxy.py +++ b/src/python/m5/proxy.py @@ -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: diff --git a/src/python/m5/simulate.py b/src/python/m5/simulate.py index 18fb1d6cd4..587bfa0202 100644 --- a/src/python/m5/simulate.py +++ b/src/python/m5/simulate.py @@ -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() diff --git a/src/python/m5/stats/__init__.py b/src/python/m5/stats/__init__.py index 6bc50cfad9..ce7a2d267d 100644 --- a/src/python/m5/stats/__init__.py +++ b/src/python/m5/stats/__init__.py @@ -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++ diff --git a/src/python/m5/ticks.py b/src/python/m5/ticks.py index c1c6a507ee..47b033cfb4 100644 --- a/src/python/m5/ticks.py +++ b/src/python/m5/ticks.py @@ -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 diff --git a/src/python/m5/util/__init__.py b/src/python/m5/util/__init__.py index 5ae48754ab..34c5ee8a49 100644 --- a/src/python/m5/util/__init__.py +++ b/src/python/m5/util/__init__.py @@ -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) diff --git a/src/python/m5/util/convert.py b/src/python/m5/util/convert.py index ca897ba9c8..72c748360c 100644 --- a/src/python/m5/util/convert.py +++ b/src/python/m5/util/convert.py @@ -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)) diff --git a/src/python/m5/util/dot_writer.py b/src/python/m5/util/dot_writer.py index 6d49f4ef79..b491a98448 100644 --- a/src/python/m5/util/dot_writer.py +++ b/src/python/m5/util/dot_writer.py @@ -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 diff --git a/src/python/m5/util/dot_writer_ruby.py b/src/python/m5/util/dot_writer_ruby.py index e23a1064bc..fa21ae1a01 100644 --- a/src/python/m5/util/dot_writer_ruby.py +++ b/src/python/m5/util/dot_writer_ruby.py @@ -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): diff --git a/src/python/m5/util/pybind.py b/src/python/m5/util/pybind.py index 52d38e5302..54fd111f38 100644 --- a/src/python/m5/util/pybind.py +++ b/src/python/m5/util/pybind.py @@ -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) + ")") diff --git a/src/systemc/tests/tlm/endian_conv/testall.py b/src/systemc/tests/tlm/endian_conv/testall.py index b9e10ad94d..3bc7f136e9 100644 --- a/src/systemc/tests/tlm/endian_conv/testall.py +++ b/src/systemc/tests/tlm/endian_conv/testall.py @@ -545,23 +545,16 @@ for txn in txn_generator(nr_txns_to_test): else: if memory_state != golden_memory_state: raise FragmenterDifference( - """ -fragmenter: %s + f""" +fragmenter: {fragmenter} transaction: -%s +{txn} start memory: -%s +{initial_memory} golden memory: -%s +{golden_memory_state} actual memory: -%s""" - % ( - fragmenter, - txn, - initial_memory, - golden_memory_state, - memory_state, - ) +{memory_state}""" ) print("."), diff --git a/src/systemc/tests/verify.py b/src/systemc/tests/verify.py index 0d8ce3cf75..c0e072e3c2 100755 --- a/src/systemc/tests/verify.py +++ b/src/systemc/tests/verify.py @@ -413,11 +413,7 @@ class VerifyPhase(TestPhaseBase): total_passed = len(self._passed) total_failed = sum(map(len, self._failed.values())) print() - print( - "Passed: {passed:4} - Failed: {failed:4}".format( - passed=total_passed, failed=total_failed - ) - ) + print(f"Passed: {total_passed:4} - Failed: {total_failed:4}") def write_result_file(self, path): results = { @@ -626,7 +622,7 @@ def collect_phases(args): for group in phase_groups[1:]: name = group[0] if name in names: - raise RuntimeException("Phase %s specified more than once" % name) + raise RuntimeException(f"Phase {name} specified more than once") phase = test_phase_classes[name] phases.append(phase(main_args, *group[1:])) phases.sort() @@ -669,10 +665,10 @@ with open(json_path) as f: if main_args.list: for target, props in sorted(filtered_tests.items()): - print("%s.%s" % (target, main_args.flavor)) + print(f"{target}.{main_args.flavor}") for key, val in props.items(): - print(" %s: %s" % (key, val)) - print("Total tests: %d" % len(filtered_tests)) + print(f" {key}: {val}") + print(f"Total tests: {len(filtered_tests)}") else: tests_to_run = list( [ diff --git a/tests/configs/dram-lowp.py b/tests/configs/dram-lowp.py index a2a0ce37b7..25e7cc3087 100644 --- a/tests/configs/dram-lowp.py +++ b/tests/configs/dram-lowp.py @@ -52,7 +52,7 @@ def run_test(root): argv = [ sys.argv[0], # Add a specific page policy and specify the number of ranks - "-p%s" % page_policy, + f"-p{page_policy}", "-r 2", ] diff --git a/tests/gem5/arm-boot-tests/test_linux_boot.py b/tests/gem5/arm-boot-tests/test_linux_boot.py index 364125691c..d6e8ac94a5 100644 --- a/tests/gem5/arm-boot-tests/test_linux_boot.py +++ b/tests/gem5/arm-boot-tests/test_linux_boot.py @@ -66,9 +66,7 @@ arm-boot-test" if to_tick: name += "_to-tick" exit_regex = re.compile( - "Exiting @ tick {} because simulate\(\) limit reached".format( - str(to_tick) - ) + f"Exiting @ tick {str(to_tick)} because simulate\\(\\) limit reached" ) verifiers.append(verifier.MatchRegex(exit_regex)) config_args += ["--tick-exit", str(to_tick)] diff --git a/tests/gem5/configs/arm_boot_exit_run.py b/tests/gem5/configs/arm_boot_exit_run.py index aea3c4160f..a8ea6eeea7 100644 --- a/tests/gem5/configs/arm_boot_exit_run.py +++ b/tests/gem5/configs/arm_boot_exit_run.py @@ -161,9 +161,7 @@ elif args.mem_system == "mi_example": cache_hierarchy = MIExampleCacheHierarchy(size="32kB", assoc=4) else: raise NotImplementedError( - "Memory type '{}' is not supported in the boot tests.".format( - args.mem_system - ) + f"Memory type '{args.mem_system}' is not supported in the boot tests." ) # Setup the system memory. diff --git a/tests/gem5/configs/boot_kvm_fork_run.py b/tests/gem5/configs/boot_kvm_fork_run.py index 18f6e9d416..84e273d842 100644 --- a/tests/gem5/configs/boot_kvm_fork_run.py +++ b/tests/gem5/configs/boot_kvm_fork_run.py @@ -151,9 +151,7 @@ elif args.mem_system == "classic": cache_hierarchy = PrivateL1CacheHierarchy(l1d_size="16kB", l1i_size="16kB") else: raise NotImplementedError( - "Memory system '{}' is not supported in the boot tests.".format( - args.mem_system - ) + f"Memory system '{args.mem_system}' is not supported in the boot tests." ) assert cache_hierarchy != None diff --git a/tests/gem5/configs/boot_kvm_switch_exit.py b/tests/gem5/configs/boot_kvm_switch_exit.py index 25f5808e13..1347e68ba4 100644 --- a/tests/gem5/configs/boot_kvm_switch_exit.py +++ b/tests/gem5/configs/boot_kvm_switch_exit.py @@ -137,9 +137,7 @@ elif args.mem_system == "classic": cache_hierarchy = PrivateL1CacheHierarchy(l1d_size="16kB", l1i_size="16kB") else: raise NotImplementedError( - "Memory system '{}' is not supported in the boot tests.".format( - args.mem_system - ) + f"Memory system '{args.mem_system}' is not supported in the boot tests." ) assert cache_hierarchy != None diff --git a/tests/gem5/configs/checkpoint.py b/tests/gem5/configs/checkpoint.py index d5d58922a3..f1b8a1bf72 100644 --- a/tests/gem5/configs/checkpoint.py +++ b/tests/gem5/configs/checkpoint.py @@ -73,7 +73,7 @@ def _run_step(name, restore=None, interval=0.5): elif cause in _exit_normal: sys.exit(_exitcode_done) else: - print("Test failed: Unknown exit cause: %s" % cause) + print(f"Test failed: Unknown exit cause: {cause}") sys.exit(_exitcode_fail) @@ -129,5 +129,5 @@ def run_test(root, interval=0.5, max_checkpoints=5): if cause in _exit_normal: sys.exit(0) else: - print("Test failed: Unknown exit cause: %s" % cause) + print(f"Test failed: Unknown exit cause: {cause}") sys.exit(1) diff --git a/tests/gem5/configs/parsec_disk_run.py b/tests/gem5/configs/parsec_disk_run.py index fbe1cd3688..5c2fa75f65 100644 --- a/tests/gem5/configs/parsec_disk_run.py +++ b/tests/gem5/configs/parsec_disk_run.py @@ -199,9 +199,9 @@ board = X86Board( command = ( "cd /home/gem5/parsec-benchmark\n" + "source env.sh\n" - + "parsecmgmt -a run -p {} ".format(args.benchmark) - + "-c gcc-hooks -i {} ".format(args.size) - + "-n {}\n".format(str(args.num_cpus)) + + f"parsecmgmt -a run -p {args.benchmark} " + + f"-c gcc-hooks -i {args.size} " + + f"-n {str(args.num_cpus)}\n" ) board.set_kernel_disk_workload( @@ -247,12 +247,8 @@ print("Done running the simulation") print() print("Performance statistics:") -print("Simulated time in ROI: {}s".format((roi_ticks[0]) / 1e12)) +print(f"Simulated time in ROI: {roi_ticks[0] / 1000000000000.0}s") print( - "Ran a total of {} simulated seconds".format( - simulator.get_current_tick() / 1e12 - ) -) -print( - "Total wallclock time: {}s, {} min".format(global_time, (global_time) / 60) + f"Ran a total of {simulator.get_current_tick() / 1000000000000.0} simulated seconds" ) +print(f"Total wallclock time: {global_time}s, {global_time / 60} min") diff --git a/tests/gem5/configs/riscv_boot_exit_run.py b/tests/gem5/configs/riscv_boot_exit_run.py index 4424868112..e9fc06b27b 100644 --- a/tests/gem5/configs/riscv_boot_exit_run.py +++ b/tests/gem5/configs/riscv_boot_exit_run.py @@ -144,7 +144,7 @@ elif args.cpu == "minor": cpu_type = CPUTypes.MINOR else: raise NotImplementedError( - "CPU type '{}' is not supported in the boot tests.".format(args.cpu) + f"CPU type '{args.cpu}' is not supported in the boot tests." ) processor = SimpleProcessor( diff --git a/tests/gem5/configs/switcheroo.py b/tests/gem5/configs/switcheroo.py index 5f38543c52..72736a9d87 100644 --- a/tests/gem5/configs/switcheroo.py +++ b/tests/gem5/configs/switcheroo.py @@ -125,7 +125,7 @@ def run_test(root, switcher=None, freq=1000, verbose=False): if verbose: print("Switching CPUs...") - print("Next CPU: %s" % type(next_cpu)) + print(f"Next CPU: {type(next_cpu)}") m5.drain() if current_cpu != next_cpu: m5.switchCpus( @@ -144,5 +144,5 @@ def run_test(root, switcher=None, freq=1000, verbose=False): sys.exit(0) else: - print("Test failed: Unknown exit cause: %s" % exit_cause) + print(f"Test failed: Unknown exit cause: {exit_cause}") sys.exit(1) diff --git a/tests/gem5/configs/x86_boot_exit_run.py b/tests/gem5/configs/x86_boot_exit_run.py index 5458b6db6c..e9eeacefd8 100644 --- a/tests/gem5/configs/x86_boot_exit_run.py +++ b/tests/gem5/configs/x86_boot_exit_run.py @@ -152,9 +152,7 @@ elif args.mem_system == "classic": cache_hierarchy = PrivateL1CacheHierarchy(l1d_size="16kB", l1i_size="16kB") else: raise NotImplementedError( - "Memory system '{}' is not supported in the boot tests.".format( - args.mem_system - ) + f"Memory system '{args.mem_system}' is not supported in the boot tests." ) assert cache_hierarchy != None diff --git a/tests/gem5/cpu_tests/test.py b/tests/gem5/cpu_tests/test.py index bbdb492c82..4a2a104ea7 100644 --- a/tests/gem5/cpu_tests/test.py +++ b/tests/gem5/cpu_tests/test.py @@ -88,10 +88,10 @@ for isa in valid_isas: for cpu in valid_isas[isa]: gem5_verify_config( - name="cpu_test_{}_{}".format(cpu, workload), + name=f"cpu_test_{cpu}_{workload}", verifiers=verifiers, config=joinpath(getcwd(), "run.py"), - config_args=["--cpu={}".format(cpu), binary], + config_args=[f"--cpu={cpu}", binary], valid_isas=(constants.all_compiled_tag,), fixtures=[workload_binary], ) diff --git a/tests/gem5/fixture.py b/tests/gem5/fixture.py index 6f5dd616ab..d3312c9a63 100644 --- a/tests/gem5/fixture.py +++ b/tests/gem5/fixture.py @@ -172,7 +172,7 @@ class SConsFixture(UniqueFixture): log.test_log.message( "Building the following targets. This may take a while." ) - log.test_log.message("%s" % (", ".join(self.targets))) + log.test_log.message(f"{', '.join(self.targets)}") log.test_log.message( "You may want to use --skip-build, or use 'rerun'." ) @@ -188,7 +188,7 @@ class Gem5Fixture(SConsFixture): target_dir = joinpath(config.build_dir, isa.upper()) if protocol: target_dir += "_" + protocol - target = joinpath(target_dir, "gem5.%s" % variant) + target = joinpath(target_dir, f"gem5.{variant}") obj = super(Gem5Fixture, cls).__new__(cls, target) return obj @@ -207,7 +207,7 @@ class Gem5Fixture(SConsFixture): class MakeFixture(Fixture): def __init__(self, directory, *args, **kwargs): - name = "make -C %s" % directory + name = f"make -C {directory}" super(MakeFixture, self).__init__( build_once=True, lazy_init=False, name=name, *args, **kwargs ) diff --git a/tests/gem5/kvm-fork-tests/test_kvm_fork_run.py b/tests/gem5/kvm-fork-tests/test_kvm_fork_run.py index 7467c02763..7dcfc8517c 100644 --- a/tests/gem5/kvm-fork-tests/test_kvm_fork_run.py +++ b/tests/gem5/kvm-fork-tests/test_kvm_fork_run.py @@ -46,9 +46,7 @@ def test_kvm_fork_run(cpu: str, num_cpus: int, mem_system: str, length: str): # Don't run the tests if KVM is unavailable. return - name = "{}-cpu_{}-cores_{}_kvm-fork-run-test".format( - cpu, str(num_cpus), mem_system - ) + name = f"{cpu}-cpu_{str(num_cpus)}-cores_{mem_system}_kvm-fork-run-test" verifiers = [] if mem_system == "mesi_two_level": diff --git a/tests/gem5/kvm-switch-tests/test_kvm_cpu_switch.py b/tests/gem5/kvm-switch-tests/test_kvm_cpu_switch.py index 222c26b9e2..85e9268e2d 100644 --- a/tests/gem5/kvm-switch-tests/test_kvm_cpu_switch.py +++ b/tests/gem5/kvm-switch-tests/test_kvm_cpu_switch.py @@ -46,9 +46,7 @@ def test_kvm_switch(cpu: str, num_cpus: int, mem_system: str, length: str): # Don't run the tests if KVM is unavailable. return - name = "{}-cpu_{}-cores_{}_kvm-switch-test".format( - cpu, str(num_cpus), mem_system - ) + name = f"{cpu}-cpu_{str(num_cpus)}-cores_{mem_system}_kvm-switch-test" verifiers = [] if mem_system == "mesi_two_level": diff --git a/tests/gem5/replacement-policies/run_replacement_policy_test.py b/tests/gem5/replacement-policies/run_replacement_policy_test.py index 31076c6d99..ec38bf382f 100644 --- a/tests/gem5/replacement-policies/run_replacement_policy_test.py +++ b/tests/gem5/replacement-policies/run_replacement_policy_test.py @@ -91,6 +91,4 @@ m5.instantiate() generator.start_traffic() print("Beginning simulation!") exit_event = m5.simulate() -print( - "Exiting @ tick {} because {}.".format(m5.curTick(), exit_event.getCause()) -) +print(f"Exiting @ tick {m5.curTick()} because {exit_event.getCause()}.") diff --git a/tests/gem5/riscv-boot-tests/test_linux_boot.py b/tests/gem5/riscv-boot-tests/test_linux_boot.py index 5ba4fa5dc0..55e0ae6109 100644 --- a/tests/gem5/riscv-boot-tests/test_linux_boot.py +++ b/tests/gem5/riscv-boot-tests/test_linux_boot.py @@ -51,9 +51,7 @@ def test_boot( verifiers = [] exit_regex = re.compile( - "Exiting @ tick {} because simulate\(\) limit reached".format( - str(to_tick) - ) + f"Exiting @ tick {str(to_tick)} because simulate\\(\\) limit reached" ) verifiers.append(verifier.MatchRegex(exit_regex)) diff --git a/tests/gem5/suite.py b/tests/gem5/suite.py index 36532aa9f7..7e0935d9eb 100644 --- a/tests/gem5/suite.py +++ b/tests/gem5/suite.py @@ -106,9 +106,7 @@ def gem5_verify_config( ) # Common name of this generated testcase. - _name = "{given_name}-{isa}-{host}-{opt}".format( - given_name=name, isa=isa, host=host, opt=opt - ) + _name = f"{name}-{isa}-{host}-{opt}" if protocol: _name += "-" + protocol diff --git a/tests/gem5/traffic_gen/simple_traffic_run.py b/tests/gem5/traffic_gen/simple_traffic_run.py index 4e38155070..7c0f18865a 100644 --- a/tests/gem5/traffic_gen/simple_traffic_run.py +++ b/tests/gem5/traffic_gen/simple_traffic_run.py @@ -207,9 +207,7 @@ m5.instantiate() generator.start_traffic() print("Beginning simulation!") exit_event = m5.simulate() -print( - "Exiting @ tick {} because {}.".format(m5.curTick(), exit_event.getCause()) -) +print(f"Exiting @ tick {m5.curTick()} because {exit_event.getCause()}.") simstats = get_simstat(root, prepare_stats=True) json_output = Path(m5.options.outdir) / "output.json" diff --git a/tests/gem5/verifier.py b/tests/gem5/verifier.py index 075cec15d2..93d47c8d10 100644 --- a/tests/gem5/verifier.py +++ b/tests/gem5/verifier.py @@ -115,8 +115,7 @@ class MatchGoldStandard(Verifier): ) if diff is not None: test_util.fail( - "Stdout did not match:\n%s\nSee %s for full results" - % (diff, tempdir) + f"Stdout did not match:\n{diff}\nSee {tempdir} for full results" ) def _generic_instance_warning(self, kwargs): diff --git a/tests/gem5/x86-boot-tests/test_linux_boot.py b/tests/gem5/x86-boot-tests/test_linux_boot.py index 76d593bd3a..1907aaf0e4 100644 --- a/tests/gem5/x86-boot-tests/test_linux_boot.py +++ b/tests/gem5/x86-boot-tests/test_linux_boot.py @@ -54,9 +54,7 @@ def test_boot( if to_tick != None: name += "_to-tick" exit_regex = re.compile( - "Exiting @ tick {} because simulate\(\) limit reached".format( - str(to_tick) - ) + f"Exiting @ tick {str(to_tick)} because simulate\\(\\) limit reached" ) verifiers.append(verifier.MatchRegex(exit_regex)) additional_config_args.append("--tick-exit") diff --git a/tests/run.py b/tests/run.py index e24d4b3bdd..dde8f70749 100644 --- a/tests/run.py +++ b/tests/run.py @@ -56,7 +56,7 @@ def skip_test(reason=""): """ if reason: - print("Skipping test: %s" % reason) + print(f"Skipping test: {reason}") sys.exit(2) @@ -90,7 +90,7 @@ def require_sim_object(name, fatal=False): if has_sim_object(name): return else: - msg = "Test requires the '%s' SimObject." % name + msg = f"Test requires the '{name}' SimObject." if fatal: m5.fatal(msg) else: @@ -113,7 +113,7 @@ def require_file(path, fatal=False, mode=os.F_OK): if os.access(path, mode): return else: - msg = "Test requires '%s'" % path + msg = f"Test requires '{path}'" if not os.path.exists(path): msg += " which does not exist." else: diff --git a/util/checkpoint-tester.py b/util/checkpoint-tester.py index 6bc636ac18..1e4024b858 100755 --- a/util/checkpoint-tester.py +++ b/util/checkpoint-tester.py @@ -142,8 +142,8 @@ for i in range(1, len(cpts)): "-ru", "-I", "^##.*", - "%s/%s" % (cptdir, cpt_name), - "%s/%s" % (mydir, cpt_name), + f"{cptdir}/{cpt_name}", + f"{mydir}/{cpt_name}", ], stdout=diffout, ) diff --git a/util/cpt_upgrader.py b/util/cpt_upgrader.py index 06f98d8a74..a852294fbc 100755 --- a/util/cpt_upgrader.py +++ b/util/cpt_upgrader.py @@ -102,7 +102,7 @@ class Upgrader: self.depends = [self.depends] if not isinstance(self.depends, list): - print("Error: 'depends' for {} is the wrong type".format(self.tag)) + print(f"Error: 'depends' for {self.tag} is the wrong type") sys.exit(1) if hasattr(self, "fwd_depends"): @@ -112,37 +112,25 @@ class Upgrader: self.fwd_depends = [] if not isinstance(self.fwd_depends, list): - print( - "Error: 'fwd_depends' for {} is the wrong type".format( - self.tag - ) - ) + print(f"Error: 'fwd_depends' for {self.tag} is the wrong type") sys.exit(1) if hasattr(self, "upgrader"): if not isinstance(self.upgrader, types.FunctionType): print( - "Error: 'upgrader' for {} is {}, not function".format( - self.tag, type(self) - ) + f"Error: 'upgrader' for {self.tag} is {type(self)}, not function" ) sys.exit(1) Upgrader.tag_set.add(self.tag) elif hasattr(self, "downgrader"): if not isinstance(self.downgrader, types.FunctionType): print( - "Error: 'downgrader' for {} is {}, not function".format( - self.tag, type(self) - ) + f"Error: 'downgrader' for {self.tag} is {type(self)}, not function" ) sys.exit(1) Upgrader.untag_set.add(self.tag) else: - print( - "Error: no upgrader or downgrader method for {}".format( - self.tag - ) - ) + print(f"Error: no upgrader or downgrader method for {self.tag}") sys.exit(1) if hasattr(self, "legacy_version"): @@ -196,8 +184,7 @@ class Upgrader: for dep in upg.depends: if dep not in Upgrader.by_tag: print( - "Error: '{}' cannot depend on " - "nonexistent tag '{}'".format(tag, dep) + f"Error: '{tag}' cannot depend on nonexistent tag '{dep}'" ) sys.exit(1) @@ -208,7 +195,7 @@ def process_file(path, **kwargs): raise IOError(errno.ENOENT, "No such file", path) - verboseprint("Processing file %s...." % path) + verboseprint(f"Processing file {path}....") if kwargs.get("backup", True): import shutil @@ -337,7 +324,7 @@ if __name__ == "__main__": print() print("std::set version_tags = {") for tag in sorted(Upgrader.tag_set): - print(' "{}",'.format(tag)) + print(f' "{tag}",') print("};") print() print("} // namespace gem5") @@ -369,7 +356,7 @@ if __name__ == "__main__": elif osp.isfile(cpt_file): process_file(cpt_file, **vars(args)) else: - print("Error: checkpoint file not found in {} ".format(path)) + print(f"Error: checkpoint file not found in {path} ") print("and recurse not specified") sys.exit(1) sys.exit(0) diff --git a/util/cpt_upgraders/arm-hdlcd-upgrade.py b/util/cpt_upgraders/arm-hdlcd-upgrade.py index bbd2b9c79e..96d6368718 100644 --- a/util/cpt_upgraders/arm-hdlcd-upgrade.py +++ b/util/cpt_upgraders/arm-hdlcd-upgrade.py @@ -82,7 +82,7 @@ def upgrader(cpt): # Create a DMA engine section. The LCD controller will # initialize the DMA it after the next VSync, so we don't # care about the actual values - sec_dma = "%s.dmaEngine" % sec + sec_dma = f"{sec}.dmaEngine" cpt.add_section(sec_dma) cpt.set(sec_dma, "nextLineAddr", "0") cpt.set(sec_dma, "frameEnd", "0") diff --git a/util/cpt_upgraders/etherswitch.py b/util/cpt_upgraders/etherswitch.py index e10fa3601c..6f2cc74c8c 100644 --- a/util/cpt_upgraders/etherswitch.py +++ b/util/cpt_upgraders/etherswitch.py @@ -11,7 +11,7 @@ def upgrader(cpt): if "outputFifo" in new_sec_name: new_sec_name = new_sec_name.rstrip("outputFifo") new_sec_name += ".outputFifo" - new_sec_name = "system.system.%s" % (new_sec_name) + new_sec_name = f"system.system.{new_sec_name}" if not cpt.has_section(new_sec_name): cpt.add_section(new_sec_name) if old_opt_name == "size": diff --git a/util/cpt_upgraders/isa-is-simobject.py b/util/cpt_upgraders/isa-is-simobject.py index 077d4d98bf..0fd33f733e 100644 --- a/util/cpt_upgraders/isa-is-simobject.py +++ b/util/cpt_upgraders/isa-is-simobject.py @@ -79,7 +79,7 @@ def upgrader(cpt): if key in isa_fields: isa_section.append((key, value)) - name = "%s.isa" % re_cpu_match.group(1) + name = f"{re_cpu_match.group(1)}.isa" isa_sections.append((name, isa_section)) for (key, value) in isa_section: diff --git a/util/cpt_upgraders/process-fdmap-rename.py b/util/cpt_upgraders/process-fdmap-rename.py index dfd23bd5e0..3b8776af31 100644 --- a/util/cpt_upgraders/process-fdmap-rename.py +++ b/util/cpt_upgraders/process-fdmap-rename.py @@ -15,7 +15,7 @@ def upgrader(cpt): for sec in cpt.sections(): fdm = "FdMap" fde = "FDEntry" - if re.match(".*\.%s.*" % fdm, sec): + if re.match(f".*\\.{fdm}.*", sec): rename = re.sub(fdm, fde, sec) split = re.split(fde, rename) @@ -26,7 +26,7 @@ def upgrader(cpt): # add in entries 257 to 1023 if split[1] == "0": for x in range(257, 1024): - seq = (split[0], fde, "%s" % x) + seq = (split[0], fde, f"{x}") section = "".join(seq) cpt.add_section(section) cpt.set(section, "fd", "-1") diff --git a/util/decode_inst_dep_trace.py b/util/decode_inst_dep_trace.py index 2a43f52d54..ded0051ae1 100755 --- a/util/decode_inst_dep_trace.py +++ b/util/decode_inst_dep_trace.py @@ -164,20 +164,20 @@ def main(): num_packets += 1 # Write to file the seq num - ascii_out.write("%s" % (packet.seq_num)) + ascii_out.write(f"{packet.seq_num}") # Write to file the pc of the instruction, default is 0 if packet.HasField("pc"): - ascii_out.write(",%s" % (packet.pc)) + ascii_out.write(f",{packet.pc}") else: ascii_out.write(",0") # Write to file the weight, default is 1 if packet.HasField("weight"): - ascii_out.write(",%s" % (packet.weight)) + ascii_out.write(f",{packet.weight}") else: ascii_out.write(",1") # Write to file the type of the record try: - ascii_out.write(",%s" % enumNames[packet.type]) + ascii_out.write(f",{enumNames[packet.type]}") except KeyError: print( "Seq. num", packet.seq_num, "has unsupported type", packet.type @@ -187,21 +187,21 @@ def main(): # Write to file if it has the optional fields physical addr, size, # flags if packet.HasField("p_addr"): - ascii_out.write(",%s" % (packet.p_addr)) + ascii_out.write(f",{packet.p_addr}") if packet.HasField("size"): - ascii_out.write(",%s" % (packet.size)) + ascii_out.write(f",{packet.size}") if packet.HasField("flags"): - ascii_out.write(",%s" % (packet.flags)) + ascii_out.write(f",{packet.flags}") # Write to file the comp delay - ascii_out.write(",%s" % (packet.comp_delay)) + ascii_out.write(f",{packet.comp_delay}") # Write to file the repeated field order dependency ascii_out.write(":") if packet.rob_dep: num_robdeps += 1 for dep in packet.rob_dep: - ascii_out.write(",%s" % dep) + ascii_out.write(f",{dep}") # Write to file the repeated field register dependency ascii_out.write(":") if packet.reg_dep: @@ -209,7 +209,7 @@ def main(): 1 # No. of packets with atleast 1 register dependency ) for dep in packet.reg_dep: - ascii_out.write(",%s" % dep) + ascii_out.write(f",{dep}") # New line ascii_out.write("\n") diff --git a/util/decode_packet_trace.py b/util/decode_packet_trace.py index 798a824ecb..66a74c6f01 100755 --- a/util/decode_packet_trace.py +++ b/util/decode_packet_trace.py @@ -93,18 +93,15 @@ def main(): # ReadReq is 1 and WriteReq is 4 in src/mem/packet.hh Command enum cmd = "r" if packet.cmd == 1 else ("w" if packet.cmd == 4 else "u") if packet.HasField("pkt_id"): - ascii_out.write("%s," % (packet.pkt_id)) + ascii_out.write(f"{packet.pkt_id},") if packet.HasField("flags"): ascii_out.write( - "%s,%s,%s,%s,%s" - % (cmd, packet.addr, packet.size, packet.flags, packet.tick) + f"{cmd},{packet.addr},{packet.size},{packet.flags},{packet.tick}" ) else: - ascii_out.write( - "%s,%s,%s,%s" % (cmd, packet.addr, packet.size, packet.tick) - ) + ascii_out.write(f"{cmd},{packet.addr},{packet.size},{packet.tick}") if packet.HasField("pc"): - ascii_out.write(",%s\n" % (packet.pc)) + ascii_out.write(f",{packet.pc}\n") else: ascii_out.write("\n") diff --git a/util/find_copyrights.py b/util/find_copyrights.py index 6fbb10cb61..0bd0ef3a51 100644 --- a/util/find_copyrights.py +++ b/util/find_copyrights.py @@ -103,7 +103,7 @@ def find_copyright_block(lines, lang_type): return else: - raise AttributeError("Could not handle language %s" % lang_type) + raise AttributeError(f"Could not handle language {lang_type}") date_range_re = re.compile(r"([0-9]{4})\s*-\s*([0-9]{4})") @@ -254,7 +254,7 @@ if __name__ == "__main__": elif os.path.isdir(base): files += find_files(base) else: - raise AttributeError("can't access '%s'" % base) + raise AttributeError(f"can't access '{base}'") copyrights = {} counts = {} @@ -273,8 +273,8 @@ if __name__ == "__main__": except Exception as e: if verbose: if len(e.args) == 1: - e.args = ("%s (%s))" % (e, filename),) - print("could not parse %s: %s" % (filename, e)) + e.args = (f"{e} ({filename}))",) + print(f"could not parse {filename}: {e}") continue for owner, dates, authors, start, end in data: @@ -290,5 +290,5 @@ if __name__ == "__main__": for count, dates, owner in sorted(info, reverse=True): if show_counts: - owner = "%s (%s files)" % (owner, count) - print("Copyright (c) %s %s" % (datestr(dates), owner)) + owner = f"{owner} ({count} files)" + print(f"Copyright (c) {datestr(dates)} {owner}") diff --git a/util/gem5art/artifact/gem5art/artifact/_artifactdb.py b/util/gem5art/artifact/gem5art/artifact/_artifactdb.py index c1b9a69f5b..16d35e86e8 100644 --- a/util/gem5art/artifact/gem5art/artifact/_artifactdb.py +++ b/util/gem5art/artifact/gem5art/artifact/_artifactdb.py @@ -209,7 +209,7 @@ class ArtifactMongoDB(ArtifactDB): some type and a regex name.""" data = self.artifacts.find( - {"type": typ, "name": {"$regex": "{}".format(name)}}, limit=limit + {"type": typ, "name": {"$regex": f"{name}"}}, limit=limit ) for d in data: yield d diff --git a/util/gem5art/artifact/gem5art/artifact/artifact.py b/util/gem5art/artifact/gem5art/artifact/artifact.py index 46664e82fb..b71369c689 100644 --- a/util/gem5art/artifact/gem5art/artifact/artifact.py +++ b/util/gem5art/artifact/gem5art/artifact/artifact.py @@ -76,9 +76,9 @@ def getGit(path: Path) -> Dict[str, str]: ] res = subprocess.run(command, stdout=subprocess.PIPE, cwd=path) if res.returncode != 0: - raise Exception("git repo doesn't exist for {}".format(path)) + raise Exception(f"git repo doesn't exist for {path}") if res.stdout: - raise Exception("git repo dirty for {}".format(path)) + raise Exception(f"git repo dirty for {path}") command = ["git", "remote", "get-url", "origin"] origin = subprocess.check_output(command, cwd=path) @@ -203,14 +203,14 @@ class Artifact: data["git"] = getGit(ppath) data["hash"] = data["git"]["hash"] else: - raise Exception("Path {} doesn't exist".format(ppath)) + raise Exception(f"Path {ppath} doesn't exist") pcwd = Path(cwd) data["cwd"] = pcwd if not pcwd.exists(): - raise Exception("cwd {} doesn't exist.".format(pcwd)) + raise Exception(f"cwd {pcwd} doesn't exist.") if not pcwd.is_dir(): - raise Exception("cwd {} is not a directory".format(pcwd)) + raise Exception(f"cwd {pcwd} is not a directory") data["inputs"] = [i._id for i in inputs] diff --git a/util/gem5art/run/gem5art/run.py b/util/gem5art/run/gem5art/run.py index 89bd4637c4..12e4b3e208 100644 --- a/util/gem5art/run/gem5art/run.py +++ b/util/gem5art/run/gem5art/run.py @@ -316,7 +316,7 @@ class gem5Run: try: return cls.loadFromDict(d) except KeyError: - print("Incompatible json file: {}!".format(filename)) + print(f"Incompatible json file: {filename}!") raise @classmethod @@ -521,7 +521,7 @@ class gem5Run: # Check again in five seconds time.sleep(5) - print("Done running {}".format(" ".join(self.command))) + print(f"Done running {' '.join(self.command)}") # Done executing self.running = False @@ -540,7 +540,7 @@ class gem5Run: # Store current gem5 run in the database db.put(self._id, self._getSerializable()) - print("Done storing the results of {}".format(" ".join(self.command))) + print(f"Done storing the results of {' '.join(self.command)}") def run(self, task: Any = None, cwd: str = ".") -> None: """Actually run the test. diff --git a/util/gem5art/run/tests/test_run.py b/util/gem5art/run/tests/test_run.py index 1710dbc706..0bdd561220 100644 --- a/util/gem5art/run/tests/test_run.py +++ b/util/gem5art/run/tests/test_run.py @@ -112,7 +112,7 @@ class TestSERun(unittest.TestCase): [ "gem5/build/X86/gem5.opt", "-re", - "--outdir={}".format(os.path.abspath("results/run_test/out")), + f"--outdir={os.path.abspath('results/run_test/out')}", "configs-tests/run_test.py", "extra", "params", diff --git a/util/gem5img.py b/util/gem5img.py index 9b32b6c1a5..8eb0965c9e 100755 --- a/util/gem5img.py +++ b/util/gem5img.py @@ -135,7 +135,7 @@ def findProg(program, cleanupDev=None): if returncode != 0: if cleanupDev: cleanupDev.destroy() - exit("Unable to find program %s, check your PATH variable." % program) + exit(f"Unable to find program {program}, check your PATH variable.") return out.strip() @@ -197,7 +197,7 @@ def findPartOffset(devFile, fileName, partition): else: # No partition description was found print("No partition description was found in sfdisk output:") - print("\n".join(" {}".format(line.rstrip()) for line in lines)) + print("\n".join(f" {line.rstrip()}" for line in lines)) print("Could not determine size of first partition.") exit(1) @@ -242,7 +242,7 @@ class Command(object): posUsage = "" for posArg in posArgs: (argName, argDesc) = posArg - usage += " %s" % argName + usage += f" {argName}" posUsage += "\n %s: %s" % posArg usage += posUsage self.parser = ArgumentParser(usage=usage, description=description) @@ -266,7 +266,7 @@ class Command(object): def runCom(self): if not self.func: - exit("Unimplemented command %s!" % self.name) + exit(f"Unimplemented command {self.name}!") self.func(self.options, self.args) @@ -300,7 +300,7 @@ mountCom = Command( def mountComFunc(options, args): (path, mountPoint) = args if not os.path.isdir(mountPoint): - print("Mount point %s is not a directory." % mountPoint) + print(f"Mount point {mountPoint} is not a directory.") dev = LoopbackDevice() if dev.setup(path, offset=True) != 0: @@ -324,12 +324,12 @@ umountCom = Command( def umountComFunc(options, args): (mountPoint,) = args if not os.path.isdir(mountPoint): - print("Mount point %s is not a directory." % mountPoint) + print(f"Mount point {mountPoint} is not a directory.") exit(1) dev = mountPointToDev(mountPoint) if not dev: - print("Unable to find mount information for %s." % mountPoint) + print(f"Unable to find mount information for {mountPoint}.") # Unmount the loopback device. if runPriv([findProg("umount"), mountPoint]) != 0: @@ -424,7 +424,7 @@ formatCom.addArgument( def formatImage(dev, fsType): - return runPriv([findProg("mkfs.%s" % fsType, dev), str(dev)]) + return runPriv([findProg(f"mkfs.{fsType}", dev), str(dev)]) def formatComFunc(options, args): @@ -474,7 +474,7 @@ if len(argv) < 2 or argv[1] not in commands: print("where [command] is one of ") for name in commandOrder: command = commands[name] - print(" %s: %s" % (command.name, command.description)) + print(f" {command.name}: {command.description}") print("Watch for orphaned loopback devices and delete them with") print("losetup -d. Mounted images will belong to root, so you may need") print("to use sudo to modify their contents.") diff --git a/util/gen_arm_fs_files.py b/util/gen_arm_fs_files.py index 548abe819f..6446d79bfb 100755 --- a/util/gen_arm_fs_files.py +++ b/util/gen_arm_fs_files.py @@ -49,7 +49,7 @@ import os def run_cmd(explanation, working_dir, cmd, stdout=None): - print("Running phase '%s'" % explanation) + print(f"Running phase '{explanation}'") sys.stdout.flush() # some of the commands need $PWD to be properly set @@ -296,11 +296,11 @@ def xen(): [ "./configure", "--host=aarch64-linux-gnu", - "--with-kernel-dir={}".format(linux_dir), - "--with-dtb={}".format(dtb_bin), - "--with-cmdline='{}'".format(linux_cmdline), - "--with-xen-cmdline='{}'".format(xen_cmdline), - "--with-xen={}".format(os.path.join(xen_dir, "xen", "xen")), + f"--with-kernel-dir={linux_dir}", + f"--with-dtb={dtb_bin}", + f"--with-cmdline='{linux_cmdline}'", + f"--with-xen-cmdline='{xen_cmdline}'", + f"--with-xen={os.path.join(xen_dir, 'xen', 'xen')}", "--enable-psci", "--enable-gicv3", ], @@ -372,11 +372,11 @@ parser.add_argument( args = parser.parse_args() if not os.path.isdir(args.dest_dir): - print("Error: %s is not a directory." % args.dest_dir) + print(f"Error: {args.dest_dir} is not a directory.") sys.exit(1) if not os.path.isdir(args.gem5_dir): - print("Error: %s is not a directory." % args.gem5_dir) + print(f"Error: {args.gem5_dir} is not a directory.") sys.exit(1) if machine() != "x86_64": @@ -386,13 +386,13 @@ if machine() != "x86_64": binaries_dir = args.dest_dir + "/binaries" if os.path.exists(binaries_dir): - print("Error: %s already exists." % binaries_dir) + print(f"Error: {binaries_dir} already exists.") sys.exit(1) revisions_dir = args.dest_dir + "/revisions" if os.path.exists(revisions_dir): - print("Error: %s already exists." % revisions_dir) + print(f"Error: {revisions_dir} already exists.") sys.exit(1) os.mkdir(binaries_dir) @@ -413,6 +413,6 @@ binaries = args.fs_binaries if args.fs_binaries else list(all_binaries.keys()) for fs_binary in binaries: all_binaries[fs_binary]() -print("Done! All the generated files can be found in %s" % binaries_dir) +print(f"Done! All the generated files can be found in {binaries_dir}") sys.exit(0) diff --git a/util/git-pre-commit.py b/util/git-pre-commit.py index 766013fe3c..c6f3b3c033 100755 --- a/util/git-pre-commit.py +++ b/util/git-pre-commit.py @@ -67,7 +67,7 @@ staged_mismatch = set() for status, fname in git.status(filter="MA", cached=True): if args.verbose: - print("Checking {}...".format(fname)) + print(f"Checking {fname}...") if check_ignores(fname): continue if status == "M": @@ -112,7 +112,7 @@ if failing_files: print("Style checker failed for the following files:", file=sys.stderr) for f in failing_files: if f not in staged_mismatch: - print("\t{}".format(f), file=sys.stderr) + print(f"\t{f}", file=sys.stderr) print("\n", file=sys.stderr) print( "Please run the style checker manually to fix " @@ -130,6 +130,6 @@ if failing_files: file=sys.stderr, ) for f in staged_mismatch: - print("\t{}".format(f), file=sys.stderr) + print(f"\t{f}", file=sys.stderr) print("Please `git --add' them", file=sys.stderr) sys.exit(1) diff --git a/util/maint/list_changes.py b/util/maint/list_changes.py index 87e4ea2d20..0d61e39fde 100755 --- a/util/maint/list_changes.py +++ b/util/maint/list_changes.py @@ -104,7 +104,7 @@ class Commit(object): return cids[0] def __str__(self): - return "%s: %s" % (self.rev[0:8], self.log[0]) + return f"{self.rev[0:8]}: {self.log[0]}" def list_revs(branch, baseline=None, paths=[]): @@ -117,7 +117,7 @@ def list_revs(branch, baseline=None, paths=[]): """ if baseline is not None: - query = "%s..%s" % (branch, baseline) + query = f"{branch}..{baseline}" else: query = str(branch) diff --git a/util/maint/show_changes_by_file.py b/util/maint/show_changes_by_file.py index d5055c1ff4..75b7e7edd9 100755 --- a/util/maint/show_changes_by_file.py +++ b/util/maint/show_changes_by_file.py @@ -51,7 +51,7 @@ def diff_files(upstream, feature, paths=[]): """ raw = subprocess.check_output( - ["git", "diff", "--name-status", "%s..%s" % (upstream, feature), "--"] + ["git", "diff", "--name-status", f"{upstream}..{feature}", "--"] + paths ) @@ -61,7 +61,7 @@ def diff_files(upstream, feature, paths=[]): for p in path: direc = subprocess.check_output(["dirname", p]).strip() + "/" filename = subprocess.check_output(["basename", p]).strip() - odd[direc].append("%s" % filename) + odd[direc].append(f"{filename}") return odd @@ -76,7 +76,7 @@ def cl_hash(upstream, feature, path): """ raw = subprocess.check_output( - ["git", "log", "--oneline", "%s..%s" % (upstream, feature), "--", path] + ["git", "log", "--oneline", f"{upstream}..{feature}", "--", path] ) return [l.split()[0] for l in raw.splitlines()] @@ -119,11 +119,11 @@ def _main(): for key, value in odd.items(): print(key) for entry in value: - print(" %s" % entry) + print(f" {entry}") path = key + entry sha = cl_hash(args.upstream, args.feature, path) for s in sha: - print("\t%s" % s) + print(f"\t{s}") print() diff --git a/util/minorview/model.py b/util/minorview/model.py index 86f49a3da0..126b730bea 100644 --- a/util/minorview/model.py +++ b/util/minorview/model.py @@ -529,12 +529,12 @@ class Inst(IdedObj): def table_line(self): if self.nextAddr is not None: - addrStr = "0x%x->0x%x" % (self.addr, self.nextAddr) + addrStr = f"0x{self.addr:x}->0x{self.nextAddr:x}" else: - addrStr = "0x%x" % self.addr + addrStr = f"0x{self.addr:x}" ret = [addrStr, self.disassembly] for name, value in self.pairs.items(): - ret.append("%s=%s" % (name, str(value))) + ret.append(f"{name}={str(value)}") return ret @@ -547,7 +547,7 @@ class InstFault(IdedObj): self.addr = addr def table_line(self): - ret = ["0x%x" % self.addr, self.fault] + ret = [f"0x{self.addr:x}", self.fault] for name, value in self.pairs: ret.append("%s=%s", name, str(value)) return ret @@ -563,7 +563,7 @@ class Line(IdedObj): self.size = size def table_line(self): - ret = ["0x%x/0x%x" % (self.vaddr, self.paddr), "%d" % self.size] + ret = [f"0x{self.vaddr:x}/0x{self.paddr:x}", "%d" % self.size] for name, value in self.pairs: ret.append("%s=%s", name, str(value)) return ret @@ -578,7 +578,7 @@ class LineFault(IdedObj): self.fault = fault def table_line(self): - ret = ["0x%x" % self.vaddr, self.fault] + ret = [f"0x{self.vaddr:x}", self.fault] for name, value in self.pairs: ret.append("%s=%s", name, str(value)) return ret diff --git a/util/minorview/point.py b/util/minorview/point.py index 5df990998f..17190e1ca7 100644 --- a/util/minorview/point.py +++ b/util/minorview/point.py @@ -60,10 +60,10 @@ class Point(object): return (self.x, self.y) def __str__(self): - return "Point(%f,%f)" % (self.x, self.y) + return f"Point({self.x:f},{self.y:f})" def __repr__(self): - return "Point(%f,%f)" % (self.x, self.y) + return f"Point({self.x:f},{self.y:f})" def is_within_box(self, box): """Is this point inside the (centre, size) box box""" diff --git a/util/o3-pipeview.py b/util/o3-pipeview.py index 18f66129c8..fe49706dad 100755 --- a/util/o3-pipeview.py +++ b/util/o3-pipeview.py @@ -425,7 +425,7 @@ def print_inst( ) ) if timestamps: - outfile.write(" f=%s, r=%s" % (inst["fetch"], inst["retire"])) + outfile.write(f" f={inst['fetch']}, r={inst['retire']}") outfile.write("\n") else: outfile.write("...".center(12) + "\n") @@ -522,7 +522,7 @@ def main(): args.timestamps, args.only_committed, args.store_completions, - *(tick_range + inst_range) + *(tick_range + inst_range), ) print("done!") diff --git a/util/on-chip-network-power-area.py b/util/on-chip-network-power-area.py index 6a576bbdb3..61a316a99c 100644 --- a/util/on-chip-network-power-area.py +++ b/util/on-chip-network-power-area.py @@ -40,7 +40,7 @@ if not os.path.exists(build_dir): os.makedirs(build_dir) os.chdir(build_dir) -error = call(["cmake", "../../../%s" % src_dir]) +error = call(["cmake", f"../../../{src_dir}"]) if error: print("Failed to run cmake") exit(-1) @@ -154,18 +154,18 @@ def computeRouterPowerAndArea( ni_flit_size_bits, ) - print("%s Power: " % router, power) + print(f"{router} Power: ", power) ## Compute the power consumed by the given link def computeLinkPower(link, stats_file, config, sim_seconds): frequency = getClock(link + ".nls0", config) power = dsent.computeLinkPower(frequency) - print("%s.nls0 Power: " % link, power) + print(f"{link}.nls0 Power: ", power) frequency = getClock(link + ".nls1", config) power = dsent.computeLinkPower(frequency) - print("%s.nls1 Power: " % link, power) + print(f"{link}.nls1 Power: ", power) def parseStats( @@ -269,10 +269,10 @@ def main(): routers, int_links, ext_links, - ) = parseConfig("%s/%s/config.ini" % (sys.argv[1], sys.argv[2])) + ) = parseConfig(f"{sys.argv[1]}/{sys.argv[2]}/config.ini") parseStats( - "%s/%s/stats.txt" % (sys.argv[1], sys.argv[2]), + f"{sys.argv[1]}/{sys.argv[2]}/stats.txt", config, sys.argv[3], sys.argv[4], diff --git a/util/oprofile-top.py b/util/oprofile-top.py index b71c629f4e..4d5a693451 100755 --- a/util/oprofile-top.py +++ b/util/oprofile-top.py @@ -45,7 +45,7 @@ def category(app, sym): for regexp, cat in categories_re: if regexp.match(name): return cat - print("no match for symbol %s" % name) + print(f"no match for symbol {name}") return "other" @@ -99,4 +99,4 @@ if showidle: for d in cats: if d in prof: - print("%s -- %5.1f%% " % (d, 100 * float(prof[d]) / float(total))) + print(f"{d} -- {100 * float(prof[d]) / float(total):5.1f}% ") diff --git a/util/plot_dram/PlotPowerStates.py b/util/plot_dram/PlotPowerStates.py index 7f0b326812..b476a24da1 100755 --- a/util/plot_dram/PlotPowerStates.py +++ b/util/plot_dram/PlotPowerStates.py @@ -295,7 +295,7 @@ def plotStackedStates(delay, states_list, bottom_state, plot_name, ylabel_str): for prev_sum, new_s in zip(time_sum, l_states[state]) ] - ax[sub_idx].set_title("Bank util %s" % bank_util) + ax[sub_idx].set_title(f"Bank util {bank_util}") ax[sub_idx].xaxis.set_ticks(ind + width / 2.0) ax[sub_idx].xaxis.set_ticklabels(seqBytesValues, rotation=45) ax[sub_idx].set_xlabel("Seq. bytes") diff --git a/util/plot_dram/dram_sweep_plot.py b/util/plot_dram/dram_sweep_plot.py index ad7bc5e3b6..1350f7af77 100755 --- a/util/plot_dram/dram_sweep_plot.py +++ b/util/plot_dram/dram_sweep_plot.py @@ -147,7 +147,7 @@ def main(): # avg_pwr is in mW, peak_bw in MiByte/s, bus_util in percent z.append(avg_pwr[j] / (bus_util[j] / 100.0 * peak_bw[j] / 1000.0)) else: - print("Unexpected mode %s" % mode) + print(f"Unexpected mode {mode}") exit(-1) i += 1 diff --git a/util/plot_dram/lowp_dram_sweep_plot.py b/util/plot_dram/lowp_dram_sweep_plot.py index 03a47f9abd..dedd1e0c0d 100755 --- a/util/plot_dram/lowp_dram_sweep_plot.py +++ b/util/plot_dram/lowp_dram_sweep_plot.py @@ -76,7 +76,7 @@ parser.add_argument("--pdf", action="store_true", help="output Latex and pdf") def main(): args = parser.parse_args() if not os.path.isfile(args.statsfile): - exit("Error! File not found: %s" % args.statsfile) + exit(f"Error! File not found: {args.statsfile}") if not os.path.isdir(args.outdir): os.mkdir(args.outdir) diff --git a/util/streamline/m5stats2streamline.py b/util/streamline/m5stats2streamline.py index f8bc9bc987..8dc72bf0f9 100755 --- a/util/streamline/m5stats2streamline.py +++ b/util/streamline/m5stats2streamline.py @@ -383,7 +383,7 @@ def timestampList(x): def writeBinary(outfile, binary_list): for i in binary_list: - outfile.write("%c" % i) + outfile.write(f"{i:c}") ############################################################ @@ -751,7 +751,7 @@ def parseProcessInfo(task_file): if len(unified_event_list) == num_events: print("Truncating at", num_events, "events!") break - print("Found %d events." % len(unified_event_list)) + print(f"Found {len(unified_event_list)} events.") for process in process_list: if process.pid > 9990: # fix up framebuffer ticks @@ -1012,8 +1012,7 @@ def readGem5Stats(stats, gem5_stats_file): sim_freq = int(m.group(1)) # ticks in 1 sec ticks_in_ns = int(sim_freq / 1e9) print( - "Simulation frequency found! 1 tick == %e sec\n" - % (1.0 / sim_freq) + f"Simulation frequency found! 1 tick == {1.0 / sim_freq:e} sec\n" ) # Final tick in gem5 stats: current absolute timestamp @@ -1145,7 +1144,7 @@ def doCapturedXML(output_path, stats): s.set("title", stat.group) s.set("name", stat_name) s.set("color", "0x00000000") - s.set("key", "0x%08x" % stat.key) + s.set("key", f"0x{stat.key:08x}") s.set("type", stat_name) s.set("event", "0x00000000") if stat.per_cpu: @@ -1354,7 +1353,7 @@ output_path = args.output_path # Make sure input path exists #### if not os.path.exists(input_path): - print("ERROR: Input path %s does not exist!" % input_path) + print(f"ERROR: Input path {input_path} does not exist!") sys.exit(1) #### @@ -1389,7 +1388,7 @@ gem5_stats_file = input_path + "/stats.txt.gz" if not os.path.exists(gem5_stats_file): gem5_stats_file = input_path + "/stats.txt" if not os.path.exists(gem5_stats_file): - print("ERROR: stats.txt[.gz] file does not exist in %s!" % input_path) + print(f"ERROR: stats.txt[.gz] file does not exist in {input_path}!") sys.exit(1) readGem5Stats(stats, gem5_stats_file) diff --git a/util/style.py b/util/style.py index 4007ff9f9e..27d6568ec3 100755 --- a/util/style.py +++ b/util/style.py @@ -62,12 +62,11 @@ def verify( verifiers = style.verifiers.all_verifiers if verbose: - print("Verifying %s[%s]..." % (filename, regions)) + print(f"Verifying {filename}[{regions}]...") for verifier in [v(ui, opts, base=base) for v in verifiers]: if verbose: print( - "Applying %s (%s)" - % (verifier.test_name, verifier.__class__.__name__) + f"Applying {verifier.test_name} ({verifier.__class__.__name__})" ) if verifier.apply(filename, regions=regions): return False diff --git a/util/style/region.py b/util/style/region.py index 39eaba50be..bd2fc89251 100644 --- a/util/style/region.py +++ b/util/style/region.py @@ -100,7 +100,7 @@ class Region(tuple): return tuple.__new__(cls, args) def __repr__(self): - return "Region(%s, %s)" % (self[0], self[1]) + return f"Region({self[0]}, {self[1]})" @property def start(self): @@ -267,7 +267,7 @@ class Regions(object): return result def __repr__(self): - return "Regions(%s)" % ([(r[0], r[1]) for r in self.regions],) + return f"Regions({[(r[0], r[1]) for r in self.regions]})" all_regions = Regions(Region(neg_inf, pos_inf)) @@ -279,12 +279,12 @@ if __name__ == "__main__": n = Region(9, 10) def test(left, right): - print("%s == %s: %s" % (left, right, left == right)) - print("%s != %s: %s" % (left, right, left != right)) - print("%s < %s: %s" % (left, right, left < right)) - print("%s <= %s: %s" % (left, right, left <= right)) - print("%s > %s: %s" % (left, right, left > right)) - print("%s >= %s: %s" % (left, right, left >= right)) + print(f"{left} == {right}: {left == right}") + print(f"{left} != {right}: {left != right}") + print(f"{left} < {right}: {left < right}") + print(f"{left} <= {right}: {left <= right}") + print(f"{left} > {right}: {left > right}") + print(f"{left} >= {right}: {left >= right}") print("\n") test(neg_inf, neg_inf) diff --git a/util/style/repo.py b/util/style/repo.py index 20dfde4042..18079cea6a 100644 --- a/util/style/repo.py +++ b/util/style/repo.py @@ -192,7 +192,7 @@ class GitRepo(AbstractRepo): if cached: cmd.append("--cached") if filter: - cmd += ["--diff-filter=%s" % filter] + cmd += [f"--diff-filter={filter}"] cmd += [self.head_revision(), "--"] + files status = subprocess.check_output(cmd).decode("utf-8").rstrip("\n") @@ -202,13 +202,13 @@ class GitRepo(AbstractRepo): return [] def file_from_index(self, name): - return subprocess.check_output( - [self.git, "show", ":%s" % (name,)] - ).decode("utf-8") + return subprocess.check_output([self.git, "show", f":{name}"]).decode( + "utf-8" + ) def file_from_head(self, name): return subprocess.check_output( - [self.git, "show", "%s:%s" % (self.head_revision(), name)] + [self.git, "show", f"{self.head_revision()}:{name}"] ).decode("utf-8") diff --git a/util/style/sort_includes.py b/util/style/sort_includes.py index 67e7ca9fbc..9c532b5669 100644 --- a/util/style/sort_includes.py +++ b/util/style/sort_includes.py @@ -136,7 +136,7 @@ def _include_matcher_main(): base, ext = m.groups() (keyword, fname, extra) = base_matcher(context, line) try: - if fname == "%s.%s" % (base, header_map[ext]): + if fname == f"{base}.{header_map[ext]}": return (keyword, fname, extra) except KeyError: pass @@ -342,6 +342,6 @@ if __name__ == "__main__": dir_ignore=args.dir_ignore, ): if args.dry_run: - print("{}: {}".format(filename, language)) + print(f"{filename}: {language}") else: update_file(filename, filename, language, SortIncludes()) diff --git a/util/style/verifiers.py b/util/style/verifiers.py index 4ccd35af48..dbcce1c764 100644 --- a/util/style/verifiers.py +++ b/util/style/verifiers.py @@ -147,7 +147,7 @@ class Verifier(object, metaclass=ABCMeta): try: f = open(filename, mode) except OSError as msg: - print("could not open file {}: {}".format(filename, msg)) + print(f"could not open file {filename}: {msg}") return None return f @@ -247,7 +247,7 @@ class LineVerifier(Verifier): % (self.test_name, filename, num + 1) ) if self.ui.verbose: - self.ui.write(">>%s<<\n" % s_line[:-1]) + self.ui.write(f">>{s_line[:-1]}<<\n") errors += 1 if close: fobj.close() diff --git a/util/update-copyright.py b/util/update-copyright.py index c22638c2eb..1c3fd611ac 100755 --- a/util/update-copyright.py +++ b/util/update-copyright.py @@ -130,7 +130,7 @@ else: filter_repo_args = git_filter_repo.FilteringOptions.default_options() filter_repo_args.force = True filter_repo_args.partial = True -filter_repo_args.refs = ["{}..HEAD".format(args.start)] +filter_repo_args.refs = [f"{args.start}..HEAD"] filter_repo_args.repack = False filter_repo_args.replace_refs = "update-no-add"