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