pyi_generator.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  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 textwrap
  11. import typing
  12. from inspect import getfullargspec
  13. from multiprocessing import Pool, cpu_count
  14. from pathlib import Path
  15. from types import ModuleType, SimpleNamespace
  16. from typing import Any, Callable, Iterable, Type, get_args
  17. try:
  18. import black
  19. import black.mode
  20. except ImportError:
  21. black = None
  22. from reflex.components.component import Component
  23. from reflex.utils import types as rx_types
  24. from reflex.vars import Var
  25. logger = logging.getLogger("pyi_generator")
  26. INIT_FILE = Path("reflex/__init__.pyi").resolve()
  27. PWD = Path(".").resolve()
  28. EXCLUDED_FILES = [
  29. "__init__.py",
  30. "app.py",
  31. "component.py",
  32. "bare.py",
  33. "foreach.py",
  34. "cond.py",
  35. "match.py",
  36. "multiselect.py",
  37. "literals.py",
  38. ]
  39. # These props exist on the base component, but should not be exposed in create methods.
  40. EXCLUDED_PROPS = [
  41. "alias",
  42. "children",
  43. "event_triggers",
  44. "library",
  45. "lib_dependencies",
  46. "tag",
  47. "is_default",
  48. "special_props",
  49. "_invalid_children",
  50. "_memoization_mode",
  51. "_rename_props",
  52. "_valid_children",
  53. "_valid_parents",
  54. "State",
  55. ]
  56. DEFAULT_TYPING_IMPORTS = {
  57. "overload",
  58. "Any",
  59. "Dict",
  60. # "List",
  61. "Literal",
  62. "Optional",
  63. "Union",
  64. }
  65. def _walk_files(path):
  66. """Walk all files in a path.
  67. This can be replaced with Path.walk() in python3.12.
  68. Args:
  69. path: The path to walk.
  70. Yields:
  71. The next file in the path.
  72. """
  73. for p in Path(path).iterdir():
  74. if p.is_dir():
  75. yield from _walk_files(p)
  76. continue
  77. yield p.resolve()
  78. def _relative_to_pwd(path: Path) -> Path:
  79. """Get the relative path of a path to the current working directory.
  80. Args:
  81. path: The path to get the relative path for.
  82. Returns:
  83. The relative path.
  84. """
  85. if path.is_absolute():
  86. return path.relative_to(PWD)
  87. return path
  88. def _get_type_hint(value, type_hint_globals, is_optional=True) -> str:
  89. """Resolve the type hint for value.
  90. Args:
  91. value: The type annotation as a str or actual types/aliases.
  92. type_hint_globals: The globals to use to resolving a type hint str.
  93. is_optional: Whether the type hint should be wrapped in Optional.
  94. Returns:
  95. The resolved type hint as a str.
  96. """
  97. res = ""
  98. args = get_args(value)
  99. if args:
  100. inner_container_type_args = (
  101. [repr(arg) for arg in args]
  102. if rx_types.is_literal(value)
  103. else [
  104. _get_type_hint(arg, type_hint_globals, is_optional=False)
  105. for arg in args
  106. if arg is not type(None)
  107. ]
  108. )
  109. res = f"{value.__name__}[{', '.join(inner_container_type_args)}]"
  110. if value.__name__ == "Var":
  111. # For Var types, Union with the inner args so they can be passed directly.
  112. types = [res] + [
  113. _get_type_hint(arg, type_hint_globals, is_optional=False)
  114. for arg in args
  115. if arg is not type(None)
  116. ]
  117. if len(types) > 1:
  118. res = ", ".join(types)
  119. res = f"Union[{res}]"
  120. elif isinstance(value, str):
  121. ev = eval(value, type_hint_globals)
  122. res = (
  123. _get_type_hint(ev, type_hint_globals, is_optional=False)
  124. if ev.__name__ == "Var"
  125. else value
  126. )
  127. else:
  128. res = value.__name__
  129. if is_optional and not res.startswith("Optional"):
  130. res = f"Optional[{res}]"
  131. return res
  132. def _generate_imports(typing_imports: Iterable[str]) -> list[ast.ImportFrom]:
  133. """Generate the import statements for the stub file.
  134. Args:
  135. typing_imports: The typing imports to include.
  136. Returns:
  137. The list of import statements.
  138. """
  139. return [
  140. ast.ImportFrom(
  141. module="typing",
  142. names=[ast.alias(name=imp) for imp in sorted(typing_imports)],
  143. ),
  144. *ast.parse( # type: ignore
  145. textwrap.dedent(
  146. """
  147. from reflex.vars import Var, BaseVar, ComputedVar
  148. from reflex.event import EventChain, EventHandler, EventSpec
  149. from reflex.style import Style"""
  150. )
  151. ).body,
  152. # *[
  153. # ast.ImportFrom(module=name, names=[ast.alias(name=val) for val in values])
  154. # for name, values in EXTRA_IMPORTS.items()
  155. # ],
  156. ]
  157. def _generate_docstrings(clzs: list[Type[Component]], props: list[str]) -> str:
  158. """Generate the docstrings for the create method.
  159. Args:
  160. clzs: The classes to generate docstrings for.
  161. props: The props to generate docstrings for.
  162. Returns:
  163. The docstring for the create method.
  164. """
  165. props_comments = {}
  166. comments = []
  167. for clz in clzs:
  168. for line in inspect.getsource(clz).splitlines():
  169. reached_functions = re.search("def ", line)
  170. if reached_functions:
  171. # We've reached the functions, so stop.
  172. break
  173. # Get comments for prop
  174. if line.strip().startswith("#"):
  175. comments.append(line)
  176. continue
  177. # Check if this line has a prop.
  178. match = re.search("\\w+:", line)
  179. if match is None:
  180. # This line doesn't have a var, so continue.
  181. continue
  182. # Get the prop.
  183. prop = match.group(0).strip(":")
  184. if prop in props:
  185. if not comments: # do not include undocumented props
  186. continue
  187. props_comments[prop] = [
  188. comment.strip().strip("#") for comment in comments
  189. ]
  190. comments.clear()
  191. clz = clzs[0]
  192. new_docstring = []
  193. for line in (clz.create.__doc__ or "").splitlines():
  194. if "**" in line:
  195. indent = line.split("**")[0]
  196. for nline in [
  197. f"{indent}{n}:{' '.join(c)}" for n, c in props_comments.items()
  198. ]:
  199. new_docstring.append(nline)
  200. new_docstring.append(line)
  201. return "\n".join(new_docstring)
  202. def _extract_func_kwargs_as_ast_nodes(
  203. func: Callable,
  204. type_hint_globals: dict[str, Any],
  205. ) -> list[tuple[ast.arg, ast.Constant | None]]:
  206. """Get the kwargs already defined on the function.
  207. Args:
  208. func: The function to extract kwargs from.
  209. type_hint_globals: The globals to use to resolving a type hint str.
  210. Returns:
  211. The list of kwargs as ast arg nodes.
  212. """
  213. spec = getfullargspec(func)
  214. kwargs = []
  215. for kwarg in spec.kwonlyargs:
  216. arg = ast.arg(arg=kwarg)
  217. if kwarg in spec.annotations:
  218. arg.annotation = ast.Name(
  219. id=_get_type_hint(spec.annotations[kwarg], type_hint_globals)
  220. )
  221. default = None
  222. if spec.kwonlydefaults is not None and kwarg in spec.kwonlydefaults:
  223. default = ast.Constant(value=spec.kwonlydefaults[kwarg])
  224. kwargs.append((arg, default))
  225. return kwargs
  226. def _extract_class_props_as_ast_nodes(
  227. func: Callable,
  228. clzs: list[Type],
  229. type_hint_globals: dict[str, Any],
  230. extract_real_default: bool = False,
  231. ) -> list[tuple[ast.arg, ast.Constant | None]]:
  232. """Get the props defined on the class and all parents.
  233. Args:
  234. func: The function that kwargs will be added to.
  235. clzs: The classes to extract props from.
  236. type_hint_globals: The globals to use to resolving a type hint str.
  237. extract_real_default: Whether to extract the real default value from the
  238. pydantic field definition.
  239. Returns:
  240. The list of props as ast arg nodes
  241. """
  242. spec = getfullargspec(func)
  243. all_props = []
  244. kwargs = []
  245. for target_class in clzs:
  246. # Import from the target class to ensure type hints are resolvable.
  247. exec(f"from {target_class.__module__} import *", type_hint_globals)
  248. for name, value in target_class.__annotations__.items():
  249. if (
  250. name in spec.kwonlyargs
  251. or name in EXCLUDED_PROPS
  252. or name in all_props
  253. or (isinstance(value, str) and "ClassVar" in value)
  254. ):
  255. continue
  256. all_props.append(name)
  257. default = None
  258. if extract_real_default:
  259. # TODO: This is not currently working since the default is not type compatible
  260. # with the annotation in some cases.
  261. with contextlib.suppress(AttributeError, KeyError):
  262. # Try to get default from pydantic field definition.
  263. default = target_class.__fields__[name].default
  264. if isinstance(default, Var):
  265. default = default._decode() # type: ignore
  266. kwargs.append(
  267. (
  268. ast.arg(
  269. arg=name,
  270. annotation=ast.Name(
  271. id=_get_type_hint(value, type_hint_globals)
  272. ),
  273. ),
  274. ast.Constant(value=default),
  275. )
  276. )
  277. return kwargs
  278. def _get_parent_imports(func):
  279. _imports = {"reflex.vars": ["Var"]}
  280. for type_hint in inspect.get_annotations(func).values():
  281. try:
  282. match = re.match(r"\w+\[([\w\d]+)\]", type_hint)
  283. except TypeError:
  284. continue
  285. if match:
  286. type_hint = match.group(1)
  287. if type_hint in importlib.import_module(func.__module__).__dir__():
  288. _imports.setdefault(func.__module__, []).append(type_hint)
  289. return _imports
  290. def _generate_component_create_functiondef(
  291. node: ast.FunctionDef | None,
  292. clz: type[Component] | type[SimpleNamespace],
  293. type_hint_globals: dict[str, Any],
  294. ) -> ast.FunctionDef:
  295. """Generate the create function definition for a Component.
  296. Args:
  297. node: The existing create functiondef node from the ast
  298. clz: The Component class to generate the create functiondef for.
  299. type_hint_globals: The globals to use to resolving a type hint str.
  300. Returns:
  301. The create functiondef node for the ast.
  302. Raises:
  303. TypeError: If clz is not a subclass of Component.
  304. """
  305. if not issubclass(clz, Component):
  306. raise TypeError(f"clz must be a subclass of Component, not {clz!r}")
  307. # add the imports needed by get_type_hint later
  308. type_hint_globals.update(
  309. {name: getattr(typing, name) for name in DEFAULT_TYPING_IMPORTS}
  310. )
  311. if clz.__module__ != clz.create.__module__:
  312. _imports = _get_parent_imports(clz.create)
  313. for name, values in _imports.items():
  314. exec(f"from {name} import {','.join(values)}", type_hint_globals)
  315. kwargs = _extract_func_kwargs_as_ast_nodes(clz.create, type_hint_globals)
  316. # kwargs associated with props defined in the class and its parents
  317. all_classes = [c for c in clz.__mro__ if issubclass(c, Component)]
  318. prop_kwargs = _extract_class_props_as_ast_nodes(
  319. clz.create, all_classes, type_hint_globals
  320. )
  321. all_props = [arg[0].arg for arg in prop_kwargs]
  322. kwargs.extend(prop_kwargs)
  323. # event handler kwargs
  324. kwargs.extend(
  325. (
  326. ast.arg(
  327. arg=trigger,
  328. annotation=ast.Name(
  329. id="Optional[Union[EventHandler, EventSpec, list, function, BaseVar]]"
  330. ),
  331. ),
  332. ast.Constant(value=None),
  333. )
  334. for trigger in sorted(clz().get_event_triggers().keys())
  335. )
  336. logger.debug(f"Generated {clz.__name__}.create method with {len(kwargs)} kwargs")
  337. create_args = ast.arguments(
  338. args=[ast.arg(arg="cls")],
  339. posonlyargs=[],
  340. vararg=ast.arg(arg="children"),
  341. kwonlyargs=[arg[0] for arg in kwargs],
  342. kw_defaults=[arg[1] for arg in kwargs],
  343. kwarg=ast.arg(arg="props"),
  344. defaults=[],
  345. )
  346. definition = ast.FunctionDef(
  347. name="create",
  348. args=create_args,
  349. body=[
  350. ast.Expr(
  351. value=ast.Constant(value=_generate_docstrings(all_classes, all_props))
  352. ),
  353. ast.Expr(
  354. value=ast.Ellipsis(),
  355. ),
  356. ],
  357. decorator_list=[
  358. ast.Name(id="overload"),
  359. *(
  360. node.decorator_list
  361. if node is not None
  362. else [ast.Name(id="classmethod")]
  363. ),
  364. ],
  365. lineno=node.lineno if node is not None else None,
  366. returns=ast.Constant(value=clz.__name__),
  367. )
  368. return definition
  369. def _generate_namespace_call_functiondef(
  370. clz_name: str,
  371. classes: dict[str, type[Component] | type[SimpleNamespace]],
  372. type_hint_globals: dict[str, Any],
  373. ) -> ast.FunctionDef | None:
  374. """Generate the __call__ function definition for a SimpleNamespace.
  375. Args:
  376. clz_name: The name of the SimpleNamespace class to generate the __call__ functiondef for.
  377. classes: Map name to actual class definition.
  378. type_hint_globals: The globals to use to resolving a type hint str.
  379. Returns:
  380. The create functiondef node for the ast.
  381. """
  382. # add the imports needed by get_type_hint later
  383. type_hint_globals.update(
  384. {name: getattr(typing, name) for name in DEFAULT_TYPING_IMPORTS}
  385. )
  386. clz = classes[clz_name]
  387. # Determine which class is wrapped by the namespace __call__ method
  388. component_clz = clz.__call__.__self__
  389. # Only generate for create functions
  390. if clz.__call__.__func__.__name__ != "create":
  391. return None
  392. definition = _generate_component_create_functiondef(
  393. node=None,
  394. clz=component_clz, # type: ignore
  395. type_hint_globals=type_hint_globals,
  396. )
  397. definition.name = "__call__"
  398. # Turn the definition into a staticmethod
  399. del definition.args.args[0] # remove `cls` arg
  400. definition.decorator_list = [ast.Name(id="staticmethod")]
  401. return definition
  402. class StubGenerator(ast.NodeTransformer):
  403. """A node transformer that will generate the stubs for a given module."""
  404. def __init__(
  405. self, module: ModuleType, classes: dict[str, Type[Component | SimpleNamespace]]
  406. ):
  407. """Initialize the stub generator.
  408. Args:
  409. module: The actual module object module to generate stubs for.
  410. classes: The actual Component class objects to generate stubs for.
  411. """
  412. super().__init__()
  413. # Dict mapping class name to actual class object.
  414. self.classes = classes
  415. # Track the last class node that was visited.
  416. self.current_class = None
  417. # These imports will be included in the AST of stub files.
  418. self.typing_imports = DEFAULT_TYPING_IMPORTS
  419. # Whether those typing imports have been inserted yet.
  420. self.inserted_imports = False
  421. # Collected import statements from the module.
  422. self.import_statements: list[str] = []
  423. # This dict is used when evaluating type hints.
  424. self.type_hint_globals = module.__dict__.copy()
  425. @staticmethod
  426. def _remove_docstring(
  427. node: ast.Module | ast.ClassDef | ast.FunctionDef,
  428. ) -> ast.Module | ast.ClassDef | ast.FunctionDef:
  429. """Removes any docstring in place.
  430. Args:
  431. node: The node to remove the docstring from.
  432. Returns:
  433. The modified node.
  434. """
  435. if (
  436. node.body
  437. and isinstance(node.body[0], ast.Expr)
  438. and isinstance(node.body[0].value, ast.Constant)
  439. ):
  440. node.body.pop(0)
  441. return node
  442. def _current_class_is_component(self) -> bool:
  443. """Check if the current class is a Component.
  444. Returns:
  445. Whether the current class is a Component.
  446. """
  447. return (
  448. self.current_class is not None
  449. and self.current_class in self.classes
  450. and issubclass(self.classes[self.current_class], Component)
  451. )
  452. def visit_Module(self, node: ast.Module) -> ast.Module:
  453. """Visit a Module node and remove docstring from body.
  454. Args:
  455. node: The Module node to visit.
  456. Returns:
  457. The modified Module node.
  458. """
  459. self.generic_visit(node)
  460. return self._remove_docstring(node) # type: ignore
  461. def visit_Import(
  462. self, node: ast.Import | ast.ImportFrom
  463. ) -> ast.Import | ast.ImportFrom | list[ast.Import | ast.ImportFrom]:
  464. """Collect import statements from the module.
  465. If this is the first import statement, insert the typing imports before it.
  466. Args:
  467. node: The import node to visit.
  468. Returns:
  469. The modified import node(s).
  470. """
  471. self.import_statements.append(ast.unparse(node))
  472. if not self.inserted_imports:
  473. self.inserted_imports = True
  474. return _generate_imports(self.typing_imports) + [node]
  475. return node
  476. def visit_ImportFrom(
  477. self, node: ast.ImportFrom
  478. ) -> ast.Import | ast.ImportFrom | list[ast.Import | ast.ImportFrom] | None:
  479. """Visit an ImportFrom node.
  480. Remove any `from __future__ import *` statements, and hand off to visit_Import.
  481. Args:
  482. node: The ImportFrom node to visit.
  483. Returns:
  484. The modified ImportFrom node.
  485. """
  486. if node.module == "__future__":
  487. return None # ignore __future__ imports
  488. return self.visit_Import(node)
  489. def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:
  490. """Visit a ClassDef node.
  491. Remove all assignments in the class body, and add a create functiondef
  492. if one does not exist.
  493. Args:
  494. node: The ClassDef node to visit.
  495. Returns:
  496. The modified ClassDef node.
  497. """
  498. exec("\n".join(self.import_statements), self.type_hint_globals)
  499. self.current_class = node.name
  500. self._remove_docstring(node)
  501. # Define `__call__` as a real function so the docstring appears in the stub.
  502. call_definition = None
  503. for child in node.body[:]:
  504. found_call = False
  505. if isinstance(child, ast.Assign):
  506. for target in child.targets[:]:
  507. if isinstance(target, ast.Name) and target.id == "__call__":
  508. child.targets.remove(target)
  509. found_call = True
  510. if not found_call:
  511. continue
  512. if not child.targets[:]:
  513. node.body.remove(child)
  514. call_definition = _generate_namespace_call_functiondef(
  515. self.current_class,
  516. self.classes,
  517. type_hint_globals=self.type_hint_globals,
  518. )
  519. break
  520. self.generic_visit(node) # Visit child nodes.
  521. if (
  522. not any(
  523. isinstance(child, ast.FunctionDef) and child.name == "create"
  524. for child in node.body
  525. )
  526. and self._current_class_is_component()
  527. ):
  528. # Add a new .create FunctionDef since one does not exist.
  529. node.body.append(
  530. _generate_component_create_functiondef(
  531. node=None,
  532. clz=self.classes[self.current_class],
  533. type_hint_globals=self.type_hint_globals,
  534. )
  535. )
  536. if call_definition is not None:
  537. node.body.append(call_definition)
  538. if not node.body:
  539. # We should never return an empty body.
  540. node.body.append(ast.Expr(value=ast.Ellipsis()))
  541. self.current_class = None
  542. return node
  543. def visit_FunctionDef(self, node: ast.FunctionDef) -> Any:
  544. """Visit a FunctionDef node.
  545. Special handling for `.create` functions to add type hints for all props
  546. defined on the component class.
  547. Remove all private functions and blank out the function body of the
  548. remaining public functions.
  549. Args:
  550. node: The FunctionDef node to visit.
  551. Returns:
  552. The modified FunctionDef node (or None).
  553. """
  554. if node.name == "create" and self.current_class in self.classes:
  555. node = _generate_component_create_functiondef(
  556. node, self.classes[self.current_class], self.type_hint_globals
  557. )
  558. else:
  559. if node.name.startswith("_") and node.name != "__call__":
  560. return None # remove private methods
  561. if node.body[-1] != ast.Expr(value=ast.Ellipsis()):
  562. # Blank out the function body for public functions.
  563. node.body = [ast.Expr(value=ast.Ellipsis())]
  564. return node
  565. def visit_Assign(self, node: ast.Assign) -> ast.Assign | None:
  566. """Remove non-annotated assignment statements.
  567. Args:
  568. node: The Assign node to visit.
  569. Returns:
  570. The modified Assign node (or None).
  571. """
  572. # Special case for assignments to `typing.Any` as fallback.
  573. if (
  574. node.value is not None
  575. and isinstance(node.value, ast.Name)
  576. and node.value.id == "Any"
  577. ):
  578. return node
  579. if self._current_class_is_component():
  580. # Remove annotated assignments in Component classes (props)
  581. return None
  582. return node
  583. def visit_AnnAssign(self, node: ast.AnnAssign) -> ast.AnnAssign | None:
  584. """Visit an AnnAssign node (Annotated assignment).
  585. Remove private target and remove the assignment value in the stub.
  586. Args:
  587. node: The AnnAssign node to visit.
  588. Returns:
  589. The modified AnnAssign node (or None).
  590. """
  591. # skip ClassVars
  592. if (
  593. isinstance(node.annotation, ast.Subscript)
  594. and isinstance(node.annotation.value, ast.Name)
  595. and node.annotation.value.id == "ClassVar"
  596. ):
  597. return node
  598. if isinstance(node.target, ast.Name) and node.target.id.startswith("_"):
  599. return None
  600. if self.current_class in self.classes:
  601. # Remove annotated assignments in Component classes (props)
  602. return None
  603. # Blank out assignments in type stubs.
  604. node.value = None
  605. return node
  606. class PyiGenerator:
  607. """A .pyi file generator that will scan all defined Component in Reflex and
  608. generate the approriate stub.
  609. """
  610. modules: list = []
  611. root: str = ""
  612. current_module: Any = {}
  613. def _write_pyi_file(self, module_path: Path, source: str):
  614. relpath = str(_relative_to_pwd(module_path)).replace("\\", "/")
  615. pyi_content = [
  616. f'"""Stub file for {relpath}"""',
  617. "# ------------------- DO NOT EDIT ----------------------",
  618. "# This file was generated by `reflex/utils/pyi_generator.py`!",
  619. "# ------------------------------------------------------",
  620. "",
  621. ]
  622. if black is not None:
  623. for formatted_line in black.format_file_contents(
  624. src_contents=source,
  625. fast=True,
  626. mode=black.mode.Mode(is_pyi=True),
  627. ).splitlines():
  628. # Bit of a hack here, since the AST cannot represent comments.
  629. if "def create(" in formatted_line:
  630. pyi_content.append(formatted_line + " # type: ignore")
  631. elif "Figure" in formatted_line:
  632. pyi_content.append(formatted_line + " # type: ignore")
  633. else:
  634. pyi_content.append(formatted_line)
  635. pyi_content.append("") # add empty line at the end for formatting
  636. else:
  637. pyi_content = source.splitlines()
  638. pyi_path = module_path.with_suffix(".pyi")
  639. pyi_path.write_text("\n".join(pyi_content))
  640. logger.info(f"Wrote {relpath}")
  641. def _scan_file(self, module_path: Path):
  642. module_import = (
  643. _relative_to_pwd(module_path)
  644. .with_suffix("")
  645. .as_posix()
  646. .replace("/", ".")
  647. .replace("\\", ".")
  648. )
  649. module = importlib.import_module(module_import)
  650. logger.debug(f"Read {module_path}")
  651. class_names = {
  652. name: obj
  653. for name, obj in vars(module).items()
  654. if inspect.isclass(obj)
  655. and (issubclass(obj, Component) or issubclass(obj, SimpleNamespace))
  656. and obj != Component
  657. and inspect.getmodule(obj) == module
  658. }
  659. if not class_names:
  660. return
  661. new_tree = StubGenerator(module, class_names).visit(
  662. ast.parse(inspect.getsource(module))
  663. )
  664. self._write_pyi_file(module_path, ast.unparse(new_tree))
  665. def _scan_files_multiprocess(self, files: list[Path]):
  666. with Pool(processes=cpu_count()) as pool:
  667. pool.map(self._scan_file, files)
  668. def _scan_files(self, files: list[Path]):
  669. for file in files:
  670. self._scan_file(file)
  671. def scan_all(self, targets, changed_files: list[Path] | None = None):
  672. """Scan all targets for class inheriting Component and generate the .pyi files.
  673. Args:
  674. targets: the list of file/folders to scan.
  675. changed_files (optional): the list of changed files since the last run.
  676. """
  677. file_targets = []
  678. for target in targets:
  679. target_path = Path(target)
  680. if (
  681. target_path.is_file()
  682. and target_path.suffix == ".py"
  683. and target_path.name not in EXCLUDED_FILES
  684. ):
  685. file_targets.append(target_path)
  686. continue
  687. if not target_path.is_dir():
  688. continue
  689. for file_path in _walk_files(target_path):
  690. relative = _relative_to_pwd(file_path)
  691. if relative.name in EXCLUDED_FILES or file_path.suffix != ".py":
  692. continue
  693. if (
  694. changed_files is not None
  695. and _relative_to_pwd(file_path) not in changed_files
  696. ):
  697. continue
  698. file_targets.append(file_path)
  699. # check if pyi changed but not the source
  700. if changed_files is not None:
  701. for changed_file in changed_files:
  702. if changed_file.suffix != ".pyi":
  703. continue
  704. py_file_path = changed_file.with_suffix(".py")
  705. if not py_file_path.exists() and changed_file.exists():
  706. changed_file.unlink()
  707. if py_file_path in file_targets:
  708. continue
  709. subprocess.run(["git", "checkout", changed_file])
  710. if cpu_count() == 1 or len(file_targets) < 5:
  711. self._scan_files(file_targets)
  712. else:
  713. self._scan_files_multiprocess(file_targets)
  714. def generate_init():
  715. """Generate a pyi file for the main __init__.py."""
  716. from reflex import _MAPPING # type: ignore
  717. imports = [
  718. f"from {path if mod != path.rsplit('.')[-1] or mod == 'page' else '.'.join(path.rsplit('.')[:-1])} import {mod} as {mod}"
  719. for mod, path in _MAPPING.items()
  720. ]
  721. imports.append("")
  722. with contextlib.suppress(Exception):
  723. INIT_FILE.write_text("\n".join(imports))