pyi_generator.py 33 KB

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