Debian Codegraph @

gi/_signature.py

raw
1 # Copyright (C) 2024 James Henstridge <[email protected]>
2 #
3 # _signature.py: callable signature generator for gi.
4 #
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License, or (at your option) any later version.
9 #
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
18 # USA
19
20 from importlib import import_module
21 from inspect import Parameter, Signature
22 from typing import Any, Optional
23 from collections.abc import Callable
24
25 from ._error import GError
26 from ._gi import (
27 VFuncInfo,
28 FunctionInfo,
29 CallableInfo,
30 CallbackInfo,
31 Direction,
32 GType,
33 TypeInfo,
34 TypeTag,
35 )
36
37 __all__ = ["generate_signature"]
38
39
40 tag_pytype = {
41 TypeTag.BOOLEAN: bool,
42 TypeTag.INT8: int,
43 TypeTag.UINT8: int,
44 TypeTag.INT16: int,
45 TypeTag.UINT16: int,
46 TypeTag.INT32: int,
47 TypeTag.UINT32: int,
48 TypeTag.INT64: int,
49 TypeTag.UINT64: int,
50 TypeTag.FLOAT: float,
51 TypeTag.DOUBLE: float,
52 TypeTag.GTYPE: GType,
53 TypeTag.UTF8: str,
54 TypeTag.FILENAME: str,
55 TypeTag.UNICHAR: str,
56 TypeTag.ERROR: GError,
57 }
58
59 list_tag_types = {TypeTag.GLIST, TypeTag.GSLIST, TypeTag.ARRAY}
60
61
62 def get_pytype(gi_type: TypeInfo) -> object:
63 tag = gi_type.get_tag()
64 if pytype := tag_pytype.get(tag):
65 return pytype
66 if tag == TypeTag.VOID:
67 if gi_type.is_pointer():
68 return Any
69 return None
70 if tag in list_tag_types:
71 value_type = get_pytype(gi_type.get_param_type(0))
72 if value_type is Parameter.empty:
73 return list
74 return list[value_type]
75 if tag == TypeTag.GHASH:
76 key_type = get_pytype(gi_type.get_param_type(0))
77 value_type = get_pytype(gi_type.get_param_type(1))
78 if key_type is Parameter.empty or value_type is Parameter.empty:
79 return dict
80 return dict[key_type, value_type]
81 if tag == TypeTag.INTERFACE:
82 info = gi_type.get_interface()
83 if isinstance(info, CallbackInfo):
84 sig = generate_signature(info)
85 return Callable[
86 [param.annotation for param in sig.parameters.values()],
87 sig.return_annotation,
88 ]
89 info_name = info.get_name()
90 if not info_name:
91 return gi_type.get_tag_as_string()
92 info_namespace = info.get_namespace()
93 module = import_module(f"gi.repository.{info_namespace}")
94 try:
95 return getattr(module, info_name)
96 except NotImplementedError:
97 return f"{info_namespace}.{info_name}"
98 else:
99 return gi_type.get_tag_as_string()
100
101
102 def generate_signature(info: CallableInfo) -> Signature:
103 args = info.get_arguments()
104 arg_names = {arg.get_name() for arg in args}
105
106 def unique(name):
107 while name in arg_names:
108 name += "_"
109 arg_names.add(name)
110 return name
111
112 params = []
113 if isinstance(info, FunctionInfo):
114 if info.is_constructor():
115 params.append(Parameter(unique("cls"), Parameter.POSITIONAL_OR_KEYWORD))
116 elif info.is_method():
117 params.append(Parameter(unique("self"), Parameter.POSITIONAL_OR_KEYWORD))
118 elif isinstance(info, VFuncInfo):
119 params.append(Parameter(unique("type"), Parameter.POSITIONAL_OR_KEYWORD))
120 params.append(Parameter(unique("self"), Parameter.POSITIONAL_OR_KEYWORD))
121
122 # Build lists of indices prior to adding the docs because it is possible
123 # the index retrieved comes before input arguments being used.
124 ignore_indices = {info.get_return_type().get_array_length_index()}
125 user_data_indices = set()
126 for arg in args:
127 ignore_indices.add(arg.get_destroy_index())
128 ignore_indices.add(arg.get_type_info().get_array_length_index())
129 user_data_indices.add(arg.get_closure_index())
130
131 for i, arg in enumerate(args):
132 if arg.get_direction() == Direction.OUT:
133 continue # skip exclusively output args
134 if i in ignore_indices:
135 continue
136
137 default = Parameter.empty
138 annotation = get_pytype(arg.get_type_info())
139 if arg.may_be_null() or i in user_data_indices:
140 # allow-none or user_data from a closure
141 default = None
142 if annotation is not Parameter.empty and annotation is not Any:
143 annotation = Optional[annotation] # noqa: UP045
144 elif arg.is_optional():
145 # TODO: Can we retrieve the default value?
146 default = ...
147
148 params.append(
149 Parameter(
150 arg.get_name(),
151 Parameter.POSITIONAL_OR_KEYWORD,
152 default=default,
153 annotation=annotation,
154 )
155 )
156
157 # Remove defaults from params after the last required parameter.
158 last_required = max(
159 (i for (i, param) in enumerate(params) if param.default is Parameter.empty),
160 default=0,
161 )
162 for i, param in enumerate(params):
163 if i >= last_required:
164 break
165 if param.default is not Parameter.empty:
166 params[i] = param.replace(default=Parameter.empty)
167
168 return_annotation = get_pytype(info.get_return_type())
169 if info.may_return_null():
170 return_annotation = Optional[return_annotation] # noqa: UP045
171
172 out_args = []
173 for i, arg in enumerate(args):
174 if arg.get_direction() == Direction.IN:
175 continue # skip exclusively input args
176 if i in ignore_indices:
177 continue
178 annotation = get_pytype(arg.get_type_info())
179 if arg.may_be_null() and annotation is not Parameter.empty:
180 annotation = Optional[annotation] # noqa: UP045
181 out_args.append(annotation)
182
183 if return_annotation is not None:
184 out_args.insert(0, return_annotation)
185 if len(out_args) > 1:
186 return_annotation = tuple[tuple(out_args)]
187 elif len(out_args) == 1:
188 return_annotation = out_args[0]
189
190 return Signature(params, return_annotation=return_annotation)