pyi_generator.py 41 KB

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