pyi_generator.py 40 KB

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