pyi_generator.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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, Optional, Union, get_args # NOQA
  10. import black
  11. from reflex.components.component import Component
  12. from reflex.vars import Var
  13. ruff_dont_remove = [Var, Optional, Dict, List]
  14. EXCLUDED_FILES = [
  15. "__init__.py",
  16. "component.py",
  17. "bare.py",
  18. "foreach.py",
  19. "cond.py",
  20. "multiselect.py",
  21. ]
  22. DEFAULT_TYPING_IMPORTS = {"overload", "Optional", "Union"}
  23. def _get_type_hint(value, top_level=True, no_union=False):
  24. res = ""
  25. args = get_args(value)
  26. if args:
  27. res = f"{value.__name__}[{', '.join([_get_type_hint(arg, top_level=False) for arg in args if arg is not type(None)])}]"
  28. if value.__name__ == "Var":
  29. types = [res] + [
  30. _get_type_hint(arg, top_level=False)
  31. for arg in args
  32. if arg is not type(None)
  33. ]
  34. if len(types) > 1 and not no_union:
  35. res = ", ".join(types)
  36. res = f"Union[{res}]"
  37. elif isinstance(value, str):
  38. ev = eval(value)
  39. res = _get_type_hint(ev, top_level=False) if ev.__name__ == "Var" else value
  40. else:
  41. res = value.__name__
  42. if top_level and not res.startswith("Optional"):
  43. res = f"Optional[{res}]"
  44. return res
  45. def _get_typing_import(_module):
  46. src = [
  47. line
  48. for line in inspect.getsource(_module).split("\n")
  49. if line.startswith("from typing")
  50. ]
  51. if len(src):
  52. return set(src[0].rpartition("from typing import ")[-1].split(", "))
  53. return set()
  54. def _get_var_definition(_module, _var_name):
  55. return [
  56. line.split(" = ")[0]
  57. for line in inspect.getsource(_module).splitlines()
  58. if line.startswith(_var_name)
  59. ]
  60. class PyiGenerator:
  61. """A .pyi file generator that will scan all defined Component in Reflex and
  62. generate the approriate stub.
  63. """
  64. modules: list = []
  65. root: str = ""
  66. current_module: Any = {}
  67. default_typing_imports: set = DEFAULT_TYPING_IMPORTS
  68. def _generate_imports(self, variables, classes):
  69. variables_imports = {
  70. type(_var) for _, _var in variables if isinstance(_var, Component)
  71. }
  72. bases = {
  73. base
  74. for _, _class in classes
  75. for base in _class.__bases__
  76. if inspect.getmodule(base) != self.current_module
  77. } | variables_imports
  78. bases.add(Component)
  79. typing_imports = self.default_typing_imports | _get_typing_import(
  80. self.current_module
  81. )
  82. bases = sorted(bases, key=lambda base: base.__name__)
  83. return [
  84. f"from typing import {','.join(sorted(typing_imports))}",
  85. *[f"from {base.__module__} import {base.__name__}" for base in bases],
  86. "from reflex.vars import Var, BaseVar, ComputedVar",
  87. "from reflex.event import EventHandler, EventChain, EventSpec",
  88. ]
  89. def _generate_pyi_class(self, _class: type[Component]):
  90. create_spec = getfullargspec(_class.create)
  91. lines = [
  92. "",
  93. f"class {_class.__name__}({', '.join([base.__name__ for base in _class.__bases__])}):",
  94. ]
  95. definition = f" @overload\n @classmethod\n def create(cls, *children, "
  96. for kwarg in create_spec.kwonlyargs:
  97. if kwarg in create_spec.annotations:
  98. definition += f"{kwarg}: {_get_type_hint(create_spec.annotations[kwarg])} = None, "
  99. else:
  100. definition += f"{kwarg}, "
  101. for name, value in _class.__annotations__.items():
  102. if name in create_spec.kwonlyargs:
  103. continue
  104. definition += f"{name}: {_get_type_hint(value)} = None, "
  105. for trigger in sorted(_class().get_event_triggers().keys()):
  106. definition += f"{trigger}: Optional[Union[EventHandler, EventSpec, List, function, BaseVar]] = None, "
  107. definition = definition.rstrip(", ")
  108. definition += f", **props) -> '{_class.__name__}': # type: ignore\n"
  109. definition += self._generate_docstrings(_class, _class.__annotations__.keys())
  110. lines.append(definition)
  111. lines.append(" ...")
  112. return lines
  113. def _generate_docstrings(self, _class, _props):
  114. props_comments = {}
  115. comments = []
  116. for _i, line in enumerate(inspect.getsource(_class).splitlines()):
  117. reached_functions = re.search("def ", line)
  118. if reached_functions:
  119. # We've reached the functions, so stop.
  120. break
  121. # Get comments for prop
  122. if line.strip().startswith("#"):
  123. comments.append(line)
  124. continue
  125. # Check if this line has a prop.
  126. match = re.search("\\w+:", line)
  127. if match is None:
  128. # This line doesn't have a var, so continue.
  129. continue
  130. # Get the prop.
  131. prop = match.group(0).strip(":")
  132. if prop in _props:
  133. # This isn't a prop, so continue.
  134. props_comments[prop] = "\n".join(
  135. [comment.strip().strip("#") for comment in comments]
  136. )
  137. comments.clear()
  138. continue
  139. new_docstring = []
  140. for i, line in enumerate(_class.create.__doc__.splitlines()):
  141. if i == 0:
  142. new_docstring.append(" " * 8 + '"""' + line)
  143. else:
  144. new_docstring.append(line)
  145. if "*children" in line:
  146. for nline in [
  147. f"{line.split('*')[0]}{n}:{c}" for n, c in props_comments.items()
  148. ]:
  149. new_docstring.append(nline)
  150. new_docstring += ['"""']
  151. return "\n".join(new_docstring)
  152. def _generate_pyi_variable(self, _name, _var):
  153. return _get_var_definition(self.current_module, _name)
  154. def _generate_function(self, _name, _func):
  155. import textwrap
  156. # Don't generate indented functions.
  157. source = inspect.getsource(_func)
  158. if textwrap.dedent(source) != source:
  159. return []
  160. definition = "".join([line for line in source.split(":\n")[0].split("\n")])
  161. return [f"{definition}:", " ..."]
  162. def _write_pyi_file(self, variables, functions, classes):
  163. pyi_content = [
  164. f'"""Stub file for {self.current_module_path}.py"""',
  165. "# ------------------- DO NOT EDIT ----------------------",
  166. "# This file was generated by `scripts/pyi_generator.py`!",
  167. "# ------------------------------------------------------",
  168. "",
  169. ]
  170. pyi_content.extend(self._generate_imports(variables, classes))
  171. for _name, _var in variables:
  172. pyi_content.extend(self._generate_pyi_variable(_name, _var))
  173. for _fname, _func in functions:
  174. pyi_content.extend(self._generate_function(_fname, _func))
  175. for _, _class in classes:
  176. pyi_content.extend(self._generate_pyi_class(_class))
  177. pyi_filename = f"{self.current_module_path}.pyi"
  178. pyi_path = os.path.join(self.root, pyi_filename)
  179. with open(pyi_path, "w") as pyi_file:
  180. pyi_file.write("\n".join(pyi_content))
  181. black.format_file_in_place(
  182. src=Path(pyi_path),
  183. fast=True,
  184. mode=black.FileMode(),
  185. write_back=black.WriteBack.YES,
  186. )
  187. def _scan_file(self, file):
  188. self.current_module_path = os.path.splitext(file)[0]
  189. module_import = os.path.splitext(os.path.join(self.root, file))[0].replace(
  190. "/", "."
  191. )
  192. self.current_module = importlib.import_module(module_import)
  193. local_variables = [
  194. (name, obj)
  195. for name, obj in vars(self.current_module).items()
  196. if not name.startswith("_")
  197. and not inspect.isclass(obj)
  198. and not inspect.isfunction(obj)
  199. ]
  200. functions = [
  201. (name, obj)
  202. for name, obj in vars(self.current_module).items()
  203. if not name.startswith("__")
  204. and (
  205. not inspect.getmodule(obj)
  206. or inspect.getmodule(obj) == self.current_module
  207. )
  208. and inspect.isfunction(obj)
  209. ]
  210. class_names = [
  211. (name, obj)
  212. for name, obj in vars(self.current_module).items()
  213. if inspect.isclass(obj)
  214. and issubclass(obj, Component)
  215. and obj != Component
  216. and inspect.getmodule(obj) == self.current_module
  217. ]
  218. if not class_names:
  219. return
  220. print(f"Parsed {file}: Found {[n for n,_ in class_names]}")
  221. self._write_pyi_file(local_variables, functions, class_names)
  222. def _scan_folder(self, folder):
  223. for root, _, files in os.walk(folder):
  224. self.root = root
  225. for file in files:
  226. if file in EXCLUDED_FILES:
  227. continue
  228. if file.endswith(".py"):
  229. self._scan_file(file)
  230. def scan_all(self, targets):
  231. """Scan all targets for class inheriting Component and generate the .pyi files.
  232. Args:
  233. targets: the list of file/folders to scan.
  234. """
  235. for target in targets:
  236. if target.endswith(".py"):
  237. self.root, _, file = target.rpartition("/")
  238. self._scan_file(file)
  239. else:
  240. self._scan_folder(target)
  241. if __name__ == "__main__":
  242. targets = sys.argv[1:] if len(sys.argv) > 1 else ["reflex/components"]
  243. print(f"Running .pyi generator for {targets}")
  244. gen = PyiGenerator()
  245. gen.scan_all(targets)