pyi_generator.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. """The pyi generator module."""
  2. import importlib
  3. import inspect
  4. import os
  5. import re
  6. import sys
  7. from inspect import getfullargspec
  8. from pathlib import Path
  9. from typing import Any, Dict, List, Literal, Optional, Union, get_args # NOQA
  10. import black
  11. from reflex.components.component import Component
  12. # NOQA
  13. from reflex.components.graphing.recharts.recharts import (
  14. LiteralAnimationEasing,
  15. LiteralAreaType,
  16. LiteralComposedChartBaseValue,
  17. LiteralDirection,
  18. LiteralGridType,
  19. LiteralIconType,
  20. LiteralIfOverflow,
  21. LiteralInterval,
  22. LiteralLayout,
  23. LiteralLegendAlign,
  24. LiteralLineType,
  25. LiteralOrientationTopBottom,
  26. LiteralOrientationTopBottomLeftRight,
  27. LiteralPolarRadiusType,
  28. LiteralPosition,
  29. LiteralScale,
  30. LiteralShape,
  31. LiteralStackOffset,
  32. LiteralSyncMethod,
  33. LiteralVerticalAlign,
  34. )
  35. from reflex.components.libs.chakra import (
  36. LiteralAlertDialogSize,
  37. LiteralAvatarSize,
  38. LiteralChakraDirection,
  39. LiteralColorScheme,
  40. LiteralDrawerSize,
  41. LiteralImageLoading,
  42. LiteralInputVariant,
  43. LiteralMenuOption,
  44. LiteralMenuStrategy,
  45. LiteralTagSize,
  46. )
  47. # NOQA
  48. from reflex.utils import format
  49. from reflex.utils import types as rx_types
  50. from reflex.vars import Var
  51. ruff_dont_remove = [
  52. Var,
  53. Optional,
  54. Dict,
  55. List,
  56. LiteralInputVariant,
  57. LiteralColorScheme,
  58. LiteralChakraDirection,
  59. LiteralTagSize,
  60. LiteralDrawerSize,
  61. LiteralMenuStrategy,
  62. LiteralMenuOption,
  63. LiteralAlertDialogSize,
  64. LiteralAvatarSize,
  65. LiteralImageLoading,
  66. LiteralLayout,
  67. LiteralAnimationEasing,
  68. LiteralGridType,
  69. LiteralPolarRadiusType,
  70. LiteralScale,
  71. LiteralSyncMethod,
  72. LiteralStackOffset,
  73. LiteralComposedChartBaseValue,
  74. LiteralOrientationTopBottom,
  75. LiteralAreaType,
  76. LiteralShape,
  77. LiteralLineType,
  78. LiteralDirection,
  79. LiteralIfOverflow,
  80. LiteralOrientationTopBottomLeftRight,
  81. LiteralInterval,
  82. LiteralLegendAlign,
  83. LiteralVerticalAlign,
  84. LiteralIconType,
  85. LiteralPosition,
  86. ]
  87. EXCLUDED_FILES = [
  88. "__init__.py",
  89. "component.py",
  90. "bare.py",
  91. "foreach.py",
  92. "cond.py",
  93. "multiselect.py",
  94. ]
  95. DEFAULT_TYPING_IMPORTS = {"overload", "Optional", "Union"}
  96. def _get_type_hint(value, top_level=True, no_union=False):
  97. res = ""
  98. args = get_args(value)
  99. if args:
  100. inner_container_type_args = (
  101. [format.wrap(arg, '"') for arg in args]
  102. if rx_types.is_literal(value)
  103. else [
  104. _get_type_hint(arg, top_level=False)
  105. for arg in args
  106. if arg is not type(None)
  107. ]
  108. )
  109. res = f"{value.__name__}[{', '.join(inner_container_type_args)}]"
  110. if value.__name__ == "Var":
  111. types = [res] + [
  112. _get_type_hint(arg, top_level=False)
  113. for arg in args
  114. if arg is not type(None)
  115. ]
  116. if len(types) > 1 and not no_union:
  117. res = ", ".join(types)
  118. res = f"Union[{res}]"
  119. elif isinstance(value, str):
  120. ev = eval(value)
  121. res = _get_type_hint(ev, top_level=False) if ev.__name__ == "Var" else value
  122. else:
  123. res = value.__name__
  124. if top_level and not res.startswith("Optional"):
  125. res = f"Optional[{res}]"
  126. return res
  127. def _get_typing_import(_module):
  128. src = [
  129. line
  130. for line in inspect.getsource(_module).split("\n")
  131. if line.startswith("from typing")
  132. ]
  133. if len(src):
  134. return set(src[0].rpartition("from typing import ")[-1].split(", "))
  135. return set()
  136. def _get_var_definition(_module, _var_name):
  137. return [
  138. line.split(" = ")[0]
  139. for line in inspect.getsource(_module).splitlines()
  140. if line.startswith(_var_name)
  141. ]
  142. class PyiGenerator:
  143. """A .pyi file generator that will scan all defined Component in Reflex and
  144. generate the approriate stub.
  145. """
  146. modules: list = []
  147. root: str = ""
  148. current_module: Any = {}
  149. default_typing_imports: set = DEFAULT_TYPING_IMPORTS
  150. def _generate_imports(self, variables, classes):
  151. variables_imports = {
  152. type(_var) for _, _var in variables if isinstance(_var, Component)
  153. }
  154. bases = {
  155. base
  156. for _, _class in classes
  157. for base in _class.__bases__
  158. if inspect.getmodule(base) != self.current_module
  159. } | variables_imports
  160. bases.add(Component)
  161. typing_imports = self.default_typing_imports | _get_typing_import(
  162. self.current_module
  163. )
  164. bases = sorted(bases, key=lambda base: base.__name__)
  165. return [
  166. f"from typing import {','.join(sorted(typing_imports))}",
  167. *[f"from {base.__module__} import {base.__name__}" for base in bases],
  168. "from reflex.vars import Var, BaseVar, ComputedVar",
  169. "from reflex.event import EventHandler, EventChain, EventSpec",
  170. ]
  171. def _generate_pyi_class(self, _class: type[Component]):
  172. create_spec = getfullargspec(_class.create)
  173. lines = [
  174. "",
  175. f"class {_class.__name__}({', '.join([base.__name__ for base in _class.__bases__])}):",
  176. ]
  177. definition = f" @overload\n @classmethod\n def create(cls, *children, "
  178. for kwarg in create_spec.kwonlyargs:
  179. if kwarg in create_spec.annotations:
  180. definition += f"{kwarg}: {_get_type_hint(create_spec.annotations[kwarg])} = None, "
  181. else:
  182. definition += f"{kwarg}, "
  183. for name, value in _class.__annotations__.items():
  184. if name in create_spec.kwonlyargs:
  185. continue
  186. definition += f"{name}: {_get_type_hint(value)} = None, "
  187. for trigger in sorted(_class().get_event_triggers().keys()):
  188. definition += f"{trigger}: Optional[Union[EventHandler, EventSpec, List, function, BaseVar]] = None, "
  189. definition = definition.rstrip(", ")
  190. definition += f", **props) -> '{_class.__name__}': # type: ignore\n"
  191. definition += self._generate_docstrings(_class, _class.__annotations__.keys())
  192. lines.append(definition)
  193. lines.append(" ...")
  194. return lines
  195. def _generate_docstrings(self, _class, _props):
  196. props_comments = {}
  197. comments = []
  198. for _i, line in enumerate(inspect.getsource(_class).splitlines()):
  199. reached_functions = re.search("def ", line)
  200. if reached_functions:
  201. # We've reached the functions, so stop.
  202. break
  203. # Get comments for prop
  204. if line.strip().startswith("#"):
  205. comments.append(line)
  206. continue
  207. # Check if this line has a prop.
  208. match = re.search("\\w+:", line)
  209. if match is None:
  210. # This line doesn't have a var, so continue.
  211. continue
  212. # Get the prop.
  213. prop = match.group(0).strip(":")
  214. if prop in _props:
  215. # This isn't a prop, so continue.
  216. props_comments[prop] = "\n".join(
  217. [comment.strip().strip("#") for comment in comments]
  218. )
  219. comments.clear()
  220. continue
  221. new_docstring = []
  222. for i, line in enumerate(_class.create.__doc__.splitlines()):
  223. if i == 0:
  224. new_docstring.append(" " * 8 + '"""' + line)
  225. else:
  226. new_docstring.append(line)
  227. if "*children" in line:
  228. for nline in [
  229. f"{line.split('*')[0]}{n}:{c}" for n, c in props_comments.items()
  230. ]:
  231. new_docstring.append(nline)
  232. new_docstring += ['"""']
  233. return "\n".join(new_docstring)
  234. def _generate_pyi_variable(self, _name, _var):
  235. return _get_var_definition(self.current_module, _name)
  236. def _generate_function(self, _name, _func):
  237. import textwrap
  238. # Don't generate indented functions.
  239. source = inspect.getsource(_func)
  240. if textwrap.dedent(source) != source:
  241. return []
  242. definition = "".join([line for line in source.split(":\n")[0].split("\n")])
  243. return [f"{definition}:", " ..."]
  244. def _write_pyi_file(self, variables, functions, classes):
  245. pyi_content = [
  246. f'"""Stub file for {self.current_module_path}.py"""',
  247. "# ------------------- DO NOT EDIT ----------------------",
  248. "# This file was generated by `scripts/pyi_generator.py`!",
  249. "# ------------------------------------------------------",
  250. "",
  251. ]
  252. pyi_content.extend(self._generate_imports(variables, classes))
  253. for _name, _var in variables:
  254. pyi_content.extend(self._generate_pyi_variable(_name, _var))
  255. for _fname, _func in functions:
  256. pyi_content.extend(self._generate_function(_fname, _func))
  257. for _, _class in classes:
  258. pyi_content.extend(self._generate_pyi_class(_class))
  259. pyi_filename = f"{self.current_module_path}.pyi"
  260. pyi_path = os.path.join(self.root, pyi_filename)
  261. with open(pyi_path, "w") as pyi_file:
  262. pyi_file.write("\n".join(pyi_content))
  263. black.format_file_in_place(
  264. src=Path(pyi_path),
  265. fast=True,
  266. mode=black.FileMode(),
  267. write_back=black.WriteBack.YES,
  268. )
  269. def _scan_file(self, file):
  270. self.current_module_path = os.path.splitext(file)[0]
  271. module_import = os.path.splitext(os.path.join(self.root, file))[0].replace(
  272. "/", "."
  273. )
  274. self.current_module = importlib.import_module(module_import)
  275. local_variables = [
  276. (name, obj)
  277. for name, obj in vars(self.current_module).items()
  278. if not name.startswith("_")
  279. and not inspect.isclass(obj)
  280. and not inspect.isfunction(obj)
  281. ]
  282. functions = [
  283. (name, obj)
  284. for name, obj in vars(self.current_module).items()
  285. if not name.startswith("__")
  286. and (
  287. not inspect.getmodule(obj)
  288. or inspect.getmodule(obj) == self.current_module
  289. )
  290. and inspect.isfunction(obj)
  291. ]
  292. class_names = [
  293. (name, obj)
  294. for name, obj in vars(self.current_module).items()
  295. if inspect.isclass(obj)
  296. and issubclass(obj, Component)
  297. and obj != Component
  298. and inspect.getmodule(obj) == self.current_module
  299. ]
  300. if not class_names:
  301. return
  302. print(f"Parsed {file}: Found {[n for n, _ in class_names]}")
  303. self._write_pyi_file(local_variables, functions, class_names)
  304. def _scan_folder(self, folder):
  305. for root, _, files in os.walk(folder):
  306. self.root = root
  307. for file in files:
  308. if file in EXCLUDED_FILES:
  309. continue
  310. if file.endswith(".py"):
  311. self._scan_file(file)
  312. def scan_all(self, targets):
  313. """Scan all targets for class inheriting Component and generate the .pyi files.
  314. Args:
  315. targets: the list of file/folders to scan.
  316. """
  317. for target in targets:
  318. if target.endswith(".py"):
  319. self.root, _, file = target.rpartition("/")
  320. self._scan_file(file)
  321. else:
  322. self._scan_folder(target)
  323. if __name__ == "__main__":
  324. targets = sys.argv[1:] if len(sys.argv) > 1 else ["reflex/components"]
  325. print(f"Running .pyi generator for {targets}")
  326. gen = PyiGenerator()
  327. gen.scan_all(targets)