pyi_generator.py 20 KB

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