pyi_generator.py 32 KB

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