pyi_generator.py 32 KB

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