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.
Files changed (79) hide show
  1. map_conform/__init__.py +5 -0
  2. map_conform/__main__.py +7 -0
  3. map_conform/batch/__init__.py +1 -0
  4. map_conform/batch/arrow.py +80 -0
  5. map_conform/batch/columnar.py +125 -0
  6. map_conform/batch/engine.py +191 -0
  7. map_conform/batch/files.py +207 -0
  8. map_conform/cli.py +460 -0
  9. map_conform/doctor.py +178 -0
  10. map_conform/errors.py +107 -0
  11. map_conform/expr/__init__.py +6 -0
  12. map_conform/expr/compiler.py +562 -0
  13. map_conform/expr/functions.py +542 -0
  14. map_conform/expr/sandbox.py +333 -0
  15. map_conform/expr/sdk.py +116 -0
  16. map_conform/map-conform-spec.schema.json +1204 -0
  17. map_conform/mapper.py +355 -0
  18. map_conform/metadata.py +73 -0
  19. map_conform/metrics.py +62 -0
  20. map_conform/naming/__init__.py +1 -0
  21. map_conform/naming/ascii-table.json +980 -0
  22. map_conform/naming/conform.py +262 -0
  23. map_conform/naming/flatten.py +148 -0
  24. map_conform/naming/nested.py +117 -0
  25. map_conform/naming/reserved/ansi.txt +369 -0
  26. map_conform/naming/reserved/duckdb.txt +114 -0
  27. map_conform/naming/reserved/postgres.txt +105 -0
  28. map_conform/naming/reserved/snowflake.txt +90 -0
  29. map_conform/naming/reserved.py +34 -0
  30. map_conform/naming/shape.py +96 -0
  31. map_conform/naming/streams.py +76 -0
  32. map_conform/naming/translit.py +170 -0
  33. map_conform/plan/__init__.py +1 -0
  34. map_conform/plan/chain.py +667 -0
  35. map_conform/plan/compile.py +551 -0
  36. map_conform/plan/lower.py +281 -0
  37. map_conform/plan/ops.py +336 -0
  38. map_conform/plan/row.py +212 -0
  39. map_conform/plan/vector.py +71 -0
  40. map_conform/rejects.py +92 -0
  41. map_conform/settings.py +157 -0
  42. map_conform/spec/__init__.py +1 -0
  43. map_conform/spec/_struct.py +483 -0
  44. map_conform/spec/bridge.py +109 -0
  45. map_conform/spec/check.py +380 -0
  46. map_conform/spec/errors.py +22 -0
  47. map_conform/spec/importer.py +87 -0
  48. map_conform/spec/jsonschema.py +54 -0
  49. map_conform/spec/load.py +357 -0
  50. map_conform/spec/model.py +473 -0
  51. map_conform/spec/reference.py +179 -0
  52. map_conform/spec/steps.py +297 -0
  53. map_conform/spec/stream_maps.py +233 -0
  54. map_conform/spec/zamboni.py +99 -0
  55. map_conform/transforms/__init__.py +1 -0
  56. map_conform/transforms/builtins.py +63 -0
  57. map_conform/transforms/casts.py +310 -0
  58. map_conform/transforms/fake.py +150 -0
  59. map_conform/transforms/nested.py +111 -0
  60. map_conform/transforms/numeric.py +318 -0
  61. map_conform/transforms/polars_vector.py +151 -0
  62. map_conform/transforms/privacy.py +220 -0
  63. map_conform/transforms/registry.py +116 -0
  64. map_conform/transforms/temporal.py +410 -0
  65. map_conform/transforms/text.py +249 -0
  66. map_conform/transforms/vector.py +386 -0
  67. map_conform/types/__init__.py +1 -0
  68. map_conform/types/canonical.py +255 -0
  69. map_conform/types/from_jsonschema.py +177 -0
  70. map_conform/types/jsontext.py +63 -0
  71. map_conform/types/to_arrow.py +52 -0
  72. map_conform/types/to_jsonschema.py +65 -0
  73. map_conform/types/wire.py +53 -0
  74. map_conform/udfs.py +327 -0
  75. map_conform-0.1.0.dist-info/METADATA +157 -0
  76. map_conform-0.1.0.dist-info/RECORD +79 -0
  77. map_conform-0.1.0.dist-info/WHEEL +4 -0
  78. map_conform-0.1.0.dist-info/entry_points.txt +2 -0
  79. map_conform-0.1.0.dist-info/licenses/LICENSE +201 -0
map_conform/errors.py ADDED
@@ -0,0 +1,107 @@
1
+ """Runtime conform errors and the on_error policy (detailed design §12).
2
+
3
+ A :class:`ConformError` names the stream, column, row, value and rule, so a data engineer can
4
+ find the bad cell and decide: fix the cleanup in the spec, or drop the column. The default
5
+ policy is ``raise``; ``null`` and ``keep`` trade correctness for continuity, and ``reject``
6
+ sends the row to the dead-letter sink.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from typing import Literal
13
+
14
+ OnError = Literal["raise", "null", "keep", "reject"]
15
+
16
+ _VALUE_PREVIEW = 80
17
+
18
+
19
+ @dataclass(frozen=True)
20
+ class CellError:
21
+ """What went wrong with one value, before the row context is known."""
22
+
23
+ rule: str
24
+ """The step that failed, e.g. ``cast: decimal(10,2)`` or ``strip_chars``."""
25
+ reason: str
26
+
27
+
28
+ class ConformError(ValueError):
29
+ """A value that could not be conformed, with everything needed to find and fix it."""
30
+
31
+ def __init__( # noqa: PLR0913 -- the context is the point of this error
32
+ self,
33
+ *,
34
+ stream: str,
35
+ column: str,
36
+ row: int | None,
37
+ value: object,
38
+ rule: str,
39
+ reason: str,
40
+ ) -> None:
41
+ """Record the context and build a one-line message."""
42
+ self.stream = stream
43
+ self.column = column
44
+ self.row = row
45
+ self.value = value
46
+ self.rule = rule
47
+ self.reason = reason
48
+ where = f"row {row}" if row is not None else "a row"
49
+ shown = repr(value)
50
+ if len(shown) > _VALUE_PREVIEW:
51
+ shown = shown[: _VALUE_PREVIEW - 3] + "..."
52
+ super().__init__(
53
+ f"stream {stream!r}, column {column!r}, {where}: {rule} failed on {shown}: {reason}. "
54
+ "Fix the column's transform in the spec, set on_error, or drop the column."
55
+ )
56
+
57
+
58
+ class StepFailed(Exception): # noqa: N818 -- raised by a step to signal a CellError
59
+ """Raised inside a transform; the executor adds the row context."""
60
+
61
+ def __init__(self, reason: str) -> None:
62
+ """Say why the value failed."""
63
+ self.reason = reason
64
+ super().__init__(reason)
65
+
66
+
67
+ class RowRejected(Exception): # noqa: N818 -- a control-flow signal, not a failure
68
+ """The row goes to the dead-letter sink (on_error: reject)."""
69
+
70
+ def __init__(self, error: ConformError) -> None:
71
+ """Keep the error that rejected the row."""
72
+ self.error = error
73
+ super().__init__(str(error))
74
+
75
+
76
+ def apply_policy(policy: OnError, error: ConformError, raw: object) -> object:
77
+ """What a failed value becomes under ``policy``.
78
+
79
+ Returns:
80
+ None for ``null``; the raw input value for ``keep``.
81
+
82
+ Raises:
83
+ ConformError: for ``raise``.
84
+ RowRejected: for ``reject``.
85
+ """
86
+ if policy == "null":
87
+ return None
88
+ if policy == "keep":
89
+ return raw
90
+ if policy == "reject":
91
+ raise RowRejected(error)
92
+ raise error
93
+
94
+
95
+ class ThresholdExceeded(RuntimeError): # noqa: N818 -- reads as what happened
96
+ """A stream's reject or null rate went over its limit."""
97
+
98
+ def __init__( # noqa: PLR0913 -- the numbers that explain the failure
99
+ self, stream: str, *, what: str, rate: float, limit: float, count: int, rows: int
100
+ ) -> None:
101
+ """Say which stream, which rate, and by how much."""
102
+ self.stream = stream
103
+ super().__init__(
104
+ f"stream {stream!r}: {count} of {rows} rows {what} ({rate:.1%}), over the limit of "
105
+ f"{limit:.1%}. The source may have changed; check its rejects or nulls, then fix "
106
+ "the spec or raise the limit."
107
+ )
@@ -0,0 +1,6 @@
1
+ """The safe expression language (detailed design §7)."""
2
+
3
+ from map_conform.expr.compiler import ExprError, Expression, Names, Row, compile_expr
4
+ from map_conform.expr.functions import FUNCTIONS, Function
5
+
6
+ __all__ = ["FUNCTIONS", "ExprError", "Expression", "Function", "Names", "Row", "compile_expr"]
@@ -0,0 +1,562 @@
1
+ """Compile expressions to Python closures (detailed design §7).
2
+
3
+ An expression is parsed once with ``ast.parse(mode="eval")``. A whitelist visitor turns each
4
+ node into a closure, so evaluation never walks the tree again, and every name is resolved at
5
+ compile time: an unknown name is an error at the spec path, not a crash on the first row.
6
+
7
+ **Names**, in the order they are looked up:
8
+
9
+ 1. comprehension variables;
10
+ 2. ``value`` (alias ``self``): the value the step works on, in a column chain;
11
+ 3. ``record`` (alias ``_``): the source record, read-only; ``row_number``; ``NULL``;
12
+ 4. the compile-time constants: ``config``, ``stream``, ``source_stream`` (and the SDK names
13
+ ``__stream_name__``, ``__original_stream_name__``);
14
+ 5. the stream's columns, by conformed name: their conformed values (the column being
15
+ computed is not one of them: use ``value``, or ``record[...]`` for its source);
16
+ 6. the caller's functions (builtin steps, ``cast``, macros, UDFs), then the function library
17
+ and the read-only modules.
18
+
19
+ In call position (``name(...)``) functions are looked up first, after comprehension
20
+ variables, so a column named ``max`` does not hide ``max()``, and ``fake(value, 'name')`` is
21
+ the step while ``fake.name()`` uses the ``fake`` object. ``source(name)`` reads the source
22
+ record by raw name.
23
+
24
+ Anything outside the whitelist (assignment, lambdas, ``await``, the walrus operator, private
25
+ attributes, calls through anything but a name or an attribute) is a compile error. What an
26
+ evaluation may reach at run time is bounded by :mod:`map_conform.expr.sandbox`.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import ast
32
+ import operator
33
+ import warnings
34
+ from collections.abc import Callable, Iterator, Mapping
35
+ from dataclasses import dataclass, field
36
+ from types import MappingProxyType
37
+ from typing import Any
38
+
39
+ from map_conform.errors import StepFailed
40
+ from map_conform.expr.functions import FUNCTIONS
41
+ from map_conform.expr.sandbox import (
42
+ MAX_ITEMS,
43
+ SandboxError,
44
+ check_format_spec,
45
+ get_attribute,
46
+ left_shift,
47
+ multiply,
48
+ power,
49
+ )
50
+
51
+ Closure = Callable[["Frame"], Any]
52
+
53
+ _VALUE_NAMES = frozenset({"value", "self"})
54
+ _RECORD_NAMES = frozenset({"record", "_"})
55
+ _STREAM_ALIASES = MappingProxyType(
56
+ {"__stream_name__": "stream", "__original_stream_name__": "source_stream"}
57
+ )
58
+
59
+
60
+ class ExprError(Exception):
61
+ """An expression that cannot be compiled; the message says where and why."""
62
+
63
+
64
+ @dataclass(slots=True)
65
+ class Row:
66
+ """What expressions can see of the row being conformed."""
67
+
68
+ record: Mapping[str, Any]
69
+ """The source record, read-only."""
70
+ values: dict[str, Any] = field(default_factory=dict)
71
+ """Conformed values of the columns computed so far, by output name."""
72
+ number: int = 0
73
+ """The row's ordinal within its tap stream."""
74
+ dropped: list[tuple[str, str]] = field(default_factory=list)
75
+ """(column, member path) for each member a declared shape dropped in this row."""
76
+
77
+ @classmethod
78
+ def of(cls, record: Mapping[str, Any], number: int = 0) -> Row:
79
+ """A row over a source record, which expressions cannot change."""
80
+ return cls(MappingProxyType(dict(record)), {}, number, [])
81
+
82
+
83
+ @dataclass(slots=True)
84
+ class Frame:
85
+ """One evaluation: the row, the current value and any comprehension variables."""
86
+
87
+ row: Row
88
+ value: Any
89
+ local: dict[str, Any]
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class Names:
94
+ """What an expression may refer to, fixed when it is compiled."""
95
+
96
+ columns: frozenset[str] = frozenset()
97
+ """Conformed column names in scope."""
98
+ own: str | None = None
99
+ """The column this expression computes, which it cannot read by name."""
100
+ value: bool = True
101
+ """Whether ``value``/``self`` are in scope (true in column chains)."""
102
+ constants: Mapping[str, Any] = field(default_factory=lambda: MappingProxyType({}))
103
+ """``config``, ``stream`` and ``source_stream``."""
104
+ functions: Mapping[str, Any] = field(default_factory=lambda: MappingProxyType({}))
105
+ """Callables besides the library: builtin steps, ``cast``, macros and UDFs. Like the
106
+ library, they win over columns in call position and lose to them elsewhere."""
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class Expression:
111
+ """A compiled expression."""
112
+
113
+ text: str
114
+ reads: frozenset[str]
115
+ """The columns it reads, by conformed name; its dependencies."""
116
+ uses_value: bool
117
+ _fn: Closure = field(repr=False, compare=False)
118
+
119
+ def evaluate(self, row: Row, value: object = None) -> Any: # noqa: ANN401 -- any value
120
+ """Evaluate on a row.
121
+
122
+ Raises:
123
+ StepFailed: naming the error, for the caller's ``on_error``.
124
+ """
125
+ try:
126
+ result = self._fn(Frame(row, value, {}))
127
+ except StepFailed:
128
+ raise
129
+ except SandboxError as exc:
130
+ raise StepFailed(str(exc)) from None
131
+ except Exception as exc: # noqa: BLE001 -- any failure becomes a cell error with context
132
+ raise StepFailed(f"{type(exc).__name__}: {exc}") from None
133
+ # The read-only record view leaves the sandbox as a plain dict (``_data: record``).
134
+ return dict(result) if isinstance(result, MappingProxyType) else result
135
+
136
+
137
+ def parse_expression(text: str) -> ast.Expression:
138
+ r"""Parse expression text.
139
+
140
+ ``"\d"`` in a non-raw string stays a backslash and a d, as in Python, without a warning
141
+ (a SyntaxWarning from Python 3.12, a DeprecationWarning before).
142
+
143
+ Raises:
144
+ SyntaxError: for text that is not an expression.
145
+ """
146
+ with warnings.catch_warnings():
147
+ warnings.simplefilter("ignore", SyntaxWarning)
148
+ warnings.simplefilter("ignore", DeprecationWarning)
149
+ return ast.parse(text.strip(), mode="eval")
150
+
151
+
152
+ def compile_expr(text: str, names: Names | None = None) -> Expression:
153
+ """Compile an expression.
154
+
155
+ Raises:
156
+ ExprError: for a syntax error, a construct outside the whitelist, or an unknown name.
157
+ """
158
+ names = names or Names()
159
+ try:
160
+ tree = parse_expression(text)
161
+ except SyntaxError as exc:
162
+ raise ExprError(f"syntax error: {exc.msg} (at column {exc.offset or 0})") from None
163
+ except (ValueError, RecursionError, MemoryError) as exc:
164
+ raise ExprError(f"cannot parse: {type(exc).__name__}") from None
165
+ compiler = _Compiler(names)
166
+ fn = compiler.node(tree.body)
167
+ return Expression(text, frozenset(compiler.reads), compiler.uses_value, fn)
168
+
169
+
170
+ _BINARY: Mapping[type[ast.operator], Callable[[Any, Any], Any]] = MappingProxyType(
171
+ {
172
+ ast.Add: operator.add,
173
+ ast.Sub: operator.sub,
174
+ ast.Mult: multiply,
175
+ ast.Div: operator.truediv,
176
+ ast.FloorDiv: operator.floordiv,
177
+ ast.Mod: lambda a, b: operator.mod(check_format_spec(a) if isinstance(a, str) else a, b),
178
+ ast.Pow: power,
179
+ ast.LShift: left_shift,
180
+ ast.RShift: operator.rshift,
181
+ ast.BitOr: operator.or_,
182
+ ast.BitXor: operator.xor,
183
+ ast.BitAnd: operator.and_,
184
+ }
185
+ )
186
+ _UNARY: Mapping[type[ast.unaryop], Callable[[Any], Any]] = MappingProxyType(
187
+ {
188
+ ast.Not: operator.not_,
189
+ ast.USub: operator.neg,
190
+ ast.UAdd: operator.pos,
191
+ ast.Invert: operator.invert,
192
+ }
193
+ )
194
+ _COMPARE: Mapping[type[ast.cmpop], Callable[[Any, Any], bool]] = MappingProxyType(
195
+ {
196
+ ast.Eq: operator.eq,
197
+ ast.NotEq: operator.ne,
198
+ ast.Lt: operator.lt,
199
+ ast.LtE: operator.le,
200
+ ast.Gt: operator.gt,
201
+ ast.GtE: operator.ge,
202
+ ast.Is: operator.is_,
203
+ ast.IsNot: operator.is_not,
204
+ ast.In: lambda a, b: a in b,
205
+ ast.NotIn: lambda a, b: a not in b,
206
+ }
207
+ )
208
+ _CONVERSIONS: Mapping[int, Callable[[Any], Any]] = MappingProxyType(
209
+ {-1: lambda v: v, ord("s"): str, ord("r"): repr, ord("a"): ascii}
210
+ )
211
+
212
+
213
+ class _Compiler:
214
+ """Turns whitelisted AST nodes into closures."""
215
+
216
+ def __init__(self, names: Names) -> None:
217
+ self.names = names
218
+ self.reads: set[str] = set()
219
+ self.uses_value = False
220
+ self.scopes: list[frozenset[str]] = []
221
+
222
+ def node(self, node: ast.expr) -> Closure:
223
+ method = getattr(self, f"_{type(node).__name__}", None)
224
+ if method is None:
225
+ raise ExprError(f"{_describe(node)} is not allowed in expressions{_at(node)}")
226
+ return method(node)
227
+
228
+ # --- leaves -------------------------------------------------------------------------
229
+
230
+ def _Constant(self, node: ast.Constant) -> Closure: # noqa: N802 -- AST node name
231
+ value = node.value
232
+ return lambda _f: value
233
+
234
+ def _Name(self, node: ast.Name, *, call: bool = False) -> Closure: # noqa: N802, C901, PLR0911, PLR0912 -- one branch per scope
235
+ name = node.id
236
+ if any(name in scope for scope in self.scopes):
237
+ return lambda f: f.local[name]
238
+ if name in _VALUE_NAMES and self.names.value:
239
+ self.uses_value = True
240
+ return lambda f: f.value
241
+ if name in _RECORD_NAMES:
242
+ return lambda f: f.row.record
243
+ if name == "row_number":
244
+ return lambda f: f.row.number
245
+ if name == "NULL":
246
+ return lambda _f: None
247
+ if call and (fn := self._function(name)) is not None:
248
+ return lambda _f: fn
249
+ constant_name = _STREAM_ALIASES.get(name, name)
250
+ if constant_name in self.names.constants:
251
+ constant = self.names.constants[constant_name]
252
+ return lambda _f: constant
253
+ if name == self.names.own:
254
+ raise ExprError(
255
+ f"{name!r} is the column being computed; use value, or record[{name!r}] "
256
+ f"for its source{_at(node)}"
257
+ )
258
+ if name in self.names.columns:
259
+ self.reads.add(name)
260
+ return lambda f: f.row.values.get(name)
261
+ if (fn := self._function(name)) is not None:
262
+ return lambda _f: fn
263
+ if name in _VALUE_NAMES:
264
+ hint = " (no value here)"
265
+ elif name.startswith("_"):
266
+ hint = ""
267
+ else:
268
+ hint = f"; use record[{name!r}] for a source property"
269
+ raise ExprError(f"unknown name {name!r}{hint}{_at(node)}")
270
+
271
+ def _function(self, name: str) -> object | None:
272
+ if name in self.names.functions:
273
+ return self.names.functions[name]
274
+ return FUNCTIONS[name].fn if name in FUNCTIONS else None
275
+
276
+ # --- operators ----------------------------------------------------------------------
277
+
278
+ def _BinOp(self, node: ast.BinOp) -> Closure: # noqa: N802
279
+ op = _BINARY.get(type(node.op))
280
+ if op is None:
281
+ raise ExprError(f"operator {type(node.op).__name__} is not allowed{_at(node)}")
282
+ left, right = self.node(node.left), self.node(node.right)
283
+ return lambda f: op(left(f), right(f))
284
+
285
+ def _UnaryOp(self, node: ast.UnaryOp) -> Closure: # noqa: N802
286
+ op = _UNARY[type(node.op)]
287
+ operand = self.node(node.operand)
288
+ return lambda f: op(operand(f))
289
+
290
+ def _BoolOp(self, node: ast.BoolOp) -> Closure: # noqa: N802
291
+ parts = [self.node(v) for v in node.values]
292
+ if isinstance(node.op, ast.And):
293
+
294
+ def all_of(f: Frame) -> Any: # noqa: ANN401
295
+ result: Any = True
296
+ for part in parts:
297
+ result = part(f)
298
+ if not result:
299
+ return result
300
+ return result
301
+
302
+ return all_of
303
+
304
+ def any_of(f: Frame) -> Any: # noqa: ANN401
305
+ result: Any = False
306
+ for part in parts:
307
+ result = part(f)
308
+ if result:
309
+ return result
310
+ return result
311
+
312
+ return any_of
313
+
314
+ def _Compare(self, node: ast.Compare) -> Closure: # noqa: N802
315
+ left = self.node(node.left)
316
+ steps = [
317
+ (_COMPARE[type(op)], self.node(right))
318
+ for op, right in zip(node.ops, node.comparators, strict=True)
319
+ ]
320
+
321
+ def compare(f: Frame) -> bool:
322
+ current = left(f)
323
+ for op, right in steps:
324
+ following = right(f)
325
+ if not op(current, following):
326
+ return False
327
+ current = following
328
+ return True
329
+
330
+ return compare
331
+
332
+ def _IfExp(self, node: ast.IfExp) -> Closure: # noqa: N802
333
+ test, body, orelse = self.node(node.test), self.node(node.body), self.node(node.orelse)
334
+ return lambda f: body(f) if test(f) else orelse(f)
335
+
336
+ # --- access -------------------------------------------------------------------------
337
+
338
+ def _Attribute(self, node: ast.Attribute) -> Closure: # noqa: N802
339
+ if node.attr.startswith("_"):
340
+ raise ExprError(f"attribute {node.attr!r} is not allowed{_at(node)}")
341
+ obj = self.node(node.value)
342
+ attr = node.attr
343
+ return lambda f: get_attribute(obj(f), attr)
344
+
345
+ def _Subscript(self, node: ast.Subscript) -> Closure: # noqa: N802
346
+ obj, key = self.node(node.value), self.node(node.slice)
347
+ return lambda f: obj(f)[key(f)]
348
+
349
+ def _Slice(self, node: ast.Slice) -> Closure: # noqa: N802
350
+ parts = [None if p is None else self.node(p) for p in (node.lower, node.upper, node.step)]
351
+ return lambda f: slice(*(None if p is None else p(f) for p in parts))
352
+
353
+ def _Call(self, node: ast.Call) -> Closure: # noqa: N802
354
+ if (
355
+ isinstance(node.func, ast.Name)
356
+ and node.func.id == "source"
357
+ and not self._local("source")
358
+ ):
359
+ return self._source(node)
360
+ if isinstance(node.func, ast.Name):
361
+ func = self._Name(node.func, call=True)
362
+ elif isinstance(node.func, ast.Attribute):
363
+ func = self._Attribute(node.func)
364
+ else:
365
+ raise ExprError(f"only named functions and methods can be called{_at(node)}")
366
+ args = self._items(node.args)
367
+ kwargs = [(k.arg, self.node(k.value)) for k in node.keywords]
368
+
369
+ def call(f: Frame) -> Any: # noqa: ANN401
370
+ named: dict[str, Any] = {}
371
+ for key, value in kwargs:
372
+ if key is None:
373
+ named.update(value(f))
374
+ else:
375
+ named[key] = value(f)
376
+ return func(f)(*args(f), **named)
377
+
378
+ return call
379
+
380
+ def _source(self, node: ast.Call) -> Closure:
381
+ if len(node.args) != 1 or node.keywords:
382
+ raise ExprError(f"source takes one source property name{_at(node)}")
383
+ name = self.node(node.args[0])
384
+ return lambda f: f.row.record.get(name(f))
385
+
386
+ def _local(self, name: str) -> bool:
387
+ return any(name in scope for scope in self.scopes)
388
+
389
+ # --- displays -----------------------------------------------------------------------
390
+
391
+ def _items(self, nodes: list[ast.expr]) -> Callable[[Frame], list[Any]]:
392
+ parts: list[tuple[bool, Closure]] = []
393
+ for item in nodes:
394
+ if isinstance(item, ast.Starred):
395
+ parts.append((True, self.node(item.value)))
396
+ else:
397
+ parts.append((False, self.node(item)))
398
+
399
+ def items(f: Frame) -> list[Any]:
400
+ out: list[Any] = []
401
+ for starred, part in parts:
402
+ if starred:
403
+ out.extend(part(f))
404
+ else:
405
+ out.append(part(f))
406
+ return out
407
+
408
+ return items
409
+
410
+ def _List(self, node: ast.List) -> Closure: # noqa: N802
411
+ return self._items(node.elts)
412
+
413
+ def _Tuple(self, node: ast.Tuple) -> Closure: # noqa: N802
414
+ items = self._items(node.elts)
415
+ return lambda f: tuple(items(f))
416
+
417
+ def _Set(self, node: ast.Set) -> Closure: # noqa: N802
418
+ items = self._items(node.elts)
419
+ return lambda f: set(items(f))
420
+
421
+ def _Dict(self, node: ast.Dict) -> Closure: # noqa: N802
422
+ pairs = [
423
+ (None if k is None else self.node(k), self.node(v))
424
+ for k, v in zip(node.keys, node.values, strict=True)
425
+ ]
426
+
427
+ def build(f: Frame) -> dict[Any, Any]:
428
+ out: dict[Any, Any] = {}
429
+ for key, value in pairs:
430
+ if key is None:
431
+ out.update(value(f))
432
+ else:
433
+ out[key(f)] = value(f)
434
+ return out
435
+
436
+ return build
437
+
438
+ def _JoinedStr(self, node: ast.JoinedStr) -> Closure: # noqa: N802
439
+ parts = [self.node(v) for v in node.values]
440
+ return lambda f: "".join(str(p(f)) for p in parts)
441
+
442
+ def _FormattedValue(self, node: ast.FormattedValue) -> Closure: # noqa: N802
443
+ value = self.node(node.value)
444
+ convert = _CONVERSIONS[node.conversion]
445
+ spec = None if node.format_spec is None else self.node(node.format_spec)
446
+ if spec is None:
447
+ return lambda f: format(convert(value(f)))
448
+ return lambda f: format(convert(value(f)), check_format_spec(spec(f)))
449
+
450
+ # --- comprehensions -----------------------------------------------------------------
451
+
452
+ def _comprehension(
453
+ self, node: ast.ListComp | ast.SetComp | ast.GeneratorExp | ast.DictComp
454
+ ) -> tuple[list[tuple[Callable[[Any, dict[str, Any]], None], Closure, list[Closure]]], Any]:
455
+ loops: list[tuple[Callable[[Any, dict[str, Any]], None], Closure, list[Closure]]] = []
456
+ pushed = 0
457
+ try:
458
+ for gen in node.generators:
459
+ if gen.is_async:
460
+ raise ExprError(f"async comprehensions are not allowed{_at(node)}")
461
+ iterable = self.node(gen.iter) # evaluated in the enclosing scope
462
+ bind, bound = _binder(gen.target)
463
+ self.scopes.append(bound)
464
+ pushed += 1
465
+ loops.append((bind, iterable, [self.node(c) for c in gen.ifs]))
466
+ if isinstance(node, ast.DictComp):
467
+ body: Any = (self.node(node.key), self.node(_present(node.value)))
468
+ else:
469
+ body = self.node(node.elt)
470
+ finally:
471
+ del self.scopes[len(self.scopes) - pushed :]
472
+ return loops, body
473
+
474
+ def _ListComp(self, node: ast.ListComp) -> Closure: # noqa: N802
475
+ loops, body = self._comprehension(node)
476
+ return lambda f: [body(inner) for inner in _iterate(loops, f)]
477
+
478
+ def _GeneratorExp(self, node: ast.GeneratorExp) -> Closure: # noqa: N802
479
+ # Evaluated eagerly: a generator object would carry a frame out of the sandbox.
480
+ loops, body = self._comprehension(node)
481
+ return lambda f: [body(inner) for inner in _iterate(loops, f)]
482
+
483
+ def _SetComp(self, node: ast.SetComp) -> Closure: # noqa: N802
484
+ loops, body = self._comprehension(node)
485
+ return lambda f: {body(inner) for inner in _iterate(loops, f)}
486
+
487
+ def _DictComp(self, node: ast.DictComp) -> Closure: # noqa: N802
488
+ loops, (key, value) = self._comprehension(node)
489
+ return lambda f: {key(inner): value(inner) for inner in _iterate(loops, f)}
490
+
491
+
492
+ def _binder(target: ast.expr) -> tuple[Callable[[Any, dict[str, Any]], None], frozenset[str]]:
493
+ """How a comprehension target binds an item, and the names it binds."""
494
+ if isinstance(target, ast.Name):
495
+ name = target.id
496
+
497
+ def bind_name(item: object, local: dict[str, Any]) -> None:
498
+ local[name] = item
499
+
500
+ return bind_name, frozenset({name})
501
+ if isinstance(target, ast.Tuple) and all(isinstance(e, ast.Name) for e in target.elts):
502
+ names = [e.id for e in target.elts if isinstance(e, ast.Name)]
503
+
504
+ def bind_tuple(item: Any, local: dict[str, Any]) -> None: # noqa: ANN401
505
+ values = tuple(item)
506
+ if len(values) != len(names):
507
+ msg = f"cannot unpack {len(values)} values into {len(names)} names"
508
+ raise ValueError(msg)
509
+ local.update(zip(names, values, strict=True))
510
+
511
+ return bind_tuple, frozenset(names)
512
+ raise ExprError(f"a comprehension target must be a name or a tuple of names{_at(target)}")
513
+
514
+
515
+ def _iterate(
516
+ loops: list[tuple[Callable[[Any, dict[str, Any]], None], Closure, list[Closure]]],
517
+ frame: Frame,
518
+ ) -> Iterator[Frame]:
519
+ """Every combination of the loops' items that passes their conditions, at most MAX_ITEMS."""
520
+ budget = [MAX_ITEMS]
521
+
522
+ def level(index: int, current: Frame) -> Iterator[Frame]:
523
+ if index == len(loops):
524
+ yield current
525
+ return
526
+ bind, iterable, conditions = loops[index]
527
+ for item in iterable(current):
528
+ budget[0] -= 1
529
+ if budget[0] < 0:
530
+ msg = f"more than {MAX_ITEMS} steps in one comprehension is not allowed"
531
+ raise SandboxError(msg)
532
+ local = dict(current.local)
533
+ bind(item, local)
534
+ inner = Frame(current.row, current.value, local)
535
+ if all(condition(inner) for condition in conditions):
536
+ yield from level(index + 1, inner)
537
+
538
+ return level(0, frame)
539
+
540
+
541
+ def _present(node: ast.expr | None) -> ast.expr:
542
+ """A child node the grammar requires (typeshed marks some optional on newer Pythons)."""
543
+ if node is None:
544
+ raise ExprError("incomplete expression")
545
+ return node
546
+
547
+
548
+ def _describe(node: ast.AST) -> str:
549
+ names = {
550
+ "Lambda": "a lambda",
551
+ "NamedExpr": "assignment (:=)",
552
+ "Await": "await",
553
+ "Yield": "yield",
554
+ "YieldFrom": "yield",
555
+ "Starred": "unpacking here",
556
+ }
557
+ return names.get(type(node).__name__, type(node).__name__)
558
+
559
+
560
+ def _at(node: ast.AST) -> str:
561
+ offset = getattr(node, "col_offset", None)
562
+ return "" if offset is None else f" (at column {offset + 1})"