pyi_generator.py 39 KB

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