pyi_generator.py 40 KB

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