map-conform 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- map_conform/__init__.py +5 -0
- map_conform/__main__.py +7 -0
- map_conform/batch/__init__.py +1 -0
- map_conform/batch/arrow.py +80 -0
- map_conform/batch/columnar.py +125 -0
- map_conform/batch/engine.py +191 -0
- map_conform/batch/files.py +207 -0
- map_conform/cli.py +460 -0
- map_conform/doctor.py +178 -0
- map_conform/errors.py +107 -0
- map_conform/expr/__init__.py +6 -0
- map_conform/expr/compiler.py +562 -0
- map_conform/expr/functions.py +542 -0
- map_conform/expr/sandbox.py +333 -0
- map_conform/expr/sdk.py +116 -0
- map_conform/map-conform-spec.schema.json +1204 -0
- map_conform/mapper.py +355 -0
- map_conform/metadata.py +73 -0
- map_conform/metrics.py +62 -0
- map_conform/naming/__init__.py +1 -0
- map_conform/naming/ascii-table.json +980 -0
- map_conform/naming/conform.py +262 -0
- map_conform/naming/flatten.py +148 -0
- map_conform/naming/nested.py +117 -0
- map_conform/naming/reserved/ansi.txt +369 -0
- map_conform/naming/reserved/duckdb.txt +114 -0
- map_conform/naming/reserved/postgres.txt +105 -0
- map_conform/naming/reserved/snowflake.txt +90 -0
- map_conform/naming/reserved.py +34 -0
- map_conform/naming/shape.py +96 -0
- map_conform/naming/streams.py +76 -0
- map_conform/naming/translit.py +170 -0
- map_conform/plan/__init__.py +1 -0
- map_conform/plan/chain.py +667 -0
- map_conform/plan/compile.py +551 -0
- map_conform/plan/lower.py +281 -0
- map_conform/plan/ops.py +336 -0
- map_conform/plan/row.py +212 -0
- map_conform/plan/vector.py +71 -0
- map_conform/rejects.py +92 -0
- map_conform/settings.py +157 -0
- map_conform/spec/__init__.py +1 -0
- map_conform/spec/_struct.py +483 -0
- map_conform/spec/bridge.py +109 -0
- map_conform/spec/check.py +380 -0
- map_conform/spec/errors.py +22 -0
- map_conform/spec/importer.py +87 -0
- map_conform/spec/jsonschema.py +54 -0
- map_conform/spec/load.py +357 -0
- map_conform/spec/model.py +473 -0
- map_conform/spec/reference.py +179 -0
- map_conform/spec/steps.py +297 -0
- map_conform/spec/stream_maps.py +233 -0
- map_conform/spec/zamboni.py +99 -0
- map_conform/transforms/__init__.py +1 -0
- map_conform/transforms/builtins.py +63 -0
- map_conform/transforms/casts.py +310 -0
- map_conform/transforms/fake.py +150 -0
- map_conform/transforms/nested.py +111 -0
- map_conform/transforms/numeric.py +318 -0
- map_conform/transforms/polars_vector.py +151 -0
- map_conform/transforms/privacy.py +220 -0
- map_conform/transforms/registry.py +116 -0
- map_conform/transforms/temporal.py +410 -0
- map_conform/transforms/text.py +249 -0
- map_conform/transforms/vector.py +386 -0
- map_conform/types/__init__.py +1 -0
- map_conform/types/canonical.py +255 -0
- map_conform/types/from_jsonschema.py +177 -0
- map_conform/types/jsontext.py +63 -0
- map_conform/types/to_arrow.py +52 -0
- map_conform/types/to_jsonschema.py +65 -0
- map_conform/types/wire.py +53 -0
- map_conform/udfs.py +327 -0
- map_conform-0.1.0.dist-info/METADATA +157 -0
- map_conform-0.1.0.dist-info/RECORD +79 -0
- map_conform-0.1.0.dist-info/WHEEL +4 -0
- map_conform-0.1.0.dist-info/entry_points.txt +2 -0
- map_conform-0.1.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
"""The safety envelope of the expression language (detailed design §7).
|
|
2
|
+
|
|
3
|
+
Expressions are untrusted text from a spec, so what they can reach is closed:
|
|
4
|
+
|
|
5
|
+
- **Attributes** are read only on values of the types in :data:`ALLOWED_TYPES` (and on those
|
|
6
|
+
classes themselves), never when the name starts with ``_``, never ``format``,
|
|
7
|
+
``format_map`` or ``mro`` (which can reach attributes or classes indirectly), and never a
|
|
8
|
+
method that mutates a list, dict or set, so one column cannot change what the next sees.
|
|
9
|
+
- **Modules** are reached through :class:`ModuleProxy`, which exposes an explicit list of
|
|
10
|
+
names and nothing that changes global state (no ``decimal.setcontext``).
|
|
11
|
+
- **Sizes** are bounded where one short expression could exhaust memory: repetition,
|
|
12
|
+
powers, shifts, padding, format widths, ``range`` and comprehension lengths.
|
|
13
|
+
|
|
14
|
+
Generators, frames, code objects, functions' globals and classes outside the list are never
|
|
15
|
+
reachable, because no attribute access on them is allowed.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import datetime as dt
|
|
21
|
+
import decimal
|
|
22
|
+
import json
|
|
23
|
+
import math
|
|
24
|
+
import re
|
|
25
|
+
import sys
|
|
26
|
+
import uuid
|
|
27
|
+
from types import MappingProxyType, ModuleType
|
|
28
|
+
from typing import TYPE_CHECKING, Any
|
|
29
|
+
|
|
30
|
+
if sys.version_info >= (3, 12):
|
|
31
|
+
from typing import override
|
|
32
|
+
else:
|
|
33
|
+
from typing_extensions import override
|
|
34
|
+
|
|
35
|
+
if TYPE_CHECKING:
|
|
36
|
+
from collections.abc import Callable, Iterable, Iterator, Mapping
|
|
37
|
+
|
|
38
|
+
MAX_LENGTH = 1_000_000
|
|
39
|
+
"""Longest string, bytes or sequence an expression may build by repetition or padding."""
|
|
40
|
+
MAX_ITEMS = 100_000
|
|
41
|
+
"""Most items one comprehension, or one ``range``, may produce."""
|
|
42
|
+
MAX_EXPONENT = 10_000
|
|
43
|
+
"""Largest integer exponent or shift."""
|
|
44
|
+
|
|
45
|
+
ALLOWED_TYPES: tuple[type, ...] = (
|
|
46
|
+
str,
|
|
47
|
+
bytes,
|
|
48
|
+
int,
|
|
49
|
+
float,
|
|
50
|
+
complex,
|
|
51
|
+
bool,
|
|
52
|
+
type(None),
|
|
53
|
+
decimal.Decimal,
|
|
54
|
+
dt.date,
|
|
55
|
+
dt.datetime,
|
|
56
|
+
dt.time,
|
|
57
|
+
dt.timedelta,
|
|
58
|
+
dt.tzinfo,
|
|
59
|
+
uuid.UUID,
|
|
60
|
+
list,
|
|
61
|
+
tuple,
|
|
62
|
+
dict,
|
|
63
|
+
set,
|
|
64
|
+
frozenset,
|
|
65
|
+
MappingProxyType,
|
|
66
|
+
re.Pattern,
|
|
67
|
+
re.Match,
|
|
68
|
+
)
|
|
69
|
+
"""Types whose public attributes and methods an expression may use."""
|
|
70
|
+
|
|
71
|
+
_DENIED = frozenset({"format", "format_map", "mro"})
|
|
72
|
+
_MUTATORS = frozenset(
|
|
73
|
+
{
|
|
74
|
+
"append",
|
|
75
|
+
"extend",
|
|
76
|
+
"insert",
|
|
77
|
+
"pop",
|
|
78
|
+
"remove",
|
|
79
|
+
"clear",
|
|
80
|
+
"sort",
|
|
81
|
+
"reverse",
|
|
82
|
+
"update",
|
|
83
|
+
"setdefault",
|
|
84
|
+
"popitem",
|
|
85
|
+
"add",
|
|
86
|
+
"discard",
|
|
87
|
+
"difference_update",
|
|
88
|
+
"intersection_update",
|
|
89
|
+
"symmetric_difference_update",
|
|
90
|
+
}
|
|
91
|
+
)
|
|
92
|
+
_MUTABLE = (list, dict, set)
|
|
93
|
+
_PADDING = frozenset({"ljust", "rjust", "center", "zfill", "expandtabs"})
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
class SandboxError(Exception):
|
|
97
|
+
"""An expression tried to leave the safety envelope."""
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
class Proxy:
|
|
101
|
+
"""An object whose attributes expressions reach only through :meth:`attribute`."""
|
|
102
|
+
|
|
103
|
+
__slots__ = ()
|
|
104
|
+
|
|
105
|
+
def attribute(self, name: str) -> object:
|
|
106
|
+
"""The attribute, or a SandboxError."""
|
|
107
|
+
raise NotImplementedError
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class ModuleProxy(Proxy):
|
|
111
|
+
"""A read-only view of a module that exposes only the listed names."""
|
|
112
|
+
|
|
113
|
+
__slots__ = ("_exposed", "_name")
|
|
114
|
+
|
|
115
|
+
def __init__(self, module: ModuleType, names: Iterable[str]) -> None:
|
|
116
|
+
"""Expose ``names`` of ``module``."""
|
|
117
|
+
self._name = module.__name__
|
|
118
|
+
self._exposed: Mapping[str, object] = MappingProxyType(
|
|
119
|
+
{name: getattr(module, name) for name in names}
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
@override
|
|
123
|
+
def attribute(self, name: str) -> object:
|
|
124
|
+
"""The exposed attribute.
|
|
125
|
+
|
|
126
|
+
Raises:
|
|
127
|
+
SandboxError: for a name the proxy does not expose.
|
|
128
|
+
"""
|
|
129
|
+
try:
|
|
130
|
+
return self._exposed[name]
|
|
131
|
+
except KeyError:
|
|
132
|
+
msg = f"{self._name}.{name} is not available in expressions"
|
|
133
|
+
raise SandboxError(msg) from None
|
|
134
|
+
|
|
135
|
+
def names(self) -> tuple[str, ...]:
|
|
136
|
+
"""The exposed names, sorted."""
|
|
137
|
+
return tuple(sorted(self._exposed))
|
|
138
|
+
|
|
139
|
+
@override
|
|
140
|
+
def __repr__(self) -> str:
|
|
141
|
+
"""``<module datetime (read-only)>``."""
|
|
142
|
+
return f"<module {self._name} (read-only)>"
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
MODULES: Mapping[str, ModuleProxy] = MappingProxyType(
|
|
146
|
+
{
|
|
147
|
+
"datetime": ModuleProxy(
|
|
148
|
+
dt,
|
|
149
|
+
(
|
|
150
|
+
"date",
|
|
151
|
+
"datetime",
|
|
152
|
+
"time",
|
|
153
|
+
"timedelta",
|
|
154
|
+
"timezone",
|
|
155
|
+
"tzinfo",
|
|
156
|
+
"UTC",
|
|
157
|
+
"MINYEAR",
|
|
158
|
+
"MAXYEAR",
|
|
159
|
+
),
|
|
160
|
+
),
|
|
161
|
+
"decimal": ModuleProxy(
|
|
162
|
+
decimal,
|
|
163
|
+
(
|
|
164
|
+
"Decimal",
|
|
165
|
+
"InvalidOperation",
|
|
166
|
+
*(name for name in dir(decimal) if name.startswith("ROUND_")),
|
|
167
|
+
),
|
|
168
|
+
),
|
|
169
|
+
"math": ModuleProxy(
|
|
170
|
+
math,
|
|
171
|
+
tuple(
|
|
172
|
+
name
|
|
173
|
+
for name in dir(math)
|
|
174
|
+
if not name.startswith("_") and name not in {"factorial", "comb", "perm"}
|
|
175
|
+
),
|
|
176
|
+
),
|
|
177
|
+
"re": ModuleProxy(
|
|
178
|
+
re,
|
|
179
|
+
(
|
|
180
|
+
"compile",
|
|
181
|
+
"escape",
|
|
182
|
+
"findall",
|
|
183
|
+
"fullmatch",
|
|
184
|
+
"match",
|
|
185
|
+
"search",
|
|
186
|
+
"split",
|
|
187
|
+
"sub",
|
|
188
|
+
"subn",
|
|
189
|
+
"A",
|
|
190
|
+
"ASCII",
|
|
191
|
+
"I",
|
|
192
|
+
"IGNORECASE",
|
|
193
|
+
"M",
|
|
194
|
+
"MULTILINE",
|
|
195
|
+
"S",
|
|
196
|
+
"DOTALL",
|
|
197
|
+
"X",
|
|
198
|
+
"VERBOSE",
|
|
199
|
+
),
|
|
200
|
+
),
|
|
201
|
+
"json": ModuleProxy(json, ("dumps", "loads")),
|
|
202
|
+
}
|
|
203
|
+
)
|
|
204
|
+
"""The modules expressions may use, by name. ``math.factorial`` and friends are left out
|
|
205
|
+
because a small argument makes a huge number."""
|
|
206
|
+
|
|
207
|
+
_EXTRA_RECEIVERS: list[type] = []
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def allow_receiver(cls: type) -> None:
|
|
211
|
+
"""Allow attribute access on instances of ``cls`` (e.g. a Faker generator)."""
|
|
212
|
+
if cls not in _EXTRA_RECEIVERS:
|
|
213
|
+
_EXTRA_RECEIVERS.append(cls)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _allowed_receiver(obj: object) -> bool:
|
|
217
|
+
if isinstance(obj, type):
|
|
218
|
+
return issubclass(obj, ALLOWED_TYPES)
|
|
219
|
+
return isinstance(obj, (*ALLOWED_TYPES, *_EXTRA_RECEIVERS))
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def get_attribute(obj: object, name: str) -> object:
|
|
223
|
+
"""``obj.name``, when the sandbox allows it.
|
|
224
|
+
|
|
225
|
+
Raises:
|
|
226
|
+
SandboxError: for a private, denied or mutating attribute, or a receiver outside the
|
|
227
|
+
allowed types.
|
|
228
|
+
"""
|
|
229
|
+
if isinstance(obj, Proxy):
|
|
230
|
+
return obj.attribute(name)
|
|
231
|
+
if name.startswith("_") or name in _DENIED:
|
|
232
|
+
msg = f"attribute {name!r} is not available in expressions"
|
|
233
|
+
raise SandboxError(msg)
|
|
234
|
+
if not _allowed_receiver(obj):
|
|
235
|
+
msg = f"attributes of {type(obj).__name__} values are not available in expressions"
|
|
236
|
+
raise SandboxError(msg)
|
|
237
|
+
if name in _MUTATORS and isinstance(obj, _MUTABLE):
|
|
238
|
+
msg = f"{type(obj).__name__}.{name} would change a shared value; build a new one instead"
|
|
239
|
+
raise SandboxError(msg)
|
|
240
|
+
value = getattr(obj, name)
|
|
241
|
+
if name in _PADDING and isinstance(obj, (str, bytes)):
|
|
242
|
+
return _guard_padding(value)
|
|
243
|
+
return value
|
|
244
|
+
|
|
245
|
+
|
|
246
|
+
def _guard_padding(method: Callable[..., Any]) -> Callable[..., Any]:
|
|
247
|
+
def padded(width: Any = 8, *args: object) -> object: # noqa: ANN401 -- as given
|
|
248
|
+
if isinstance(width, int) and width > MAX_LENGTH:
|
|
249
|
+
msg = f"a width over {MAX_LENGTH} is not allowed"
|
|
250
|
+
raise SandboxError(msg)
|
|
251
|
+
return method(width, *args)
|
|
252
|
+
|
|
253
|
+
return padded
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def check_format_spec(spec: str) -> str:
|
|
257
|
+
"""Refuse format widths and precisions over :data:`MAX_LENGTH`.
|
|
258
|
+
|
|
259
|
+
Raises:
|
|
260
|
+
SandboxError: for a format spec that would build a huge string.
|
|
261
|
+
"""
|
|
262
|
+
if any(int(n) > MAX_LENGTH for n in re.findall(r"\d+", spec)):
|
|
263
|
+
msg = f"a format width over {MAX_LENGTH} is not allowed"
|
|
264
|
+
raise SandboxError(msg)
|
|
265
|
+
return spec
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _sized(value: object) -> int | None:
|
|
269
|
+
return len(value) if isinstance(value, (str, bytes, list, tuple)) else None
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def multiply(left: Any, right: Any) -> Any: # noqa: ANN401 -- any operands
|
|
273
|
+
"""``left * right``, refusing repetition beyond :data:`MAX_LENGTH`.
|
|
274
|
+
|
|
275
|
+
Raises:
|
|
276
|
+
SandboxError: when the result would be too long.
|
|
277
|
+
"""
|
|
278
|
+
for seq, count in ((left, right), (right, left)):
|
|
279
|
+
size = _sized(seq)
|
|
280
|
+
if size is not None and isinstance(count, int) and size * count > MAX_LENGTH:
|
|
281
|
+
msg = f"a result longer than {MAX_LENGTH} is not allowed"
|
|
282
|
+
raise SandboxError(msg)
|
|
283
|
+
return left * right
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def power(left: Any, right: Any) -> Any: # noqa: ANN401 -- any operands
|
|
287
|
+
"""``left ** right``, refusing integer exponents beyond :data:`MAX_EXPONENT`.
|
|
288
|
+
|
|
289
|
+
Raises:
|
|
290
|
+
SandboxError: for a huge integer exponent.
|
|
291
|
+
"""
|
|
292
|
+
if isinstance(right, int) and abs(right) > MAX_EXPONENT and not isinstance(left, float):
|
|
293
|
+
msg = f"an exponent over {MAX_EXPONENT} is not allowed"
|
|
294
|
+
raise SandboxError(msg)
|
|
295
|
+
return left**right
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
def left_shift(left: Any, right: Any) -> Any: # noqa: ANN401 -- any operands
|
|
299
|
+
"""``left << right``, refusing shifts beyond :data:`MAX_EXPONENT`.
|
|
300
|
+
|
|
301
|
+
Raises:
|
|
302
|
+
SandboxError: for a huge shift.
|
|
303
|
+
"""
|
|
304
|
+
if isinstance(right, int) and right > MAX_EXPONENT:
|
|
305
|
+
msg = f"a shift over {MAX_EXPONENT} is not allowed"
|
|
306
|
+
raise SandboxError(msg)
|
|
307
|
+
return left << right
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def bounded(items: Iterable[Any]) -> Iterator[Any]:
|
|
311
|
+
"""Iterate, refusing more than :data:`MAX_ITEMS` items.
|
|
312
|
+
|
|
313
|
+
Raises:
|
|
314
|
+
SandboxError: past the limit.
|
|
315
|
+
"""
|
|
316
|
+
for count, item in enumerate(items):
|
|
317
|
+
if count >= MAX_ITEMS:
|
|
318
|
+
msg = f"more than {MAX_ITEMS} items in one comprehension is not allowed"
|
|
319
|
+
raise SandboxError(msg)
|
|
320
|
+
yield item
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def safe_range(*args: int) -> range:
|
|
324
|
+
"""``range``, refusing more than :data:`MAX_ITEMS` items.
|
|
325
|
+
|
|
326
|
+
Raises:
|
|
327
|
+
SandboxError: for a longer range.
|
|
328
|
+
"""
|
|
329
|
+
result = range(*args)
|
|
330
|
+
if len(result) > MAX_ITEMS:
|
|
331
|
+
msg = f"a range of more than {MAX_ITEMS} items is not allowed"
|
|
332
|
+
raise SandboxError(msg)
|
|
333
|
+
return result
|
map_conform/expr/sdk.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"""SDK stream-map expressions in map-conform's scope (detailed design §15).
|
|
2
|
+
|
|
3
|
+
An SDK stream-map expression sees the *source* record's properties as bare names. In
|
|
4
|
+
map-conform a bare name is a conformed column, so an SDK expression is rewritten once, when
|
|
5
|
+
its stream map is translated: every free name that the SDK would have resolved from the
|
|
6
|
+
record becomes ``record['name']``. ``self``, ``_``, ``record``, ``config``,
|
|
7
|
+
``__stream_name__``, ``__original_stream_name__``, ``fake`` and the SDK functions keep their
|
|
8
|
+
meaning, so the rewritten text evaluates exactly as the SDK would.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import ast
|
|
14
|
+
import sys
|
|
15
|
+
|
|
16
|
+
if sys.version_info >= (3, 12):
|
|
17
|
+
from typing import override
|
|
18
|
+
else:
|
|
19
|
+
from typing_extensions import override
|
|
20
|
+
|
|
21
|
+
_Comprehension = ast.ListComp | ast.SetComp | ast.GeneratorExp | ast.DictComp
|
|
22
|
+
|
|
23
|
+
_SDK_NAMES = frozenset(
|
|
24
|
+
{
|
|
25
|
+
"self",
|
|
26
|
+
"_",
|
|
27
|
+
"record",
|
|
28
|
+
"config",
|
|
29
|
+
"__stream_name__",
|
|
30
|
+
"__original_stream_name__",
|
|
31
|
+
"fake",
|
|
32
|
+
# simpleeval's DEFAULT_FUNCTIONS, its compound types, and the SDK's additions
|
|
33
|
+
"list",
|
|
34
|
+
"tuple",
|
|
35
|
+
"dict",
|
|
36
|
+
"set",
|
|
37
|
+
"rand",
|
|
38
|
+
"randint",
|
|
39
|
+
"int",
|
|
40
|
+
"float",
|
|
41
|
+
"str",
|
|
42
|
+
"md5",
|
|
43
|
+
"sha256",
|
|
44
|
+
"datetime",
|
|
45
|
+
"bool",
|
|
46
|
+
"json",
|
|
47
|
+
# literals simpleeval also names
|
|
48
|
+
"True",
|
|
49
|
+
"False",
|
|
50
|
+
"None",
|
|
51
|
+
}
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class _RecordNames(ast.NodeTransformer):
|
|
56
|
+
"""Rewrites free names to ``record[...]``, leaving comprehension variables alone."""
|
|
57
|
+
|
|
58
|
+
def __init__(self) -> None:
|
|
59
|
+
self.bound: list[set[str]] = []
|
|
60
|
+
self.changed = False
|
|
61
|
+
|
|
62
|
+
@override
|
|
63
|
+
def visit_Name(self, node: ast.Name) -> ast.expr:
|
|
64
|
+
if (
|
|
65
|
+
not isinstance(node.ctx, ast.Load)
|
|
66
|
+
or node.id in _SDK_NAMES
|
|
67
|
+
or any(node.id in scope for scope in self.bound)
|
|
68
|
+
):
|
|
69
|
+
return node
|
|
70
|
+
self.changed = True
|
|
71
|
+
record = ast.Name(id="record", ctx=ast.Load())
|
|
72
|
+
return ast.copy_location(
|
|
73
|
+
ast.Subscript(value=record, slice=ast.Constant(node.id), ctx=ast.Load()), node
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
def _comprehension(self, node: _Comprehension) -> ast.expr:
|
|
77
|
+
pushed = 0
|
|
78
|
+
for gen in node.generators:
|
|
79
|
+
gen.iter = self.visit(gen.iter)
|
|
80
|
+
self.bound.append({n.id for n in ast.walk(gen.target) if isinstance(n, ast.Name)})
|
|
81
|
+
pushed += 1
|
|
82
|
+
gen.ifs = [self.visit(cond) for cond in gen.ifs]
|
|
83
|
+
if isinstance(node, ast.DictComp):
|
|
84
|
+
node.key = self.visit(node.key)
|
|
85
|
+
node.value = self.visit(_present(node.value))
|
|
86
|
+
else:
|
|
87
|
+
node.elt = self.visit(node.elt)
|
|
88
|
+
del self.bound[len(self.bound) - pushed :]
|
|
89
|
+
return node
|
|
90
|
+
|
|
91
|
+
visit_ListComp = visit_SetComp = visit_GeneratorExp = visit_DictComp = _comprehension # noqa: N815
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _present(node: ast.expr | None) -> ast.expr:
|
|
95
|
+
"""A child node the grammar requires (typeshed marks some optional on newer Pythons)."""
|
|
96
|
+
if node is None:
|
|
97
|
+
msg = "incomplete expression"
|
|
98
|
+
raise SyntaxError(msg)
|
|
99
|
+
return node
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def rewrite_sdk_expression(text: str) -> str:
|
|
103
|
+
"""The expression with the record's properties read through ``record[...]``.
|
|
104
|
+
|
|
105
|
+
Text that does not parse, or needs no change, is returned as written; compiling text
|
|
106
|
+
that does not parse reports the error.
|
|
107
|
+
"""
|
|
108
|
+
try:
|
|
109
|
+
tree = ast.parse(text.strip(), mode="eval")
|
|
110
|
+
except (SyntaxError, ValueError, RecursionError, MemoryError):
|
|
111
|
+
return text
|
|
112
|
+
transformer = _RecordNames()
|
|
113
|
+
rewritten = transformer.visit(tree)
|
|
114
|
+
if not transformer.changed:
|
|
115
|
+
return text
|
|
116
|
+
return ast.unparse(ast.fix_missing_locations(rewritten))
|