pyi_generator.py 40 KB

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