1
0

pyi_generator.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938
  1. """The pyi generator module."""
  2. import ast
  3. import contextlib
  4. import importlib
  5. import inspect
  6. import logging
  7. import re
  8. import subprocess
  9. import sys
  10. import textwrap
  11. import typing
  12. from inspect import getfullargspec
  13. from multiprocessing import Pool, cpu_count
  14. from pathlib import Path
  15. from types import ModuleType, SimpleNamespace
  16. from typing import Any, Callable, Iterable, Type, get_args
  17. import black
  18. import black.mode
  19. from reflex.components.component import Component
  20. from reflex.utils import types as rx_types
  21. from reflex.vars import Var
  22. logger = logging.getLogger("pyi_generator")
  23. LAST_RUN_COMMIT_SHA_FILE = Path(".pyi_generator_last_run").resolve()
  24. INIT_FILE = Path("reflex/__init__.pyi").resolve()
  25. PWD = Path(".").resolve()
  26. GENERATOR_FILE = Path(__file__).resolve()
  27. GENERATOR_DIFF_FILE = Path(".pyi_generator_diff").resolve()
  28. EXCLUDED_FILES = [
  29. "__init__.py",
  30. "component.py",
  31. "bare.py",
  32. "foreach.py",
  33. "cond.py",
  34. "match.py",
  35. "multiselect.py",
  36. "literals.py",
  37. ]
  38. # These props exist on the base component, but should not be exposed in create methods.
  39. EXCLUDED_PROPS = [
  40. "alias",
  41. "children",
  42. "event_triggers",
  43. "library",
  44. "lib_dependencies",
  45. "tag",
  46. "is_default",
  47. "special_props",
  48. "_invalid_children",
  49. "_memoization_mode",
  50. "_rename_props",
  51. "_valid_children",
  52. "_valid_parents",
  53. ]
  54. DEFAULT_TYPING_IMPORTS = {
  55. "overload",
  56. "Any",
  57. "Dict",
  58. # "List",
  59. "Literal",
  60. "Optional",
  61. "Union",
  62. }
  63. def _walk_files(path):
  64. """Walk all files in a path.
  65. This can be replaced with Path.walk() in python3.12.
  66. Args:
  67. path: The path to walk.
  68. Yields:
  69. The next file in the path.
  70. """
  71. for p in Path(path).iterdir():
  72. if p.is_dir():
  73. yield from _walk_files(p)
  74. continue
  75. yield p.resolve()
  76. def _relative_to_pwd(path: Path) -> Path:
  77. """Get the relative path of a path to the current working directory.
  78. Args:
  79. path: The path to get the relative path for.
  80. Returns:
  81. The relative path.
  82. """
  83. if path.is_absolute():
  84. return path.relative_to(PWD)
  85. return path
  86. def _git_diff(args: list[str]) -> str:
  87. """Run a git diff command.
  88. Args:
  89. args: The args to pass to git diff.
  90. Returns:
  91. The output of the git diff command.
  92. """
  93. cmd = ["git", "diff", "--no-color", *args]
  94. return subprocess.run(cmd, capture_output=True, encoding="utf-8").stdout
  95. def _git_changed_files(args: list[str] | None = None) -> list[Path]:
  96. """Get the list of changed files for a git diff command.
  97. Args:
  98. args: The args to pass to git diff.
  99. Returns:
  100. The list of changed files.
  101. """
  102. if not args:
  103. args = []
  104. if "--name-only" not in args:
  105. args.insert(0, "--name-only")
  106. diff = _git_diff(args).splitlines()
  107. return [Path(file.strip()) for file in diff]
  108. def _get_changed_files() -> list[Path] | None:
  109. """Get the list of changed files since the last run of the generator.
  110. Returns:
  111. The list of changed files, or None if all files should be regenerated.
  112. """
  113. try:
  114. last_run_commit_sha = LAST_RUN_COMMIT_SHA_FILE.read_text().strip()
  115. except FileNotFoundError:
  116. logger.info(
  117. "pyi_generator.py last run could not be determined, regenerating all .pyi files"
  118. )
  119. return None
  120. changed_files = _git_changed_files([f"{last_run_commit_sha}..HEAD"])
  121. # get all unstaged changes
  122. changed_files.extend(_git_changed_files())
  123. if _relative_to_pwd(GENERATOR_FILE) not in changed_files:
  124. return changed_files
  125. logger.info("pyi_generator.py has changed, checking diff now")
  126. diff = "".join(_git_diff([GENERATOR_FILE.as_posix()]).splitlines()[2:])
  127. try:
  128. last_diff = GENERATOR_DIFF_FILE.read_text()
  129. if diff != last_diff:
  130. logger.info("pyi_generator.py has changed, regenerating all .pyi files")
  131. changed_files = None
  132. else:
  133. logger.info(
  134. "pyi_generator.py has not changed, only regenerating changed files"
  135. )
  136. except FileNotFoundError:
  137. logger.info(
  138. "pyi_generator.py diff could not be determined, regenerating all .pyi files"
  139. )
  140. changed_files = None
  141. GENERATOR_DIFF_FILE.write_text(diff)
  142. return changed_files
  143. def _get_type_hint(value, type_hint_globals, is_optional=True) -> str:
  144. """Resolve the type hint for value.
  145. Args:
  146. value: The type annotation as a str or actual types/aliases.
  147. type_hint_globals: The globals to use to resolving a type hint str.
  148. is_optional: Whether the type hint should be wrapped in Optional.
  149. Returns:
  150. The resolved type hint as a str.
  151. """
  152. res = ""
  153. args = get_args(value)
  154. if args:
  155. inner_container_type_args = (
  156. [repr(arg) for arg in args]
  157. if rx_types.is_literal(value)
  158. else [
  159. _get_type_hint(arg, type_hint_globals, is_optional=False)
  160. for arg in args
  161. if arg is not type(None)
  162. ]
  163. )
  164. res = f"{value.__name__}[{', '.join(inner_container_type_args)}]"
  165. if value.__name__ == "Var":
  166. # For Var types, Union with the inner args so they can be passed directly.
  167. types = [res] + [
  168. _get_type_hint(arg, type_hint_globals, is_optional=False)
  169. for arg in args
  170. if arg is not type(None)
  171. ]
  172. if len(types) > 1:
  173. res = ", ".join(types)
  174. res = f"Union[{res}]"
  175. elif isinstance(value, str):
  176. ev = eval(value, type_hint_globals)
  177. res = (
  178. _get_type_hint(ev, type_hint_globals, is_optional=False)
  179. if ev.__name__ == "Var"
  180. else value
  181. )
  182. else:
  183. res = value.__name__
  184. if is_optional and not res.startswith("Optional"):
  185. res = f"Optional[{res}]"
  186. return res
  187. def _generate_imports(typing_imports: Iterable[str]) -> list[ast.ImportFrom]:
  188. """Generate the import statements for the stub file.
  189. Args:
  190. typing_imports: The typing imports to include.
  191. Returns:
  192. The list of import statements.
  193. """
  194. return [
  195. ast.ImportFrom(
  196. module="typing",
  197. names=[ast.alias(name=imp) for imp in sorted(typing_imports)],
  198. ),
  199. *ast.parse( # type: ignore
  200. textwrap.dedent(
  201. """
  202. from reflex.vars import Var, BaseVar, ComputedVar
  203. from reflex.event import EventChain, EventHandler, EventSpec
  204. from reflex.style import Style"""
  205. )
  206. ).body,
  207. # *[
  208. # ast.ImportFrom(module=name, names=[ast.alias(name=val) for val in values])
  209. # for name, values in EXTRA_IMPORTS.items()
  210. # ],
  211. ]
  212. def _generate_docstrings(clzs: list[Type[Component]], props: list[str]) -> str:
  213. """Generate the docstrings for the create method.
  214. Args:
  215. clzs: The classes to generate docstrings for.
  216. props: The props to generate docstrings for.
  217. Returns:
  218. The docstring for the create method.
  219. """
  220. props_comments = {}
  221. comments = []
  222. for clz in clzs:
  223. for line in inspect.getsource(clz).splitlines():
  224. reached_functions = re.search("def ", line)
  225. if reached_functions:
  226. # We've reached the functions, so stop.
  227. break
  228. # Get comments for prop
  229. if line.strip().startswith("#"):
  230. comments.append(line)
  231. continue
  232. # Check if this line has a prop.
  233. match = re.search("\\w+:", line)
  234. if match is None:
  235. # This line doesn't have a var, so continue.
  236. continue
  237. # Get the prop.
  238. prop = match.group(0).strip(":")
  239. if prop in props:
  240. if not comments: # do not include undocumented props
  241. continue
  242. props_comments[prop] = [
  243. comment.strip().strip("#") for comment in comments
  244. ]
  245. comments.clear()
  246. clz = clzs[0]
  247. new_docstring = []
  248. for line in (clz.create.__doc__ or "").splitlines():
  249. if "**" in line:
  250. indent = line.split("**")[0]
  251. for nline in [
  252. f"{indent}{n}:{' '.join(c)}" for n, c in props_comments.items()
  253. ]:
  254. new_docstring.append(nline)
  255. new_docstring.append(line)
  256. return "\n".join(new_docstring)
  257. def _extract_func_kwargs_as_ast_nodes(
  258. func: Callable,
  259. type_hint_globals: dict[str, Any],
  260. ) -> list[tuple[ast.arg, ast.Constant | None]]:
  261. """Get the kwargs already defined on the function.
  262. Args:
  263. func: The function to extract kwargs from.
  264. type_hint_globals: The globals to use to resolving a type hint str.
  265. Returns:
  266. The list of kwargs as ast arg nodes.
  267. """
  268. spec = getfullargspec(func)
  269. kwargs = []
  270. for kwarg in spec.kwonlyargs:
  271. arg = ast.arg(arg=kwarg)
  272. if kwarg in spec.annotations:
  273. arg.annotation = ast.Name(
  274. id=_get_type_hint(spec.annotations[kwarg], type_hint_globals)
  275. )
  276. default = None
  277. if spec.kwonlydefaults is not None and kwarg in spec.kwonlydefaults:
  278. default = ast.Constant(value=spec.kwonlydefaults[kwarg])
  279. kwargs.append((arg, default))
  280. return kwargs
  281. def _extract_class_props_as_ast_nodes(
  282. func: Callable,
  283. clzs: list[Type],
  284. type_hint_globals: dict[str, Any],
  285. extract_real_default: bool = False,
  286. ) -> list[tuple[ast.arg, ast.Constant | None]]:
  287. """Get the props defined on the class and all parents.
  288. Args:
  289. func: The function that kwargs will be added to.
  290. clzs: The classes to extract props from.
  291. type_hint_globals: The globals to use to resolving a type hint str.
  292. extract_real_default: Whether to extract the real default value from the
  293. pydantic field definition.
  294. Returns:
  295. The list of props as ast arg nodes
  296. """
  297. spec = getfullargspec(func)
  298. all_props = []
  299. kwargs = []
  300. for target_class in clzs:
  301. # Import from the target class to ensure type hints are resolvable.
  302. exec(f"from {target_class.__module__} import *", type_hint_globals)
  303. for name, value in target_class.__annotations__.items():
  304. if (
  305. name in spec.kwonlyargs
  306. or name in EXCLUDED_PROPS
  307. or name in all_props
  308. or (isinstance(value, str) and "ClassVar" in value)
  309. ):
  310. continue
  311. all_props.append(name)
  312. default = None
  313. if extract_real_default:
  314. # TODO: This is not currently working since the default is not type compatible
  315. # with the annotation in some cases.
  316. with contextlib.suppress(AttributeError, KeyError):
  317. # Try to get default from pydantic field definition.
  318. default = target_class.model_fields[name].default
  319. if isinstance(default, Var):
  320. default = default._decode() # type: ignore
  321. kwargs.append(
  322. (
  323. ast.arg(
  324. arg=name,
  325. annotation=ast.Name(
  326. id=_get_type_hint(value, type_hint_globals)
  327. ),
  328. ),
  329. ast.Constant(value=default),
  330. )
  331. )
  332. return kwargs
  333. def _get_parent_imports(func):
  334. _imports = {"reflex.vars": ["Var"]}
  335. for type_hint in inspect.get_annotations(func).values():
  336. try:
  337. match = re.match(r"\w+\[([\w\d]+)\]", type_hint)
  338. except TypeError:
  339. continue
  340. if match:
  341. type_hint = match.group(1)
  342. if type_hint in importlib.import_module(func.__module__).__dir__():
  343. _imports.setdefault(func.__module__, []).append(type_hint)
  344. return _imports
  345. def _generate_component_create_functiondef(
  346. node: ast.FunctionDef | None,
  347. clz: type[Component] | type[SimpleNamespace],
  348. type_hint_globals: dict[str, Any],
  349. ) -> ast.FunctionDef:
  350. """Generate the create function definition for a Component.
  351. Args:
  352. node: The existing create functiondef node from the ast
  353. clz: The Component class to generate the create functiondef for.
  354. type_hint_globals: The globals to use to resolving a type hint str.
  355. Returns:
  356. The create functiondef node for the ast.
  357. Raises:
  358. TypeError: If clz is not a subclass of Component.
  359. """
  360. if not issubclass(clz, Component):
  361. raise TypeError(f"clz must be a subclass of Component, not {clz!r}")
  362. # add the imports needed by get_type_hint later
  363. type_hint_globals.update(
  364. {name: getattr(typing, name) for name in DEFAULT_TYPING_IMPORTS}
  365. )
  366. if clz.__module__ != clz.create.__module__:
  367. _imports = _get_parent_imports(clz.create)
  368. for name, values in _imports.items():
  369. exec(f"from {name} import {','.join(values)}", type_hint_globals)
  370. kwargs = _extract_func_kwargs_as_ast_nodes(clz.create, type_hint_globals)
  371. # kwargs associated with props defined in the class and its parents
  372. all_classes = [c for c in clz.__mro__ if issubclass(c, Component)]
  373. prop_kwargs = _extract_class_props_as_ast_nodes(
  374. clz.create, all_classes, type_hint_globals
  375. )
  376. all_props = [arg[0].arg for arg in prop_kwargs]
  377. kwargs.extend(prop_kwargs)
  378. # event handler kwargs
  379. kwargs.extend(
  380. (
  381. ast.arg(
  382. arg=trigger,
  383. annotation=ast.Name(
  384. id="Optional[Union[EventHandler, EventSpec, list, function, BaseVar]]"
  385. ),
  386. ),
  387. ast.Constant(value=None),
  388. )
  389. for trigger in sorted(clz().get_event_triggers().keys())
  390. )
  391. logger.debug(f"Generated {clz.__name__}.create method with {len(kwargs)} kwargs")
  392. create_args = ast.arguments(
  393. args=[ast.arg(arg="cls")],
  394. posonlyargs=[],
  395. vararg=ast.arg(arg="children"),
  396. kwonlyargs=[arg[0] for arg in kwargs],
  397. kw_defaults=[arg[1] for arg in kwargs],
  398. kwarg=ast.arg(arg="props"),
  399. defaults=[],
  400. )
  401. definition = ast.FunctionDef(
  402. name="create",
  403. args=create_args,
  404. body=[
  405. ast.Expr(
  406. value=ast.Constant(value=_generate_docstrings(all_classes, all_props))
  407. ),
  408. ast.Expr(
  409. value=ast.Ellipsis(),
  410. ),
  411. ],
  412. decorator_list=[
  413. ast.Name(id="overload"),
  414. *(
  415. node.decorator_list
  416. if node is not None
  417. else [ast.Name(id="classmethod")]
  418. ),
  419. ],
  420. lineno=node.lineno if node is not None else None,
  421. returns=ast.Constant(value=clz.__name__),
  422. )
  423. return definition
  424. def _generate_namespace_call_functiondef(
  425. clz_name: str,
  426. classes: dict[str, type[Component] | type[SimpleNamespace]],
  427. type_hint_globals: dict[str, Any],
  428. ) -> ast.FunctionDef | None:
  429. """Generate the __call__ function definition for a SimpleNamespace.
  430. Args:
  431. clz_name: The name of the SimpleNamespace class to generate the __call__ functiondef for.
  432. classes: Map name to actual class definition.
  433. type_hint_globals: The globals to use to resolving a type hint str.
  434. Returns:
  435. The create functiondef node for the ast.
  436. """
  437. # add the imports needed by get_type_hint later
  438. type_hint_globals.update(
  439. {name: getattr(typing, name) for name in DEFAULT_TYPING_IMPORTS}
  440. )
  441. clz = classes[clz_name]
  442. # Determine which class is wrapped by the namespace __call__ method
  443. component_clz = clz.__call__.__self__
  444. # Only generate for create functions
  445. if clz.__call__.__func__.__name__ != "create":
  446. return None
  447. definition = _generate_component_create_functiondef(
  448. node=None,
  449. clz=component_clz, # type: ignore
  450. type_hint_globals=type_hint_globals,
  451. )
  452. definition.name = "__call__"
  453. # Turn the definition into a staticmethod
  454. del definition.args.args[0] # remove `cls` arg
  455. definition.decorator_list = [ast.Name(id="staticmethod")]
  456. return definition
  457. class StubGenerator(ast.NodeTransformer):
  458. """A node transformer that will generate the stubs for a given module."""
  459. def __init__(
  460. self, module: ModuleType, classes: dict[str, Type[Component | SimpleNamespace]]
  461. ):
  462. """Initialize the stub generator.
  463. Args:
  464. module: The actual module object module to generate stubs for.
  465. classes: The actual Component class objects to generate stubs for.
  466. """
  467. super().__init__()
  468. # Dict mapping class name to actual class object.
  469. self.classes = classes
  470. # Track the last class node that was visited.
  471. self.current_class = None
  472. # These imports will be included in the AST of stub files.
  473. self.typing_imports = DEFAULT_TYPING_IMPORTS
  474. # Whether those typing imports have been inserted yet.
  475. self.inserted_imports = False
  476. # Collected import statements from the module.
  477. self.import_statements: list[str] = []
  478. # This dict is used when evaluating type hints.
  479. self.type_hint_globals = module.__dict__.copy()
  480. @staticmethod
  481. def _remove_docstring(
  482. node: ast.Module | ast.ClassDef | ast.FunctionDef,
  483. ) -> ast.Module | ast.ClassDef | ast.FunctionDef:
  484. """Removes any docstring in place.
  485. Args:
  486. node: The node to remove the docstring from.
  487. Returns:
  488. The modified node.
  489. """
  490. if (
  491. node.body
  492. and isinstance(node.body[0], ast.Expr)
  493. and isinstance(node.body[0].value, ast.Constant)
  494. ):
  495. node.body.pop(0)
  496. return node
  497. def _current_class_is_component(self) -> bool:
  498. """Check if the current class is a Component.
  499. Returns:
  500. Whether the current class is a Component.
  501. """
  502. return (
  503. self.current_class is not None
  504. and self.current_class in self.classes
  505. and issubclass(self.classes[self.current_class], Component)
  506. )
  507. def visit_Module(self, node: ast.Module) -> ast.Module:
  508. """Visit a Module node and remove docstring from body.
  509. Args:
  510. node: The Module node to visit.
  511. Returns:
  512. The modified Module node.
  513. """
  514. self.generic_visit(node)
  515. return self._remove_docstring(node) # type: ignore
  516. def visit_Import(
  517. self, node: ast.Import | ast.ImportFrom
  518. ) -> ast.Import | ast.ImportFrom | list[ast.Import | ast.ImportFrom]:
  519. """Collect import statements from the module.
  520. If this is the first import statement, insert the typing imports before it.
  521. Args:
  522. node: The import node to visit.
  523. Returns:
  524. The modified import node(s).
  525. """
  526. self.import_statements.append(ast.unparse(node))
  527. if not self.inserted_imports:
  528. self.inserted_imports = True
  529. return _generate_imports(self.typing_imports) + [node]
  530. return node
  531. def visit_ImportFrom(
  532. self, node: ast.ImportFrom
  533. ) -> ast.Import | ast.ImportFrom | list[ast.Import | ast.ImportFrom] | None:
  534. """Visit an ImportFrom node.
  535. Remove any `from __future__ import *` statements, and hand off to visit_Import.
  536. Args:
  537. node: The ImportFrom node to visit.
  538. Returns:
  539. The modified ImportFrom node.
  540. """
  541. if node.module == "__future__":
  542. return None # ignore __future__ imports
  543. return self.visit_Import(node)
  544. def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:
  545. """Visit a ClassDef node.
  546. Remove all assignments in the class body, and add a create functiondef
  547. if one does not exist.
  548. Args:
  549. node: The ClassDef node to visit.
  550. Returns:
  551. The modified ClassDef node.
  552. """
  553. exec("\n".join(self.import_statements), self.type_hint_globals)
  554. self.current_class = node.name
  555. self._remove_docstring(node)
  556. # Define `__call__` as a real function so the docstring appears in the stub.
  557. call_definition = None
  558. for child in node.body[:]:
  559. found_call = False
  560. if isinstance(child, ast.Assign):
  561. for target in child.targets[:]:
  562. if isinstance(target, ast.Name) and target.id == "__call__":
  563. child.targets.remove(target)
  564. found_call = True
  565. if not found_call:
  566. continue
  567. if not child.targets[:]:
  568. node.body.remove(child)
  569. call_definition = _generate_namespace_call_functiondef(
  570. self.current_class,
  571. self.classes,
  572. type_hint_globals=self.type_hint_globals,
  573. )
  574. break
  575. self.generic_visit(node) # Visit child nodes.
  576. if (
  577. not any(
  578. isinstance(child, ast.FunctionDef) and child.name == "create"
  579. for child in node.body
  580. )
  581. and self._current_class_is_component()
  582. ):
  583. # Add a new .create FunctionDef since one does not exist.
  584. node.body.append(
  585. _generate_component_create_functiondef(
  586. node=None,
  587. clz=self.classes[self.current_class],
  588. type_hint_globals=self.type_hint_globals,
  589. )
  590. )
  591. if call_definition is not None:
  592. node.body.append(call_definition)
  593. if not node.body:
  594. # We should never return an empty body.
  595. node.body.append(ast.Expr(value=ast.Ellipsis()))
  596. self.current_class = None
  597. return node
  598. def visit_FunctionDef(self, node: ast.FunctionDef) -> Any:
  599. """Visit a FunctionDef node.
  600. Special handling for `.create` functions to add type hints for all props
  601. defined on the component class.
  602. Remove all private functions and blank out the function body of the
  603. remaining public functions.
  604. Args:
  605. node: The FunctionDef node to visit.
  606. Returns:
  607. The modified FunctionDef node (or None).
  608. """
  609. if node.name == "create" and self.current_class in self.classes:
  610. node = _generate_component_create_functiondef(
  611. node, self.classes[self.current_class], self.type_hint_globals
  612. )
  613. else:
  614. if node.name.startswith("_") and node.name != "__call__":
  615. return None # remove private methods
  616. if node.body[-1] != ast.Expr(value=ast.Ellipsis()):
  617. # Blank out the function body for public functions.
  618. node.body = [ast.Expr(value=ast.Ellipsis())]
  619. return node
  620. def visit_Assign(self, node: ast.Assign) -> ast.Assign | None:
  621. """Remove non-annotated assignment statements.
  622. Args:
  623. node: The Assign node to visit.
  624. Returns:
  625. The modified Assign node (or None).
  626. """
  627. # Special case for assignments to `typing.Any` as fallback.
  628. if (
  629. node.value is not None
  630. and isinstance(node.value, ast.Name)
  631. and node.value.id == "Any"
  632. ):
  633. return node
  634. if self._current_class_is_component():
  635. # Remove annotated assignments in Component classes (props)
  636. return None
  637. return node
  638. def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AnnAssign | None:
  639. """Visit an AnnAssign node (Annotated assignment).
  640. Remove private target and remove the assignment value in the stub.
  641. Args:
  642. node: The AnnAssign node to visit.
  643. Returns:
  644. The modified AnnAssign node (or None).
  645. """
  646. # skip ClassVars
  647. if (
  648. isinstance(node.annotation, ast.Subscript)
  649. and isinstance(node.annotation.value, ast.Name)
  650. and node.annotation.value.id == "ClassVar"
  651. ):
  652. return node
  653. if isinstance(node.target, ast.Name) and node.target.id.startswith("_"):
  654. return None
  655. if self.current_class in self.classes:
  656. # Remove annotated assignments in Component classes (props)
  657. return None
  658. # Blank out assignments in type stubs.
  659. node.value = None
  660. return node
  661. class PyiGenerator:
  662. """A .pyi file generator that will scan all defined Component in Reflex and
  663. generate the approriate stub.
  664. """
  665. modules: list = []
  666. root: str = ""
  667. current_module: Any = {}
  668. def _write_pyi_file(self, module_path: Path, source: str):
  669. relpath = str(_relative_to_pwd(module_path)).replace("\\", "/")
  670. pyi_content = [
  671. f'"""Stub file for {relpath}"""',
  672. "# ------------------- DO NOT EDIT ----------------------",
  673. "# This file was generated by `scripts/pyi_generator.py`!",
  674. "# ------------------------------------------------------",
  675. "",
  676. ]
  677. for formatted_line in black.format_file_contents(
  678. src_contents=source,
  679. fast=True,
  680. mode=black.mode.Mode(is_pyi=True),
  681. ).splitlines():
  682. # Bit of a hack here, since the AST cannot represent comments.
  683. if "def create(" in formatted_line:
  684. pyi_content.append(formatted_line + " # type: ignore")
  685. elif "Figure" in formatted_line:
  686. pyi_content.append(formatted_line + " # type: ignore")
  687. else:
  688. pyi_content.append(formatted_line)
  689. pyi_content.append("") # add empty line at the end for formatting
  690. pyi_path = module_path.with_suffix(".pyi")
  691. pyi_path.write_text("\n".join(pyi_content))
  692. logger.info(f"Wrote {relpath}")
  693. def _scan_file(self, module_path: Path):
  694. module_import = (
  695. _relative_to_pwd(module_path)
  696. .with_suffix("")
  697. .as_posix()
  698. .replace("/", ".")
  699. .replace("\\", ".")
  700. )
  701. module = importlib.import_module(module_import)
  702. logger.debug(f"Read {module_path}")
  703. class_names = {
  704. name: obj
  705. for name, obj in vars(module).items()
  706. if inspect.isclass(obj)
  707. and (issubclass(obj, Component) or issubclass(obj, SimpleNamespace))
  708. and obj != Component
  709. and inspect.getmodule(obj) == module
  710. }
  711. if not class_names:
  712. return
  713. new_tree = StubGenerator(module, class_names).visit(
  714. ast.parse(inspect.getsource(module))
  715. )
  716. self._write_pyi_file(module_path, ast.unparse(new_tree))
  717. def _scan_files_multiprocess(self, files: list[Path]):
  718. with Pool(processes=cpu_count()) as pool:
  719. pool.map(self._scan_file, files)
  720. def _scan_files(self, files: list[Path]):
  721. for file in files:
  722. self._scan_file(file)
  723. def scan_all(self, targets, changed_files: list[Path] | None = None):
  724. """Scan all targets for class inheriting Component and generate the .pyi files.
  725. Args:
  726. targets: the list of file/folders to scan.
  727. changed_files (optional): the list of changed files since the last run.
  728. """
  729. file_targets = []
  730. for target in targets:
  731. target_path = Path(target)
  732. if target_path.is_file() and target_path.suffix == ".py":
  733. file_targets.append(target_path)
  734. continue
  735. if not target_path.is_dir():
  736. continue
  737. for file_path in _walk_files(target_path):
  738. relative = _relative_to_pwd(file_path)
  739. if relative.name in EXCLUDED_FILES or file_path.suffix != ".py":
  740. continue
  741. if (
  742. changed_files is not None
  743. and _relative_to_pwd(file_path) not in changed_files
  744. ):
  745. continue
  746. file_targets.append(file_path)
  747. # check if pyi changed but not the source
  748. if changed_files is not None:
  749. for changed_file in changed_files:
  750. if changed_file.suffix != ".pyi":
  751. continue
  752. py_file_path = changed_file.with_suffix(".py")
  753. if not py_file_path.exists() and changed_file.exists():
  754. changed_file.unlink()
  755. if py_file_path in file_targets:
  756. continue
  757. subprocess.run(["git", "checkout", changed_file])
  758. if cpu_count() == 1 or len(file_targets) < 5:
  759. self._scan_files(file_targets)
  760. else:
  761. self._scan_files_multiprocess(file_targets)
  762. def generate_init():
  763. """Generate a pyi file for the main __init__.py."""
  764. from reflex import _MAPPING # type: ignore
  765. imports = [
  766. f"from {path if mod != path.rsplit('.')[-1] or mod == 'page' else '.'.join(path.rsplit('.')[:-1])} import {mod} as {mod}"
  767. for mod, path in _MAPPING.items()
  768. ]
  769. imports.append("")
  770. INIT_FILE.write_text("\n".join(imports))
  771. if __name__ == "__main__":
  772. logging.basicConfig(level=logging.DEBUG)
  773. logging.getLogger("blib2to3.pgen2.driver").setLevel(logging.INFO)
  774. targets = (
  775. [arg for arg in sys.argv[1:] if not arg.startswith("tests")]
  776. if len(sys.argv) > 1
  777. else ["reflex/components"]
  778. )
  779. logger.info(f"Running .pyi generator for {targets}")
  780. changed_files = _get_changed_files()
  781. if changed_files is None:
  782. logger.info("Changed files could not be detected, regenerating all .pyi files")
  783. else:
  784. logger.info(f"Detected changed files: {changed_files}")
  785. gen = PyiGenerator()
  786. gen.scan_all(targets, changed_files)
  787. generate_init()
  788. current_commit_sha = subprocess.run(
  789. ["git", "rev-parse", "HEAD"], capture_output=True, encoding="utf-8"
  790. ).stdout.strip()
  791. LAST_RUN_COMMIT_SHA_FILE.write_text(current_commit_sha)