pyi_generator.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210
  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, Sequence, Type, get_args, get_origin
  18. from reflex.components.component import Component
  19. from reflex.utils import types as rx_types
  20. from reflex.vars.base import Var
  21. logger = logging.getLogger("pyi_generator")
  22. PWD = Path.cwd()
  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.components.core.breakpoints": ["Breakpoints"],
  64. "reflex.event": [
  65. "EventChain",
  66. "EventHandler",
  67. "EventSpec",
  68. "EventType",
  69. "BASE_STATE",
  70. "KeyInputInfo",
  71. ],
  72. "reflex.style": ["Style"],
  73. "reflex.vars.base": ["Var"],
  74. }
  75. def _walk_files(path: str | Path):
  76. """Walk all files in a path.
  77. This can be replaced with Path.walk() in python3.12.
  78. Args:
  79. path: The path to walk.
  80. Yields:
  81. The next file in the path.
  82. """
  83. for p in Path(path).iterdir():
  84. if p.is_dir():
  85. yield from _walk_files(p)
  86. continue
  87. yield p.resolve()
  88. def _relative_to_pwd(path: Path) -> Path:
  89. """Get the relative path of a path to the current working directory.
  90. Args:
  91. path: The path to get the relative path for.
  92. Returns:
  93. The relative path.
  94. """
  95. if path.is_absolute():
  96. return path.relative_to(PWD)
  97. return path
  98. def _get_type_hint(
  99. value: Any, type_hint_globals: dict, is_optional: bool = True
  100. ) -> str:
  101. """Resolve the type hint for value.
  102. Args:
  103. value: The type annotation as a str or actual types/aliases.
  104. type_hint_globals: The globals to use to resolving a type hint str.
  105. is_optional: Whether the type hint should be wrapped in Optional.
  106. Returns:
  107. The resolved type hint as a str.
  108. Raises:
  109. TypeError: If the value name is not visible in the type hint globals.
  110. """
  111. res = ""
  112. args = get_args(value)
  113. if value is type(None):
  114. return "None"
  115. if rx_types.is_union(value):
  116. if type(None) in value.__args__:
  117. res_args = [
  118. _get_type_hint(arg, type_hint_globals, rx_types.is_optional(arg))
  119. for arg in value.__args__
  120. if arg is not type(None)
  121. ]
  122. res_args.sort()
  123. if len(res_args) == 1:
  124. return f"Optional[{res_args[0]}]"
  125. else:
  126. res = f"Union[{', '.join(res_args)}]"
  127. return f"Optional[{res}]"
  128. res_args = [
  129. _get_type_hint(arg, type_hint_globals, rx_types.is_optional(arg))
  130. for arg in value.__args__
  131. ]
  132. res_args.sort()
  133. return f"Union[{', '.join(res_args)}]"
  134. if args:
  135. inner_container_type_args = (
  136. sorted((repr(arg) for arg in args))
  137. if rx_types.is_literal(value)
  138. else [
  139. _get_type_hint(arg, type_hint_globals, is_optional=False)
  140. for arg in args
  141. if arg is not type(None)
  142. ]
  143. )
  144. if (
  145. value.__module__ not in ["builtins", "__builtins__"]
  146. and value.__name__ not in type_hint_globals
  147. ):
  148. raise TypeError(
  149. f"{value.__module__ + '.' + value.__name__} is not a default import, "
  150. "add it to DEFAULT_IMPORTS in pyi_generator.py"
  151. )
  152. res = f"{value.__name__}[{', '.join(inner_container_type_args)}]"
  153. if value.__name__ == "Var":
  154. args = list(
  155. chain.from_iterable(
  156. [get_args(arg) if rx_types.is_union(arg) else [arg] for arg in args]
  157. )
  158. )
  159. # For Var types, Union with the inner args so they can be passed directly.
  160. types = [res] + [
  161. _get_type_hint(arg, type_hint_globals, is_optional=False)
  162. for arg in args
  163. if arg is not type(None)
  164. ]
  165. if len(types) > 1:
  166. res = ", ".join(sorted(types))
  167. res = f"Union[{res}]"
  168. elif isinstance(value, str):
  169. ev = eval(value, type_hint_globals)
  170. if rx_types.is_optional(ev):
  171. return _get_type_hint(ev, type_hint_globals, is_optional=False)
  172. if rx_types.is_union(ev):
  173. res = [
  174. _get_type_hint(arg, type_hint_globals, rx_types.is_optional(arg))
  175. for arg in ev.__args__
  176. ]
  177. return f"Union[{', '.join(res)}]"
  178. res = (
  179. _get_type_hint(ev, type_hint_globals, is_optional=False)
  180. if ev.__name__ == "Var"
  181. else value
  182. )
  183. else:
  184. res = value.__name__
  185. if is_optional and not res.startswith("Optional"):
  186. res = f"Optional[{res}]"
  187. return res
  188. def _generate_imports(
  189. typing_imports: Iterable[str],
  190. ) -> list[ast.ImportFrom | ast.Import]:
  191. """Generate the import statements for the stub file.
  192. Args:
  193. typing_imports: The typing imports to include.
  194. Returns:
  195. The list of import statements.
  196. """
  197. return [
  198. *[
  199. ast.ImportFrom(module=name, names=[ast.alias(name=val) for val in values]) # pyright: ignore [reportCallIssue]
  200. for name, values in DEFAULT_IMPORTS.items()
  201. ],
  202. ast.Import([ast.alias("reflex")]),
  203. ]
  204. def _generate_docstrings(clzs: list[Type[Component]], props: list[str]) -> str:
  205. """Generate the docstrings for the create method.
  206. Args:
  207. clzs: The classes to generate docstrings for.
  208. props: The props to generate docstrings for.
  209. Returns:
  210. The docstring for the create method.
  211. """
  212. props_comments = {}
  213. comments = []
  214. for clz in clzs:
  215. for line in inspect.getsource(clz).splitlines():
  216. reached_functions = re.search("def ", line)
  217. if reached_functions:
  218. # We've reached the functions, so stop.
  219. break
  220. if line == "":
  221. # We hit a blank line, so clear comments to avoid commented out prop appearing in next prop docs.
  222. comments.clear()
  223. continue
  224. # Get comments for prop
  225. if line.strip().startswith("#"):
  226. # Remove noqa from the comments.
  227. line = line.partition(" # noqa")[0]
  228. comments.append(line)
  229. continue
  230. # Check if this line has a prop.
  231. match = re.search("\\w+:", line)
  232. if match is None:
  233. # This line doesn't have a var, so continue.
  234. continue
  235. # Get the prop.
  236. prop = match.group(0).strip(":")
  237. if prop in props:
  238. if not comments: # do not include undocumented props
  239. continue
  240. props_comments[prop] = [
  241. comment.strip().strip("#") for comment in comments
  242. ]
  243. comments.clear()
  244. clz = clzs[0]
  245. new_docstring = []
  246. for line in (clz.create.__doc__ or "").splitlines():
  247. if "**" in line:
  248. indent = line.split("**")[0]
  249. new_docstring.extend(
  250. [f"{indent}{n}:{' '.join(c)}" for n, c in props_comments.items()]
  251. )
  252. new_docstring.append(line)
  253. return "\n".join(new_docstring)
  254. def _extract_func_kwargs_as_ast_nodes(
  255. func: Callable,
  256. type_hint_globals: dict[str, Any],
  257. ) -> list[tuple[ast.arg, ast.Constant | None]]:
  258. """Get the kwargs already defined on the function.
  259. Args:
  260. func: The function to extract kwargs from.
  261. type_hint_globals: The globals to use to resolving a type hint str.
  262. Returns:
  263. The list of kwargs as ast arg nodes.
  264. """
  265. spec = getfullargspec(func)
  266. kwargs = []
  267. for kwarg in spec.kwonlyargs:
  268. arg = ast.arg(arg=kwarg)
  269. if kwarg in spec.annotations:
  270. arg.annotation = ast.Name(
  271. id=_get_type_hint(spec.annotations[kwarg], type_hint_globals)
  272. )
  273. default = None
  274. if spec.kwonlydefaults is not None and kwarg in spec.kwonlydefaults:
  275. default = ast.Constant(value=spec.kwonlydefaults[kwarg])
  276. kwargs.append((arg, default))
  277. return kwargs
  278. def _extract_class_props_as_ast_nodes(
  279. func: Callable,
  280. clzs: list[Type],
  281. type_hint_globals: dict[str, Any],
  282. extract_real_default: bool = False,
  283. ) -> list[tuple[ast.arg, ast.Constant | None]]:
  284. """Get the props defined on the class and all parents.
  285. Args:
  286. func: The function that kwargs will be added to.
  287. clzs: The classes to extract props from.
  288. type_hint_globals: The globals to use to resolving a type hint str.
  289. extract_real_default: Whether to extract the real default value from the
  290. pydantic field definition.
  291. Returns:
  292. The list of props as ast arg nodes
  293. """
  294. spec = getfullargspec(func)
  295. all_props = []
  296. kwargs = []
  297. for target_class in clzs:
  298. event_triggers = target_class().get_event_triggers()
  299. # Import from the target class to ensure type hints are resolvable.
  300. exec(f"from {target_class.__module__} import *", type_hint_globals)
  301. for name, value in target_class.__annotations__.items():
  302. if (
  303. name in spec.kwonlyargs
  304. or name in EXCLUDED_PROPS
  305. or name in all_props
  306. or name in event_triggers
  307. or (isinstance(value, str) and "ClassVar" in value)
  308. ):
  309. continue
  310. all_props.append(name)
  311. default = None
  312. if extract_real_default:
  313. # TODO: This is not currently working since the default is not type compatible
  314. # with the annotation in some cases.
  315. with contextlib.suppress(AttributeError, KeyError):
  316. # Try to get default from pydantic field definition.
  317. default = target_class.__fields__[name].default
  318. if isinstance(default, Var):
  319. default = default._decode()
  320. kwargs.append(
  321. (
  322. ast.arg(
  323. arg=name,
  324. annotation=ast.Name(
  325. id=_get_type_hint(value, type_hint_globals)
  326. ),
  327. ),
  328. ast.Constant(value=default),
  329. )
  330. )
  331. return kwargs
  332. def type_to_ast(typ: Any, cls: type) -> ast.AST:
  333. """Converts any type annotation into its AST representation.
  334. Handles nested generic types, unions, etc.
  335. Args:
  336. typ: The type annotation to convert.
  337. cls: The class where the type annotation is used.
  338. Returns:
  339. The AST representation of the type annotation.
  340. """
  341. if typ is type(None):
  342. return ast.Name(id="None")
  343. origin = get_origin(typ)
  344. # Handle plain types (int, str, custom classes, etc.)
  345. if origin is None:
  346. if hasattr(typ, "__name__"):
  347. if typ.__module__.startswith("reflex."):
  348. typ_parts = typ.__module__.split(".")
  349. cls_parts = cls.__module__.split(".")
  350. zipped = list(zip(typ_parts, cls_parts, strict=False))
  351. if all(a == b for a, b in zipped) and len(typ_parts) == len(cls_parts):
  352. return ast.Name(id=typ.__name__)
  353. return ast.Name(id=typ.__module__ + "." + typ.__name__)
  354. return ast.Name(id=typ.__name__)
  355. elif hasattr(typ, "_name"):
  356. return ast.Name(id=typ._name)
  357. return ast.Name(id=str(typ))
  358. # Get the base type name (List, Dict, Optional, etc.)
  359. base_name = origin._name if hasattr(origin, "_name") else origin.__name__
  360. # Get type arguments
  361. args = get_args(typ)
  362. # Handle empty type arguments
  363. if not args:
  364. return ast.Name(id=base_name)
  365. # Convert all type arguments recursively
  366. arg_nodes = [type_to_ast(arg, cls) for arg in args]
  367. # Special case for single-argument types (like List[T] or Optional[T])
  368. if len(arg_nodes) == 1:
  369. slice_value = arg_nodes[0]
  370. else:
  371. slice_value = ast.Tuple(elts=arg_nodes, ctx=ast.Load()) # pyright: ignore [reportArgumentType]
  372. return ast.Subscript(
  373. value=ast.Name(id=base_name),
  374. slice=ast.Index(value=slice_value), # pyright: ignore [reportArgumentType]
  375. ctx=ast.Load(),
  376. )
  377. def _get_parent_imports(func: Callable):
  378. _imports = {"reflex.vars": ["Var"]}
  379. for type_hint in inspect.get_annotations(func).values():
  380. try:
  381. match = re.match(r"\w+\[([\w\d]+)\]", type_hint)
  382. except TypeError:
  383. continue
  384. if match:
  385. type_hint = match.group(1)
  386. if type_hint in importlib.import_module(func.__module__).__dir__():
  387. _imports.setdefault(func.__module__, []).append(type_hint)
  388. return _imports
  389. def _generate_component_create_functiondef(
  390. node: ast.FunctionDef | None,
  391. clz: type[Component] | type[SimpleNamespace],
  392. type_hint_globals: dict[str, Any],
  393. ) -> ast.FunctionDef:
  394. """Generate the create function definition for a Component.
  395. Args:
  396. node: The existing create functiondef node from the ast
  397. clz: The Component class to generate the create functiondef for.
  398. type_hint_globals: The globals to use to resolving a type hint str.
  399. Returns:
  400. The create functiondef node for the ast.
  401. Raises:
  402. TypeError: If clz is not a subclass of Component.
  403. """
  404. if not issubclass(clz, Component):
  405. raise TypeError(f"clz must be a subclass of Component, not {clz!r}")
  406. # add the imports needed by get_type_hint later
  407. type_hint_globals.update(
  408. {name: getattr(typing, name) for name in DEFAULT_TYPING_IMPORTS}
  409. )
  410. if clz.__module__ != clz.create.__module__:
  411. _imports = _get_parent_imports(clz.create)
  412. for name, values in _imports.items():
  413. exec(f"from {name} import {','.join(values)}", type_hint_globals)
  414. kwargs = _extract_func_kwargs_as_ast_nodes(clz.create, type_hint_globals)
  415. # kwargs associated with props defined in the class and its parents
  416. all_classes = [c for c in clz.__mro__ if issubclass(c, Component)]
  417. prop_kwargs = _extract_class_props_as_ast_nodes(
  418. clz.create, all_classes, type_hint_globals
  419. )
  420. all_props = [arg[0].arg for arg in prop_kwargs]
  421. kwargs.extend(prop_kwargs)
  422. def figure_out_return_type(annotation: Any):
  423. if inspect.isclass(annotation) and issubclass(annotation, inspect._empty):
  424. return ast.Name(id="EventType[..., BASE_STATE]")
  425. if not isinstance(annotation, str) and get_origin(annotation) is tuple:
  426. arguments = get_args(annotation)
  427. arguments_without_var = [
  428. get_args(argument)[0] if get_origin(argument) == Var else argument
  429. for argument in arguments
  430. ]
  431. # Convert each argument type to its AST representation
  432. type_args = [type_to_ast(arg, cls=clz) for arg in arguments_without_var]
  433. # Get all prefixes of the type arguments
  434. all_count_args_type = [
  435. ast.Name(
  436. f"EventType[[{', '.join([ast.unparse(arg) for arg in type_args[:i]])}], BASE_STATE]"
  437. )
  438. for i in range(len(type_args) + 1)
  439. ]
  440. # Create EventType using the joined string
  441. return ast.Name(
  442. id=f"Union[{', '.join(map(ast.unparse, all_count_args_type))}]"
  443. )
  444. if isinstance(annotation, str) and annotation.startswith("Tuple["):
  445. inside_of_tuple = annotation.removeprefix("Tuple[").removesuffix("]")
  446. if inside_of_tuple == "()":
  447. return ast.Name(id="EventType[[], BASE_STATE]")
  448. arguments = [""]
  449. bracket_count = 0
  450. for char in inside_of_tuple:
  451. if char == "[":
  452. bracket_count += 1
  453. elif char == "]":
  454. bracket_count -= 1
  455. if char == "," and bracket_count == 0:
  456. arguments.append("")
  457. else:
  458. arguments[-1] += char
  459. arguments = [argument.strip() for argument in arguments]
  460. arguments_without_var = [
  461. argument.removeprefix("Var[").removesuffix("]")
  462. if argument.startswith("Var[")
  463. else argument
  464. for argument in arguments
  465. ]
  466. all_count_args_type = [
  467. ast.Name(
  468. f"EventType[[{', '.join(arguments_without_var[:i])}], BASE_STATE]"
  469. )
  470. for i in range(len(arguments) + 1)
  471. ]
  472. return ast.Name(
  473. id=f"Union[{', '.join(map(ast.unparse, all_count_args_type))}]"
  474. )
  475. return ast.Name(id="EventType[..., BASE_STATE]")
  476. event_triggers = clz().get_event_triggers()
  477. # event handler kwargs
  478. kwargs.extend(
  479. (
  480. ast.arg(
  481. arg=trigger,
  482. annotation=ast.Subscript(
  483. ast.Name("Optional"),
  484. ast.Index( # pyright: ignore [reportArgumentType]
  485. value=ast.Name(
  486. id=ast.unparse(
  487. figure_out_return_type(
  488. inspect.signature(event_specs).return_annotation
  489. )
  490. if not isinstance(
  491. event_specs := event_triggers[trigger], Sequence
  492. )
  493. else ast.Subscript(
  494. ast.Name("Union"),
  495. ast.Tuple(
  496. [
  497. figure_out_return_type(
  498. inspect.signature(
  499. event_spec
  500. ).return_annotation
  501. )
  502. for event_spec in event_specs
  503. ]
  504. ),
  505. )
  506. )
  507. )
  508. ),
  509. ),
  510. ),
  511. ast.Constant(value=None),
  512. )
  513. for trigger in sorted(event_triggers)
  514. )
  515. logger.debug(f"Generated {clz.__name__}.create method with {len(kwargs)} kwargs")
  516. create_args = ast.arguments(
  517. args=[ast.arg(arg="cls")],
  518. posonlyargs=[],
  519. vararg=ast.arg(arg="children"),
  520. kwonlyargs=[arg[0] for arg in kwargs],
  521. kw_defaults=[arg[1] for arg in kwargs],
  522. kwarg=ast.arg(arg="props"),
  523. defaults=[],
  524. )
  525. definition = ast.FunctionDef( # pyright: ignore [reportCallIssue]
  526. name="create",
  527. args=create_args,
  528. body=[ # pyright: ignore [reportArgumentType]
  529. ast.Expr(
  530. value=ast.Constant(
  531. value=_generate_docstrings(
  532. all_classes, [*all_props, *event_triggers]
  533. )
  534. ),
  535. ),
  536. ast.Expr(
  537. value=ast.Constant(value=Ellipsis),
  538. ),
  539. ],
  540. decorator_list=[
  541. ast.Name(id="overload"),
  542. *(
  543. node.decorator_list
  544. if node is not None
  545. else [ast.Name(id="classmethod")]
  546. ),
  547. ],
  548. lineno=node.lineno if node is not None else None, # pyright: ignore [reportArgumentType]
  549. returns=ast.Constant(value=clz.__name__),
  550. )
  551. return definition
  552. def _generate_staticmethod_call_functiondef(
  553. node: ast.FunctionDef | None,
  554. clz: type[Component] | type[SimpleNamespace],
  555. type_hint_globals: dict[str, Any],
  556. ) -> ast.FunctionDef | None:
  557. ...
  558. fullspec = getfullargspec(clz.__call__)
  559. call_args = ast.arguments(
  560. args=[
  561. ast.arg(
  562. name,
  563. annotation=ast.Name(
  564. id=_get_type_hint(
  565. anno := fullspec.annotations[name],
  566. type_hint_globals,
  567. is_optional=rx_types.is_optional(anno),
  568. )
  569. ),
  570. )
  571. for name in fullspec.args
  572. ],
  573. posonlyargs=[],
  574. kwonlyargs=[],
  575. kw_defaults=[],
  576. kwarg=ast.arg(arg="props"),
  577. defaults=(
  578. [ast.Constant(value=default) for default in fullspec.defaults]
  579. if fullspec.defaults
  580. else []
  581. ),
  582. )
  583. definition = ast.FunctionDef( # pyright: ignore [reportCallIssue]
  584. name="__call__",
  585. args=call_args,
  586. body=[
  587. ast.Expr(value=ast.Constant(value=clz.__call__.__doc__)),
  588. ast.Expr(
  589. value=ast.Constant(...),
  590. ),
  591. ],
  592. decorator_list=[ast.Name(id="staticmethod")],
  593. lineno=node.lineno if node is not None else None, # pyright: ignore [reportArgumentType]
  594. returns=ast.Constant(
  595. value=_get_type_hint(
  596. typing.get_type_hints(clz.__call__).get("return", None),
  597. type_hint_globals,
  598. is_optional=False,
  599. )
  600. ),
  601. )
  602. return definition
  603. def _generate_namespace_call_functiondef(
  604. node: ast.ClassDef | None,
  605. clz_name: str,
  606. classes: dict[str, type[Component] | type[SimpleNamespace]],
  607. type_hint_globals: dict[str, Any],
  608. ) -> ast.FunctionDef | None:
  609. """Generate the __call__ function definition for a SimpleNamespace.
  610. Args:
  611. node: The existing __call__ classdef parent node from the ast
  612. clz_name: The name of the SimpleNamespace class to generate the __call__ functiondef for.
  613. classes: Map name to actual class definition.
  614. type_hint_globals: The globals to use to resolving a type hint str.
  615. Returns:
  616. The create functiondef node for the ast.
  617. """
  618. # add the imports needed by get_type_hint later
  619. type_hint_globals.update(
  620. {name: getattr(typing, name) for name in DEFAULT_TYPING_IMPORTS}
  621. )
  622. clz = classes[clz_name]
  623. if not hasattr(clz.__call__, "__self__"):
  624. return _generate_staticmethod_call_functiondef(node, clz, type_hint_globals) # pyright: ignore [reportArgumentType]
  625. # Determine which class is wrapped by the namespace __call__ method
  626. component_clz = clz.__call__.__self__
  627. if clz.__call__.__func__.__name__ != "create": # pyright: ignore [reportFunctionMemberAccess]
  628. return None
  629. definition = _generate_component_create_functiondef(
  630. node=None,
  631. clz=component_clz, # pyright: ignore [reportArgumentType]
  632. type_hint_globals=type_hint_globals,
  633. )
  634. definition.name = "__call__"
  635. # Turn the definition into a staticmethod
  636. del definition.args.args[0] # remove `cls` arg
  637. definition.decorator_list = [ast.Name(id="staticmethod")]
  638. return definition
  639. class StubGenerator(ast.NodeTransformer):
  640. """A node transformer that will generate the stubs for a given module."""
  641. def __init__(
  642. self, module: ModuleType, classes: dict[str, Type[Component | SimpleNamespace]]
  643. ):
  644. """Initialize the stub generator.
  645. Args:
  646. module: The actual module object module to generate stubs for.
  647. classes: The actual Component class objects to generate stubs for.
  648. """
  649. super().__init__()
  650. # Dict mapping class name to actual class object.
  651. self.classes = classes
  652. # Track the last class node that was visited.
  653. self.current_class = None
  654. # These imports will be included in the AST of stub files.
  655. self.typing_imports = DEFAULT_TYPING_IMPORTS.copy()
  656. # Whether those typing imports have been inserted yet.
  657. self.inserted_imports = False
  658. # Collected import statements from the module.
  659. self.import_statements: list[str] = []
  660. # This dict is used when evaluating type hints.
  661. self.type_hint_globals = module.__dict__.copy()
  662. @staticmethod
  663. def _remove_docstring(
  664. node: ast.Module | ast.ClassDef | ast.FunctionDef,
  665. ) -> ast.Module | ast.ClassDef | ast.FunctionDef:
  666. """Removes any docstring in place.
  667. Args:
  668. node: The node to remove the docstring from.
  669. Returns:
  670. The modified node.
  671. """
  672. if (
  673. node.body
  674. and isinstance(node.body[0], ast.Expr)
  675. and isinstance(node.body[0].value, ast.Constant)
  676. ):
  677. node.body.pop(0)
  678. return node
  679. def _current_class_is_component(self) -> bool:
  680. """Check if the current class is a Component.
  681. Returns:
  682. Whether the current class is a Component.
  683. """
  684. return (
  685. self.current_class is not None
  686. and self.current_class in self.classes
  687. and issubclass(self.classes[self.current_class], Component)
  688. )
  689. def visit_Module(self, node: ast.Module) -> ast.Module:
  690. """Visit a Module node and remove docstring from body.
  691. Args:
  692. node: The Module node to visit.
  693. Returns:
  694. The modified Module node.
  695. """
  696. self.generic_visit(node)
  697. return self._remove_docstring(node) # pyright: ignore [reportReturnType]
  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 module.
  702. If this is the first import statement, insert the typing imports before it.
  703. Args:
  704. node: The import node to visit.
  705. Returns:
  706. The modified import node(s).
  707. """
  708. self.import_statements.append(ast.unparse(node))
  709. if not self.inserted_imports:
  710. self.inserted_imports = True
  711. default_imports = _generate_imports(self.typing_imports)
  712. self.import_statements.extend(ast.unparse(i) for i in default_imports)
  713. return [*default_imports, node]
  714. return node
  715. def visit_ImportFrom(
  716. self, node: ast.ImportFrom
  717. ) -> ast.Import | ast.ImportFrom | list[ast.Import | ast.ImportFrom] | None:
  718. """Visit an ImportFrom node.
  719. Remove any `from __future__ import *` statements, and hand off to visit_Import.
  720. Args:
  721. node: The ImportFrom node to visit.
  722. Returns:
  723. The modified ImportFrom node.
  724. """
  725. if node.module == "__future__":
  726. return None # ignore __future__ imports
  727. return self.visit_Import(node)
  728. def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:
  729. """Visit a ClassDef node.
  730. Remove all assignments in the class body, and add a create functiondef
  731. if one does not exist.
  732. Args:
  733. node: The ClassDef node to visit.
  734. Returns:
  735. The modified ClassDef node.
  736. """
  737. exec("\n".join(self.import_statements), self.type_hint_globals)
  738. self.current_class = node.name
  739. self._remove_docstring(node)
  740. # Define `__call__` as a real function so the docstring appears in the stub.
  741. call_definition = None
  742. for child in node.body[:]:
  743. found_call = False
  744. if isinstance(child, ast.Assign):
  745. for target in child.targets[:]:
  746. if isinstance(target, ast.Name) and target.id == "__call__":
  747. child.targets.remove(target)
  748. found_call = True
  749. if not found_call:
  750. continue
  751. if not child.targets[:]:
  752. node.body.remove(child)
  753. call_definition = _generate_namespace_call_functiondef(
  754. node,
  755. self.current_class,
  756. self.classes,
  757. type_hint_globals=self.type_hint_globals,
  758. )
  759. break
  760. self.generic_visit(node) # Visit child nodes.
  761. if (
  762. not any(
  763. isinstance(child, ast.FunctionDef) and child.name == "create"
  764. for child in node.body
  765. )
  766. and self._current_class_is_component()
  767. ):
  768. # Add a new .create FunctionDef since one does not exist.
  769. node.body.append(
  770. _generate_component_create_functiondef(
  771. node=None,
  772. clz=self.classes[self.current_class],
  773. type_hint_globals=self.type_hint_globals,
  774. )
  775. )
  776. if call_definition is not None:
  777. node.body.append(call_definition)
  778. if not node.body:
  779. # We should never return an empty body.
  780. node.body.append(ast.Expr(value=ast.Constant(value=Ellipsis)))
  781. self.current_class = None
  782. return node
  783. def visit_FunctionDef(self, node: ast.FunctionDef) -> Any:
  784. """Visit a FunctionDef node.
  785. Special handling for `.create` functions to add type hints for all props
  786. defined on the component class.
  787. Remove all private functions and blank out the function body of the
  788. remaining public functions.
  789. Args:
  790. node: The FunctionDef node to visit.
  791. Returns:
  792. The modified FunctionDef node (or None).
  793. """
  794. if node.name == "create" and self.current_class in self.classes:
  795. node = _generate_component_create_functiondef(
  796. node, self.classes[self.current_class], self.type_hint_globals
  797. )
  798. else:
  799. if node.name.startswith("_") and node.name != "__call__":
  800. return None # remove private methods
  801. if node.body[-1] != ast.Expr(value=ast.Constant(value=Ellipsis)):
  802. # Blank out the function body for public functions.
  803. node.body = [ast.Expr(value=ast.Constant(value=Ellipsis))]
  804. return node
  805. def visit_Assign(self, node: ast.Assign) -> ast.Assign | None:
  806. """Remove non-annotated assignment statements.
  807. Args:
  808. node: The Assign node to visit.
  809. Returns:
  810. The modified Assign node (or None).
  811. """
  812. # Special case for assignments to `typing.Any` as fallback.
  813. if (
  814. node.value is not None
  815. and isinstance(node.value, ast.Name)
  816. and node.value.id == "Any"
  817. ):
  818. return node
  819. if self._current_class_is_component():
  820. # Remove annotated assignments in Component classes (props)
  821. return None
  822. # remove dunder method assignments for lazy_loader.attach
  823. for target in node.targets:
  824. if isinstance(target, ast.Tuple):
  825. for name in target.elts:
  826. if isinstance(name, ast.Name) and name.id.startswith("_"):
  827. return
  828. return node
  829. def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AnnAssign | None:
  830. """Visit an AnnAssign node (Annotated assignment).
  831. Remove private target and remove the assignment value in the stub.
  832. Args:
  833. node: The AnnAssign node to visit.
  834. Returns:
  835. The modified AnnAssign node (or None).
  836. """
  837. # skip ClassVars
  838. if (
  839. isinstance(node.annotation, ast.Subscript)
  840. and isinstance(node.annotation.value, ast.Name)
  841. and node.annotation.value.id == "ClassVar"
  842. ):
  843. return node
  844. if isinstance(node.target, ast.Name) and node.target.id.startswith("_"):
  845. return None
  846. if self.current_class in self.classes:
  847. # Remove annotated assignments in Component classes (props)
  848. return None
  849. # Blank out assignments in type stubs.
  850. node.value = None
  851. return node
  852. class InitStubGenerator(StubGenerator):
  853. """A node transformer that will generate the stubs for a given init file."""
  854. def visit_Import(
  855. self, node: ast.Import | ast.ImportFrom
  856. ) -> ast.Import | ast.ImportFrom | list[ast.Import | ast.ImportFrom]:
  857. """Collect import statements from the init module.
  858. Args:
  859. node: The import node to visit.
  860. Returns:
  861. The modified import node(s).
  862. """
  863. return [node]
  864. class PyiGenerator:
  865. """A .pyi file generator that will scan all defined Component in Reflex and
  866. generate the appropriate stub.
  867. """
  868. modules: list = []
  869. root: str = ""
  870. current_module: Any = {}
  871. written_files: list[str] = []
  872. def _write_pyi_file(self, module_path: Path, source: str):
  873. relpath = str(_relative_to_pwd(module_path)).replace("\\", "/")
  874. pyi_content = (
  875. "\n".join(
  876. [
  877. f'"""Stub file for {relpath}"""',
  878. "# ------------------- DO NOT EDIT ----------------------",
  879. "# This file was generated by `reflex/utils/pyi_generator.py`!",
  880. "# ------------------------------------------------------",
  881. "",
  882. ]
  883. )
  884. + source
  885. )
  886. pyi_path = module_path.with_suffix(".pyi")
  887. pyi_path.write_text(pyi_content)
  888. logger.info(f"Wrote {relpath}")
  889. def _get_init_lazy_imports(self, mod: tuple | ModuleType, new_tree: ast.AST):
  890. # retrieve the _SUBMODULES and _SUBMOD_ATTRS from an init file if present.
  891. sub_mods = getattr(mod, "_SUBMODULES", None)
  892. sub_mod_attrs = getattr(mod, "_SUBMOD_ATTRS", None)
  893. pyright_ignore_imports = getattr(mod, "_PYRIGHT_IGNORE_IMPORTS", [])
  894. if not sub_mods and not sub_mod_attrs:
  895. return
  896. sub_mods_imports = []
  897. sub_mod_attrs_imports = []
  898. if sub_mods:
  899. sub_mods_imports = [
  900. f"from . import {mod} as {mod}" for mod in sorted(sub_mods)
  901. ]
  902. sub_mods_imports.append("")
  903. if sub_mod_attrs:
  904. sub_mod_attrs = {
  905. attr: mod for mod, attrs in sub_mod_attrs.items() for attr in attrs
  906. }
  907. # construct the import statement and handle special cases for aliases
  908. sub_mod_attrs_imports = [
  909. f"from .{path} import {mod if not isinstance(mod, tuple) else mod[0]} as {mod if not isinstance(mod, tuple) else mod[1]}"
  910. + (
  911. " # type: ignore"
  912. if mod in pyright_ignore_imports
  913. else " # noqa: F401" # ignore ruff formatting here for cases like rx.list.
  914. if isinstance(mod, tuple)
  915. else ""
  916. )
  917. for mod, path in sub_mod_attrs.items()
  918. ]
  919. sub_mod_attrs_imports.append("")
  920. text = "\n" + "\n".join([*sub_mods_imports, *sub_mod_attrs_imports])
  921. text += ast.unparse(new_tree) + "\n"
  922. return text
  923. def _scan_file(self, module_path: Path) -> str | None:
  924. module_import = (
  925. _relative_to_pwd(module_path)
  926. .with_suffix("")
  927. .as_posix()
  928. .replace("/", ".")
  929. .replace("\\", ".")
  930. )
  931. module = importlib.import_module(module_import)
  932. logger.debug(f"Read {module_path}")
  933. class_names = {
  934. name: obj
  935. for name, obj in vars(module).items()
  936. if inspect.isclass(obj)
  937. and (issubclass(obj, Component) or issubclass(obj, SimpleNamespace))
  938. and obj != Component
  939. and inspect.getmodule(obj) == module
  940. }
  941. is_init_file = _relative_to_pwd(module_path).name == "__init__.py"
  942. if not class_names and not is_init_file:
  943. return
  944. if is_init_file:
  945. new_tree = InitStubGenerator(module, class_names).visit(
  946. ast.parse(inspect.getsource(module))
  947. )
  948. init_imports = self._get_init_lazy_imports(module, new_tree)
  949. if not init_imports:
  950. return
  951. self._write_pyi_file(module_path, init_imports)
  952. else:
  953. new_tree = StubGenerator(module, class_names).visit(
  954. ast.parse(inspect.getsource(module))
  955. )
  956. self._write_pyi_file(module_path, ast.unparse(new_tree))
  957. return str(module_path.with_suffix(".pyi").resolve())
  958. def _scan_files_multiprocess(self, files: list[Path]):
  959. with Pool(processes=cpu_count()) as pool:
  960. self.written_files.extend(f for f in pool.map(self._scan_file, files) if f)
  961. def _scan_files(self, files: list[Path]):
  962. for file in files:
  963. pyi_path = self._scan_file(file)
  964. if pyi_path:
  965. self.written_files.append(pyi_path)
  966. def scan_all(self, targets: list, changed_files: list[Path] | None = None):
  967. """Scan all targets for class inheriting Component and generate the .pyi files.
  968. Args:
  969. targets: the list of file/folders to scan.
  970. changed_files (optional): the list of changed files since the last run.
  971. """
  972. file_targets = []
  973. for target in targets:
  974. target_path = Path(target)
  975. if (
  976. target_path.is_file()
  977. and target_path.suffix == ".py"
  978. and target_path.name not in EXCLUDED_FILES
  979. ):
  980. file_targets.append(target_path)
  981. continue
  982. if not target_path.is_dir():
  983. continue
  984. for file_path in _walk_files(target_path):
  985. relative = _relative_to_pwd(file_path)
  986. if relative.name in EXCLUDED_FILES or file_path.suffix != ".py":
  987. continue
  988. if (
  989. changed_files is not None
  990. and _relative_to_pwd(file_path) not in changed_files
  991. ):
  992. continue
  993. file_targets.append(file_path)
  994. # check if pyi changed but not the source
  995. if changed_files is not None:
  996. for changed_file in changed_files:
  997. if changed_file.suffix != ".pyi":
  998. continue
  999. py_file_path = changed_file.with_suffix(".py")
  1000. if not py_file_path.exists() and changed_file.exists():
  1001. changed_file.unlink()
  1002. if py_file_path in file_targets:
  1003. continue
  1004. subprocess.run(["git", "checkout", changed_file])
  1005. if cpu_count() == 1 or len(file_targets) < 5:
  1006. self._scan_files(file_targets)
  1007. else:
  1008. self._scan_files_multiprocess(file_targets)
  1009. # Fix generated pyi files with ruff.
  1010. subprocess.run(["ruff", "format", *self.written_files])
  1011. subprocess.run(["ruff", "check", "--fix", *self.written_files])
  1012. # For some reason, we need to format the __init__.pyi files again after fixing...
  1013. init_files = [f for f in self.written_files if "/__init__.pyi" in f]
  1014. subprocess.run(["ruff", "format", *init_files])
  1015. # Post-process the generated pyi files to add hacky type: ignore comments
  1016. for file_path in self.written_files:
  1017. with FileInput(file_path, inplace=True) as f:
  1018. for line in f:
  1019. # Hack due to ast not supporting comments in the tree.
  1020. if (
  1021. "def create(" in line
  1022. or "Var[Figure]" in line
  1023. or "Var[Template]" in line
  1024. ):
  1025. line = line.rstrip() + " # type: ignore\n"
  1026. print(line, end="") # noqa: T201