pyi_generator.py 20 KB

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