pyi_generator.py 45 KB

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