Debian Codegraph @

mypyc/primitives/registry.py

raw
1 """Utilities for defining primitive ops.
2
3 Most of the ops can be automatically generated by matching against AST
4 nodes and types. For example, a func_op is automatically generated when
5 a specific function is called with the specific positional argument
6 count and argument types.
7
8 Example op definition:
9
10 list_len_op = function_op(name='builtins.len',
11 arg_types=[list_rprimitive],
12 result_type=short_int_rprimitive,
13 error_kind=ERR_NEVER,
14 c_function_name="...")
15
16 This op is automatically generated for calls to len() with a single
17 list argument. The result type is short_int_rprimitive, and this
18 never raises an exception (ERR_NEVER). The function c_function_name is
19 called when generating C for this op. The op can also be manually generated
20 using "list_len_op". Ops that are only generated automatically don't need to
21 be assigned to a module attribute.
22
23 Ops defined with custom[_primitive]_op are only explicitly generated in
24 mypyc.irbuild and won't be generated automatically. They are always
25 assigned to a module attribute, as otherwise they won't be accessible.
26
27 The actual ops are defined in other submodules of this package, grouped
28 by category.
29
30 Most operations have fallback implementations that apply to all possible
31 arguments and types. For example, there are generic implementations of
32 arbitrary function and method calls, and binary operators. These generic
33 implementations are typically slower than specialized ones, but we tend
34 to rely on them for infrequently used ops. It's impractical to have
35 optimized implementations of all ops.
36 """
37
38 from __future__ import annotations
39
40 from typing import Final, NamedTuple
41
42 from mypyc.ir.deps import Dependency
43 from mypyc.ir.ops import PrimitiveDescription, StealsDescription
44 from mypyc.ir.rtypes import RType, RTypeVar
45
46 # Error kind for functions that return negative integer on exception. This
47 # is only used for primitives. We translate it away during IR building.
48 ERR_NEG_INT: Final = 10
49
50
51 class CFunctionDescription(NamedTuple):
52 name: str
53 arg_types: list[RType]
54 return_type: RType
55 var_arg_type: RType | None
56 truncated_type: RType | None
57 c_function_name: str
58 error_kind: int
59 steals: StealsDescription
60 is_borrowed: bool
61 ordering: list[int] | None
62 extra_int_constants: list[tuple[int, RType]]
63 priority: int
64 is_pure: bool
65 returns_null: bool
66 dependencies: list[Dependency] | None
67
68
69 # A description for C load operations including LoadGlobal and LoadAddress
70 class LoadAddressDescription(NamedTuple):
71 name: str
72 type: RType
73 src: str # name of the target to load
74
75
76 # Primitive ops for method call (such as 'str.join')
77 method_call_ops: dict[str, list[PrimitiveDescription]] = {}
78
79 # Primitive ops for top level function call (such as 'builtins.list')
80 function_ops: dict[str, list[PrimitiveDescription]] = {}
81
82 # Primitive ops for binary operations
83 binary_ops: dict[str, list[PrimitiveDescription]] = {}
84
85 # Primitive ops for unary ops
86 unary_ops: dict[str, list[PrimitiveDescription]] = {}
87
88 # Mapping of type name to (type, C value variable name).
89 builtin_names: dict[str, tuple[RType, str]] = {}
90
91 # Mapping of type name to (type, C pointer variable name).
92 global_names: dict[str, tuple[RType, str]] = {}
93
94
95 def method_op(
96 name: str,
97 arg_types: list[RType],
98 return_type: RType,
99 c_function_name: str,
100 error_kind: int,
101 var_arg_type: RType | None = None,
102 truncated_type: RType | None = None,
103 ordering: list[int] | None = None,
104 extra_int_constants: list[tuple[int, RType]] | None = None,
105 steals: StealsDescription = False,
106 is_borrowed: bool = False,
107 priority: int = 1,
108 is_pure: bool = False,
109 experimental: bool = False,
110 dependencies: list[Dependency] | None = None,
111 ) -> PrimitiveDescription:
112 """Define a c function call op that replaces a method call.
113
114 This will be automatically generated by matching against the AST.
115
116 Args:
117 name: short name of the method (for example, 'append')
118 arg_types: argument types; the receiver is always the first argument
119 return_type: type of the return value. Use void_rtype to represent void.
120 c_function_name: name of the C function to call
121 error_kind: how errors are represented in the result (one of ERR_*)
122 var_arg_type: type of all variable arguments
123 truncated_type: type to truncated to(See Truncate for info)
124 if it's defined both return_type and it should be non-referenced
125 integer types or bool type
126 ordering: optional ordering of the arguments, if defined,
127 reorders the arguments accordingly.
128 should never be used together with var_arg_type.
129 all the other arguments(such as arg_types) are in the order
130 accepted by the python syntax(before reordering)
131 extra_int_constants: optional extra integer constants as the last arguments to a C call
132 steals: description of arguments that this steals (ref count wise)
133 is_borrowed: if True, returned value is borrowed (no need to decrease refcount)
134 priority: if multiple ops match, the one with the highest priority is picked
135 is_pure: if True, declare that the C function has no side effects, takes immutable
136 arguments, and never raises an exception
137 """
138 if extra_int_constants is None:
139 extra_int_constants = []
140 ops = method_call_ops.setdefault(name, [])
141 desc = PrimitiveDescription(
142 name,
143 arg_types,
144 return_type,
145 var_arg_type,
146 truncated_type,
147 c_function_name,
148 error_kind,
149 steals,
150 is_borrowed,
151 ordering,
152 extra_int_constants,
153 priority,
154 is_pure=is_pure,
155 experimental=experimental,
156 dependencies=dependencies,
157 type_params=None,
158 )
159 ops.append(desc)
160 return desc
161
162
163 def function_op(
164 name: str,
165 arg_types: list[RType],
166 return_type: RType,
167 c_function_name: str,
168 error_kind: int,
169 var_arg_type: RType | None = None,
170 truncated_type: RType | None = None,
171 ordering: list[int] | None = None,
172 extra_int_constants: list[tuple[int, RType]] | None = None,
173 steals: StealsDescription = False,
174 is_borrowed: bool = False,
175 priority: int = 1,
176 experimental: bool = False,
177 dependencies: list[Dependency] | None = None,
178 ) -> PrimitiveDescription:
179 """Define a C function call op that replaces a function call.
180
181 This will be automatically generated by matching against the AST.
182
183 Most arguments are similar to method_op().
184
185 Args:
186 name: full name of the function
187 arg_types: positional argument types for which this applies
188 """
189 if extra_int_constants is None:
190 extra_int_constants = []
191 ops = function_ops.setdefault(name, [])
192 desc = PrimitiveDescription(
193 name,
194 arg_types,
195 return_type,
196 var_arg_type=var_arg_type,
197 truncated_type=truncated_type,
198 c_function_name=c_function_name,
199 error_kind=error_kind,
200 steals=steals,
201 is_borrowed=is_borrowed,
202 ordering=ordering,
203 extra_int_constants=extra_int_constants,
204 priority=priority,
205 is_pure=False,
206 experimental=experimental,
207 dependencies=dependencies,
208 type_params=None,
209 )
210 ops.append(desc)
211 return desc
212
213
214 def binary_op(
215 name: str,
216 arg_types: list[RType],
217 return_type: RType,
218 error_kind: int,
219 c_function_name: str | None = None,
220 primitive_name: str | None = None,
221 var_arg_type: RType | None = None,
222 truncated_type: RType | None = None,
223 ordering: list[int] | None = None,
224 extra_int_constants: list[tuple[int, RType]] | None = None,
225 steals: StealsDescription = False,
226 is_borrowed: bool = False,
227 priority: int = 1,
228 dependencies: list[Dependency] | None = None,
229 ) -> PrimitiveDescription:
230 """Define a c function call op for a binary operation.
231
232 This will be automatically generated by matching against the AST.
233
234 Most arguments are similar to method_op(), but exactly two argument types
235 are expected.
236 """
237 assert c_function_name is not None or primitive_name is not None
238 assert not (c_function_name is not None and primitive_name is not None)
239 if extra_int_constants is None:
240 extra_int_constants = []
241 ops = binary_ops.setdefault(name, [])
242 desc = PrimitiveDescription(
243 name=primitive_name or name,
244 arg_types=arg_types,
245 return_type=return_type,
246 var_arg_type=var_arg_type,
247 truncated_type=truncated_type,
248 c_function_name=c_function_name,
249 error_kind=error_kind,
250 steals=steals,
251 is_borrowed=is_borrowed,
252 ordering=ordering,
253 extra_int_constants=extra_int_constants,
254 priority=priority,
255 is_pure=False,
256 experimental=False,
257 dependencies=dependencies,
258 type_params=None,
259 )
260 ops.append(desc)
261 return desc
262
263
264 def custom_op(
265 arg_types: list[RType],
266 return_type: RType,
267 c_function_name: str,
268 error_kind: int,
269 var_arg_type: RType | None = None,
270 truncated_type: RType | None = None,
271 ordering: list[int] | None = None,
272 extra_int_constants: list[tuple[int, RType]] | None = None,
273 steals: StealsDescription = False,
274 is_borrowed: bool = False,
275 *,
276 is_pure: bool = False,
277 returns_null: bool = False,
278 ) -> CFunctionDescription:
279 """Create a one-off CallC op that can't be automatically generated from the AST.
280
281 Most arguments are similar to method_op().
282 """
283 if extra_int_constants is None:
284 extra_int_constants = []
285 return CFunctionDescription(
286 "<custom>",
287 arg_types,
288 return_type,
289 var_arg_type,
290 truncated_type,
291 c_function_name,
292 error_kind,
293 steals,
294 is_borrowed,
295 ordering,
296 extra_int_constants,
297 0,
298 is_pure=is_pure,
299 returns_null=returns_null,
300 dependencies=None,
301 )
302
303
304 def custom_primitive_op(
305 name: str,
306 arg_types: list[RType],
307 return_type: RType,
308 error_kind: int,
309 c_function_name: str | None = None,
310 var_arg_type: RType | None = None,
311 truncated_type: RType | None = None,
312 ordering: list[int] | None = None,
313 extra_int_constants: list[tuple[int, RType]] | None = None,
314 steals: StealsDescription = False,
315 is_borrowed: bool = False,
316 is_pure: bool = False,
317 experimental: bool = False,
318 dependencies: list[Dependency] | None = None,
319 type_params: list[RTypeVar] | None = None,
320 ) -> PrimitiveDescription:
321 """Define a primitive op that can't be automatically generated based on the AST.
322
323 Most arguments are similar to method_op().
324 """
325 if extra_int_constants is None:
326 extra_int_constants = []
327 return PrimitiveDescription(
328 name=name,
329 arg_types=arg_types,
330 return_type=return_type,
331 var_arg_type=var_arg_type,
332 truncated_type=truncated_type,
333 c_function_name=c_function_name,
334 error_kind=error_kind,
335 steals=steals,
336 is_borrowed=is_borrowed,
337 ordering=ordering,
338 extra_int_constants=extra_int_constants,
339 priority=0,
340 is_pure=is_pure,
341 experimental=experimental,
342 dependencies=dependencies,
343 type_params=type_params,
344 )
345
346
347 def unary_op(
348 name: str,
349 arg_type: RType,
350 return_type: RType,
351 c_function_name: str,
352 error_kind: int,
353 truncated_type: RType | None = None,
354 ordering: list[int] | None = None,
355 extra_int_constants: list[tuple[int, RType]] | None = None,
356 steals: StealsDescription = False,
357 is_borrowed: bool = False,
358 priority: int = 1,
359 is_pure: bool = False,
360 dependencies: list[Dependency] | None = None,
361 ) -> PrimitiveDescription:
362 """Define a primitive op for an unary operation.
363
364 This will be automatically generated by matching against the AST.
365
366 Most arguments are similar to method_op(), but exactly one argument type
367 is expected.
368 """
369 if extra_int_constants is None:
370 extra_int_constants = []
371 ops = unary_ops.setdefault(name, [])
372 desc = PrimitiveDescription(
373 name,
374 [arg_type],
375 return_type,
376 var_arg_type=None,
377 truncated_type=truncated_type,
378 c_function_name=c_function_name,
379 error_kind=error_kind,
380 steals=steals,
381 is_borrowed=is_borrowed,
382 ordering=ordering,
383 extra_int_constants=extra_int_constants,
384 priority=priority,
385 is_pure=is_pure,
386 experimental=False,
387 dependencies=dependencies,
388 type_params=None,
389 )
390 ops.append(desc)
391 return desc
392
393
394 def load_address_op(name: str, type: RType, src: str) -> LoadAddressDescription:
395 assert name not in builtin_names, "already defined: %s" % name
396 builtin_names[name] = (type, src)
397 return LoadAddressDescription(name, type, src)
398
399
400 def load_global_op(name: str, type: RType, src: str) -> LoadAddressDescription:
401 assert name not in global_names, "already defined: %s" % name
402 global_names[name] = (type, src)
403 return LoadAddressDescription(name, type, src)
404
405
406 # Import various modules that set up global state.
407 import mypyc.primitives.bytearray_ops
408 import mypyc.primitives.bytes_ops
409 import mypyc.primitives.dict_ops
410 import mypyc.primitives.float_ops
411 import mypyc.primitives.int_ops
412 import mypyc.primitives.librt_random_ops
413 import mypyc.primitives.librt_strings_ops
414 import mypyc.primitives.librt_threading_ops
415 import mypyc.primitives.librt_time_ops
416 import mypyc.primitives.librt_vecs_ops
417 import mypyc.primitives.list_ops
418 import mypyc.primitives.misc_ops
419 import mypyc.primitives.str_ops
420 import mypyc.primitives.tuple_ops
421 import mypyc.primitives.weakref_ops # noqa: F401