pyi_generator.py 21 KB

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