Debian Codegraph @

src/trio/_tools/gen_exports.py

raw
1 #! /usr/bin/env python3
2 """
3 Code generation script for class methods
4 to be exported as public API
5 """
6
7 from __future__ import annotations
8
9 import argparse
10 import ast
11 import os
12 import subprocess
13 import sys
14 from pathlib import Path
15 from textwrap import indent
16 from typing import TYPE_CHECKING, TypeGuard
17
18 import attrs
19
20 if TYPE_CHECKING:
21 from collections.abc import Iterable, Iterator
22
23 # keep these imports up to date with conditional imports in test_gen_exports
24 # isort: split
25 import astor
26
27 PREFIX = "_generated"
28
29 HEADER = """# ***********************************************************
30 # ******* WARNING: AUTOGENERATED! ALL EDITS WILL BE LOST ******
31 # *************************************************************
32 from __future__ import annotations
33
34 import sys
35
36 from ._ki import enable_ki_protection
37 from ._run import GLOBAL_RUN_CONTEXT
38 """
39
40 TEMPLATE = """try:
41 return{}GLOBAL_RUN_CONTEXT.{}.{}
42 except AttributeError:
43 raise RuntimeError("must be called from async context") from None
44 """
45
46
47 @attrs.define
48 class File:
49 path: Path
50 modname: str
51 platform: str = attrs.field(default="", kw_only=True)
52 imports: str = attrs.field(default="", kw_only=True)
53
54
55 def is_function(node: ast.AST) -> TypeGuard[ast.FunctionDef | ast.AsyncFunctionDef]:
56 """Check if the AST node is either a function
57 or an async function
58 """
59 return isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
60
61
62 def is_public(node: ast.AST) -> TypeGuard[ast.FunctionDef | ast.AsyncFunctionDef]:
63 """Check if the AST node has a _public decorator"""
64 if is_function(node):
65 for decorator in node.decorator_list:
66 if isinstance(decorator, ast.Name) and decorator.id == "_public":
67 return True
68 return False
69
70
71 def get_public_methods(
72 tree: ast.AST,
73 ) -> Iterator[ast.FunctionDef | ast.AsyncFunctionDef]:
74 """Return a list of methods marked as public.
75 The function walks the given tree and extracts
76 all objects that are functions which are marked
77 public.
78 """
79 for node in ast.walk(tree):
80 if is_public(node):
81 yield node
82
83
84 def create_passthrough_args(funcdef: ast.FunctionDef | ast.AsyncFunctionDef) -> str:
85 """Given a function definition, create a string that represents taking all
86 the arguments from the function, and passing them through to another
87 invocation of the same function.
88
89 Example input: ast.parse("def f(a, *, b): ...")
90 Example output: "(a, b=b)"
91 """
92 call_args = [arg.arg for arg in funcdef.args.args]
93 if funcdef.args.vararg:
94 call_args.append("*" + funcdef.args.vararg.arg)
95 for arg in funcdef.args.kwonlyargs:
96 call_args.append(arg.arg + "=" + arg.arg) # noqa: PERF401 # clarity
97 if funcdef.args.kwarg:
98 call_args.append("**" + funcdef.args.kwarg.arg)
99 return "({})".format(", ".join(call_args))
100
101
102 def run_black(file: File, source: str) -> tuple[bool, str]:
103 """Run black on the specified file.
104
105 Returns:
106 Tuple of success and result string.
107 ex.:
108 (False, "Failed to run black!\nerror: cannot format ...")
109 (True, "<formatted source>")
110
111 Raises:
112 ImportError: If black is not installed.
113 """
114 # imported to check that `subprocess` calls will succeed
115 import black # noqa: F401
116
117 # Black has an undocumented API, but it doesn't easily allow reading configuration from
118 # pyproject.toml, and simultaneously pass in / receive the code as a string.
119 # https://github.com/psf/black/issues/779
120 result = subprocess.run(
121 # "-" as a filename = use stdin, return on stdout.
122 [sys.executable, "-m", "black", "--stdin-filename", file.path, "-"],
123 input=source,
124 capture_output=True,
125 encoding="utf8",
126 )
127
128 if result.returncode != 0:
129 return False, f"Failed to run black!\n{result.stderr}"
130 return True, result.stdout
131
132
133 def run_ruff(file: File, source: str) -> tuple[bool, str]:
134 """Run ruff on the specified file.
135
136 Returns:
137 Tuple of success and result string.
138 ex.:
139 (False, "Failed to run ruff!\nerror: Failed to parse ...")
140 (True, "<formatted source>")
141
142 Raises:
143 ImportError: If ruff is not installed.
144 """
145 # imported to check that `subprocess` calls will succeed
146 import ruff # noqa: F401
147
148 result = subprocess.run(
149 # "-" as a filename = use stdin, return on stdout.
150 [
151 sys.executable,
152 "-m",
153 "ruff",
154 "check",
155 "--fix",
156 "--unsafe-fixes",
157 "--stdin-filename",
158 file.path,
159 "-",
160 ],
161 input=source,
162 capture_output=True,
163 encoding="utf8",
164 )
165
166 if result.returncode != 0:
167 return False, f"Failed to run ruff!\n{result.stderr}"
168 return True, result.stdout
169
170
171 def run_linters(file: File, source: str) -> str:
172 """Format the specified file using black and ruff.
173
174 Returns:
175 Formatted source code.
176
177 Raises:
178 ImportError: If either is not installed.
179 SystemExit: If either failed.
180 """
181
182 for fn in (run_black, run_ruff):
183 success, source = fn(file, source)
184 if not success:
185 print(source)
186 sys.exit(1)
187
188 return source
189
190
191 def gen_public_wrappers_source(file: File) -> str:
192 """Scan the given .py file for @_public decorators, and generate wrapper
193 functions.
194
195 """
196 header = [HEADER]
197 header.append(file.imports)
198 if file.platform:
199 # Simple checks to avoid repeating imports. If this messes up, type checkers/tests will
200 # just give errors.
201 if "TYPE_CHECKING" not in file.imports:
202 header.append("from typing import TYPE_CHECKING\n")
203 if "import sys" not in file.imports: # pragma: no cover
204 header.append("import sys\n")
205 header.append(
206 f'\nassert not TYPE_CHECKING or sys.platform=="{file.platform}"\n',
207 )
208
209 generated = ["".join(header)]
210
211 source = astor.code_to_ast.parse_file(file.path)
212 method_names = []
213 for method in get_public_methods(source):
214 # Remove self from arguments
215 assert method.args.args[0].arg == "self"
216 del method.args.args[0]
217 method_names.append(method.name)
218
219 for dec in method.decorator_list: # pragma: no cover
220 if isinstance(dec, ast.Name) and dec.id == "contextmanager":
221 is_cm = True
222 break
223 else:
224 is_cm = False
225
226 # Remove decorators
227 method.decorator_list = [ast.Name("enable_ki_protection")]
228
229 # Create pass through arguments
230 new_args = create_passthrough_args(method)
231
232 # Remove method body without the docstring
233 if ast.get_docstring(method) is None:
234 del method.body[:]
235 else:
236 # The first entry is always the docstring
237 del method.body[1:]
238
239 # Create the function definition including the body
240 func = astor.to_source(method, indent_with=" " * 4)
241
242 if is_cm: # pragma: no cover
243 func = func.replace("->Iterator", "->AbstractContextManager")
244
245 # Create export function body
246 template = TEMPLATE.format(
247 " await " if isinstance(method, ast.AsyncFunctionDef) else " ",
248 file.modname,
249 method.name + new_args,
250 )
251
252 # Assemble function definition arguments and body
253 snippet = func + indent(template, " " * 4)
254
255 # Append the snippet to the corresponding module
256 generated.append(snippet)
257
258 method_names.sort()
259 # Insert after the header, before function definitions
260 generated.insert(1, f"__all__ = {method_names!r}")
261 return "\n\n".join(generated)
262
263
264 def matches_disk_files(new_files: dict[str, str]) -> bool:
265 for new_path, new_source in new_files.items():
266 if not os.path.exists(new_path):
267 return False
268 old_source = Path(new_path).read_text(encoding="utf-8")
269 if old_source != new_source:
270 return False
271 return True
272
273
274 def process(files: Iterable[File], *, do_test: bool) -> None:
275 new_files = {}
276 for file in files:
277 print("Scanning:", file.path)
278 new_source = gen_public_wrappers_source(file)
279 new_source = run_linters(file, new_source)
280 dirname, basename = os.path.split(file.path)
281 new_path = os.path.join(dirname, PREFIX + basename)
282 new_files[new_path] = new_source
283 matches_disk = matches_disk_files(new_files)
284 if do_test:
285 if not matches_disk:
286 print("Generated sources are outdated. Please regenerate.")
287 sys.exit(1)
288 else:
289 print("Generated sources are up to date.")
290 else:
291 for new_path, new_source in new_files.items():
292 Path(new_path).write_text(new_source, encoding="utf-8", newline="\n")
293 print("Regenerated sources successfully.")
294 if not matches_disk: # TODO: test this branch
295 # With pre-commit integration, show that we edited files.
296 sys.exit(1)
297
298
299 # This is in fact run in CI, but only in the formatting check job, which
300 # doesn't collect coverage.
301 def main() -> None: # pragma: no cover
302 parser = argparse.ArgumentParser(
303 description="Generate python code for public api wrappers",
304 )
305 parser.add_argument(
306 "--test",
307 "-t",
308 action="store_true",
309 help="test if code is still up to date",
310 )
311 parsed_args = parser.parse_args()
312
313 source_root = Path.cwd()
314 # Double-check we found the right directory
315 assert (source_root / "LICENSE").exists()
316 core = source_root / "src/trio/_core"
317 to_wrap = [
318 File(core / "_run.py", "runner", imports=IMPORTS_RUN),
319 File(
320 core / "_instrumentation.py",
321 "runner.instruments",
322 imports=IMPORTS_INSTRUMENT,
323 ),
324 File(
325 core / "_io_windows.py",
326 "runner.io_manager",
327 platform="win32",
328 imports=IMPORTS_WINDOWS,
329 ),
330 File(
331 core / "_io_epoll.py",
332 "runner.io_manager",
333 platform="linux",
334 imports=IMPORTS_EPOLL,
335 ),
336 File(
337 core / "_io_kqueue.py",
338 "runner.io_manager",
339 platform="darwin",
340 imports=IMPORTS_KQUEUE,
341 ),
342 ]
343
344 process(to_wrap, do_test=parsed_args.test)
345
346
347 IMPORTS_RUN = """\
348 from collections.abc import Awaitable, Callable
349 from typing import Any, TYPE_CHECKING
350
351 import outcome
352 import contextvars
353
354 from ._run import _NO_SEND, RunStatistics, Task
355 from ._entry_queue import TrioToken
356 from .._abc import Clock
357
358 if TYPE_CHECKING:
359 from typing_extensions import Unpack
360 from ._run import PosArgT
361 """
362 IMPORTS_INSTRUMENT = """\
363 from ._instrumentation import Instrument
364 """
365
366 IMPORTS_EPOLL = """\
367 from typing import TYPE_CHECKING
368
369 if TYPE_CHECKING:
370 from .._file_io import _HasFileNo
371 """
372
373 IMPORTS_KQUEUE = """\
374 from typing import TYPE_CHECKING
375
376 if TYPE_CHECKING:
377 import select
378 from collections.abc import Callable
379 from contextlib import AbstractContextManager
380
381 from .. import _core
382 from .._file_io import _HasFileNo
383 from ._traps import Abort, RaiseCancelT
384 """
385
386 IMPORTS_WINDOWS = """\
387 from typing import TYPE_CHECKING
388
389 if TYPE_CHECKING:
390 from contextlib import AbstractContextManager
391
392 from typing_extensions import Buffer
393
394 from .._file_io import _HasFileNo
395 from ._unbounded_queue import UnboundedQueue
396 from ._windows_cffi import Handle, CData
397 """
398
399
400 if __name__ == "__main__":
401 main()