Debian Codegraph @

mypyc/codegen/literals.py

raw
1 from __future__ import annotations
2
3 from typing import Final, TypeGuard
4
5 # Supported Python literal types. All tuple / frozenset items must have supported
6 # literal types as well, but we can't represent the type precisely.
7 LiteralValue = (
8 str | bytes | int | bool | float | complex | tuple[object, ...] | frozenset[object] | None
9 )
10
11
12 def _is_literal_value(obj: object) -> TypeGuard[LiteralValue]:
13 return isinstance(obj, (str, bytes, int, float, complex, tuple, frozenset, type(None)))
14
15
16 # Some literals are singletons and handled specially (None, False and True)
17 NUM_SINGLETONS: Final = 3
18
19
20 class Literals:
21 """Collection of literal values used in a compilation group and related helpers."""
22
23 def __init__(self) -> None:
24 # Each dict maps value to literal index (0, 1, ...)
25 self.str_literals: dict[str, int] = {}
26 self.bytes_literals: dict[bytes, int] = {}
27 self.int_literals: dict[int, int] = {}
28 self.float_literals: dict[float, int] = {}
29 self.complex_literals: dict[complex, int] = {}
30 self.tuple_literals: dict[tuple[object, ...], int] = {}
31 self.frozenset_literals: dict[frozenset[object], int] = {}
32
33 def record_literal(self, value: LiteralValue) -> None:
34 """Ensure that the literal value is available in generated code."""
35 if value is None or value is True or value is False:
36 # These are special cased and always present
37 return
38 if isinstance(value, str):
39 str_literals = self.str_literals
40 if value not in str_literals:
41 str_literals[value] = len(str_literals)
42 elif isinstance(value, bytes):
43 bytes_literals = self.bytes_literals
44 if value not in bytes_literals:
45 bytes_literals[value] = len(bytes_literals)
46 elif isinstance(value, int):
47 int_literals = self.int_literals
48 if value not in int_literals:
49 int_literals[value] = len(int_literals)
50 elif isinstance(value, float):
51 float_literals = self.float_literals
52 if value not in float_literals:
53 float_literals[value] = len(float_literals)
54 elif isinstance(value, complex):
55 complex_literals = self.complex_literals
56 if value not in complex_literals:
57 complex_literals[value] = len(complex_literals)
58 elif isinstance(value, tuple):
59 tuple_literals = self.tuple_literals
60 if value not in tuple_literals:
61 for item in value:
62 assert _is_literal_value(item)
63 self.record_literal(item)
64 tuple_literals[value] = len(tuple_literals)
65 elif isinstance(value, frozenset):
66 frozenset_literals = self.frozenset_literals
67 if value not in frozenset_literals:
68 for item in value:
69 assert _is_literal_value(item)
70 self.record_literal(item)
71 frozenset_literals[value] = len(frozenset_literals)
72 else:
73 assert False, "invalid literal: %r" % value
74
75 def literal_index(self, value: LiteralValue) -> int:
76 """Return the index to the literals array for given value."""
77 # The array contains first None and booleans, followed by all str values,
78 # followed by bytes values, etc.
79 if value is None:
80 return 0
81 elif value is False:
82 return 1
83 elif value is True:
84 return 2
85 n = NUM_SINGLETONS
86 if isinstance(value, str):
87 return n + self.str_literals[value]
88 n += len(self.str_literals)
89 if isinstance(value, bytes):
90 return n + self.bytes_literals[value]
91 n += len(self.bytes_literals)
92 if isinstance(value, int):
93 return n + self.int_literals[value]
94 n += len(self.int_literals)
95 if isinstance(value, float):
96 return n + self.float_literals[value]
97 n += len(self.float_literals)
98 if isinstance(value, complex):
99 return n + self.complex_literals[value]
100 n += len(self.complex_literals)
101 if isinstance(value, tuple):
102 return n + self.tuple_literals[value]
103 n += len(self.tuple_literals)
104 if isinstance(value, frozenset):
105 return n + self.frozenset_literals[value]
106 assert False, "invalid literal: %r" % value
107
108 def num_literals(self) -> int:
109 # The first three are for None, True and False
110 return (
111 NUM_SINGLETONS
112 + len(self.str_literals)
113 + len(self.bytes_literals)
114 + len(self.int_literals)
115 + len(self.float_literals)
116 + len(self.complex_literals)
117 + len(self.tuple_literals)
118 + len(self.frozenset_literals)
119 )
120
121 # The following methods return the C encodings of literal values
122 # of different types
123
124 def encoded_str_values(self) -> list[bytes]:
125 return _encode_str_values(self.str_literals)
126
127 def encoded_int_values(self) -> list[bytes]:
128 return _encode_int_values(self.int_literals)
129
130 def encoded_bytes_values(self) -> list[bytes]:
131 return _encode_bytes_values(self.bytes_literals)
132
133 def encoded_float_values(self) -> list[str]:
134 return _encode_float_values(self.float_literals)
135
136 def encoded_complex_values(self) -> list[str]:
137 return _encode_complex_values(self.complex_literals)
138
139 def encoded_tuple_values(self) -> list[str]:
140 return self._encode_collection_values(self.tuple_literals)
141
142 def encoded_frozenset_values(self) -> list[str]:
143 return self._encode_collection_values(self.frozenset_literals)
144
145 def _encode_collection_values(
146 self, values: dict[tuple[object, ...], int] | dict[frozenset[object], int]
147 ) -> list[str]:
148 """Encode tuple/frozenset values into a C array.
149
150 The format of the result is like this:
151
152 <number of collections>
153 <length of the first collection>
154 <literal index of first item>
155 ...
156 <literal index of last item>
157 <length of the second collection>
158 ...
159 """
160 value_by_index = {index: value for value, index in values.items()}
161 result = []
162 count = len(values)
163 result.append(str(count))
164 for i in range(count):
165 value = value_by_index[i]
166 result.append(str(len(value)))
167 for item in value:
168 assert _is_literal_value(item)
169 index = self.literal_index(item)
170 result.append(str(index))
171 return result
172
173
174 def _encode_str_values(values: dict[str, int]) -> list[bytes]:
175 value_by_index = {index: value for value, index in values.items()}
176 result = []
177 line: list[bytes] = []
178 line_len = 0
179 for i in range(len(values)):
180 value = value_by_index[i]
181 c_literal = format_str_literal(value)
182 c_len = len(c_literal)
183 if line_len > 0 and line_len + c_len > 70:
184 result.append(format_int(len(line)) + b"".join(line))
185 line = []
186 line_len = 0
187 line.append(c_literal)
188 line_len += c_len
189 if line:
190 result.append(format_int(len(line)) + b"".join(line))
191 result.append(b"")
192 return result
193
194
195 def _encode_bytes_values(values: dict[bytes, int]) -> list[bytes]:
196 value_by_index = {index: value for value, index in values.items()}
197 result = []
198 line: list[bytes] = []
199 line_len = 0
200 for i in range(len(values)):
201 value = value_by_index[i]
202 c_init = format_int(len(value))
203 c_len = len(c_init) + len(value)
204 if line_len > 0 and line_len + c_len > 70:
205 result.append(format_int(len(line)) + b"".join(line))
206 line = []
207 line_len = 0
208 line.append(c_init + value)
209 line_len += c_len
210 if line:
211 result.append(format_int(len(line)) + b"".join(line))
212 result.append(b"")
213 return result
214
215
216 def format_int(n: int) -> bytes:
217 """Format an integer using a variable-length binary encoding."""
218 if n < 128:
219 a = [n]
220 else:
221 a = []
222 while n > 0:
223 a.insert(0, n & 0x7F)
224 n >>= 7
225 for i in range(len(a) - 1):
226 # If the highest bit is set, more 7-bit digits follow
227 a[i] |= 0x80
228 return bytes(a)
229
230
231 def format_str_literal(s: str) -> bytes:
232 utf8 = s.encode("utf-8", errors="surrogatepass")
233 return format_int(len(utf8)) + utf8
234
235
236 def _encode_int_values(values: dict[int, int]) -> list[bytes]:
237 """Encode int values into C strings.
238
239 Values are stored in base 10 and separated by 0 bytes.
240 """
241 value_by_index = {index: value for value, index in values.items()}
242 result = []
243 line: list[bytes] = []
244 line_len = 0
245 for i in range(len(values)):
246 value = value_by_index[i]
247 encoded = b"%d" % value
248 if line_len > 0 and line_len + len(encoded) > 70:
249 result.append(format_int(len(line)) + b"\0".join(line))
250 line = []
251 line_len = 0
252 line.append(encoded)
253 line_len += len(encoded)
254 if line:
255 result.append(format_int(len(line)) + b"\0".join(line))
256 result.append(b"")
257 return result
258
259
260 def float_to_c(x: float) -> str:
261 """Return C literal representation of a float value."""
262 s = str(x)
263 if s == "inf":
264 return "INFINITY"
265 elif s == "-inf":
266 return "-INFINITY"
267 elif s == "nan":
268 return "NAN"
269 return s
270
271
272 def _encode_float_values(values: dict[float, int]) -> list[str]:
273 """Encode float values into a C array values.
274
275 The result contains the number of values followed by individual values.
276 """
277 value_by_index = {index: value for value, index in values.items()}
278 result = []
279 num = len(values)
280 result.append(str(num))
281 for i in range(num):
282 value = value_by_index[i]
283 result.append(float_to_c(value))
284 return result
285
286
287 def _encode_complex_values(values: dict[complex, int]) -> list[str]:
288 """Encode float values into a C array values.
289
290 The result contains the number of values followed by pairs of doubles
291 representing complex numbers.
292 """
293 value_by_index = {index: value for value, index in values.items()}
294 result = []
295 num = len(values)
296 result.append(str(num))
297 for i in range(num):
298 value = value_by_index[i]
299 result.append(float_to_c(value.real))
300 result.append(float_to_c(value.imag))
301 return result