pyi_generator.py 44 KB

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