pyi_generator.py 44 KB

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