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
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 )
158 ops.append(desc)
159 return desc
160
161
162 def function_op(
163 name: str,
164 arg_types: list[RType],
165 return_type: RType,
166 c_function_name: str,
167 error_kind: int,
168 var_arg_type: RType | None = None,
169 truncated_type: RType | None = None,
170 ordering: list[int] | None = None,
171 extra_int_constants: list[tuple[int, RType]] | None = None,
172 steals: StealsDescription = False,
173 is_borrowed: bool = False,
174 priority: int = 1,
175 experimental: bool = False,
176 dependencies: list[Dependency] | None = None,
177 ) -> PrimitiveDescription:
178 """Define a C function call op that replaces a function call.
179
180 This will be automatically generated by matching against the AST.
181
182 Most arguments are similar to method_op().
183
184 Args:
185 name: full name of the function
186 arg_types: positional argument types for which this applies
187 """
188 if extra_int_constants is None:
189 extra_int_constants = []
190 ops = function_ops.setdefault(name, [])
191 desc = PrimitiveDescription(
192 name,
193 arg_types,
194 return_type,
195 var_arg_type=var_arg_type,
196 truncated_type=truncated_type,
197 c_function_name=c_function_name,
198 error_kind=error_kind,
199 steals=steals,
200 is_borrowed=is_borrowed,
201 ordering=ordering,
202 extra_int_constants=extra_int_constants,
203 priority=priority,
204 is_pure=False,
205 experimental=experimental,
206 dependencies=dependencies,
207 )
208 ops.append(desc)
209 return desc
210
211
212 def binary_op(
213 name: str,
214 arg_types: list[RType],
215 return_type: RType,
216 error_kind: int,
217 c_function_name: str | None = None,
218 primitive_name: str | None = None,
219 var_arg_type: RType | None = None,
220 truncated_type: RType | None = None,
221 ordering: list[int] | None = None,
222 extra_int_constants: list[tuple[int, RType]] | None = None,
223 steals: StealsDescription = False,
224 is_borrowed: bool = False,
225 priority: int = 1,
226 dependencies: list[Dependency] | None = None,
227 ) -> PrimitiveDescription:
228 """Define a c function call op for a binary operation.
229
230 This will be automatically generated by matching against the AST.
231
232 Most arguments are similar to method_op(), but exactly two argument types
233 are expected.
234 """
235 assert c_function_name is not None or primitive_name is not None
236 assert not (c_function_name is not None and primitive_name is not None)
237 if extra_int_constants is None:
238 extra_int_constants = []
239 ops = binary_ops.setdefault(name, [])
240 desc = PrimitiveDescription(
241 name=primitive_name or name,
242 arg_types=arg_types,
243 return_type=return_type,
244 var_arg_type=var_arg_type,
245 truncated_type=truncated_type,
246 c_function_name=c_function_name,
247 error_kind=error_kind,
248 steals=steals,
249 is_borrowed=is_borrowed,
250 ordering=ordering,
251 extra_int_constants=extra_int_constants,
252 priority=priority,
253 is_pure=False,
254 experimental=False,
255 dependencies=dependencies,
256 )
257 ops.append(desc)
258 return desc
259
260
261 def custom_op(
262 arg_types: list[RType],
263 return_type: RType,
264 c_function_name: str,
265 error_kind: int,
266 var_arg_type: RType | None = None,
267 truncated_type: RType | None = None,
268 ordering: list[int] | None = None,
269 extra_int_constants: list[tuple[int, RType]] | None = None,
270 steals: StealsDescription = False,
271 is_borrowed: bool = False,
272 *,
273 is_pure: bool = False,
274 returns_null: bool = False,
275 ) -> CFunctionDescription:
276 """Create a one-off CallC op that can't be automatically generated from the AST.
277
278 Most arguments are similar to method_op().
279 """
280 if extra_int_constants is None:
281 extra_int_constants = []
282 return CFunctionDescription(
283 "<custom>",
284 arg_types,
285 return_type,
286 var_arg_type,
287 truncated_type,
288 c_function_name,
289 error_kind,
290 steals,
291 is_borrowed,
292 ordering,
293 extra_int_constants,
294 0,
295 is_pure=is_pure,
296 returns_null=returns_null,
297 dependencies=None,
298 )
299
300
301 def custom_primitive_op(
302 name: str,
303 arg_types: list[RType],
304 return_type: RType,
305 error_kind: int,
306 c_function_name: str | None = None,
307 var_arg_type: RType | None = None,
308 truncated_type: RType | None = None,
309 ordering: list[int] | None = None,
310 extra_int_constants: list[tuple[int, RType]] | None = None,
311 steals: StealsDescription = False,
312 is_borrowed: bool = False,
313 is_pure: bool = False,
314 experimental: bool = False,
315 dependencies: list[Dependency] | None = None,
316 ) -> PrimitiveDescription:
317 """Define a primitive op that can't be automatically generated based on the AST.
318
319 Most arguments are similar to method_op().
320 """
321 if extra_int_constants is None:
322 extra_int_constants = []
323 return PrimitiveDescription(
324 name=name,
325 arg_types=arg_types,
326 return_type=return_type,
327 var_arg_type=var_arg_type,
328 truncated_type=truncated_type,
329 c_function_name=c_function_name,
330 error_kind=error_kind,
331 steals=steals,
332 is_borrowed=is_borrowed,
333 ordering=ordering,
334 extra_int_constants=extra_int_constants,
335 priority=0,
336 is_pure=is_pure,
337 experimental=experimental,
338 dependencies=dependencies,
339 )
340
341
342 def unary_op(
343 name: str,
344 arg_type: RType,
345 return_type: RType,
346 c_function_name: str,
347 error_kind: int,
348 truncated_type: RType | None = None,
349 ordering: list[int] | None = None,
350 extra_int_constants: list[tuple[int, RType]] | None = None,
351 steals: StealsDescription = False,
352 is_borrowed: bool = False,
353 priority: int = 1,
354 is_pure: bool = False,
355 dependencies: list[Dependency] | None = None,
356 ) -> PrimitiveDescription:
357 """Define a primitive op for an unary operation.
358
359 This will be automatically generated by matching against the AST.
360
361 Most arguments are similar to method_op(), but exactly one argument type
362 is expected.
363 """
364 if extra_int_constants is None:
365 extra_int_constants = []
366 ops = unary_ops.setdefault(name, [])
367 desc = PrimitiveDescription(
368 name,
369 [arg_type],
370 return_type,
371 var_arg_type=None,
372 truncated_type=truncated_type,
373 c_function_name=c_function_name,
374 error_kind=error_kind,
375 steals=steals,
376 is_borrowed=is_borrowed,
377 ordering=ordering,
378 extra_int_constants=extra_int_constants,
379 priority=priority,
380 is_pure=is_pure,
381 experimental=False,
382 dependencies=dependencies,
383 )
384 ops.append(desc)
385 return desc
386
387
388 def load_address_op(name: str, type: RType, src: str) -> LoadAddressDescription:
389 assert name not in builtin_names, "already defined: %s" % name
390 builtin_names[name] = (type, src)
391 return LoadAddressDescription(name, type, src)
392
393
394 def load_global_op(name: str, type: RType, src: str) -> LoadAddressDescription:
395 assert name not in global_names, "already defined: %s" % name
396 global_names[name] = (type, src)
397 return LoadAddressDescription(name, type, src)
398
399
400 # Import various modules that set up global state.
401 import mypyc.primitives.bytearray_ops
402 import mypyc.primitives.bytes_ops
403 import mypyc.primitives.dict_ops
404 import mypyc.primitives.float_ops
405 import mypyc.primitives.int_ops
406 import mypyc.primitives.librt_random_ops
407 import mypyc.primitives.librt_strings_ops
408 import mypyc.primitives.librt_time_ops
409 import mypyc.primitives.librt_vecs_ops
410 import mypyc.primitives.list_ops
411 import mypyc.primitives.misc_ops
412 import mypyc.primitives.str_ops
413 import mypyc.primitives.tuple_ops
414 import mypyc.primitives.weakref_ops # noqa: F401