pyi_generator.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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 (
  217. name in spec.kwonlyargs
  218. or name in EXCLUDED_PROPS
  219. or name in all_props
  220. or (isinstance(value, str) and "ClassVar" in value)
  221. ):
  222. continue
  223. all_props.append(name)
  224. default = None
  225. if extract_real_default:
  226. # TODO: This is not currently working since the default is not type compatible
  227. # with the annotation in some cases.
  228. with contextlib.suppress(AttributeError, KeyError):
  229. # Try to get default from pydantic field definition.
  230. default = target_class.__fields__[name].default
  231. if isinstance(default, Var):
  232. default = default._decode() # type: ignore
  233. kwargs.append(
  234. (
  235. ast.arg(
  236. arg=name,
  237. annotation=ast.Name(
  238. id=_get_type_hint(value, type_hint_globals)
  239. ),
  240. ),
  241. ast.Constant(value=default),
  242. )
  243. )
  244. return kwargs
  245. def _get_parent_imports(func):
  246. _imports = {"reflex.vars": ["Var"]}
  247. for type_hint in inspect.get_annotations(func).values():
  248. try:
  249. match = re.match(r"\w+\[([\w\d]+)\]", type_hint)
  250. except TypeError:
  251. continue
  252. if match:
  253. type_hint = match.group(1)
  254. if type_hint in importlib.import_module(func.__module__).__dir__():
  255. _imports.setdefault(func.__module__, []).append(type_hint)
  256. return _imports
  257. def _generate_component_create_functiondef(
  258. node: ast.FunctionDef | None,
  259. clz: type[Component],
  260. type_hint_globals: dict[str, Any],
  261. ) -> ast.FunctionDef:
  262. """Generate the create function definition for a Component.
  263. Args:
  264. node: The existing create functiondef node from the ast
  265. clz: The Component class to generate the create functiondef for.
  266. type_hint_globals: The globals to use to resolving a type hint str.
  267. Returns:
  268. The create functiondef node for the ast.
  269. """
  270. # add the imports needed by get_type_hint later
  271. type_hint_globals.update(
  272. {name: getattr(typing, name) for name in DEFAULT_TYPING_IMPORTS}
  273. )
  274. if clz.__module__ != clz.create.__module__:
  275. _imports = _get_parent_imports(clz.create)
  276. for name, values in _imports.items():
  277. exec(f"from {name} import {','.join(values)}", type_hint_globals)
  278. kwargs = _extract_func_kwargs_as_ast_nodes(clz.create, type_hint_globals)
  279. # kwargs associated with props defined in the class and its parents
  280. all_classes = [c for c in clz.__mro__ if issubclass(c, Component)]
  281. prop_kwargs = _extract_class_props_as_ast_nodes(
  282. clz.create, all_classes, type_hint_globals
  283. )
  284. all_props = [arg[0].arg for arg in prop_kwargs]
  285. kwargs.extend(prop_kwargs)
  286. # event handler kwargs
  287. kwargs.extend(
  288. (
  289. ast.arg(
  290. arg=trigger,
  291. annotation=ast.Name(
  292. id="Optional[Union[EventHandler, EventSpec, list, function, BaseVar]]"
  293. ),
  294. ),
  295. ast.Constant(value=None),
  296. )
  297. for trigger in sorted(clz().get_event_triggers().keys())
  298. )
  299. logger.debug(f"Generated {clz.__name__}.create method with {len(kwargs)} kwargs")
  300. create_args = ast.arguments(
  301. args=[ast.arg(arg="cls")],
  302. posonlyargs=[],
  303. vararg=ast.arg(arg="children"),
  304. kwonlyargs=[arg[0] for arg in kwargs],
  305. kw_defaults=[arg[1] for arg in kwargs],
  306. kwarg=ast.arg(arg="props"),
  307. defaults=[],
  308. )
  309. definition = ast.FunctionDef(
  310. name="create",
  311. args=create_args,
  312. body=[
  313. ast.Expr(
  314. value=ast.Constant(value=_generate_docstrings(all_classes, all_props))
  315. ),
  316. ast.Expr(
  317. value=ast.Ellipsis(),
  318. ),
  319. ],
  320. decorator_list=[
  321. ast.Name(id="overload"),
  322. *(
  323. node.decorator_list
  324. if node is not None
  325. else [ast.Name(id="classmethod")]
  326. ),
  327. ],
  328. lineno=node.lineno if node is not None else None,
  329. returns=ast.Constant(value=clz.__name__),
  330. )
  331. return definition
  332. class StubGenerator(ast.NodeTransformer):
  333. """A node transformer that will generate the stubs for a given module."""
  334. def __init__(self, module: ModuleType, classes: dict[str, Type[Component]]):
  335. """Initialize the stub generator.
  336. Args:
  337. module: The actual module object module to generate stubs for.
  338. classes: The actual Component class objects to generate stubs for.
  339. """
  340. super().__init__()
  341. # Dict mapping class name to actual class object.
  342. self.classes = classes
  343. # Track the last class node that was visited.
  344. self.current_class = None
  345. # These imports will be included in the AST of stub files.
  346. self.typing_imports = DEFAULT_TYPING_IMPORTS
  347. # Whether those typing imports have been inserted yet.
  348. self.inserted_imports = False
  349. # Collected import statements from the module.
  350. self.import_statements: list[str] = []
  351. # This dict is used when evaluating type hints.
  352. self.type_hint_globals = module.__dict__.copy()
  353. @staticmethod
  354. def _remove_docstring(
  355. node: ast.Module | ast.ClassDef | ast.FunctionDef,
  356. ) -> ast.Module | ast.ClassDef | ast.FunctionDef:
  357. """Removes any docstring in place.
  358. Args:
  359. node: The node to remove the docstring from.
  360. Returns:
  361. The modified node.
  362. """
  363. if (
  364. node.body
  365. and isinstance(node.body[0], ast.Expr)
  366. and isinstance(node.body[0].value, ast.Constant)
  367. ):
  368. node.body.pop(0)
  369. return node
  370. def visit_Module(self, node: ast.Module) -> ast.Module:
  371. """Visit a Module node and remove docstring from body.
  372. Args:
  373. node: The Module node to visit.
  374. Returns:
  375. The modified Module node.
  376. """
  377. self.generic_visit(node)
  378. return self._remove_docstring(node) # type: ignore
  379. def visit_Import(
  380. self, node: ast.Import | ast.ImportFrom
  381. ) -> ast.Import | ast.ImportFrom | list[ast.Import | ast.ImportFrom]:
  382. """Collect import statements from the module.
  383. If this is the first import statement, insert the typing imports before it.
  384. Args:
  385. node: The import node to visit.
  386. Returns:
  387. The modified import node(s).
  388. """
  389. self.import_statements.append(ast.unparse(node))
  390. if not self.inserted_imports:
  391. self.inserted_imports = True
  392. return _generate_imports(self.typing_imports) + [node]
  393. return node
  394. def visit_ImportFrom(
  395. self, node: ast.ImportFrom
  396. ) -> ast.Import | ast.ImportFrom | list[ast.Import | ast.ImportFrom] | None:
  397. """Visit an ImportFrom node.
  398. Remove any `from __future__ import *` statements, and hand off to visit_Import.
  399. Args:
  400. node: The ImportFrom node to visit.
  401. Returns:
  402. The modified ImportFrom node.
  403. """
  404. if node.module == "__future__":
  405. return None # ignore __future__ imports
  406. return self.visit_Import(node)
  407. def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:
  408. """Visit a ClassDef node.
  409. Remove all assignments in the class body, and add a create functiondef
  410. if one does not exist.
  411. Args:
  412. node: The ClassDef node to visit.
  413. Returns:
  414. The modified ClassDef node.
  415. """
  416. exec("\n".join(self.import_statements), self.type_hint_globals)
  417. self.current_class = node.name
  418. self._remove_docstring(node)
  419. self.generic_visit(node) # Visit child nodes.
  420. if (
  421. not any(
  422. isinstance(child, ast.FunctionDef) and child.name == "create"
  423. for child in node.body
  424. )
  425. and self.current_class in self.classes
  426. ):
  427. # Add a new .create FunctionDef since one does not exist.
  428. node.body.append(
  429. _generate_component_create_functiondef(
  430. node=None,
  431. clz=self.classes[self.current_class],
  432. type_hint_globals=self.type_hint_globals,
  433. )
  434. )
  435. if not node.body:
  436. # We should never return an empty body.
  437. node.body.append(ast.Expr(value=ast.Ellipsis()))
  438. self.current_class = None
  439. return node
  440. def visit_FunctionDef(self, node: ast.FunctionDef) -> Any:
  441. """Visit a FunctionDef node.
  442. Special handling for `.create` functions to add type hints for all props
  443. defined on the component class.
  444. Remove all private functions and blank out the function body of the
  445. remaining public functions.
  446. Args:
  447. node: The FunctionDef node to visit.
  448. Returns:
  449. The modified FunctionDef node (or None).
  450. """
  451. if node.name == "create" and self.current_class in self.classes:
  452. node = _generate_component_create_functiondef(
  453. node, self.classes[self.current_class], self.type_hint_globals
  454. )
  455. else:
  456. if node.name.startswith("_"):
  457. return None # remove private methods
  458. # Blank out the function body for public functions.
  459. node.body = [ast.Expr(value=ast.Ellipsis())]
  460. return node
  461. def visit_Assign(self, node: ast.Assign) -> ast.Assign | None:
  462. """Remove non-annotated assignment statements.
  463. Args:
  464. node: The Assign node to visit.
  465. Returns:
  466. The modified Assign node (or None).
  467. """
  468. # Special case for assignments to `typing.Any` as fallback.
  469. if (
  470. node.value is not None
  471. and isinstance(node.value, ast.Name)
  472. and node.value.id == "Any"
  473. ):
  474. return node
  475. if self.current_class in self.classes:
  476. # Remove annotated assignments in Component classes (props)
  477. return None
  478. return node
  479. def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AnnAssign | None:
  480. """Visit an AnnAssign node (Annotated assignment).
  481. Remove private target and remove the assignment value in the stub.
  482. Args:
  483. node: The AnnAssign node to visit.
  484. Returns:
  485. The modified AnnAssign node (or None).
  486. """
  487. # skip ClassVars
  488. if (
  489. isinstance(node.annotation, ast.Subscript)
  490. and isinstance(node.annotation.value, ast.Name)
  491. and node.annotation.value.id == "ClassVar"
  492. ):
  493. return node
  494. if isinstance(node.target, ast.Name) and node.target.id.startswith("_"):
  495. return None
  496. if self.current_class in self.classes:
  497. # Remove annotated assignments in Component classes (props)
  498. return None
  499. # Blank out assignments in type stubs.
  500. node.value = None
  501. return node
  502. class PyiGenerator:
  503. """A .pyi file generator that will scan all defined Component in Reflex and
  504. generate the approriate stub.
  505. """
  506. modules: list = []
  507. root: str = ""
  508. current_module: Any = {}
  509. def _write_pyi_file(self, module_path: Path, source: str):
  510. pyi_content = [
  511. f'"""Stub file for {module_path}"""',
  512. "# ------------------- DO NOT EDIT ----------------------",
  513. "# This file was generated by `scripts/pyi_generator.py`!",
  514. "# ------------------------------------------------------",
  515. "",
  516. ]
  517. for formatted_line in black.format_file_contents(
  518. src_contents=source,
  519. fast=True,
  520. mode=black.mode.Mode(is_pyi=True),
  521. ).splitlines():
  522. # Bit of a hack here, since the AST cannot represent comments.
  523. if "def create(" in formatted_line:
  524. pyi_content.append(formatted_line + " # type: ignore")
  525. elif "Figure" in formatted_line:
  526. pyi_content.append(formatted_line + " # type: ignore")
  527. else:
  528. pyi_content.append(formatted_line)
  529. pyi_content.append("") # add empty line at the end for formatting
  530. pyi_path = module_path.with_suffix(".pyi")
  531. pyi_path.write_text("\n".join(pyi_content))
  532. logger.info(f"Wrote {pyi_path}")
  533. def _scan_file(self, module_path: Path):
  534. module_import = str(module_path.with_suffix("")).replace("/", ".")
  535. module = importlib.import_module(module_import)
  536. logger.debug(f"Read {module_path}")
  537. class_names = {
  538. name: obj
  539. for name, obj in vars(module).items()
  540. if inspect.isclass(obj)
  541. and issubclass(obj, Component)
  542. and obj != Component
  543. and inspect.getmodule(obj) == module
  544. }
  545. if not class_names:
  546. return
  547. new_tree = StubGenerator(module, class_names).visit(
  548. ast.parse(inspect.getsource(module))
  549. )
  550. self._write_pyi_file(module_path, ast.unparse(new_tree))
  551. def _scan_folder(self, folder):
  552. for root, _, files in os.walk(folder):
  553. for file in files:
  554. if file in EXCLUDED_FILES:
  555. continue
  556. if file.endswith(".py"):
  557. self._scan_file(Path(root) / file)
  558. def scan_all(self, targets):
  559. """Scan all targets for class inheriting Component and generate the .pyi files.
  560. Args:
  561. targets: the list of file/folders to scan.
  562. """
  563. for target in targets:
  564. if target.endswith(".py"):
  565. self._scan_file(Path(target))
  566. else:
  567. self._scan_folder(target)
  568. def generate_init():
  569. """Generate a pyi file for the main __init__.py."""
  570. from reflex import _MAPPING # type: ignore
  571. imports = [
  572. f"from {path if mod != path.rsplit('.')[-1] or mod == 'page' else '.'.join(path.rsplit('.')[:-1])} import {mod} as {mod}"
  573. for mod, path in _MAPPING.items()
  574. ]
  575. imports.append("")
  576. with open("reflex/__init__.pyi", "w") as pyi_file:
  577. pyi_file.writelines("\n".join(imports))
  578. if __name__ == "__main__":
  579. logging.basicConfig(level=logging.DEBUG)
  580. logging.getLogger("blib2to3.pgen2.driver").setLevel(logging.INFO)
  581. targets = sys.argv[1:] if len(sys.argv) > 1 else ["reflex/components"]
  582. logger.info(f"Running .pyi generator for {targets}")
  583. gen = PyiGenerator()
  584. gen.scan_all(targets)
  585. generate_init()