pyi_generator.py 44 KB

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