| 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 |
# Sort members so that we don't depend on frozenset iteration order. |
| 69 |
for item in sorted(value, key=literal_sort_key): |
| 70 |
assert _is_literal_value(item) |
| 71 |
self.record_literal(item) |
| 72 |
frozenset_literals[value] = len(frozenset_literals) |
| 73 |
else: |
| 74 |
assert False, "invalid literal: %r" % value |
| 75 |
|
| 76 |
def literal_index(self, value: LiteralValue) -> int: |
| 77 |
"""Return the index to the literals array for given value.""" |
| 78 |
# The array contains first None and booleans, followed by all str values, |
| 79 |
# followed by bytes values, etc. |
| 80 |
if value is None: |
| 81 |
return 0 |
| 82 |
elif value is False: |
| 83 |
return 1 |
| 84 |
elif value is True: |
| 85 |
return 2 |
| 86 |
n = NUM_SINGLETONS |
| 87 |
if isinstance(value, str): |
| 88 |
return n + self.str_literals[value] |
| 89 |
n += len(self.str_literals) |
| 90 |
if isinstance(value, bytes): |
| 91 |
return n + self.bytes_literals[value] |
| 92 |
n += len(self.bytes_literals) |
| 93 |
if isinstance(value, int): |
| 94 |
return n + self.int_literals[value] |
| 95 |
n += len(self.int_literals) |
| 96 |
if isinstance(value, float): |
| 97 |
return n + self.float_literals[value] |
| 98 |
n += len(self.float_literals) |
| 99 |
if isinstance(value, complex): |
| 100 |
return n + self.complex_literals[value] |
| 101 |
n += len(self.complex_literals) |
| 102 |
if isinstance(value, tuple): |
| 103 |
return n + self.tuple_literals[value] |
| 104 |
n += len(self.tuple_literals) |
| 105 |
if isinstance(value, frozenset): |
| 106 |
return n + self.frozenset_literals[value] |
| 107 |
assert False, "invalid literal: %r" % value |
| 108 |
|
| 109 |
def num_literals(self) -> int: |
| 110 |
# The first three are for None, True and False |
| 111 |
return ( |
| 112 |
NUM_SINGLETONS |
| 113 |
+ len(self.str_literals) |
| 114 |
+ len(self.bytes_literals) |
| 115 |
+ len(self.int_literals) |
| 116 |
+ len(self.float_literals) |
| 117 |
+ len(self.complex_literals) |
| 118 |
+ len(self.tuple_literals) |
| 119 |
+ len(self.frozenset_literals) |
| 120 |
) |
| 121 |
|
| 122 |
# The following methods return the C encodings of literal values |
| 123 |
# of different types |
| 124 |
|
| 125 |
def encoded_str_values(self) -> list[bytes]: |
| 126 |
return _encode_str_values(self.str_literals) |
| 127 |
|
| 128 |
def encoded_int_values(self) -> list[bytes]: |
| 129 |
return _encode_int_values(self.int_literals) |
| 130 |
|
| 131 |
def encoded_bytes_values(self) -> list[bytes]: |
| 132 |
return _encode_bytes_values(self.bytes_literals) |
| 133 |
|
| 134 |
def encoded_float_values(self) -> list[str]: |
| 135 |
return _encode_float_values(self.float_literals) |
| 136 |
|
| 137 |
def encoded_complex_values(self) -> list[str]: |
| 138 |
return _encode_complex_values(self.complex_literals) |
| 139 |
|
| 140 |
def encoded_tuple_values(self) -> list[str]: |
| 141 |
return self._encode_collection_values(self.tuple_literals) |
| 142 |
|
| 143 |
def encoded_frozenset_values(self) -> list[str]: |
| 144 |
# Ensure deterministic frozenset item order by sorting items. |
| 145 |
return self._encode_collection_values(self.frozenset_literals, sort_items=True) |
| 146 |
|
| 147 |
def _encode_collection_values( |
| 148 |
self, |
| 149 |
values: dict[tuple[object, ...], int] | dict[frozenset[object], int], |
| 150 |
*, |
| 151 |
sort_items: bool = False, |
| 152 |
) -> list[str]: |
| 153 |
"""Encode tuple/frozenset values into a C array. |
| 154 |
|
| 155 |
The format of the result is like this: |
| 156 |
|
| 157 |
<number of collections> |
| 158 |
<length of the first collection> |
| 159 |
<literal index of first item> |
| 160 |
... |
| 161 |
<literal index of last item> |
| 162 |
<length of the second collection> |
| 163 |
... |
| 164 |
""" |
| 165 |
value_by_index = {index: value for value, index in values.items()} |
| 166 |
result = [] |
| 167 |
count = len(values) |
| 168 |
result.append(str(count)) |
| 169 |
for i in range(count): |
| 170 |
value = value_by_index[i] |
| 171 |
result.append(str(len(value))) |
| 172 |
items = sorted(value, key=literal_sort_key) if sort_items else value |
| 173 |
for item in items: |
| 174 |
assert _is_literal_value(item) |
| 175 |
index = self.literal_index(item) |
| 176 |
result.append(str(index)) |
| 177 |
return result |
| 178 |
|
| 179 |
|
| 180 |
def _encode_str_values(values: dict[str, int]) -> list[bytes]: |
| 181 |
value_by_index = {index: value for value, index in values.items()} |
| 182 |
result = [] |
| 183 |
line: list[bytes] = [] |
| 184 |
line_len = 0 |
| 185 |
for i in range(len(values)): |
| 186 |
value = value_by_index[i] |
| 187 |
c_literal = format_str_literal(value) |
| 188 |
c_len = len(c_literal) |
| 189 |
if line_len > 0 and line_len + c_len > 70: |
| 190 |
result.append(format_int(len(line)) + b"".join(line)) |
| 191 |
line = [] |
| 192 |
line_len = 0 |
| 193 |
line.append(c_literal) |
| 194 |
line_len += c_len |
| 195 |
if line: |
| 196 |
result.append(format_int(len(line)) + b"".join(line)) |
| 197 |
result.append(b"") |
| 198 |
return result |
| 199 |
|
| 200 |
|
| 201 |
def _encode_bytes_values(values: dict[bytes, int]) -> list[bytes]: |
| 202 |
value_by_index = {index: value for value, index in values.items()} |
| 203 |
result = [] |
| 204 |
line: list[bytes] = [] |
| 205 |
line_len = 0 |
| 206 |
for i in range(len(values)): |
| 207 |
value = value_by_index[i] |
| 208 |
c_init = format_int(len(value)) |
| 209 |
c_len = len(c_init) + len(value) |
| 210 |
if line_len > 0 and line_len + c_len > 70: |
| 211 |
result.append(format_int(len(line)) + b"".join(line)) |
| 212 |
line = [] |
| 213 |
line_len = 0 |
| 214 |
line.append(c_init + value) |
| 215 |
line_len += c_len |
| 216 |
if line: |
| 217 |
result.append(format_int(len(line)) + b"".join(line)) |
| 218 |
result.append(b"") |
| 219 |
return result |
| 220 |
|
| 221 |
|
| 222 |
def format_int(n: int) -> bytes: |
| 223 |
"""Format an integer using a variable-length binary encoding.""" |
| 224 |
if n < 128: |
| 225 |
a = [n] |
| 226 |
else: |
| 227 |
a = [] |
| 228 |
while n > 0: |
| 229 |
a.insert(0, n & 0x7F) |
| 230 |
n >>= 7 |
| 231 |
for i in range(len(a) - 1): |
| 232 |
# If the highest bit is set, more 7-bit digits follow |
| 233 |
a[i] |= 0x80 |
| 234 |
return bytes(a) |
| 235 |
|
| 236 |
|
| 237 |
def format_str_literal(s: str) -> bytes: |
| 238 |
utf8 = s.encode("utf-8", errors="surrogatepass") |
| 239 |
return format_int(len(utf8)) + utf8 |
| 240 |
|
| 241 |
|
| 242 |
def _encode_int_values(values: dict[int, int]) -> list[bytes]: |
| 243 |
"""Encode int values into C strings. |
| 244 |
|
| 245 |
Values are stored in base 10 and separated by 0 bytes. |
| 246 |
""" |
| 247 |
value_by_index = {index: value for value, index in values.items()} |
| 248 |
result = [] |
| 249 |
line: list[bytes] = [] |
| 250 |
line_len = 0 |
| 251 |
for i in range(len(values)): |
| 252 |
value = value_by_index[i] |
| 253 |
encoded = b"%d" % value |
| 254 |
if line_len > 0 and line_len + len(encoded) > 70: |
| 255 |
result.append(format_int(len(line)) + b"\0".join(line)) |
| 256 |
line = [] |
| 257 |
line_len = 0 |
| 258 |
line.append(encoded) |
| 259 |
line_len += len(encoded) |
| 260 |
if line: |
| 261 |
result.append(format_int(len(line)) + b"\0".join(line)) |
| 262 |
result.append(b"") |
| 263 |
return result |
| 264 |
|
| 265 |
|
| 266 |
def float_to_c(x: float) -> str: |
| 267 |
"""Return C literal representation of a float value.""" |
| 268 |
s = str(x) |
| 269 |
if s == "inf": |
| 270 |
return "INFINITY" |
| 271 |
elif s == "-inf": |
| 272 |
return "-INFINITY" |
| 273 |
elif s == "nan": |
| 274 |
return "NAN" |
| 275 |
return s |
| 276 |
|
| 277 |
|
| 278 |
def _encode_float_values(values: dict[float, int]) -> list[str]: |
| 279 |
"""Encode float values into a C array values. |
| 280 |
|
| 281 |
The result contains the number of values followed by individual values. |
| 282 |
""" |
| 283 |
value_by_index = {index: value for value, index in values.items()} |
| 284 |
result = [] |
| 285 |
num = len(values) |
| 286 |
result.append(str(num)) |
| 287 |
for i in range(num): |
| 288 |
value = value_by_index[i] |
| 289 |
result.append(float_to_c(value)) |
| 290 |
return result |
| 291 |
|
| 292 |
|
| 293 |
def _encode_complex_values(values: dict[complex, int]) -> list[str]: |
| 294 |
"""Encode float values into a C array values. |
| 295 |
|
| 296 |
The result contains the number of values followed by pairs of doubles |
| 297 |
representing complex numbers. |
| 298 |
""" |
| 299 |
value_by_index = {index: value for value, index in values.items()} |
| 300 |
result = [] |
| 301 |
num = len(values) |
| 302 |
result.append(str(num)) |
| 303 |
for i in range(num): |
| 304 |
value = value_by_index[i] |
| 305 |
result.append(float_to_c(value.real)) |
| 306 |
result.append(float_to_c(value.imag)) |
| 307 |
return result |
| 308 |
|
| 309 |
|
| 310 |
def literal_sort_key(value: object) -> tuple[object, ...]: |
| 311 |
"""Return a sort key for a literal value.""" |
| 312 |
if isinstance(value, frozenset): |
| 313 |
# Sort items to avoid depending on the unpredictable iteration order. |
| 314 |
return ("frozenset", tuple(sorted(literal_sort_key(item) for item in value))) |
| 315 |
elif isinstance(value, tuple): |
| 316 |
return ("tuple", tuple(literal_sort_key(item) for item in value)) |
| 317 |
return (type(value).__name__, repr(value)) |