pyi_generator.py 41 KB

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