pyi_generator.py 44 KB

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