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
@@ -0,0 +1,667 @@
1
+ """Compile a column's transform chain (detailed design §3.4, §7, §9).
2
+
3
+ Compilation resolves each step to a builtin, a macro, an ``expr`` or a ``case``, validates
4
+ kwargs with the spec's strict parser, compiles expressions, and tracks the value's type
5
+ through the chain as a *stage*: ``None`` is the raw tap value (or an expression's result),
6
+ otherwise the CType the value has. The chain must end as the column's declared type: when it
7
+ ends raw, or typed differently with no explicit cast, the implicit cast is appended,
8
+ configured from the stream defaults, the column's overrides and its ``parse``.
9
+
10
+ - A step with ``when`` must keep the value's type, since rows where it is false skip it.
11
+ Before the cast this always holds: every row is raw afterwards, and the cast follows.
12
+ - A ``case`` whose branches end in different types gets the implicit cast at the end of each
13
+ branch, so every row leaves it as the column's type.
14
+ - A column's ``expr`` is its first step; its ``when`` applies the whole chain only where it
15
+ is truthy, and other rows get the implicit cast alone; ``fields`` run after the cast.
16
+
17
+ Every problem is recorded with its spec path; nothing is checked again at run time.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import dataclasses
23
+ import json
24
+ import re
25
+ import typing
26
+ from collections.abc import Mapping
27
+ from dataclasses import dataclass, field
28
+ from types import MappingProxyType
29
+ from typing import TYPE_CHECKING, Any
30
+
31
+ from map_conform.errors import StepFailed
32
+ from map_conform.expr.compiler import ExprError, Expression, Names, compile_expr
33
+ from map_conform.expr.functions import FUNCTIONS
34
+ from map_conform.naming.shape import Shape
35
+ from map_conform.plan.ops import (
36
+ CaseOp,
37
+ CastArgs,
38
+ CompiledChain,
39
+ CompiledStep,
40
+ ExprOp,
41
+ FieldOp,
42
+ FieldsOp,
43
+ GuardedOp,
44
+ Op,
45
+ ShapeOp,
46
+ StepError,
47
+ path_segments,
48
+ )
49
+ from map_conform.spec._struct import (
50
+ INVALID,
51
+ Invalid,
52
+ Issues,
53
+ child,
54
+ parse_dataclass,
55
+ thaw,
56
+ thaw_mapping,
57
+ )
58
+ from map_conform.spec.model import ColumnSpec, Defaults
59
+ from map_conform.spec.steps import CallStep, CaseStep, Chain, ExprStep, Macro
60
+ from map_conform.transforms.registry import Context, Registry
61
+ from map_conform.types.canonical import CType, CTypeError, parse_ctype
62
+
63
+ if TYPE_CHECKING:
64
+ from map_conform.spec.model import FieldSpec
65
+ from map_conform.spec.steps import Step
66
+ from map_conform.transforms.registry import Transform
67
+
68
+ _PARAM = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}")
69
+ _STRING = CType("string")
70
+
71
+
72
+ @dataclass(frozen=True)
73
+ class _Sequence:
74
+ """Compiled ops, the stage they end at, and whether an explicit cast ran."""
75
+
76
+ ops: tuple[Op, ...]
77
+ stage: CType | None
78
+ cast_seen: bool
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class _Context:
83
+ """What the steps of one chain share."""
84
+
85
+ column: ColumnSpec | None
86
+ target: CType
87
+ own: str | None
88
+ column_expr: str | None = None
89
+ """The spec path of the column's ``expr``, while its first step is still to compile."""
90
+
91
+
92
+ @dataclass
93
+ class ChainCompiler:
94
+ """Compiles chains for one stream: its settings, macros, registry and expression scope."""
95
+
96
+ registry: Registry
97
+ settings: Defaults
98
+ macros: Mapping[str, Macro]
99
+ issues: Issues
100
+ scope: Names = field(default_factory=Names)
101
+ """Columns and constants expressions may use; ``own`` is set per column."""
102
+ stream: str = ""
103
+
104
+ def __post_init__(self) -> None:
105
+ """Make builtins, casts and macros callable from expressions."""
106
+ if "cast" in self.scope.functions:
107
+ return # already set up (a scratch copy made by dataclasses.replace)
108
+ functions: dict[str, Any] = {
109
+ name: _StepFunction(self, transform)
110
+ for name, transform in self.registry.transforms.items()
111
+ if name not in FUNCTIONS
112
+ }
113
+ functions["cast"] = _CastFunction(self)
114
+ functions.update(self.scope.functions)
115
+ self.scope = dataclasses.replace(self.scope, functions=MappingProxyType(functions))
116
+
117
+ # --- columns ------------------------------------------------------------------------
118
+
119
+ def compile_column(
120
+ self, spec: ColumnSpec | None, target: CType, path: str, own: str | None = None
121
+ ) -> CompiledChain | None:
122
+ """A column's whole chain: ``expr``, ``transform``, the cast, ``fields`` and ``when``.
123
+
124
+ Returns None when there were problems (recorded in ``issues``).
125
+ """
126
+ if spec is None:
127
+ return self.compile(None, None, target, path, own=own)
128
+ steps: list[Step] = []
129
+ if spec.expr is not None:
130
+ steps.append(ExprStep(spec.expr))
131
+ if spec.transform is not None:
132
+ steps.extend(spec.transform.steps)
133
+ before = len(self.issues.items)
134
+ full = self.compile(
135
+ Chain(tuple(steps)) if steps else None,
136
+ spec,
137
+ target,
138
+ path,
139
+ own=own,
140
+ column_expr=child(path, "expr") if spec.expr is not None else None,
141
+ )
142
+ if spec.fields is not None:
143
+ fields = self._fields(spec, target, path, own)
144
+ if full is not None and fields is not None:
145
+ full = CompiledChain((*full.steps, fields), target)
146
+ if spec.shape is not None and full is not None: # first, on the source value
147
+ shape = ShapeOp(Shape.of(thaw_mapping(spec.shape)), own or path)
148
+ full = CompiledChain((shape, *full.steps), target)
149
+ if full is None or len(self.issues.items) != before:
150
+ return None
151
+ if spec.when is None:
152
+ return full
153
+ when = self._expr(spec.when, child(path, "when"), own, target)
154
+ otherwise = self.compile(None, spec, target, path, own=own)
155
+ if when is None or otherwise is None:
156
+ return None
157
+ return CompiledChain((CaseOp(((when, full),), otherwise, label="when"),), target)
158
+
159
+ def compile( # noqa: PLR0913 -- the column context
160
+ self,
161
+ chain: Chain | None,
162
+ column: ColumnSpec | None,
163
+ target: CType,
164
+ path: str,
165
+ *,
166
+ own: str | None = None,
167
+ column_expr: str | None = None,
168
+ ) -> CompiledChain | None:
169
+ """Compile a chain ending as ``target``; None when it had problems."""
170
+ before = len(self.issues.items)
171
+ context = _Context(column, target, own, column_expr)
172
+ seq = self._sequence(chain, child(path, "transform"), None, context, ())
173
+ if seq is None or len(self.issues.items) != before:
174
+ return None # a failed step makes any further type error a consequence of it
175
+ ops = list(seq.ops)
176
+ stage = seq.stage
177
+ if stage != target and (stage is None or not seq.cast_seen):
178
+ implicit = self.cast_step(
179
+ arg=None, extra={}, column=column, target=target, stage=stage,
180
+ path=child(path, "transform"),
181
+ ) # fmt: skip
182
+ if implicit is None:
183
+ return None
184
+ ops.append(implicit)
185
+ stage = target
186
+ if stage != target:
187
+ self.issues.add(
188
+ child(path, "transform"),
189
+ f"the chain ends as {_stage(stage)}, but the column is {target}",
190
+ )
191
+ return None
192
+ return CompiledChain(tuple(ops), target)
193
+
194
+ # --- sequences ----------------------------------------------------------------------
195
+
196
+ def _sequence(
197
+ self,
198
+ chain: Chain | None,
199
+ base: str,
200
+ stage: CType | None,
201
+ context: _Context,
202
+ stack: tuple[str, ...],
203
+ ) -> _Sequence | None:
204
+ """Compile steps in order from ``stage``; None when any step failed."""
205
+ if chain is None:
206
+ return _Sequence((), stage, cast_seen=False)
207
+ ops: list[Op] = []
208
+ cast_seen = False
209
+ ok = True
210
+ many = len(chain.steps) > 1
211
+ for i, step in enumerate(chain.steps):
212
+ step_path = child(base, i) if many else base
213
+ expr_at = child(step_path, "expr")
214
+ if context.column_expr is not None:
215
+ expr_at = step_path = context.column_expr # the column's own expr
216
+ context = dataclasses.replace(context, column_expr=None)
217
+ compiled = self._step(step, step_path, expr_at, stage, context, stack)
218
+ if compiled is None:
219
+ ok = False
220
+ continue
221
+ ops.extend(compiled.ops)
222
+ stage = compiled.stage
223
+ cast_seen = cast_seen or compiled.cast_seen
224
+ return _Sequence(tuple(ops), stage, cast_seen) if ok else None
225
+
226
+ def _step( # noqa: PLR0913, PLR0917 -- the step and where it sits
227
+ self,
228
+ step: Step,
229
+ path: str,
230
+ expr_at: str,
231
+ stage: CType | None,
232
+ context: _Context,
233
+ stack: tuple[str, ...],
234
+ ) -> _Sequence | None:
235
+ seq: _Sequence | None
236
+ if isinstance(step, ExprStep):
237
+ expression = self._expr(step.expr, expr_at, context.own, context.target)
238
+ seq = (
239
+ None
240
+ if expression is None
241
+ else _Sequence((ExprOp(expression),), None, cast_seen=False)
242
+ )
243
+ elif isinstance(step, CaseStep):
244
+ seq = self._case(step, path, stage, context, stack)
245
+ elif step.name in self.macros:
246
+ seq = self._macro(step, path, stage, context, stack)
247
+ else:
248
+ seq = self._call(step, path, stage, context)
249
+ if seq is None or step.when is None:
250
+ return seq
251
+ when = self._expr(step.when, child(path, "when"), context.own, context.target)
252
+ if when is None:
253
+ return None
254
+ if stage is not None and seq.stage != stage:
255
+ self.issues.add(
256
+ path,
257
+ f"a step with 'when' must keep the value's type ({_stage(stage)} becomes "
258
+ f"{_stage(seq.stage)}); use case, or put 'when' on the column",
259
+ )
260
+ return None
261
+ # Before the cast, rows that skip the step stay raw, so the value is raw after it.
262
+ return _Sequence((GuardedOp(when, seq.ops),), stage, cast_seen=False)
263
+
264
+ def _call( # noqa: PLR0911 -- one early return per problem
265
+ self, step: CallStep, path: str, stage: CType | None, context: _Context
266
+ ) -> _Sequence | None:
267
+ if step.name == "cast":
268
+ compiled = self.cast_step(
269
+ arg=step.arg, extra=step.kwargs, column=context.column, target=context.target,
270
+ stage=stage, path=path,
271
+ ) # fmt: skip
272
+ if compiled is None:
273
+ return None
274
+ return _Sequence((compiled,), compiled.kwargs.target, cast_seen=True)
275
+ transform = self.registry.transforms.get(step.name)
276
+ if transform is None:
277
+ self.issues.add(path, f"unknown step {step.name!r}: not a builtin or a macro")
278
+ return None
279
+ if not transform.accepts_stage(stage):
280
+ self.issues.add(path, f"{step.name} cannot take {_stage(stage)} here")
281
+ return None
282
+ kinds = transform.column_kinds
283
+ if kinds is not None and context.target.kind not in kinds:
284
+ self.issues.add(
285
+ path,
286
+ f"{step.name} works only in {', '.join(sorted(kinds))} columns, not "
287
+ f"{context.target}; declare the column's type",
288
+ )
289
+ return None
290
+ kwargs = self._kwargs(transform, step.arg, step.kwargs, path)
291
+ if isinstance(kwargs, Invalid):
292
+ return None
293
+ out = transform.output_stage(stage, kwargs)
294
+ return _Sequence((CompiledStep(transform, kwargs, step.name),), out, cast_seen=False)
295
+
296
+ def _case(
297
+ self,
298
+ step: CaseStep,
299
+ path: str,
300
+ stage: CType | None,
301
+ context: _Context,
302
+ stack: tuple[str, ...],
303
+ ) -> _Sequence | None:
304
+ """Branches compile from the same stage; differing ends are each cast to the column."""
305
+ case_path = child(path, "case")
306
+ branches: list[tuple[Expression | None, _Sequence, str]] = []
307
+ ok = True
308
+ for i, branch in enumerate(step.branches):
309
+ when = self._expr(
310
+ branch.when, child(child(case_path, i), "when"), context.own, context.target
311
+ )
312
+ then_path = child(child(case_path, i), "then")
313
+ seq = self._sequence(branch.then, then_path, stage, context, stack)
314
+ if when is None or seq is None:
315
+ ok = False
316
+ continue
317
+ branches.append((when, seq, then_path))
318
+ else_path = child(child(case_path, len(step.branches)), "else")
319
+ otherwise = self._sequence(step.otherwise, else_path, stage, context, stack)
320
+ if not ok or otherwise is None:
321
+ return None
322
+ branches.append((None, otherwise, else_path))
323
+ stages = {seq.stage for _, seq, _ in branches}
324
+ out = stages.pop() if len(stages) == 1 else context.target
325
+ finished: list[CompiledChain] = []
326
+ for _, seq, branch_path in branches:
327
+ ops = list(seq.ops)
328
+ if seq.stage != out:
329
+ cast = self.cast_step(
330
+ arg=None, extra={}, column=context.column, target=context.target,
331
+ stage=seq.stage, path=branch_path,
332
+ ) # fmt: skip
333
+ if cast is None:
334
+ return None
335
+ ops.append(cast)
336
+ finished.append(CompiledChain(tuple(ops), out or context.target))
337
+ else_chain = finished.pop()
338
+ whens = tuple(
339
+ (when, chain)
340
+ for (when, _, _), chain in zip(branches, finished, strict=False)
341
+ if when is not None
342
+ )
343
+ keep_else = step.otherwise is not None or bool(else_chain.steps)
344
+ cast_seen = all(seq.cast_seen for _, seq, _ in branches)
345
+ return _Sequence((CaseOp(whens, else_chain if keep_else else None),), out, cast_seen)
346
+
347
+ def _macro(
348
+ self,
349
+ step: CallStep,
350
+ path: str,
351
+ stage: CType | None,
352
+ context: _Context,
353
+ stack: tuple[str, ...],
354
+ ) -> _Sequence | None:
355
+ expanded = self._expand_macro(step, path, stack)
356
+ if expanded is None:
357
+ return None
358
+ # Steps inside a macro report at its definition, where they would be fixed.
359
+ definition = child(child("macros", step.name), "steps")
360
+ return self._sequence(expanded, definition, stage, context, (*stack, step.name))
361
+
362
+ def _expand_macro(self, step: CallStep, path: str, stack: tuple[str, ...]) -> Chain | None:
363
+ if step.name in stack:
364
+ cycle = " -> ".join((*stack, step.name))
365
+ self.issues.add(path, f"macro cycle: {cycle}")
366
+ return None
367
+ macro = self.macros[step.name]
368
+ params = thaw_mapping(macro.params)
369
+ if step.arg is not None and not isinstance(step.arg, Mapping):
370
+ self.issues.add(path, f"macro {step.name!r} takes named parameters, not a value")
371
+ return None
372
+ given = thaw_mapping(step.arg) if isinstance(step.arg, Mapping) else {}
373
+ given.update(thaw_mapping(step.kwargs))
374
+ unknown = sorted(set(given) - set(params))
375
+ if unknown:
376
+ self.issues.add(path, f"macro {step.name!r} has no parameter {', '.join(unknown)}")
377
+ return None
378
+ params.update(given)
379
+ raw = _fill(macro.steps.spec_dump(), params)
380
+ expanded = Chain.spec_parse(raw, child(child("macros", step.name), "steps"), self.issues)
381
+ return expanded if isinstance(expanded, Chain) else None
382
+
383
+ # --- expressions --------------------------------------------------------------------
384
+
385
+ def _expr(
386
+ self, text: str, path: str, own: str | None, target: CType = _STRING
387
+ ) -> Expression | None:
388
+ """Compile an expression; macros called in it cast bare types to ``target``."""
389
+ macros = {name: _MacroFunction(self, name, target) for name in self.macros}
390
+ scope = dataclasses.replace(
391
+ self.scope, own=own, functions={**self.scope.functions, **macros}
392
+ )
393
+ try:
394
+ return compile_expr(text, scope)
395
+ except ExprError as exc:
396
+ self.issues.add(path, str(exc))
397
+ return None
398
+
399
+ # --- nested fields ------------------------------------------------------------------
400
+
401
+ def _fields(
402
+ self, spec: ColumnSpec, target: CType, path: str, own: str | None
403
+ ) -> FieldsOp | None:
404
+ fields_path = child(path, "fields")
405
+ members = spec.fields or {}
406
+ if target.kind not in {"struct", "json"}:
407
+ self.issues.add(fields_path, f"fields needs a struct or json column, not {target}")
408
+ return None
409
+ ops = [
410
+ op
411
+ for member_path, member in members.items()
412
+ if (op := self._field(member_path, member, target, child(fields_path, member_path),
413
+ own)) is not None
414
+ ] # fmt: skip
415
+ return FieldsOp(tuple(ops)) if len(ops) == len(members) else None
416
+
417
+ def _field( # noqa: PLR0911 -- one early return per problem
418
+ self, member_path: str, member: FieldSpec, target: CType, path: str, own: str | None
419
+ ) -> FieldOp | None:
420
+ segments = path_segments(member_path)
421
+ if segments is None:
422
+ self.issues.add(path, "a member path is names joined by '.', with [*] for list items")
423
+ return None
424
+ member_type = _member_type(target, segments) if target.kind == "struct" else None
425
+ if target.kind == "struct" and member_type is None:
426
+ self.issues.add(path, f"{member_path!r} is not a member of {target}")
427
+ return None
428
+ if member.drop and target.kind == "struct":
429
+ self.issues.add(path, "drop works on json members; for a struct, declare its type")
430
+ return None
431
+ when = None
432
+ if member.when is not None:
433
+ when = self._expr(member.when, child(path, "when"), own)
434
+ if when is None:
435
+ return None
436
+ chain = None
437
+ if member.transform is not None:
438
+ context = _Context(None, member_type or target, own)
439
+ transform_path = child(path, "transform")
440
+ seq = self._sequence(member.transform, transform_path, member_type, context, ())
441
+ if seq is None:
442
+ return None
443
+ if member_type is not None and seq.stage != member_type:
444
+ self.issues.add(
445
+ transform_path,
446
+ f"the member is {member_type}, but its chain ends as {_stage(seq.stage)}",
447
+ )
448
+ return None
449
+ chain = CompiledChain(seq.ops, member_type or target)
450
+ return FieldOp(member_path, segments, chain, when, member.drop)
451
+
452
+ # --- kwargs and casts ---------------------------------------------------------------
453
+
454
+ def _kwargs(
455
+ self, transform: Transform, arg: object, extra: Mapping[str, Any], path: str
456
+ ) -> Any: # noqa: ANN401 -- the transform's own kwargs dataclass
457
+ data: dict[str, Any] = {}
458
+ if isinstance(arg, Mapping) and not _positional_takes_mapping(transform, arg):
459
+ data.update(thaw_mapping(arg)) # {hash: {algo: md5}}: keyword arguments
460
+ elif arg is not None:
461
+ if transform.positional is None:
462
+ self.issues.add(path, f"{transform.name} takes keyword arguments only")
463
+ return INVALID
464
+ data[transform.positional] = thaw(arg)
465
+ data.update(thaw_mapping(extra))
466
+ return parse_dataclass(transform.kwargs, data, path, self.issues)
467
+
468
+ def cast_step( # noqa: PLR0913 -- the cast's full context
469
+ self,
470
+ *,
471
+ arg: object,
472
+ extra: Mapping[str, Any],
473
+ column: ColumnSpec | None,
474
+ target: CType,
475
+ stage: CType | None,
476
+ path: str,
477
+ ) -> CompiledStep | None:
478
+ """Resolve a cast to ``target`` (or to ``arg``), with layered options."""
479
+ cast_target = self._cast_target(arg, target, path)
480
+ if cast_target is None:
481
+ return None
482
+ caster = self.registry.casts.get(cast_target.kind)
483
+ if caster is None:
484
+ self.issues.add(path, f"there is no cast to {cast_target.kind} yet")
485
+ return None
486
+ if not caster.accepts_stage(stage):
487
+ self.issues.add(path, f"cast to {cast_target} cannot take {_stage(stage)}")
488
+ return None
489
+ data = caster.defaults(self.settings, column) if caster.defaults else {}
490
+ if column is not None and column.parse:
491
+ data.update(thaw_mapping(column.parse))
492
+ data.update(thaw_mapping(extra))
493
+ options = parse_dataclass(caster.kwargs, data, path, self.issues)
494
+ if isinstance(options, Invalid):
495
+ return None
496
+ return CompiledStep(caster, CastArgs(cast_target, options), f"cast: {cast_target}")
497
+
498
+ def _cast_target(self, arg: object, target: CType, path: str) -> CType | None:
499
+ if arg is None:
500
+ return target
501
+ if not isinstance(arg, str):
502
+ self.issues.add(path, "cast takes a type name, e.g. {cast: decimal}")
503
+ return None
504
+ if arg == target.kind: # {cast: decimal} on a decimal(18,2) column
505
+ return target
506
+ try:
507
+ return parse_ctype(arg)
508
+ except CTypeError as exc:
509
+ self.issues.add(path, str(exc))
510
+ return None
511
+
512
+ def sequence(self, chain: Chain, path: str, target: CType) -> CompiledChain | None:
513
+ """A chain from the raw value with no implicit cast, as a macro called as a function."""
514
+ seq = self._sequence(chain, path, None, _Context(None, target, None), ())
515
+ return None if seq is None else CompiledChain(seq.ops, seq.stage or target)
516
+
517
+ def context(self, target: CType = _STRING) -> Context:
518
+ """A context for steps called from an expression."""
519
+ fake = self.scope.constants.get("fake")
520
+ return Context(self.stream, "<expr>", self.settings, target, fake=fake)
521
+
522
+
523
+ def _member_type(ctype: CType, segments: tuple[str, ...]) -> CType | None:
524
+ current: CType | None = ctype
525
+ for segment in segments:
526
+ if current is None:
527
+ return None
528
+ if segment == "[*]":
529
+ current = current.item if current.kind == "list" else None
530
+ elif current.kind == "struct":
531
+ current = dict(current.members).get(segment)
532
+ else:
533
+ return None
534
+ return current
535
+
536
+
537
+ # --- steps called as functions from expressions ------------------------------------------------
538
+
539
+
540
+ def _problems(issues: Issues) -> str:
541
+ return "; ".join(str(issue) for issue in issues.items)
542
+
543
+
544
+ def _key(*parts: object) -> str:
545
+ return json.dumps(parts, sort_keys=True, default=repr)
546
+
547
+
548
+ class _StepFunction:
549
+ """A builtin step called from an expression: ``pad(value, 5)``, ``hash(value, algo='md5')``."""
550
+
551
+ def __init__(self, compiler: ChainCompiler, transform: Transform) -> None:
552
+ self.compiler = compiler
553
+ self.transform = transform
554
+ self.cache: dict[str, Any] = {}
555
+
556
+ def __call__(self, value: object, *args: object, **kwargs: object) -> object:
557
+ transform = self.transform
558
+ if args:
559
+ if transform.positional is None or len(args) > 1:
560
+ raise StepFailed(f"{transform.name} takes the value and keyword arguments")
561
+ kwargs[transform.positional] = args[0]
562
+ key = _key(kwargs)
563
+ if key not in self.cache:
564
+ issues = Issues()
565
+ parsed = parse_dataclass(transform.kwargs, dict(kwargs), transform.name, issues)
566
+ if issues:
567
+ raise StepFailed(_problems(issues))
568
+ self.cache[key] = parsed
569
+ if value is None and not transform.null_safe:
570
+ return None
571
+ return transform.scalar(value, self.cache[key], self.compiler.context())
572
+
573
+
574
+ class _CastFunction:
575
+ """``cast(value, "decimal(18,2)", **options)`` from an expression."""
576
+
577
+ def __init__(self, compiler: ChainCompiler) -> None:
578
+ self.compiler = compiler
579
+ self.cache: dict[str, CompiledStep] = {}
580
+
581
+ def __call__(self, value: object, type_name: str, **options: object) -> object:
582
+ key = _key(type_name, options)
583
+ if key not in self.cache:
584
+ try:
585
+ target = parse_ctype(type_name)
586
+ except CTypeError as exc:
587
+ raise StepFailed(str(exc)) from None
588
+ scratch = dataclasses.replace(self.compiler, issues=Issues())
589
+ step = scratch.cast_step(
590
+ arg=None, extra=options, column=None, target=target, stage=None, path="cast"
591
+ )
592
+ if step is None:
593
+ raise StepFailed(_problems(scratch.issues))
594
+ self.cache[key] = step
595
+ step = self.cache[key]
596
+ if value is None:
597
+ return None
598
+ return step.transform.scalar(value, step.kwargs, self.compiler.context(step.kwargs.target))
599
+
600
+
601
+ class _MacroFunction:
602
+ """A macro called from an expression: ``money(value, currency='€')``."""
603
+
604
+ def __init__(self, compiler: ChainCompiler, name: str, target: CType) -> None:
605
+ self.compiler = compiler
606
+ self.name = name
607
+ self.target = target
608
+ """The column's type: a bare ``{cast: decimal}`` in the macro means it."""
609
+ self.cache: dict[str, CompiledChain] = {}
610
+
611
+ def __call__(self, value: object, **params: object) -> object:
612
+ key = _key(params)
613
+ if key not in self.cache:
614
+ self.cache[key] = self._compile(params)
615
+ chain = self.cache[key]
616
+ try:
617
+ return chain.run(value, self.compiler.context(chain.target))
618
+ except StepError as exc:
619
+ raise StepFailed(f"{self.name}: {exc.cell.rule}: {exc.cell.reason}") from None
620
+
621
+ def _compile(self, params: Mapping[str, object]) -> CompiledChain:
622
+ scratch = dataclasses.replace(self.compiler, issues=Issues())
623
+ step = CallStep(self.name, arg=MappingProxyType(dict(params)) if params else None)
624
+ chain = scratch.sequence(Chain((step,)), self.name, self.target)
625
+ if chain is None:
626
+ raise StepFailed(_problems(scratch.issues))
627
+ if chain.reads:
628
+ raise StepFailed(f"macro {self.name!r} reads columns; use it as a step instead")
629
+ return chain
630
+
631
+
632
+ def _positional_takes_mapping(transform: Transform, arg: Mapping[str, Any]) -> bool:
633
+ """Whether a mapping argument is the positional value, as in ``{map_values: {Y: yes}}``.
634
+
635
+ That is so only when the positional kwarg is itself a mapping and the argument's keys are
636
+ not all kwarg names (``{map_values: {values: {...}, default: x}}`` is keyword arguments).
637
+ """
638
+ if transform.positional is None:
639
+ return False
640
+ hints = typing.get_type_hints(transform.kwargs)
641
+ if typing.get_origin(hints[transform.positional]) not in (Mapping, dict):
642
+ return False
643
+ return not set(arg) <= {f.name for f in dataclasses.fields(transform.kwargs)}
644
+
645
+
646
+ def _stage(stage: CType | None) -> str:
647
+ return "the raw value" if stage is None else f"a {stage} value"
648
+
649
+
650
+ def _fill(data: object, params: Mapping[str, object]) -> object:
651
+ """Substitute macro parameters into a macro's steps."""
652
+ if isinstance(data, dict):
653
+ return {k: _fill(v, params) for k, v in data.items()}
654
+ if isinstance(data, list):
655
+ return [_fill(v, params) for v in data]
656
+ if isinstance(data, str):
657
+ whole = _PARAM.fullmatch(data)
658
+ if whole and whole.group(1) in params:
659
+ return params[whole.group(1)]
660
+ return _PARAM.sub(
661
+ lambda m: _text(params[m.group(1)]) if m.group(1) in params else m.group(0), data
662
+ )
663
+ return data
664
+
665
+
666
+ def _text(value: object) -> str:
667
+ return value if isinstance(value, str) else json.dumps(value)