Debian Codegraph @

mypyc/ir/func_ir.py

raw
1 """Intermediate representation of functions."""
2
3 from __future__ import annotations
4
5 import inspect
6 from collections.abc import Sequence
7 from typing import Final
8
9 from mypy.nodes import ARG_POS, ArgKind, Block, FuncDef
10 from mypyc.common import BITMAP_BITS, JsonDict, bitmap_name, get_id_from_name, short_id_from_name
11 from mypyc.ir.ops import (
12 Assign,
13 AssignMulti,
14 BasicBlock,
15 Box,
16 ControlOp,
17 DeserMaps,
18 Float,
19 Integer,
20 LoadAddress,
21 LoadLiteral,
22 Register,
23 TupleSet,
24 Value,
25 )
26 from mypyc.ir.rtypes import (
27 RType,
28 bitmap_rprimitive,
29 deserialize_type,
30 is_bool_rprimitive,
31 is_none_rprimitive,
32 )
33 from mypyc.namegen import NameGenerator
34
35
36 class RuntimeArg:
37 """Description of a function argument in IR.
38
39 Argument kind is one of ARG_* constants defined in mypy.nodes.
40 """
41
42 def __init__(
43 self, name: str, typ: RType, kind: ArgKind = ARG_POS, pos_only: bool = False
44 ) -> None:
45 self.name = name
46 self.type = typ
47 self.kind = kind
48 self.pos_only = pos_only
49
50 @property
51 def optional(self) -> bool:
52 return self.kind.is_optional()
53
54 def __repr__(self) -> str:
55 return "RuntimeArg(name={}, type={}, optional={!r}, pos_only={!r})".format(
56 self.name, self.type, self.optional, self.pos_only
57 )
58
59 def serialize(self) -> JsonDict:
60 return {
61 "name": self.name,
62 "type": self.type.serialize(),
63 "kind": int(self.kind.value),
64 "pos_only": self.pos_only,
65 }
66
67 @classmethod
68 def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RuntimeArg:
69 return RuntimeArg(
70 data["name"],
71 deserialize_type(data["type"], ctx),
72 ArgKind(data["kind"]),
73 data["pos_only"],
74 )
75
76
77 class FuncSignature:
78 """Signature of a function in IR."""
79
80 # TODO: Track if method?
81
82 def __init__(self, args: Sequence[RuntimeArg], ret_type: RType) -> None:
83 self.args = tuple(args)
84 self.ret_type = ret_type
85 # Bitmap arguments are use to mark default values for arguments that
86 # have types with overlapping error values.
87 self.num_bitmap_args = num_bitmap_args(self.args)
88 if self.num_bitmap_args:
89 extra = [
90 RuntimeArg(bitmap_name(i), bitmap_rprimitive, pos_only=True)
91 for i in range(self.num_bitmap_args)
92 ]
93 self.args = self.args + tuple(reversed(extra))
94
95 def real_args(self) -> tuple[RuntimeArg, ...]:
96 """Return arguments without any synthetic bitmap arguments."""
97 if self.num_bitmap_args:
98 return self.args[: -self.num_bitmap_args]
99 return self.args
100
101 def bound_sig(self) -> FuncSignature:
102 if self.num_bitmap_args:
103 return FuncSignature(self.args[1 : -self.num_bitmap_args], self.ret_type)
104 else:
105 return FuncSignature(self.args[1:], self.ret_type)
106
107 def __repr__(self) -> str:
108 return f"FuncSignature(args={self.args!r}, ret={self.ret_type!r})"
109
110 def serialize(self) -> JsonDict:
111 if self.num_bitmap_args:
112 args = self.args[: -self.num_bitmap_args]
113 else:
114 args = self.args
115 return {"args": [t.serialize() for t in args], "ret_type": self.ret_type.serialize()}
116
117 @classmethod
118 def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> FuncSignature:
119 return FuncSignature(
120 [RuntimeArg.deserialize(arg, ctx) for arg in data["args"]],
121 deserialize_type(data["ret_type"], ctx),
122 )
123
124
125 def num_bitmap_args(args: tuple[RuntimeArg, ...]) -> int:
126 n = 0
127 for arg in args:
128 if arg.type.error_overlap and arg.kind.is_optional():
129 n += 1
130 return (n + (BITMAP_BITS - 1)) // BITMAP_BITS
131
132
133 FUNC_NORMAL: Final = 0
134 FUNC_STATICMETHOD: Final = 1
135 FUNC_CLASSMETHOD: Final = 2
136
137
138 class FuncDecl:
139 """Declaration of a function in IR (without body or implementation).
140
141 A function can be a regular module-level function, a method, a
142 static method, a class method, or a property getter/setter.
143 """
144
145 def __init__(
146 self,
147 name: str,
148 class_name: str | None,
149 module_name: str,
150 sig: FuncSignature,
151 kind: int = FUNC_NORMAL,
152 *,
153 is_prop_setter: bool = False,
154 is_prop_getter: bool = False,
155 is_generator: bool = False,
156 is_coroutine: bool = False,
157 implicit: bool = False,
158 internal: bool = False,
159 ) -> None:
160 self.name = name
161 self.class_name = class_name
162 self.module_name = module_name
163 self.sig = sig
164 self.kind = kind
165 self.is_prop_setter = is_prop_setter
166 self.is_prop_getter = is_prop_getter
167 self.is_generator = is_generator
168 self.is_coroutine = is_coroutine
169 if class_name is None:
170 self.bound_sig: FuncSignature | None = None
171 else:
172 if kind == FUNC_STATICMETHOD:
173 self.bound_sig = sig
174 else:
175 self.bound_sig = sig.bound_sig()
176
177 # If True, not present in the mypy AST and must be synthesized during irbuild
178 # Currently only supported for property getters/setters
179 self.implicit = implicit
180
181 # If True, only direct C level calls are supported (no wrapper function)
182 self.internal = internal
183
184 # This is optional because this will be set to the line number when the corresponding
185 # FuncIR is created
186 self._line: int | None = None
187
188 @property
189 def line(self) -> int:
190 assert self._line is not None
191 return self._line
192
193 @line.setter
194 def line(self, line: int) -> None:
195 self._line = line
196
197 @property
198 def id(self) -> str:
199 assert self.line is not None
200 return get_id_from_name(self.name, self.fullname, self.line)
201
202 @staticmethod
203 def compute_shortname(class_name: str | None, name: str) -> str:
204 return class_name + "." + name if class_name else name
205
206 @property
207 def shortname(self) -> str:
208 return FuncDecl.compute_shortname(self.class_name, self.name)
209
210 @property
211 def fullname(self) -> str:
212 return self.module_name + "." + self.shortname
213
214 def cname(self, names: NameGenerator) -> str:
215 partial_name = short_id_from_name(self.name, self.shortname, self._line)
216 return names.private_name(self.module_name, partial_name)
217
218 def serialize(self) -> JsonDict:
219 return {
220 "name": self.name,
221 "class_name": self.class_name,
222 "module_name": self.module_name,
223 "sig": self.sig.serialize(),
224 "kind": self.kind,
225 "is_prop_setter": self.is_prop_setter,
226 "is_prop_getter": self.is_prop_getter,
227 "is_generator": self.is_generator,
228 "is_coroutine": self.is_coroutine,
229 "implicit": self.implicit,
230 "internal": self.internal,
231 }
232
233 # TODO: move this to FuncIR?
234 @staticmethod
235 def get_id_from_json(func_ir: JsonDict) -> str:
236 """Get the id from the serialized FuncIR associated with this FuncDecl"""
237 decl = func_ir["decl"]
238 shortname = FuncDecl.compute_shortname(decl["class_name"], decl["name"])
239 fullname = decl["module_name"] + "." + shortname
240 return get_id_from_name(decl["name"], fullname, func_ir["line"])
241
242 @classmethod
243 def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> FuncDecl:
244 return FuncDecl(
245 data["name"],
246 data["class_name"],
247 data["module_name"],
248 FuncSignature.deserialize(data["sig"], ctx),
249 data["kind"],
250 is_prop_setter=data["is_prop_setter"],
251 is_prop_getter=data["is_prop_getter"],
252 is_generator=data["is_generator"],
253 is_coroutine=data["is_coroutine"],
254 implicit=data["implicit"],
255 internal=data["internal"],
256 )
257
258
259 class FuncIR:
260 """Intermediate representation of a function with contextual information.
261
262 Unlike FuncDecl, this includes the IR of the body (basic blocks).
263 """
264
265 def __init__(
266 self,
267 decl: FuncDecl,
268 arg_regs: list[Register],
269 blocks: list[BasicBlock],
270 line: int = -1,
271 traceback_name: str | None = None,
272 ) -> None:
273 # Declaration of the function, including the signature
274 self.decl = decl
275 # Registers for all the arguments to the function
276 self.arg_regs = arg_regs
277 # Body of the function
278 self.blocks = blocks
279 self.decl.line = line
280 # The name that should be displayed for tracebacks that
281 # include this function. Function will be omitted from
282 # tracebacks if None.
283 self.traceback_name = traceback_name
284
285 @property
286 def line(self) -> int:
287 return self.decl.line
288
289 @property
290 def args(self) -> Sequence[RuntimeArg]:
291 return self.decl.sig.args
292
293 @property
294 def ret_type(self) -> RType:
295 return self.decl.sig.ret_type
296
297 @property
298 def class_name(self) -> str | None:
299 return self.decl.class_name
300
301 @property
302 def sig(self) -> FuncSignature:
303 return self.decl.sig
304
305 @property
306 def name(self) -> str:
307 return self.decl.name
308
309 @property
310 def fullname(self) -> str:
311 return self.decl.fullname
312
313 @property
314 def id(self) -> str:
315 return self.decl.id
316
317 @property
318 def internal(self) -> bool:
319 return self.decl.internal
320
321 def cname(self, names: NameGenerator) -> str:
322 return self.decl.cname(names)
323
324 def __repr__(self) -> str:
325 if self.class_name:
326 return f"<FuncIR {self.class_name}.{self.name}>"
327 else:
328 return f"<FuncIR {self.name}>"
329
330 def serialize(self) -> JsonDict:
331 # We don't include blocks in the serialized version
332 return {
333 "decl": self.decl.serialize(),
334 "line": self.line,
335 "traceback_name": self.traceback_name,
336 }
337
338 @classmethod
339 def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> FuncIR:
340 return FuncIR(
341 FuncDecl.deserialize(data["decl"], ctx), [], [], data["line"], data["traceback_name"]
342 )
343
344
345 INVALID_FUNC_DEF: Final = FuncDef("<INVALID_FUNC_DEF>", [], Block([]))
346
347
348 def all_values(args: list[Register], blocks: list[BasicBlock]) -> list[Value]:
349 """Return the set of all values that may be initialized in the blocks.
350
351 This omits registers that are only read.
352 """
353 values: list[Value] = list(args)
354 seen_registers = set(args)
355
356 for block in blocks:
357 for op in block.ops:
358 if not isinstance(op, ControlOp):
359 if isinstance(op, (Assign, AssignMulti)):
360 if op.dest not in seen_registers:
361 values.append(op.dest)
362 seen_registers.add(op.dest)
363 elif op.is_void:
364 continue
365 else:
366 # If we take the address of a register, it might get initialized.
367 if (
368 isinstance(op, LoadAddress)
369 and isinstance(op.src, Register)
370 and op.src not in seen_registers
371 ):
372 values.append(op.src)
373 seen_registers.add(op.src)
374 values.append(op)
375
376 return values
377
378
379 def all_values_full(args: list[Register], blocks: list[BasicBlock]) -> list[Value]:
380 """Return set of all values that are initialized or accessed."""
381 values: list[Value] = list(args)
382 seen_registers = set(args)
383
384 for block in blocks:
385 for op in block.ops:
386 for source in op.sources():
387 # Look for uninitialized registers that are accessed. Ignore
388 # non-registers since we don't allow ops outside basic blocks.
389 if isinstance(source, Register) and source not in seen_registers:
390 values.append(source)
391 seen_registers.add(source)
392 if not isinstance(op, ControlOp):
393 if isinstance(op, (Assign, AssignMulti)):
394 if op.dest not in seen_registers:
395 values.append(op.dest)
396 seen_registers.add(op.dest)
397 elif op.is_void:
398 continue
399 else:
400 values.append(op)
401
402 return values
403
404
405 _ARG_KIND_TO_INSPECT: Final = {
406 ArgKind.ARG_POS: inspect.Parameter.POSITIONAL_OR_KEYWORD,
407 ArgKind.ARG_OPT: inspect.Parameter.POSITIONAL_OR_KEYWORD,
408 ArgKind.ARG_STAR: inspect.Parameter.VAR_POSITIONAL,
409 ArgKind.ARG_NAMED: inspect.Parameter.KEYWORD_ONLY,
410 ArgKind.ARG_STAR2: inspect.Parameter.VAR_KEYWORD,
411 ArgKind.ARG_NAMED_OPT: inspect.Parameter.KEYWORD_ONLY,
412 }
413
414 # Sentinel indicating a value that cannot be represented in a text signature.
415 _NOT_REPRESENTABLE = object()
416
417
418 def get_text_signature(fn: FuncIR, *, bound: bool = False) -> str | None:
419 """Return a text signature in CPython's internal doc format, or None
420 if the function's signature cannot be represented.
421 """
422 parameters = []
423 mark_self = (fn.class_name is not None) and (fn.decl.kind != FUNC_STATICMETHOD) and not bound
424 sig = fn.decl.bound_sig if bound and fn.decl.bound_sig is not None else fn.decl.sig
425 # Pre-scan for end of positional-only parameters.
426 # This is needed to handle signatures like 'def foo(self, __x)', where mypy
427 # currently sees 'self' as being positional-or-keyword and '__x' as positional-only.
428 pos_only_idx = -1
429 for idx, arg in enumerate(sig.args):
430 if arg.pos_only and arg.kind in (ArgKind.ARG_POS, ArgKind.ARG_OPT):
431 pos_only_idx = idx
432 for idx, arg in enumerate(sig.args):
433 if arg.name.startswith(("__bitmap", "__mypyc")):
434 continue
435 kind = (
436 inspect.Parameter.POSITIONAL_ONLY
437 if idx <= pos_only_idx
438 else _ARG_KIND_TO_INSPECT[arg.kind]
439 )
440 default: object = inspect.Parameter.empty
441 if arg.optional:
442 default = _find_default_argument(arg.name, fn.blocks)
443 if default is _NOT_REPRESENTABLE:
444 # This default argument cannot be represented in a __text_signature__
445 return None
446
447 curr_param = inspect.Parameter(arg.name, kind, default=default)
448 parameters.append(curr_param)
449 if mark_self:
450 # Parameter.__init__/Parameter.replace do not accept $
451 curr_param._name = f"${arg.name}" # type: ignore[attr-defined]
452 mark_self = False
453 return f"{fn.name}{inspect.Signature(parameters)}"
454
455
456 def _find_default_argument(name: str, blocks: list[BasicBlock]) -> object:
457 # Find assignment inserted by gen_arg_defaults. Assumed to be the first assignment.
458 for block in blocks:
459 for op in block.ops:
460 if isinstance(op, Assign) and op.dest.name == name:
461 return _extract_python_literal(op.src)
462 return _NOT_REPRESENTABLE
463
464
465 def _extract_python_literal(value: Value) -> object:
466 if isinstance(value, Integer):
467 if is_none_rprimitive(value.type):
468 return None
469 val = value.numeric_value()
470 if is_bool_rprimitive(value.type):
471 return bool(val)
472 return val
473 elif isinstance(value, Float):
474 return value.value
475 elif isinstance(value, LoadLiteral):
476 return value.value
477 elif isinstance(value, Box):
478 return _extract_python_literal(value.src)
479 elif isinstance(value, TupleSet):
480 items = tuple(_extract_python_literal(item) for item in value.items)
481 if any(itm is _NOT_REPRESENTABLE for itm in items):
482 return _NOT_REPRESENTABLE
483 return items
484 return _NOT_REPRESENTABLE