pyi_generator.py 30 KB

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