Debian Codegraph @

mypyc/irbuild/util.py

raw
1 """Various utilities that don't depend on other modules in mypyc.irbuild."""
2
3 from __future__ import annotations
4
5 from typing import Any, Final, Literal, TypedDict
6 from typing_extensions import NotRequired
7
8 from mypy.nodes import (
9 ARG_NAMED,
10 ARG_NAMED_OPT,
11 ARG_OPT,
12 ARG_POS,
13 GDEF,
14 ArgKind,
15 AssignmentStmt,
16 BytesExpr,
17 CallExpr,
18 ClassDef,
19 Decorator,
20 Expression,
21 FloatExpr,
22 FuncDef,
23 IntExpr,
24 NameExpr,
25 OverloadedFuncDef,
26 RefExpr,
27 StrExpr,
28 TempNode,
29 TupleExpr,
30 UnaryExpr,
31 Var,
32 is_class_var,
33 )
34 from mypy.semanal import refers_to_fullname
35 from mypy.types import FINAL_DECORATOR_NAMES
36 from mypyc.errors import Errors
37 from mypyc.ir.class_ir import ClassIR
38 from mypyc.ir.rtypes import is_none_rprimitive, is_object_rprimitive, is_optional_type
39
40 MYPYC_ATTRS: Final[frozenset[MypycAttr]] = frozenset(
41 ["native_class", "allow_interpreted_subclasses", "serializable", "free_list_len", "acyclic"]
42 )
43
44 DATACLASS_DECORATORS: Final = frozenset(["dataclasses.dataclass", "attr.s", "attr.attrs"])
45
46
47 MypycAttr = Literal[
48 "native_class", "allow_interpreted_subclasses", "serializable", "free_list_len", "acyclic"
49 ]
50
51
52 class MypycAttrs(TypedDict):
53 native_class: NotRequired[bool]
54 allow_interpreted_subclasses: NotRequired[bool]
55 serializable: NotRequired[bool]
56 free_list_len: NotRequired[int]
57 acyclic: NotRequired[bool]
58
59
60 def is_final_decorator(d: Expression) -> bool:
61 return refers_to_fullname(d, FINAL_DECORATOR_NAMES)
62
63
64 def is_trait_decorator(d: Expression) -> bool:
65 return isinstance(d, RefExpr) and d.fullname == "mypy_extensions.trait"
66
67
68 def is_trait(cdef: ClassDef) -> bool:
69 return any(is_trait_decorator(d) for d in cdef.decorators) or cdef.info.is_protocol
70
71
72 def dataclass_decorator_type(d: Expression) -> str | None:
73 if isinstance(d, RefExpr) and d.fullname in DATACLASS_DECORATORS:
74 return d.fullname.split(".")[0]
75 elif (
76 isinstance(d, CallExpr)
77 and isinstance(d.callee, RefExpr)
78 and d.callee.fullname in DATACLASS_DECORATORS
79 ):
80 name = d.callee.fullname.split(".")[0]
81 if name == "attr" and "auto_attribs" in d.arg_names:
82 # Note: the mypy attrs plugin checks that the value of auto_attribs is
83 # not computed at runtime, so we don't need to perform that check here
84 auto = d.args[d.arg_names.index("auto_attribs")]
85 if isinstance(auto, NameExpr) and auto.name == "True":
86 return "attr-auto"
87 return name
88 else:
89 return None
90
91
92 def is_dataclass_decorator(d: Expression) -> bool:
93 return dataclass_decorator_type(d) is not None
94
95
96 def is_dataclass(cdef: ClassDef) -> bool:
97 return any(is_dataclass_decorator(d) for d in cdef.decorators)
98
99
100 # The string values returned by this function are inspected in
101 # mypyc/lib-rt/misc_ops.c:CPyDataclass_SleightOfHand(...).
102 def dataclass_type(cdef: ClassDef) -> str | None:
103 for d in cdef.decorators:
104 typ = dataclass_decorator_type(d)
105 if typ is not None:
106 return typ
107 return None
108
109
110 def _defaults_skip(stmt: AssignmentStmt, cls_type: str | None) -> bool:
111 """Whether a class-level default assignment is skipped when emitting
112 __mypyc_defaults_setup, based on class type.
113
114 - attr (auto_attribs=False): skip all (handled by attr.ib machinery).
115 - dataclasses / attr-auto: skip annotated assignments.
116 - regular extension class: skip nothing.
117 """
118 if cls_type == "attr":
119 return True
120 if cls_type in ("dataclasses", "attr-auto"):
121 return stmt.type is not None
122 return False
123
124
125 def default_attr_name(stmt: AssignmentStmt, ir: ClassIR, cls_type: str | None) -> str | None:
126 """Return the attribute name if `stmt` is a class-level default assignment
127 that __mypyc_defaults_setup should emit; otherwise None.
128
129 Single source of truth for the predicate used by both
130 mypyc.irbuild.classdef.find_attr_initializers (IR build) and
131 mypyc.irbuild.prepare._has_own_default_attrs (prepare-phase decl registration).
132 """
133 lvalue = stmt.lvalues[0]
134 if not isinstance(lvalue, NameExpr) or is_class_var(lvalue):
135 return None
136 if isinstance(stmt.rvalue, TempNode):
137 return None
138 name = lvalue.name
139 if name in ("__slots__", "__deletable__") or name not in ir.attributes:
140 return None
141 if _defaults_skip(stmt, cls_type):
142 return None
143 if isinstance(stmt.rvalue, RefExpr) and stmt.rvalue.fullname == "builtins.None":
144 attr_type = ir.attributes[name]
145 if (
146 not is_optional_type(attr_type)
147 and not is_object_rprimitive(attr_type)
148 and not is_none_rprimitive(attr_type)
149 ):
150 return None
151 return name
152
153
154 def get_mypyc_attr_literal(e: Expression) -> Any:
155 """Convert an expression from a mypyc_attr decorator to a value.
156
157 Supports a pretty limited range."""
158 if isinstance(e, (StrExpr, IntExpr, FloatExpr)):
159 return e.value
160 elif isinstance(e, RefExpr) and e.fullname == "builtins.True":
161 return True
162 elif isinstance(e, RefExpr) and e.fullname == "builtins.False":
163 return False
164 elif isinstance(e, RefExpr) and e.fullname == "builtins.None":
165 return None
166 elif isinstance(e, IntExpr):
167 return e.value
168 return NotImplemented
169
170
171 def get_mypyc_attr_call(d: Expression) -> CallExpr | None:
172 """Check if an expression is a call to mypyc_attr and return it if so."""
173 if (
174 isinstance(d, CallExpr)
175 and isinstance(d.callee, RefExpr)
176 and d.callee.fullname == "mypy_extensions.mypyc_attr"
177 ):
178 return d
179 return None
180
181
182 def get_mypyc_attrs(
183 stmt: ClassDef | Decorator, path: str, errors: Errors
184 ) -> tuple[MypycAttrs, dict[MypycAttr, int]]:
185 """Collect all the mypyc_attr attributes on a class definition or a function."""
186 attrs: MypycAttrs = {}
187 lines: dict[MypycAttr, int] = {}
188
189 def set_mypyc_attr(key: str, value: Any, line: int) -> None:
190 if key in MYPYC_ATTRS:
191 attrs[key] = value
192 lines[key] = line
193 else:
194 errors.error(f'"{key}" is not a supported "mypyc_attr"', path, line)
195 supported_keys = '", "'.join(sorted(MYPYC_ATTRS))
196 errors.note(f'supported keys: "{supported_keys}"', path, line)
197
198 for dec in stmt.decorators:
199 if d := get_mypyc_attr_call(dec):
200 line = d.line
201 for name, arg in zip(d.arg_names, d.args):
202 if name is None:
203 if isinstance(arg, StrExpr):
204 set_mypyc_attr(arg.value, True, line)
205 else:
206 errors.error(
207 'All "mypyc_attr" positional arguments must be string literals.',
208 path,
209 line,
210 )
211 else:
212 arg_value = get_mypyc_attr_literal(arg)
213 set_mypyc_attr(name, arg_value, line)
214
215 return attrs, lines
216
217
218 def is_extension_class(path: str, cdef: ClassDef, errors: Errors) -> bool:
219 # Check for @mypyc_attr(native_class=True/False) decorator.
220 explicit_native_class = get_explicit_native_class(path, cdef, errors)
221
222 # Classes with native_class=False are explicitly marked as non extension.
223 if explicit_native_class is False:
224 return False
225
226 implicit_extension_class, reason = is_implicit_extension_class(cdef)
227
228 # Classes with native_class=True should be extension classes, but they might
229 # not be able to be due to other reasons. Print an error in that case.
230 if explicit_native_class is True and not implicit_extension_class:
231 errors.error(
232 f"Class is marked as native_class=True but it can't be a native class. {reason}",
233 path,
234 cdef.line,
235 )
236
237 return implicit_extension_class
238
239
240 def get_explicit_native_class(path: str, cdef: ClassDef, errors: Errors) -> bool | None:
241 """Return value of @mypyc_attr(native_class=True/False) decorator.
242
243 Look for a @mypyc_attr decorator with native_class=True/False and return
244 the value assigned or None if it doesn't exist. Other values are an error.
245 """
246
247 for d in cdef.decorators:
248 mypyc_attr_call = get_mypyc_attr_call(d)
249 if not mypyc_attr_call:
250 continue
251
252 for i, name in enumerate(mypyc_attr_call.arg_names):
253 if name != "native_class":
254 continue
255
256 arg = mypyc_attr_call.args[i]
257 if not isinstance(arg, NameExpr):
258 errors.error("native_class must be used with True or False only", path, cdef.line)
259 return None
260
261 if arg.name == "False":
262 return False
263 elif arg.name == "True":
264 return True
265 else:
266 errors.error("native_class must be used with True or False only", path, cdef.line)
267 return None
268 return None
269
270
271 def is_implicit_extension_class(cdef: ClassDef) -> tuple[bool, str]:
272 """Check if class can be extension class and return a user-friendly reason it can't be one."""
273
274 for d in cdef.decorators:
275 if (
276 not is_trait_decorator(d)
277 and not is_dataclass_decorator(d)
278 and not get_mypyc_attr_call(d)
279 and not is_final_decorator(d)
280 ):
281 return (
282 False,
283 "Classes that have decorators other than supported decorators"
284 " can't be native classes.",
285 )
286
287 if cdef.info.typeddict_type:
288 return False, "TypedDict classes can't be native classes."
289 if cdef.info.is_named_tuple:
290 return False, "NamedTuple classes can't be native classes."
291 if cdef.info.metaclass_type and cdef.info.metaclass_type.type.fullname not in (
292 "abc.ABCMeta",
293 "typing.TypingMeta",
294 "typing.GenericMeta",
295 ):
296 return (
297 False,
298 "Classes with a metaclass other than ABCMeta, TypingMeta or"
299 " GenericMeta can't be native classes.",
300 )
301 return True, ""
302
303
304 def get_func_def(op: FuncDef | Decorator | OverloadedFuncDef) -> FuncDef:
305 if isinstance(op, OverloadedFuncDef):
306 assert op.impl
307 op = op.impl
308 if isinstance(op, Decorator):
309 op = op.func
310 return op
311
312
313 def concrete_arg_kind(kind: ArgKind) -> ArgKind:
314 """Find the concrete version of an arg kind that is being passed."""
315 if kind == ARG_OPT:
316 return ARG_POS
317 elif kind == ARG_NAMED_OPT:
318 return ARG_NAMED
319 else:
320 return kind
321
322
323 def is_constant(e: Expression) -> bool:
324 """Check whether we allow an expression to appear as a default value.
325
326 We don't currently properly support storing the evaluated
327 values for default arguments and default attribute values, so
328 we restrict what expressions we allow. We allow literals of
329 primitives types, None, and references to Final global
330 variables.
331 """
332 return (
333 isinstance(e, (StrExpr, BytesExpr, IntExpr, FloatExpr))
334 or (isinstance(e, UnaryExpr) and e.op == "-" and isinstance(e.expr, (IntExpr, FloatExpr)))
335 or (isinstance(e, TupleExpr) and all(is_constant(e) for e in e.items))
336 or (
337 isinstance(e, RefExpr)
338 and e.kind == GDEF
339 and (
340 e.fullname in ("builtins.True", "builtins.False", "builtins.None")
341 or (isinstance(e.node, Var) and e.node.is_final)
342 )
343 )
344 )
345
346
347 def bytes_from_str(value: str) -> bytes:
348 """Convert a string representing bytes into actual bytes.
349
350 This is needed because the literal characters of BytesExpr (the
351 characters inside b'') are stored in BytesExpr.value, whose type is
352 'str' not 'bytes'.
353 """
354 return bytes(value, "utf8").decode("unicode-escape").encode("raw-unicode-escape")