1
0

pyi_generator.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  1. """The pyi generator module."""
  2. import ast
  3. import contextlib
  4. import importlib
  5. import inspect
  6. import logging
  7. import os
  8. import re
  9. import sys
  10. import textwrap
  11. import typing
  12. from inspect import getfullargspec
  13. from pathlib import Path
  14. from types import ModuleType
  15. from typing import Any, Callable, Iterable, Type, get_args
  16. import black
  17. import black.mode
  18. from reflex.components.component import Component
  19. from reflex.utils import types as rx_types
  20. from reflex.vars import Var
  21. logger = logging.getLogger("pyi_generator")
  22. EXCLUDED_FILES = [
  23. "__init__.py",
  24. "component.py",
  25. "bare.py",
  26. "foreach.py",
  27. "cond.py",
  28. "match.py",
  29. "multiselect.py",
  30. "literals.py",
  31. ]
  32. # These props exist on the base component, but should not be exposed in create methods.
  33. EXCLUDED_PROPS = [
  34. "alias",
  35. "children",
  36. "event_triggers",
  37. "library",
  38. "lib_dependencies",
  39. "tag",
  40. "is_default",
  41. "special_props",
  42. "_invalid_children",
  43. "_memoization_mode",
  44. "_valid_children",
  45. ]
  46. DEFAULT_TYPING_IMPORTS = {
  47. "overload",
  48. "Any",
  49. "Dict",
  50. # "List",
  51. "Literal",
  52. "Optional",
  53. "Union",
  54. }
  55. def _get_type_hint(value, type_hint_globals, is_optional=True) -> str:
  56. """Resolve the type hint for value.
  57. Args:
  58. value: The type annotation as a str or actual types/aliases.
  59. type_hint_globals: The globals to use to resolving a type hint str.
  60. is_optional: Whether the type hint should be wrapped in Optional.
  61. Returns:
  62. The resolved type hint as a str.
  63. """
  64. res = ""
  65. args = get_args(value)
  66. if args:
  67. inner_container_type_args = (
  68. [repr(arg) for arg in args]
  69. if rx_types.is_literal(value)
  70. else [
  71. _get_type_hint(arg, type_hint_globals, is_optional=False)
  72. for arg in args
  73. if arg is not type(None)
  74. ]
  75. )
  76. res = f"{value.__name__}[{', '.join(inner_container_type_args)}]"
  77. if value.__name__ == "Var":
  78. # For Var types, Union with the inner args so they can be passed directly.
  79. types = [res] + [
  80. _get_type_hint(arg, type_hint_globals, is_optional=False)
  81. for arg in args
  82. if arg is not type(None)
  83. ]
  84. if len(types) > 1:
  85. res = ", ".join(types)
  86. res = f"Union[{res}]"
  87. elif isinstance(value, str):
  88. ev = eval(value, type_hint_globals)
  89. res = (
  90. _get_type_hint(ev, type_hint_globals, is_optional=False)
  91. if ev.__name__ == "Var"
  92. else value
  93. )
  94. else:
  95. res = value.__name__
  96. if is_optional and not res.startswith("Optional"):
  97. res = f"Optional[{res}]"
  98. return res
  99. def _generate_imports(typing_imports: Iterable[str]) -> list[ast.ImportFrom]:
  100. """Generate the import statements for the stub file.
  101. Args:
  102. typing_imports: The typing imports to include.
  103. Returns:
  104. The list of import statements.
  105. """
  106. return [
  107. ast.ImportFrom(
  108. module="typing",
  109. names=[ast.alias(name=imp) for imp in sorted(typing_imports)],
  110. ),
  111. *ast.parse( # type: ignore
  112. textwrap.dedent(
  113. """
  114. from reflex.vars import Var, BaseVar, ComputedVar
  115. from reflex.event import EventChain, EventHandler, EventSpec
  116. from reflex.style import Style"""
  117. )
  118. ).body,
  119. # *[
  120. # ast.ImportFrom(module=name, names=[ast.alias(name=val) for val in values])
  121. # for name, values in EXTRA_IMPORTS.items()
  122. # ],
  123. ]
  124. def _generate_docstrings(clzs: list[Type[Component]], props: list[str]) -> str:
  125. """Generate the docstrings for the create method.
  126. Args:
  127. clzs: The classes to generate docstrings for.
  128. props: The props to generate docstrings for.
  129. Returns:
  130. The docstring for the create method.
  131. """
  132. props_comments = {}
  133. comments = []
  134. for clz in clzs:
  135. for line in inspect.getsource(clz).splitlines():
  136. reached_functions = re.search("def ", line)
  137. if reached_functions:
  138. # We've reached the functions, so stop.
  139. break
  140. # Get comments for prop
  141. if line.strip().startswith("#"):
  142. comments.append(line)
  143. continue
  144. # Check if this line has a prop.
  145. match = re.search("\\w+:", line)
  146. if match is None:
  147. # This line doesn't have a var, so continue.
  148. continue
  149. # Get the prop.
  150. prop = match.group(0).strip(":")
  151. if prop in props:
  152. if not comments: # do not include undocumented props
  153. continue
  154. props_comments[prop] = [
  155. comment.strip().strip("#") for comment in comments
  156. ]
  157. comments.clear()
  158. clz = clzs[0]
  159. new_docstring = []
  160. for line in (clz.create.__doc__ or "").splitlines():
  161. if "**" in line:
  162. indent = line.split("**")[0]
  163. for nline in [
  164. f"{indent}{n}:{' '.join(c)}" for n, c in props_comments.items()
  165. ]:
  166. new_docstring.append(nline)
  167. new_docstring.append(line)
  168. return "\n".join(new_docstring)
  169. def _extract_func_kwargs_as_ast_nodes(
  170. func: Callable,
  171. type_hint_globals: dict[str, Any],
  172. ) -> list[tuple[ast.arg, ast.Constant | None]]:
  173. """Get the kwargs already defined on the function.
  174. Args:
  175. func: The function to extract kwargs from.
  176. type_hint_globals: The globals to use to resolving a type hint str.
  177. Returns:
  178. The list of kwargs as ast arg nodes.
  179. """
  180. spec = getfullargspec(func)
  181. kwargs = []
  182. for kwarg in spec.kwonlyargs:
  183. arg = ast.arg(arg=kwarg)
  184. if kwarg in spec.annotations:
  185. arg.annotation = ast.Name(
  186. id=_get_type_hint(spec.annotations[kwarg], type_hint_globals)
  187. )
  188. default = None
  189. if spec.kwonlydefaults is not None and kwarg in spec.kwonlydefaults:
  190. default = ast.Constant(value=spec.kwonlydefaults[kwarg])
  191. kwargs.append((arg, default))
  192. return kwargs
  193. def _extract_class_props_as_ast_nodes(
  194. func: Callable,
  195. clzs: list[Type],
  196. type_hint_globals: dict[str, Any],
  197. extract_real_default: bool = False,
  198. ) -> list[tuple[ast.arg, ast.Constant | None]]:
  199. """Get the props defined on the class and all parents.
  200. Args:
  201. func: The function that kwargs will be added to.
  202. clzs: The classes to extract props from.
  203. type_hint_globals: The globals to use to resolving a type hint str.
  204. extract_real_default: Whether to extract the real default value from the
  205. pydantic field definition.
  206. Returns:
  207. The list of props as ast arg nodes
  208. """
  209. spec = getfullargspec(func)
  210. all_props = []
  211. kwargs = []
  212. for target_class in clzs:
  213. # Import from the target class to ensure type hints are resolvable.
  214. exec(f"from {target_class.__module__} import *", type_hint_globals)
  215. for name, value in target_class.__annotations__.items():
  216. if name in spec.kwonlyargs or name in EXCLUDED_PROPS or name in all_props:
  217. continue
  218. all_props.append(name)
  219. default = None
  220. if extract_real_default:
  221. # TODO: This is not currently working since the default is not type compatible
  222. # with the annotation in some cases.
  223. with contextlib.suppress(AttributeError, KeyError):
  224. # Try to get default from pydantic field definition.
  225. default = target_class.__fields__[name].default
  226. if isinstance(default, Var):
  227. default = default._decode() # type: ignore
  228. kwargs.append(
  229. (
  230. ast.arg(
  231. arg=name,
  232. annotation=ast.Name(
  233. id=_get_type_hint(value, type_hint_globals)
  234. ),
  235. ),
  236. ast.Constant(value=default),
  237. )
  238. )
  239. return kwargs
  240. def _get_parent_imports(func):
  241. _imports = {"reflex.vars": ["Var"]}
  242. for type_hint in inspect.get_annotations(func).values():
  243. try:
  244. match = re.match(r"\w+\[([\w\d]+)\]", type_hint)
  245. except TypeError:
  246. continue
  247. if match:
  248. type_hint = match.group(1)
  249. if type_hint in importlib.import_module(func.__module__).__dir__():
  250. _imports.setdefault(func.__module__, []).append(type_hint)
  251. return _imports
  252. def _generate_component_create_functiondef(
  253. node: ast.FunctionDef | None,
  254. clz: type[Component],
  255. type_hint_globals: dict[str, Any],
  256. ) -> ast.FunctionDef:
  257. """Generate the create function definition for a Component.
  258. Args:
  259. node: The existing create functiondef node from the ast
  260. clz: The Component class to generate the create functiondef for.
  261. type_hint_globals: The globals to use to resolving a type hint str.
  262. Returns:
  263. The create functiondef node for the ast.
  264. """
  265. # add the imports needed by get_type_hint later
  266. type_hint_globals.update(
  267. {name: getattr(typing, name) for name in DEFAULT_TYPING_IMPORTS}
  268. )
  269. if clz.__module__ != clz.create.__module__:
  270. _imports = _get_parent_imports(clz.create)
  271. for name, values in _imports.items():
  272. exec(f"from {name} import {','.join(values)}", type_hint_globals)
  273. kwargs = _extract_func_kwargs_as_ast_nodes(clz.create, type_hint_globals)
  274. # kwargs associated with props defined in the class and its parents
  275. all_classes = [c for c in clz.__mro__ if issubclass(c, Component)]
  276. prop_kwargs = _extract_class_props_as_ast_nodes(
  277. clz.create, all_classes, type_hint_globals
  278. )
  279. all_props = [arg[0].arg for arg in prop_kwargs]
  280. kwargs.extend(prop_kwargs)
  281. # event handler kwargs
  282. kwargs.extend(
  283. (
  284. ast.arg(
  285. arg=trigger,
  286. annotation=ast.Name(
  287. id="Optional[Union[EventHandler, EventSpec, list, function, BaseVar]]"
  288. ),
  289. ),
  290. ast.Constant(value=None),
  291. )
  292. for trigger in sorted(clz().get_event_triggers().keys())
  293. )
  294. logger.debug(f"Generated {clz.__name__}.create method with {len(kwargs)} kwargs")
  295. create_args = ast.arguments(
  296. args=[ast.arg(arg="cls")],
  297. posonlyargs=[],
  298. vararg=ast.arg(arg="children"),
  299. kwonlyargs=[arg[0] for arg in kwargs],
  300. kw_defaults=[arg[1] for arg in kwargs],
  301. kwarg=ast.arg(arg="props"),
  302. defaults=[],
  303. )
  304. definition = ast.FunctionDef(
  305. name="create",
  306. args=create_args,
  307. body=[
  308. ast.Expr(
  309. value=ast.Constant(value=_generate_docstrings(all_classes, all_props))
  310. ),
  311. ast.Expr(
  312. value=ast.Ellipsis(),
  313. ),
  314. ],
  315. decorator_list=[
  316. ast.Name(id="overload"),
  317. *(
  318. node.decorator_list
  319. if node is not None
  320. else [ast.Name(id="classmethod")]
  321. ),
  322. ],
  323. lineno=node.lineno if node is not None else None,
  324. returns=ast.Constant(value=clz.__name__),
  325. )
  326. return definition
  327. class StubGenerator(ast.NodeTransformer):
  328. """A node transformer that will generate the stubs for a given module."""
  329. def __init__(self, module: ModuleType, classes: dict[str, Type[Component]]):
  330. """Initialize the stub generator.
  331. Args:
  332. module: The actual module object module to generate stubs for.
  333. classes: The actual Component class objects to generate stubs for.
  334. """
  335. super().__init__()
  336. # Dict mapping class name to actual class object.
  337. self.classes = classes
  338. # Track the last class node that was visited.
  339. self.current_class = None
  340. # These imports will be included in the AST of stub files.
  341. self.typing_imports = DEFAULT_TYPING_IMPORTS
  342. # Whether those typing imports have been inserted yet.
  343. self.inserted_imports = False
  344. # Collected import statements from the module.
  345. self.import_statements: list[str] = []
  346. # This dict is used when evaluating type hints.
  347. self.type_hint_globals = module.__dict__.copy()
  348. @staticmethod
  349. def _remove_docstring(
  350. node: ast.Module | ast.ClassDef | ast.FunctionDef,
  351. ) -> ast.Module | ast.ClassDef | ast.FunctionDef:
  352. """Removes any docstring in place.
  353. Args:
  354. node: The node to remove the docstring from.
  355. Returns:
  356. The modified node.
  357. """
  358. if (
  359. node.body
  360. and isinstance(node.body[0], ast.Expr)
  361. and isinstance(node.body[0].value, ast.Constant)
  362. ):
  363. node.body.pop(0)
  364. return node
  365. def visit_Module(self, node: ast.Module) -> ast.Module:
  366. """Visit a Module node and remove docstring from body.
  367. Args:
  368. node: The Module node to visit.
  369. Returns:
  370. The modified Module node.
  371. """
  372. self.generic_visit(node)
  373. return self._remove_docstring(node) # type: ignore
  374. def visit_Import(
  375. self, node: ast.Import | ast.ImportFrom
  376. ) -> ast.Import | ast.ImportFrom | list[ast.Import | ast.ImportFrom]:
  377. """Collect import statements from the module.
  378. If this is the first import statement, insert the typing imports before it.
  379. Args:
  380. node: The import node to visit.
  381. Returns:
  382. The modified import node(s).
  383. """
  384. self.import_statements.append(ast.unparse(node))
  385. if not self.inserted_imports:
  386. self.inserted_imports = True
  387. return _generate_imports(self.typing_imports) + [node]
  388. return node
  389. def visit_ImportFrom(
  390. self, node: ast.ImportFrom
  391. ) -> ast.Import | ast.ImportFrom | list[ast.Import | ast.ImportFrom] | None:
  392. """Visit an ImportFrom node.
  393. Remove any `from __future__ import *` statements, and hand off to visit_Import.
  394. Args:
  395. node: The ImportFrom node to visit.
  396. Returns:
  397. The modified ImportFrom node.
  398. """
  399. if node.module == "__future__":
  400. return None # ignore __future__ imports
  401. return self.visit_Import(node)
  402. def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:
  403. """Visit a ClassDef node.
  404. Remove all assignments in the class body, and add a create functiondef
  405. if one does not exist.
  406. Args:
  407. node: The ClassDef node to visit.
  408. Returns:
  409. The modified ClassDef node.
  410. """
  411. exec("\n".join(self.import_statements), self.type_hint_globals)
  412. self.current_class = node.name
  413. self._remove_docstring(node)
  414. self.generic_visit(node) # Visit child nodes.
  415. if (
  416. not any(
  417. isinstance(child, ast.FunctionDef) and child.name == "create"
  418. for child in node.body
  419. )
  420. and self.current_class in self.classes
  421. ):
  422. # Add a new .create FunctionDef since one does not exist.
  423. node.body.append(
  424. _generate_component_create_functiondef(
  425. node=None,
  426. clz=self.classes[self.current_class],
  427. type_hint_globals=self.type_hint_globals,
  428. )
  429. )
  430. if not node.body:
  431. # We should never return an empty body.
  432. node.body.append(ast.Expr(value=ast.Ellipsis()))
  433. self.current_class = None
  434. return node
  435. def visit_FunctionDef(self, node: ast.FunctionDef) -> Any:
  436. """Visit a FunctionDef node.
  437. Special handling for `.create` functions to add type hints for all props
  438. defined on the component class.
  439. Remove all private functions and blank out the function body of the
  440. remaining public functions.
  441. Args:
  442. node: The FunctionDef node to visit.
  443. Returns:
  444. The modified FunctionDef node (or None).
  445. """
  446. if node.name == "create" and self.current_class in self.classes:
  447. node = _generate_component_create_functiondef(
  448. node, self.classes[self.current_class], self.type_hint_globals
  449. )
  450. else:
  451. if node.name.startswith("_"):
  452. return None # remove private methods
  453. # Blank out the function body for public functions.
  454. node.body = [ast.Expr(value=ast.Ellipsis())]
  455. return node
  456. def visit_Assign(self, node: ast.Assign) -> ast.Assign | None:
  457. """Remove non-annotated assignment statements.
  458. Args:
  459. node: The Assign node to visit.
  460. Returns:
  461. The modified Assign node (or None).
  462. """
  463. # Special case for assignments to `typing.Any` as fallback.
  464. if (
  465. node.value is not None
  466. and isinstance(node.value, ast.Name)
  467. and node.value.id == "Any"
  468. ):
  469. return node
  470. if self.current_class in self.classes:
  471. # Remove annotated assignments in Component classes (props)
  472. return None
  473. return node
  474. def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AnnAssign | None:
  475. """Visit an AnnAssign node (Annotated assignment).
  476. Remove private target and remove the assignment value in the stub.
  477. Args:
  478. node: The AnnAssign node to visit.
  479. Returns:
  480. The modified AnnAssign node (or None).
  481. """
  482. if isinstance(node.target, ast.Name) and node.target.id.startswith("_"):
  483. return None
  484. if self.current_class in self.classes:
  485. # Remove annotated assignments in Component classes (props)
  486. return None
  487. # Blank out assignments in type stubs.
  488. node.value = None
  489. return node
  490. class PyiGenerator:
  491. """A .pyi file generator that will scan all defined Component in Reflex and
  492. generate the approriate stub.
  493. """
  494. modules: list = []
  495. root: str = ""
  496. current_module: Any = {}
  497. def _write_pyi_file(self, module_path: Path, source: str):
  498. pyi_content = [
  499. f'"""Stub file for {module_path}"""',
  500. "# ------------------- DO NOT EDIT ----------------------",
  501. "# This file was generated by `scripts/pyi_generator.py`!",
  502. "# ------------------------------------------------------",
  503. "",
  504. ]
  505. for formatted_line in black.format_file_contents(
  506. src_contents=source,
  507. fast=True,
  508. mode=black.mode.Mode(is_pyi=True),
  509. ).splitlines():
  510. # Bit of a hack here, since the AST cannot represent comments.
  511. if "def create(" in formatted_line:
  512. pyi_content.append(formatted_line + " # type: ignore")
  513. elif "Figure" in formatted_line:
  514. pyi_content.append(formatted_line + " # type: ignore")
  515. else:
  516. pyi_content.append(formatted_line)
  517. pyi_content.append("") # add empty line at the end for formatting
  518. pyi_path = module_path.with_suffix(".pyi")
  519. pyi_path.write_text("\n".join(pyi_content))
  520. logger.info(f"Wrote {pyi_path}")
  521. def _scan_file(self, module_path: Path):
  522. module_import = str(module_path.with_suffix("")).replace("/", ".")
  523. module = importlib.import_module(module_import)
  524. logger.debug(f"Read {module_path}")
  525. class_names = {
  526. name: obj
  527. for name, obj in vars(module).items()
  528. if inspect.isclass(obj)
  529. and issubclass(obj, Component)
  530. and obj != Component
  531. and inspect.getmodule(obj) == module
  532. }
  533. if not class_names:
  534. return
  535. new_tree = StubGenerator(module, class_names).visit(
  536. ast.parse(inspect.getsource(module))
  537. )
  538. self._write_pyi_file(module_path, ast.unparse(new_tree))
  539. def _scan_folder(self, folder):
  540. for root, _, files in os.walk(folder):
  541. for file in files:
  542. if file in EXCLUDED_FILES:
  543. continue
  544. if file.endswith(".py"):
  545. self._scan_file(Path(root) / file)
  546. def scan_all(self, targets):
  547. """Scan all targets for class inheriting Component and generate the .pyi files.
  548. Args:
  549. targets: the list of file/folders to scan.
  550. """
  551. for target in targets:
  552. if target.endswith(".py"):
  553. self._scan_file(Path(target))
  554. else:
  555. self._scan_folder(target)
  556. def generate_init():
  557. """Generate a pyi file for the main __init__.py."""
  558. from reflex import _MAPPING # type: ignore
  559. imports = [
  560. f"from {path if mod != path.rsplit('.')[-1] or mod == 'page' else '.'.join(path.rsplit('.')[:-1])} import {mod} as {mod}"
  561. for mod, path in _MAPPING.items()
  562. ]
  563. imports.append("")
  564. with open("reflex/__init__.pyi", "w") as pyi_file:
  565. pyi_file.writelines("\n".join(imports))
  566. if __name__ == "__main__":
  567. logging.basicConfig(level=logging.DEBUG)
  568. logging.getLogger("blib2to3.pgen2.driver").setLevel(logging.INFO)
  569. targets = sys.argv[1:] if len(sys.argv) > 1 else ["reflex/components"]
  570. logger.info(f"Running .pyi generator for {targets}")
  571. gen = PyiGenerator()
  572. gen.scan_all(targets)
  573. generate_init()