Skip to content

Commit 908f377

Browse files
walacglemco
authored andcommitted
rv/rvgen: replace % string formatting with f-strings
Replace all instances of percent-style string formatting with f-strings across the rvgen codebase. This modernizes the string formatting to use Python 3.6+ features, providing clearer and more maintainable code while improving runtime performance. The conversion handles all formatting cases including simple variable substitution, multi-variable formatting, and complex format specifiers. Dynamic width formatting is converted from "%*s" to "{var:>{width}}" using proper alignment syntax. Template strings for generated C code properly escape braces using double-brace syntax to produce literal braces in the output. F-strings provide approximately 2x performance improvement over percent formatting and are the recommended approach in modern Python. Signed-off-by: Wander Lairson Costa <wander@redhat.com> Reviewed-by: Nam Cao <namcao@linutronix.de> Reviewed-by: Gabriele Monaco <gmonaco@redhat.com> Link: https://lore.kernel.org/r/20260223162407.147003-4-wander@redhat.com Signed-off-by: Gabriele Monaco <gmonaco@redhat.com>
1 parent 3f305f8 commit 908f377

6 files changed

Lines changed: 83 additions & 85 deletions

File tree

tools/verification/rvgen/__main__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242

4343
try:
4444
if params.subcmd == "monitor":
45-
print("Opening and parsing the specification file %s" % params.spec)
45+
print(f"Opening and parsing the specification file {params.spec}")
4646
if params.monitor_class == "da":
4747
monitor = da2k(params.spec, params.monitor_type, vars(params))
4848
elif params.monitor_class == "ha":
@@ -58,11 +58,11 @@
5858
print(f"There was an error processing {params.spec}: {e}", file=sys.stderr)
5959
sys.exit(1)
6060

61-
print("Writing the monitor into the directory %s" % monitor.name)
61+
print(f"Writing the monitor into the directory {monitor.name}")
6262
monitor.print_files()
6363
print("Almost done, checklist")
6464
if params.subcmd == "monitor":
65-
print(" - Edit the %s/%s.c to add the instrumentation" % (monitor.name, monitor.name))
65+
print(f" - Edit the {monitor.name}/{monitor.name}.c to add the instrumentation")
6666
print(monitor.fill_tracepoint_tooltip())
6767
print(monitor.fill_makefile_tooltip())
6868
print(monitor.fill_kconfig_tooltip())

tools/verification/rvgen/rvgen/automata.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -79,11 +79,11 @@ def __get_model_name(self) -> str:
7979
basename = ntpath.basename(self.__dot_path)
8080
if not basename.endswith(".dot") and not basename.endswith(".gv"):
8181
print("not a dot file")
82-
raise AutomataError("not a dot file: %s" % self.__dot_path)
82+
raise AutomataError(f"not a dot file: {self.__dot_path}")
8383

8484
model_name = ntpath.splitext(basename)[0]
8585
if model_name.__len__() == 0:
86-
raise AutomataError("not a dot file: %s" % self.__dot_path)
86+
raise AutomataError(f"not a dot file: {self.__dot_path}")
8787

8888
return model_name
8989

@@ -102,7 +102,7 @@ def __open_dot(self) -> list[str]:
102102
line = dot_lines[cursor].split()
103103

104104
if (line[0] != "digraph") and (line[1] != "state_automaton"):
105-
raise AutomataError("Not a valid .dot format: %s" % self.__dot_path)
105+
raise AutomataError(f"Not a valid .dot format: {self.__dot_path}")
106106
else:
107107
cursor += 1
108108
return dot_lines

tools/verification/rvgen/rvgen/dot2c.py

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -29,17 +29,17 @@ def __init__(self, file_path, model_name=None):
2929

3030
def __get_enum_states_content(self) -> list[str]:
3131
buff = []
32-
buff.append("\t%s%s," % (self.initial_state, self.enum_suffix))
32+
buff.append(f"\t{self.initial_state}{self.enum_suffix},")
3333
for state in self.states:
3434
if state != self.initial_state:
35-
buff.append("\t%s%s," % (state, self.enum_suffix))
36-
buff.append("\tstate_max%s," % (self.enum_suffix))
35+
buff.append(f"\t{state}{self.enum_suffix},")
36+
buff.append(f"\tstate_max{self.enum_suffix},")
3737

3838
return buff
3939

4040
def format_states_enum(self) -> list[str]:
4141
buff = []
42-
buff.append("enum %s {" % self.enum_states_def)
42+
buff.append(f"enum {self.enum_states_def} {{")
4343
buff += self.__get_enum_states_content()
4444
buff.append("};\n")
4545

@@ -48,15 +48,15 @@ def format_states_enum(self) -> list[str]:
4848
def __get_enum_events_content(self) -> list[str]:
4949
buff = []
5050
for event in self.events:
51-
buff.append("\t%s%s," % (event, self.enum_suffix))
51+
buff.append(f"\t{event}{self.enum_suffix},")
5252

53-
buff.append("\tevent_max%s," % self.enum_suffix)
53+
buff.append(f"\tevent_max{self.enum_suffix},")
5454

5555
return buff
5656

5757
def format_events_enum(self) -> list[str]:
5858
buff = []
59-
buff.append("enum %s {" % self.enum_events_def)
59+
buff.append(f"enum {self.enum_events_def} {{")
6060
buff += self.__get_enum_events_content()
6161
buff.append("};\n")
6262

@@ -103,27 +103,27 @@ def get_minimun_type(self) -> str:
103103
min_type = "unsigned int"
104104

105105
if self.states.__len__() > 1000000:
106-
raise AutomataError("Too many states: %d" % self.states.__len__())
106+
raise AutomataError(f"Too many states: {self.states.__len__()}")
107107

108108
return min_type
109109

110110
def format_automaton_definition(self) -> list[str]:
111111
min_type = self.get_minimun_type()
112112
buff = []
113-
buff.append("struct %s {" % self.struct_automaton_def)
114-
buff.append("\tchar *state_names[state_max%s];" % (self.enum_suffix))
115-
buff.append("\tchar *event_names[event_max%s];" % (self.enum_suffix))
113+
buff.append(f"struct {self.struct_automaton_def} {{")
114+
buff.append(f"\tchar *state_names[state_max{self.enum_suffix}];")
115+
buff.append(f"\tchar *event_names[event_max{self.enum_suffix}];")
116116
if self.is_hybrid_automata():
117117
buff.append(f"\tchar *env_names[env_max{self.enum_suffix}];")
118-
buff.append("\t%s function[state_max%s][event_max%s];" % (min_type, self.enum_suffix, self.enum_suffix))
119-
buff.append("\t%s initial_state;" % min_type)
120-
buff.append("\tbool final_states[state_max%s];" % (self.enum_suffix))
118+
buff.append(f"\t{min_type} function[state_max{self.enum_suffix}][event_max{self.enum_suffix}];")
119+
buff.append(f"\t{min_type} initial_state;")
120+
buff.append(f"\tbool final_states[state_max{self.enum_suffix}];")
121121
buff.append("};\n")
122122
return buff
123123

124124
def format_aut_init_header(self) -> list[str]:
125125
buff = []
126-
buff.append("static const struct %s %s = {" % (self.struct_automaton_def, self.var_automaton_def))
126+
buff.append(f"static const struct {self.struct_automaton_def} {self.var_automaton_def} = {{")
127127
return buff
128128

129129
def __get_string_vector_per_line_content(self, entries: list[str]) -> str:
@@ -179,9 +179,9 @@ def get_aut_init_function(self) -> str:
179179
next_state = self.function[x][y] + self.enum_suffix
180180

181181
if linetoolong:
182-
line += "\t\t\t%s" % next_state
182+
line += f"\t\t\t{next_state}"
183183
else:
184-
line += "%*s" % (maxlen, next_state)
184+
line += f"{next_state:>{maxlen}}"
185185
if y != nr_events-1:
186186
line += ",\n" if linetoolong else ", "
187187
else:
@@ -225,7 +225,7 @@ def get_aut_init_final_states(self) -> str:
225225

226226
def format_aut_init_final_states(self) -> list[str]:
227227
buff = []
228-
buff.append("\t.final_states = { %s }," % self.get_aut_init_final_states())
228+
buff.append(f"\t.final_states = {{ {self.get_aut_init_final_states()} }},")
229229

230230
return buff
231231

@@ -241,7 +241,7 @@ def format_aut_init_footer(self) -> list[str]:
241241

242242
def format_invalid_state(self) -> list[str]:
243243
buff = []
244-
buff.append("#define %s state_max%s\n" % (self.invalid_state_str, self.enum_suffix))
244+
buff.append(f"#define {self.invalid_state_str} state_max{self.enum_suffix}\n")
245245

246246
return buff
247247

tools/verification/rvgen/rvgen/dot2k.py

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ def __init__(self, file_path, MonitorType, extra_params={}):
2121
self.monitor_type = MonitorType
2222
Monitor.__init__(self, extra_params)
2323
Dot2c.__init__(self, file_path, extra_params.get("model_name"))
24-
self.enum_suffix = "_%s" % self.name
24+
self.enum_suffix = f"_{self.name}"
25+
self.enum_suffix = f"_{self.name}"
2526
self.monitor_class = extra_params["monitor_class"]
2627

2728
def fill_monitor_type(self) -> str:
@@ -35,7 +36,7 @@ def fill_tracepoint_handlers_skel(self) -> str:
3536
buff = []
3637
buff += self._fill_hybrid_definitions()
3738
for event in self.events:
38-
buff.append("static void handle_%s(void *data, /* XXX: fill header */)" % event)
39+
buff.append(f"static void handle_{event}(void *data, /* XXX: fill header */)")
3940
buff.append("{")
4041
handle = "handle_event"
4142
if self.is_start_event(event):
@@ -46,39 +47,39 @@ def fill_tracepoint_handlers_skel(self) -> str:
4647
handle = "handle_start_run_event"
4748
if self.monitor_type == "per_task":
4849
buff.append("\tstruct task_struct *p = /* XXX: how do I get p? */;");
49-
buff.append("\tda_%s(p, %s%s);" % (handle, event, self.enum_suffix));
50+
buff.append(f"\tda_{handle}(p, {event}{self.enum_suffix});");
5051
elif self.monitor_type == "per_obj":
5152
buff.append("\tint id = /* XXX: how do I get the id? */;")
5253
buff.append("\tmonitor_target t = /* XXX: how do I get t? */;")
5354
buff.append(f"\tda_{handle}(id, t, {event}{self.enum_suffix});")
5455
else:
55-
buff.append("\tda_%s(%s%s);" % (handle, event, self.enum_suffix));
56+
buff.append(f"\tda_{handle}({event}{self.enum_suffix});");
5657
buff.append("}")
5758
buff.append("")
5859
return '\n'.join(buff)
5960

6061
def fill_tracepoint_attach_probe(self) -> str:
6162
buff = []
6263
for event in self.events:
63-
buff.append("\trv_attach_trace_probe(\"%s\", /* XXX: tracepoint */, handle_%s);" % (self.name, event))
64+
buff.append(f"\trv_attach_trace_probe(\"{self.name}\", /* XXX: tracepoint */, handle_{event});")
6465
return '\n'.join(buff)
6566

6667
def fill_tracepoint_detach_helper(self) -> str:
6768
buff = []
6869
for event in self.events:
69-
buff.append("\trv_detach_trace_probe(\"%s\", /* XXX: tracepoint */, handle_%s);" % (self.name, event))
70+
buff.append(f"\trv_detach_trace_probe(\"{self.name}\", /* XXX: tracepoint */, handle_{event});")
7071
return '\n'.join(buff)
7172

7273
def fill_model_h_header(self) -> list[str]:
7374
buff = []
7475
buff.append("/* SPDX-License-Identifier: GPL-2.0 */")
7576
buff.append("/*")
76-
buff.append(" * Automatically generated C representation of %s automaton" % (self.name))
77+
buff.append(f" * Automatically generated C representation of {self.name} automaton")
7778
buff.append(" * For further information about this format, see kernel documentation:")
7879
buff.append(" * Documentation/trace/rv/deterministic_automata.rst")
7980
buff.append(" */")
8081
buff.append("")
81-
buff.append("#define MONITOR_NAME %s" % (self.name))
82+
buff.append(f"#define MONITOR_NAME {self.name}")
8283
buff.append("")
8384

8485
return buff
@@ -87,11 +88,11 @@ def fill_model_h(self) -> str:
8788
#
8889
# Adjust the definition names
8990
#
90-
self.enum_states_def = "states_%s" % self.name
91-
self.enum_events_def = "events_%s" % self.name
91+
self.enum_states_def = f"states_{self.name}"
92+
self.enum_events_def = f"events_{self.name}"
9293
self.enum_envs_def = f"envs_{self.name}"
93-
self.struct_automaton_def = "automaton_%s" % self.name
94-
self.var_automaton_def = "automaton_%s" % self.name
94+
self.struct_automaton_def = f"automaton_{self.name}"
95+
self.var_automaton_def = f"automaton_{self.name}"
9596

9697
buff = self.fill_model_h_header()
9798
buff += self.format_model()
@@ -135,8 +136,8 @@ def fill_tracepoint_args_skel(self, tp_type: str) -> str:
135136
tp_args.insert(0, tp_args_id)
136137
tp_proto_c = ", ".join([a+b for a,b in tp_args])
137138
tp_args_c = ", ".join([b for a,b in tp_args])
138-
buff.append(" TP_PROTO(%s)," % tp_proto_c)
139-
buff.append(" TP_ARGS(%s)" % tp_args_c)
139+
buff.append(f" TP_PROTO({tp_proto_c}),")
140+
buff.append(f" TP_ARGS({tp_args_c})")
140141
return '\n'.join(buff)
141142

142143
def _fill_hybrid_definitions(self) -> list:

tools/verification/rvgen/rvgen/generator.py

Lines changed: 29 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def __fill_rv_kernel_dir(self):
4040
if platform.system() != "Linux":
4141
raise OSError("I can only run on Linux.")
4242

43-
kernel_path = os.path.join("/lib/modules/%s/build" % platform.release(), self.rv_dir)
43+
kernel_path = os.path.join(f"/lib/modules/{platform.release()}/build", self.rv_dir)
4444

4545
# if the current kernel is from a distro this may not be a full kernel tree
4646
# verify that one of the files we are going to modify is available
@@ -69,11 +69,11 @@ def _read_template_file(self, file):
6969
return self._read_file(path)
7070

7171
def fill_parent(self):
72-
return "&rv_%s" % self.parent if self.parent else "NULL"
72+
return f"&rv_{self.parent}" if self.parent else "NULL"
7373

7474
def fill_include_parent(self):
7575
if self.parent:
76-
return "#include <monitors/%s/%s.h>\n" % (self.parent, self.parent)
76+
return f"#include <monitors/{self.parent}/{self.parent}.h>\n"
7777
return ""
7878

7979
def fill_tracepoint_handlers_skel(self):
@@ -119,7 +119,7 @@ def fill_monitor_deps(self):
119119
buff = []
120120
buff.append(" # XXX: add dependencies if there")
121121
if self.parent:
122-
buff.append(" depends on RV_MON_%s" % self.parent.upper())
122+
buff.append(f" depends on RV_MON_{self.parent.upper()}")
123123
buff.append(" default y")
124124
return '\n'.join(buff)
125125

@@ -145,50 +145,49 @@ def fill_tracepoint_tooltip(self):
145145
monitor_class_type = self.fill_monitor_class_type()
146146
if self.auto_patch:
147147
self._patch_file("rv_trace.h",
148-
"// Add new monitors based on CONFIG_%s here" % monitor_class_type,
149-
"#include <monitors/%s/%s_trace.h>" % (self.name, self.name))
150-
return " - Patching %s/rv_trace.h, double check the result" % self.rv_dir
148+
f"// Add new monitors based on CONFIG_{monitor_class_type} here",
149+
f"#include <monitors/{self.name}/{self.name}_trace.h>")
150+
return f" - Patching {self.rv_dir}/rv_trace.h, double check the result"
151151

152-
return """ - Edit %s/rv_trace.h:
153-
Add this line where other tracepoints are included and %s is defined:
154-
#include <monitors/%s/%s_trace.h>
155-
""" % (self.rv_dir, monitor_class_type, self.name, self.name)
152+
return f""" - Edit {self.rv_dir}/rv_trace.h:
153+
Add this line where other tracepoints are included and {monitor_class_type} is defined:
154+
#include <monitors/{self.name}/{self.name}_trace.h>
155+
"""
156156

157157
def _kconfig_marker(self, container=None) -> str:
158-
return "# Add new %smonitors here" % (container + " "
159-
if container else "")
158+
return f"# Add new {container + ' ' if container else ''}monitors here"
160159

161160
def fill_kconfig_tooltip(self):
162161
if self.auto_patch:
163162
# monitors with a container should stay together in the Kconfig
164163
self._patch_file("Kconfig",
165164
self._kconfig_marker(self.parent),
166-
"source \"kernel/trace/rv/monitors/%s/Kconfig\"" % (self.name))
167-
return " - Patching %s/Kconfig, double check the result" % self.rv_dir
165+
f"source \"kernel/trace/rv/monitors/{self.name}/Kconfig\"")
166+
return f" - Patching {self.rv_dir}/Kconfig, double check the result"
168167

169-
return """ - Edit %s/Kconfig:
168+
return f""" - Edit {self.rv_dir}/Kconfig:
170169
Add this line where other monitors are included:
171-
source \"kernel/trace/rv/monitors/%s/Kconfig\"
172-
""" % (self.rv_dir, self.name)
170+
source \"kernel/trace/rv/monitors/{self.name}/Kconfig\"
171+
"""
173172

174173
def fill_makefile_tooltip(self):
175174
name = self.name
176175
name_up = name.upper()
177176
if self.auto_patch:
178177
self._patch_file("Makefile",
179178
"# Add new monitors here",
180-
"obj-$(CONFIG_RV_MON_%s) += monitors/%s/%s.o" % (name_up, name, name))
181-
return " - Patching %s/Makefile, double check the result" % self.rv_dir
179+
f"obj-$(CONFIG_RV_MON_{name_up}) += monitors/{name}/{name}.o")
180+
return f" - Patching {self.rv_dir}/Makefile, double check the result"
182181

183-
return """ - Edit %s/Makefile:
182+
return f""" - Edit {self.rv_dir}/Makefile:
184183
Add this line where other monitors are included:
185-
obj-$(CONFIG_RV_MON_%s) += monitors/%s/%s.o
186-
""" % (self.rv_dir, name_up, name, name)
184+
obj-$(CONFIG_RV_MON_{name_up}) += monitors/{name}/{name}.o
185+
"""
187186

188187
def fill_monitor_tooltip(self):
189188
if self.auto_patch:
190-
return " - Monitor created in %s/monitors/%s" % (self.rv_dir, self. name)
191-
return " - Move %s/ to the kernel's monitor directory (%s/monitors)" % (self.name, self.rv_dir)
189+
return f" - Monitor created in {self.rv_dir}/monitors/{self.name}"
190+
return f" - Move {self.name}/ to the kernel's monitor directory ({self.rv_dir}/monitors)"
192191

193192
def __create_directory(self):
194193
path = self.name
@@ -205,13 +204,13 @@ def __write_file(self, file_name, content):
205204
file.close()
206205

207206
def _create_file(self, file_name, content):
208-
path = "%s/%s" % (self.name, file_name)
207+
path = f"{self.name}/{file_name}"
209208
if self.auto_patch:
210209
path = os.path.join(self.rv_dir, "monitors", path)
211210
self.__write_file(path, content)
212211

213212
def __get_main_name(self):
214-
path = "%s/%s" % (self.name, "main.c")
213+
path = f"{self.name}/main.c"
215214
if not os.path.exists(path):
216215
return "main.c"
217216
return "__main.c"
@@ -221,11 +220,11 @@ def print_files(self):
221220

222221
self.__create_directory()
223222

224-
path = "%s.c" % self.name
223+
path = f"{self.name}.c"
225224
self._create_file(path, main_c)
226225

227226
model_h = self.fill_model_h()
228-
path = "%s.h" % self.name
227+
path = f"{self.name}.h"
229228
self._create_file(path, model_h)
230229

231230
kconfig = self.fill_kconfig()
@@ -258,5 +257,5 @@ def fill_trace_h(self):
258257
def print_files(self):
259258
super().print_files()
260259
trace_h = self.fill_trace_h()
261-
path = "%s_trace.h" % self.name
260+
path = f"{self.name}_trace.h"
262261
self._create_file(path, trace_h)

0 commit comments

Comments
 (0)