Skip to content

Commit 42ce014

Browse files
committed
PEP 8 (keep to 80 chars)
1 parent ba8e4bf commit 42ce014

File tree

7 files changed

+117
-36
lines changed

7 files changed

+117
-36
lines changed

Tools/jit/.ruff.toml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
extend = "../../.ruff.toml" # Inherit the project-wide settings
22

3-
line-length = 88
4-
53
[format]
64
preview = true
75
docstring-code-format = true

Tools/jit/_llvm.py

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,9 @@
99
import typing
1010

1111
_LLVM_VERSION = 19
12-
_LLVM_VERSION_PATTERN = re.compile(rf"version\s+{_LLVM_VERSION}\.\d+\.\d+\S*\s+")
12+
_LLVM_VERSION_PATTERN = re.compile(
13+
rf"version\s+{_LLVM_VERSION}\.\d+\.\d+\S*\s+"
14+
)
1315

1416
_P = typing.ParamSpec("_P")
1517
_R = typing.TypeVar("_R")
@@ -33,7 +35,9 @@ async def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
3335
_CORES = asyncio.BoundedSemaphore(os.cpu_count() or 1)
3436

3537

36-
async def _run(tool: str, args: typing.Iterable[str], echo: bool = False) -> str | None:
38+
async def _run(
39+
tool: str, args: typing.Iterable[str], echo: bool = False
40+
) -> str | None:
3741
command = [tool, *args]
3842
async with _CORES:
3943
if echo:
@@ -46,7 +50,9 @@ async def _run(tool: str, args: typing.Iterable[str], echo: bool = False) -> str
4650
return None
4751
out, _ = await process.communicate()
4852
if process.returncode:
49-
raise RuntimeError(f"{tool} exited with return code {process.returncode}")
53+
raise RuntimeError(
54+
f"{tool} exited with return code {process.returncode}"
55+
)
5056
return out.decode()
5157

5258

@@ -58,7 +64,9 @@ async def _check_tool_version(name: str, *, echo: bool = False) -> bool:
5864

5965
@_async_cache
6066
async def _get_brew_llvm_prefix(*, echo: bool = False) -> str | None:
61-
output = await _run("brew", ["--prefix", f"llvm@{_LLVM_VERSION}"], echo=echo)
67+
output = await _run(
68+
"brew", ["--prefix", f"llvm@{_LLVM_VERSION}"], echo=echo
69+
)
6270
return output and output.removesuffix("\n")
6371

6472

@@ -90,7 +98,9 @@ async def maybe_run(
9098
return path and await _run(path, args, echo=echo)
9199

92100

93-
async def run(tool: str, args: typing.Iterable[str], echo: bool = False) -> str:
101+
async def run(
102+
tool: str, args: typing.Iterable[str], echo: bool = False
103+
) -> str:
94104
"""Run an LLVM tool if it can be found. Otherwise, raise RuntimeError."""
95105
output = await maybe_run(tool, args, echo=echo)
96106
if output is None:

Tools/jit/_schema.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,9 @@ class COFFSection(typing.TypedDict):
9797
class ELFSection(typing.TypedDict):
9898
"""An ELF object file section."""
9999

100-
Flags: dict[typing.Literal["Flags"], list[dict[typing.Literal["Name"], str]]]
100+
Flags: dict[
101+
typing.Literal["Flags"], list[dict[typing.Literal["Name"], str]]
102+
]
101103
Index: int
102104
Info: int
103105
Relocations: list[dict[typing.Literal["Relocation"], ELFRelocation]]
@@ -110,11 +112,15 @@ class MachOSection(typing.TypedDict):
110112
"""A Mach-O object file section."""
111113

112114
Address: int
113-
Attributes: dict[typing.Literal["Flags"], list[dict[typing.Literal["Name"], str]]]
115+
Attributes: dict[
116+
typing.Literal["Flags"], list[dict[typing.Literal["Name"], str]]
117+
]
114118
Index: int
115119
Name: dict[typing.Literal["Value"], str]
116120
Relocations: typing.NotRequired[
117121
list[dict[typing.Literal["Relocation"], MachORelocation]]
118122
]
119123
SectionData: typing.NotRequired[dict[typing.Literal["Bytes"], list[int]]]
120-
Symbols: typing.NotRequired[list[dict[typing.Literal["Symbol"], _MachOSymbol]]]
124+
Symbols: typing.NotRequired[
125+
list[dict[typing.Literal["Symbol"], _MachOSymbol]]
126+
]

Tools/jit/_stencils.py

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -199,14 +199,18 @@ class Stencil:
199199

200200
body: bytearray = dataclasses.field(default_factory=bytearray, init=False)
201201
holes: list[Hole] = dataclasses.field(default_factory=list, init=False)
202-
disassembly: list[str] = dataclasses.field(default_factory=list, init=False)
202+
disassembly: list[str] = dataclasses.field(
203+
default_factory=list, init=False
204+
)
203205

204206
def pad(self, alignment: int) -> None:
205207
"""Pad the stencil to the given alignment."""
206208
offset = len(self.body)
207209
padding = -offset % alignment
208210
if padding:
209-
self.disassembly.append(f"{offset:x}: {' '.join(['00'] * padding)}")
211+
self.disassembly.append(
212+
f"{offset:x}: {' '.join(['00'] * padding)}"
213+
)
210214
self.body.extend([0] * padding)
211215

212216
def add_nops(self, nop: bytes, alignment: int) -> None:
@@ -291,13 +295,21 @@ class StencilGroup:
291295
_trampolines: set[int] = dataclasses.field(default_factory=set, init=False)
292296

293297
def process_relocations(
294-
self, known_symbols: dict[str, int], *, alignment: int = 1, nop: bytes = b""
298+
self,
299+
known_symbols: dict[str, int],
300+
*,
301+
alignment: int = 1,
302+
nop: bytes = b"",
295303
) -> None:
296304
"""Fix up all GOT and internal relocations for this stencil group."""
297305
for hole in self.code.holes.copy():
298306
if (
299307
hole.kind
300-
in {"R_AARCH64_CALL26", "R_AARCH64_JUMP26", "ARM64_RELOC_BRANCH26"}
308+
in {
309+
"R_AARCH64_CALL26",
310+
"R_AARCH64_JUMP26",
311+
"ARM64_RELOC_BRANCH26",
312+
}
301313
and hole.value is HoleValue.ZERO
302314
and hole.symbol not in self.symbols
303315
):
@@ -320,7 +332,9 @@ def process_relocations(
320332
if hole.value is HoleValue.GOT:
321333
assert hole.symbol is not None
322334
hole.value = HoleValue.DATA
323-
hole.addend += self._global_offset_table_lookup(hole.symbol)
335+
hole.addend += self._global_offset_table_lookup(
336+
hole.symbol
337+
)
324338
hole.symbol = None
325339
elif hole.symbol in self.symbols:
326340
hole.value, addend = self.symbols[hole.symbol]
@@ -338,7 +352,9 @@ def process_relocations(
338352
self.data.holes.sort(key=lambda hole: hole.offset)
339353

340354
def _global_offset_table_lookup(self, symbol: str) -> int:
341-
return len(self.data.body) + self._got.setdefault(symbol, 8 * len(self._got))
355+
return len(self.data.body) + self._got.setdefault(
356+
symbol, 8 * len(self._got)
357+
)
342358

343359
def _emit_global_offset_table(self) -> None:
344360
got = len(self.data.body)

Tools/jit/_targets.py

Lines changed: 53 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@
1717
import _writer
1818

1919
if sys.version_info < (3, 11):
20-
raise RuntimeError("Building the JIT compiler requires Python 3.11 or newer!")
20+
raise RuntimeError(
21+
"Building the JIT compiler requires Python 3.11 or newer!"
22+
)
2123

2224
TOOLS_JIT_BUILD = pathlib.Path(__file__).resolve()
2325
TOOLS_JIT = TOOLS_JIT_BUILD.parent
@@ -27,9 +29,14 @@
2729
TOOLS_JIT_TEMPLATE_C = TOOLS_JIT / "template.c"
2830
ASYNCIO_RUNNER = asyncio.Runner()
2931

30-
_S = typing.TypeVar("_S", _schema.COFFSection, _schema.ELFSection, _schema.MachOSection)
32+
_S = typing.TypeVar(
33+
"_S", _schema.COFFSection, _schema.ELFSection, _schema.MachOSection
34+
)
3135
_R = typing.TypeVar(
32-
"_R", _schema.COFFRelocation, _schema.ELFRelocation, _schema.MachORelocation
36+
"_R",
37+
_schema.COFFRelocation,
38+
_schema.ELFRelocation,
39+
_schema.MachORelocation,
3340
)
3441

3542

@@ -95,7 +102,9 @@ async def _parse(self, path: pathlib.Path) -> _stencils.StencilGroup:
95102
# ...and also COFF:
96103
output = output[output.index("[", 1, None) :]
97104
output = output[: output.rindex("]", None, -1) + 1]
98-
sections: list[dict[typing.Literal["Section"], _S]] = json.loads(output)
105+
sections: list[dict[typing.Literal["Section"], _S]] = json.loads(
106+
output
107+
)
99108
for wrapped_section in sections:
100109
self._handle_section(wrapped_section["Section"], group)
101110
assert group.symbols["_JIT_ENTRY"] == (_stencils.HoleValue.CODE, 0)
@@ -104,7 +113,9 @@ async def _parse(self, path: pathlib.Path) -> _stencils.StencilGroup:
104113
group.data.disassembly.append(line)
105114
return group
106115

107-
def _handle_section(self, section: _S, group: _stencils.StencilGroup) -> None:
116+
def _handle_section(
117+
self, section: _S, group: _stencils.StencilGroup
118+
) -> None:
108119
raise NotImplementedError(type(self))
109120

110121
def _handle_relocation(
@@ -160,7 +171,9 @@ async def _build_stencils(self) -> dict[str, _stencils.StencilGroup]:
160171
generated_cases = PYTHON_EXECUTOR_CASES_C_H.read_text()
161172
cases_and_opnames = sorted(
162173
re.findall(
163-
r"\n {8}(case (\w+): \{\n.*?\n {8}\})", generated_cases, flags=re.DOTALL
174+
r"\n {8}(case (\w+): \{\n.*?\n {8}\})",
175+
generated_cases,
176+
flags=re.DOTALL,
164177
)
165178
)
166179
tasks = []
@@ -200,7 +213,9 @@ def build(
200213
"""Build jit_stencils.h in the given directory."""
201214
if not self.stable:
202215
warning = f"JIT support for {self.triple} is still experimental!"
203-
request = "Please report any issues you encounter.".center(len(warning))
216+
request = "Please report any issues you encounter.".center(
217+
len(warning)
218+
)
204219
outline = "=" * len(warning)
205220
print("\n".join(["", outline, warning, request, outline, ""]))
206221
digest = f"// {self._compute_digest(out)}\n"
@@ -264,7 +279,9 @@ def _handle_section(
264279
hole = self._handle_relocation(base, relocation, stencil.body)
265280
stencil.holes.append(hole)
266281

267-
def _unwrap_dllimport(self, name: str) -> tuple[_stencils.HoleValue, str | None]:
282+
def _unwrap_dllimport(
283+
self, name: str
284+
) -> tuple[_stencils.HoleValue, str | None]:
268285
if name.startswith("__imp_"):
269286
name = name.removeprefix("__imp_")
270287
name = name.removeprefix(self.prefix)
@@ -291,13 +308,17 @@ def _handle_relocation(
291308
"Offset": offset,
292309
"Symbol": s,
293310
"Type": {
294-
"Name": "IMAGE_REL_AMD64_REL32" | "IMAGE_REL_I386_REL32" as kind
311+
"Name": "IMAGE_REL_AMD64_REL32"
312+
| "IMAGE_REL_I386_REL32" as kind
295313
},
296314
}:
297315
offset += base
298316
value, symbol = self._unwrap_dllimport(s)
299317
addend = (
300-
int.from_bytes(raw[offset : offset + 4], "little", signed=True) - 4
318+
int.from_bytes(
319+
raw[offset : offset + 4], "little", signed=True
320+
)
321+
- 4
301322
)
302323
case {
303324
"Offset": offset,
@@ -429,7 +450,12 @@ def _handle_section(
429450
base = section["Address"] - start_address
430451
group.symbols[section["Index"]] = value, base
431452
stencil.body.extend(
432-
[0] * (section["Address"] - len(group.code.body) - len(group.data.body))
453+
[0]
454+
* (
455+
section["Address"]
456+
- len(group.code.body)
457+
- len(group.data.body)
458+
)
433459
)
434460
stencil.body.extend(section["SectionData"]["Bytes"])
435461
assert "Symbols" in section
@@ -468,13 +494,19 @@ def _handle_relocation(
468494
case {
469495
"Offset": offset,
470496
"Symbol": {"Name": s},
471-
"Type": {"Name": "X86_64_RELOC_GOT" | "X86_64_RELOC_GOT_LOAD" as kind},
497+
"Type": {
498+
"Name": "X86_64_RELOC_GOT"
499+
| "X86_64_RELOC_GOT_LOAD" as kind
500+
},
472501
}:
473502
offset += base
474503
s = s.removeprefix(self.prefix)
475504
value, symbol = _stencils.HoleValue.GOT, s
476505
addend = (
477-
int.from_bytes(raw[offset : offset + 4], "little", signed=True) - 4
506+
int.from_bytes(
507+
raw[offset : offset + 4], "little", signed=True
508+
)
509+
- 4
478510
)
479511
case {
480512
"Offset": offset,
@@ -483,13 +515,19 @@ def _handle_relocation(
483515
} | {
484516
"Offset": offset,
485517
"Symbol": {"Name": s},
486-
"Type": {"Name": "X86_64_RELOC_BRANCH" | "X86_64_RELOC_SIGNED" as kind},
518+
"Type": {
519+
"Name": "X86_64_RELOC_BRANCH"
520+
| "X86_64_RELOC_SIGNED" as kind
521+
},
487522
}:
488523
offset += base
489524
s = s.removeprefix(self.prefix)
490525
value, symbol = _stencils.symbol_to_value(s)
491526
addend = (
492-
int.from_bytes(raw[offset : offset + 4], "little", signed=True) - 4
527+
int.from_bytes(
528+
raw[offset : offset + 4], "little", signed=True
529+
)
530+
- 4
493531
)
494532
case {
495533
"Offset": offset,

Tools/jit/_writer.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,9 @@ def _dump_footer(
4040
yield "};"
4141

4242

43-
def _dump_stencil(opname: str, group: _stencils.StencilGroup) -> typing.Iterator[str]:
43+
def _dump_stencil(
44+
opname: str, group: _stencils.StencilGroup
45+
) -> typing.Iterator[str]:
4446
yield "void"
4547
yield f"emit_{opname}("
4648
yield " unsigned char *code, unsigned char *data, _PyExecutorObject *executor,"
@@ -62,7 +64,9 @@ def _dump_stencil(opname: str, group: _stencils.StencilGroup) -> typing.Iterator
6264
yield f" memcpy({part}, {part}_body, sizeof({part}_body));"
6365
skip = False
6466
stencil.holes.sort(key=lambda hole: hole.offset)
65-
for hole, pair in itertools.zip_longest(stencil.holes, stencil.holes[1:]):
67+
for hole, pair in itertools.zip_longest(
68+
stencil.holes, stencil.holes[1:]
69+
):
6670
if skip:
6771
skip = False
6872
continue

Tools/jit/build.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,22 @@
1717
help="a PEP 11 target triple to compile for",
1818
)
1919
parser.add_argument(
20-
"-d", "--debug", action="store_true", help="compile for a debug build of Python"
20+
"-d",
21+
"--debug",
22+
action="store_true",
23+
help="compile for a debug build of Python",
2124
)
2225
parser.add_argument(
23-
"-f", "--force", action="store_true", help="force the entire JIT to be rebuilt"
26+
"-f",
27+
"--force",
28+
action="store_true",
29+
help="force the entire JIT to be rebuilt",
2430
)
2531
parser.add_argument(
26-
"-v", "--verbose", action="store_true", help="echo commands as they are run"
32+
"-v",
33+
"--verbose",
34+
action="store_true",
35+
help="echo commands as they are run",
2736
)
2837
args = parser.parse_args()
2938
for target in args.target:

0 commit comments

Comments
 (0)