pyi_generator.py 40 KB

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