ectype-data 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 (115) hide show
  1. ectype/__init__.py +134 -0
  2. ectype/_version.py +5 -0
  3. ectype/authoring/__init__.py +13 -0
  4. ectype/authoring/builder.py +134 -0
  5. ectype/authoring/spec.py +555 -0
  6. ectype/calibration/__init__.py +26 -0
  7. ectype/calibration/adjustments.py +539 -0
  8. ectype/calibration/calibrator.py +781 -0
  9. ectype/cli.py +1181 -0
  10. ectype/compiler/__init__.py +1 -0
  11. ectype/compiler/plan.py +678 -0
  12. ectype/errors.py +43 -0
  13. ectype/fingerprint/__init__.py +1 -0
  14. ectype/fingerprint/comparison.py +746 -0
  15. ectype/fingerprint/container.py +408 -0
  16. ectype/fingerprint/core.py +263 -0
  17. ectype/fingerprint/disclosure.py +207 -0
  18. ectype/fingerprint/expressions.py +1317 -0
  19. ectype/fingerprint/schema.py +645 -0
  20. ectype/fingerprint/targets.py +352 -0
  21. ectype/generation/__init__.py +1 -0
  22. ectype/generation/enforce.py +163 -0
  23. ectype/generation/generator.py +525 -0
  24. ectype/generation/identifiers.py +235 -0
  25. ectype/generation/manifest.py +71 -0
  26. ectype/generation/parallel.py +229 -0
  27. ectype/io/__init__.py +16 -0
  28. ectype/io/adapters.py +224 -0
  29. ectype/io/sql.py +289 -0
  30. ectype/io/values.py +269 -0
  31. ectype/llm/__init__.py +27 -0
  32. ectype/llm/authoring.py +766 -0
  33. ectype/llm/providers.py +269 -0
  34. ectype/models/__init__.py +8 -0
  35. ectype/models/base.py +120 -0
  36. ectype/models/chain.py +2426 -0
  37. ectype/models/copulas.py +254 -0
  38. ectype/models/encoding.py +1117 -0
  39. ectype/models/forest.py +1087 -0
  40. ectype/models/marginals.py +2099 -0
  41. ectype/models/mixtures.py +336 -0
  42. ectype/models/neural/__init__.py +21 -0
  43. ectype/models/neural/adapter.py +638 -0
  44. ectype/models/neural/vae.py +432 -0
  45. ectype/models/vines.py +608 -0
  46. ectype/plugins.py +40 -0
  47. ectype/privacy/__init__.py +49 -0
  48. ectype/privacy/attacks.py +599 -0
  49. ectype/privacy/dp.py +313 -0
  50. ectype/privacy/report.py +364 -0
  51. ectype/profiler.py +783 -0
  52. ectype/profiling/__init__.py +1 -0
  53. ectype/profiling/bivariate.py +130 -0
  54. ectype/profiling/calendar.py +743 -0
  55. ectype/profiling/conditional.py +263 -0
  56. ectype/profiling/constraints.py +661 -0
  57. ectype/profiling/entity.py +1143 -0
  58. ectype/profiling/functional.py +651 -0
  59. ectype/profiling/multivariate.py +492 -0
  60. ectype/profiling/personal.py +277 -0
  61. ectype/profiling/pseudonym.py +370 -0
  62. ectype/profiling/reference.py +334 -0
  63. ectype/profiling/sketches.py +653 -0
  64. ectype/profiling/structural.py +1087 -0
  65. ectype/profiling/structure.py +1733 -0
  66. ectype/profiling/sums.py +1710 -0
  67. ectype/profiling/tolerance.py +435 -0
  68. ectype/profiling/univariate.py +555 -0
  69. ectype/py.typed +0 -0
  70. ectype/registry.py +48 -0
  71. ectype/relational/__init__.py +61 -0
  72. ectype/relational/container.py +212 -0
  73. ectype/relational/fit.py +633 -0
  74. ectype/relational/generate.py +418 -0
  75. ectype/relational/schema.py +280 -0
  76. ectype/relational/validate.py +288 -0
  77. ectype/reporting/__init__.py +439 -0
  78. ectype/reporting/adapter.py +2003 -0
  79. ectype/reporting/charts.py +964 -0
  80. ectype/reporting/drift.py +902 -0
  81. ectype/reporting/findings.py +622 -0
  82. ectype/reporting/fmt.py +429 -0
  83. ectype/reporting/render.py +1705 -0
  84. ectype/reporting/select.py +84 -0
  85. ectype/reporting/style.py +272 -0
  86. ectype/reporting/view.py +593 -0
  87. ectype/rng.py +33 -0
  88. ectype/scenarios/__init__.py +30 -0
  89. ectype/scenarios/feasibility.py +411 -0
  90. ectype/scenarios/merge.py +1392 -0
  91. ectype/scenarios/mutate.py +1613 -0
  92. ectype/temporal/__init__.py +80 -0
  93. ectype/temporal/contract.py +221 -0
  94. ectype/temporal/detect.py +431 -0
  95. ectype/temporal/events.py +946 -0
  96. ectype/temporal/panel.py +937 -0
  97. ectype/temporal/pipeline.py +192 -0
  98. ectype/temporal/regular.py +674 -0
  99. ectype/types.py +46 -0
  100. ectype/validation/__init__.py +1 -0
  101. ectype/validation/metrics/__init__.py +7 -0
  102. ectype/validation/metrics/base.py +68 -0
  103. ectype/validation/metrics/bivariate.py +353 -0
  104. ectype/validation/metrics/missingness.py +54 -0
  105. ectype/validation/metrics/multivariate.py +265 -0
  106. ectype/validation/metrics/temporal.py +596 -0
  107. ectype/validation/metrics/univariate.py +514 -0
  108. ectype/validation/report.py +627 -0
  109. ectype/validation/validator.py +707 -0
  110. ectype_data-0.1.0.dist-info/METADATA +376 -0
  111. ectype_data-0.1.0.dist-info/RECORD +115 -0
  112. ectype_data-0.1.0.dist-info/WHEEL +4 -0
  113. ectype_data-0.1.0.dist-info/entry_points.txt +2 -0
  114. ectype_data-0.1.0.dist-info/licenses/LICENSE +192 -0
  115. ectype_data-0.1.0.dist-info/licenses/NOTICE +5 -0
@@ -0,0 +1,1317 @@
1
+ """Constraint / derived-column expression language.
2
+
3
+ A small, safe expression grammar used by constraints and derived columns. Text is tokenized
4
+ and parsed by a hand-written recursive-descent parser into an immutable AST, type-checked
5
+ against the column schema and compiled to native Polars expressions. Nothing is ever passed
6
+ to ``eval``/``exec`` and no Python UDFs are produced.
7
+
8
+ Grammar (lowest to highest precedence)::
9
+
10
+ expr := implies
11
+ implies := or_expr ("implies" implies)? # right-associative: (not a) or b
12
+ or_expr := and_expr ("or" and_expr)*
13
+ and_expr := not_expr ("and" not_expr)*
14
+ not_expr := "not" not_expr | comparison
15
+ comparison := additive (CMP additive | "in" "[" literal ("," literal)* "]")?
16
+ additive := term (("+" | "-") term)*
17
+ term := unary (("*" | "/" | "%") unary)*
18
+ unary := "-" unary | atom
19
+ atom := NUMBER | STRING | "true" | "false" | "null" | column
20
+ | FUNC "(" args ")" | "(" expr ")"
21
+ column := IDENT | "`" any text ("``" escapes a backquote) "`"
22
+
23
+ Comparisons do not chain (``a < b < c`` is an error). Integer literals must fit in int64.
24
+ Arithmetic on unsigned integer columns is done in Int64 (Float64 for ``/``), so ``a - b`` can
25
+ be negative instead of wrapping around. A categorical (string-labelled) value cannot be
26
+ compared with a number. An ISO string compared with a time-zone-aware datetime is read in
27
+ that column's time zone. Every error is an
28
+ :class:`~ectype.errors.ExpressionError` whose message names the position, and
29
+ which carries a ``position`` attribute (0-based character offset, or ``None``).
30
+
31
+ Calendar parts of a date or datetime (in the column's own time zone): ``year``, ``quarter``
32
+ (1-4), ``month``, ``day``, ``weekday`` (ISO: Monday is 1, Sunday is 7), ``week`` (ISO week
33
+ number, 1-53) and ``fiscal_year(d, m)``, the fiscal year that starts in month ``m`` (an
34
+ integer literal 1-12) named by the calendar year in which it ends: ``year(d) + 1`` from month
35
+ ``m`` on, ``year(d)`` before, and ``year(d)`` itself for ``m = 1``.
36
+
37
+ Two functions hold a table of literals, so that a column that is a pure function of another
38
+ can be written down (``profiling.functional`` detects such columns, ADR-0011):
39
+
40
+ ``lookup(x, k1, v1, ..., kn, vn)`` or ``lookup(x, k1, v1, ..., kn, vn, default)``
41
+ ``vi`` where ``x == ki``; otherwise ``default``, or null without one. The keys are distinct
42
+ literals of the kind of ``x`` (numbers, or strings for a string or categorical ``x``).
43
+ ``step(x, v0, c1, v1, ..., cn, vn)``
44
+ A step function of a numeric ``x``: ``v0`` below ``c1``, ``vi`` from ``ci`` (included) up
45
+ to ``c(i+1)`` (excluded), ``vn`` from ``cn`` on. The cut points are numeric literals in
46
+ strictly increasing order.
47
+
48
+ The values ``vi`` are literals of one kind (numbers, strings or booleans; ``null`` is allowed).
49
+ Both give null for a null ``x`` (``step`` also for NaN).
50
+ """
51
+
52
+ from __future__ import annotations
53
+
54
+ import datetime as _dt
55
+ from dataclasses import dataclass, field
56
+ from typing import Any
57
+
58
+ import numpy as np
59
+ import polars as pl
60
+
61
+ from ectype.errors import ExpressionError
62
+ from ectype.fingerprint.schema import ColumnSchema
63
+ from ectype.types import LogicalType
64
+
65
+ __all__ = [
66
+ "MAX_DEPTH",
67
+ "MAX_LENGTH",
68
+ "FUNCTIONS",
69
+ "Node",
70
+ "Literal",
71
+ "Column",
72
+ "Unary",
73
+ "Binary",
74
+ "InList",
75
+ "Call",
76
+ "parse",
77
+ "referenced_columns",
78
+ "check",
79
+ "to_polars",
80
+ "evaluate",
81
+ "unparse",
82
+ ]
83
+
84
+ MAX_LENGTH = 2000
85
+ MAX_DEPTH = 64
86
+ _INT64_MAX = 2**63 - 1
87
+ _INT64_MIN = -(2**63)
88
+
89
+ # ---------------------------------------------------------------------------------------------
90
+ # AST
91
+ # ---------------------------------------------------------------------------------------------
92
+
93
+
94
+ @dataclass(frozen=True)
95
+ class Node:
96
+ """Base class of all AST nodes. ``pos`` is the source offset and is ignored by ``==``."""
97
+
98
+
99
+ @dataclass(frozen=True)
100
+ class Literal(Node):
101
+ value: int | float | str | bool | None
102
+ kind: str # "int" | "float" | "str" | "bool" | "null" (keeps 1, 1.0 and true distinct)
103
+ pos: int = field(default=0, compare=False, repr=False)
104
+
105
+
106
+ @dataclass(frozen=True)
107
+ class Column(Node):
108
+ name: str
109
+ pos: int = field(default=0, compare=False, repr=False)
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class Unary(Node):
114
+ op: str # "-" | "not"
115
+ operand: Node
116
+ pos: int = field(default=0, compare=False, repr=False)
117
+
118
+
119
+ @dataclass(frozen=True)
120
+ class Binary(Node):
121
+ op: str # + - * / % == != < <= > >= and or implies
122
+ left: Node
123
+ right: Node
124
+ pos: int = field(default=0, compare=False, repr=False)
125
+
126
+
127
+ @dataclass(frozen=True)
128
+ class InList(Node):
129
+ operand: Node
130
+ items: tuple[Literal, ...]
131
+ pos: int = field(default=0, compare=False, repr=False)
132
+
133
+
134
+ @dataclass(frozen=True)
135
+ class Call(Node):
136
+ name: str
137
+ args: tuple[Node, ...]
138
+ pos: int = field(default=0, compare=False, repr=False)
139
+
140
+
141
+ # name -> (min arity, max arity or None for variadic)
142
+ FUNCTIONS: dict[str, tuple[int, int | None]] = {
143
+ "abs": (1, 1),
144
+ "round": (1, 2),
145
+ "min": (2, None),
146
+ "max": (2, None),
147
+ "coalesce": (1, None),
148
+ "is_null": (1, 1),
149
+ "is_not_null": (1, 1),
150
+ "floor": (1, 1),
151
+ "ceil": (1, 1),
152
+ "log": (1, 1),
153
+ "exp": (1, 1),
154
+ "sqrt": (1, 1),
155
+ "year": (1, 1),
156
+ "month": (1, 1),
157
+ "day": (1, 1),
158
+ "date_diff_days": (2, 2),
159
+ "quarter": (1, 1),
160
+ "weekday": (1, 1),
161
+ "week": (1, 1),
162
+ "fiscal_year": (2, 2),
163
+ "lookup": (3, None),
164
+ "step": (4, None),
165
+ }
166
+ #: functions whose arguments after the first are literals (a table)
167
+ _TABLE_FUNCTIONS = ("lookup", "step")
168
+
169
+ _KEYWORDS = {"and", "or", "not", "implies", "in", "true", "false", "null"}
170
+ _COMPARISONS = ("==", "!=", "<=", ">=", "<", ">")
171
+ _ARITH = ("+", "-", "*", "/", "%")
172
+
173
+ # precedence levels (higher binds tighter)
174
+ _PREC = {
175
+ "implies": 1,
176
+ "or": 2,
177
+ "and": 3,
178
+ "not": 4,
179
+ "==": 5, "!=": 5, "<": 5, "<=": 5, ">": 5, ">=": 5, "in": 5,
180
+ "+": 6, "-": 6,
181
+ "*": 7, "/": 7, "%": 7,
182
+ "neg": 8,
183
+ }
184
+ _ATOM_PREC = 9
185
+
186
+
187
+ def _error(msg: str, pos: int | None, text: str | None = None) -> ExpressionError:
188
+ if pos is None:
189
+ err = ExpressionError(msg)
190
+ else:
191
+ detail = f"{msg} (at position {pos})"
192
+ if text is not None and len(text) <= 200:
193
+ detail += f"\n {text}\n {' ' * pos}^"
194
+ err = ExpressionError(detail)
195
+ err.position = pos # type: ignore[attr-defined]
196
+ return err
197
+
198
+
199
+ # ---------------------------------------------------------------------------------------------
200
+ # Tokenizer
201
+ # ---------------------------------------------------------------------------------------------
202
+
203
+
204
+ @dataclass(frozen=True)
205
+ class _Tok:
206
+ kind: str # NUM STR IDENT QIDENT KW OP EOF
207
+ value: Any
208
+ pos: int
209
+
210
+
211
+ _OPS2 = ("==", "!=", "<=", ">=")
212
+ _OPS1 = "+-*/%<>()[],"
213
+ _ESCAPES = {"n": "\n", "t": "\t", "r": "\r", "\\": "\\", "'": "'", '"': '"', "0": "\0"}
214
+
215
+
216
+ def _tokenize(text: str) -> list[_Tok]:
217
+ toks: list[_Tok] = []
218
+ i, n = 0, len(text)
219
+ while i < n:
220
+ c = text[i]
221
+ if c.isspace():
222
+ i += 1
223
+ continue
224
+ start = i
225
+ if c.isdigit() or (c == "." and i + 1 < n and text[i + 1].isdigit()):
226
+ while i < n and text[i].isdigit():
227
+ i += 1
228
+ is_float = False
229
+ if i < n and text[i] == ".":
230
+ is_float = True
231
+ i += 1
232
+ while i < n and text[i].isdigit():
233
+ i += 1
234
+ if i < n and text[i] in "eE":
235
+ j = i + 1
236
+ if j < n and text[j] in "+-":
237
+ j += 1
238
+ if j < n and text[j].isdigit():
239
+ is_float = True
240
+ i = j
241
+ while i < n and text[i].isdigit():
242
+ i += 1
243
+ else:
244
+ raise _error("malformed exponent in number", i, text)
245
+ if i < n and (text[i].isalpha() or text[i] == "_"):
246
+ raise _error("invalid character after number", i, text)
247
+ lexeme = text[start:i]
248
+ value: int | float = float(lexeme) if is_float else int(lexeme)
249
+ if isinstance(value, int) and value > _INT64_MAX:
250
+ raise _error("integer literal is outside the int64 range "
251
+ "(write it as a float, e.g. 1e19)", start, text)
252
+ toks.append(_Tok("NUM", value, start))
253
+ elif c in "'\"":
254
+ quote = c
255
+ i += 1
256
+ buf: list[str] = []
257
+ while True:
258
+ if i >= n:
259
+ raise _error("unterminated string literal", start, text)
260
+ ch = text[i]
261
+ if ch == "\\":
262
+ if i + 1 >= n:
263
+ raise _error("unterminated string literal", start, text)
264
+ esc = text[i + 1]
265
+ if esc not in _ESCAPES:
266
+ raise _error(f"unknown escape sequence '\\{esc}'", i, text)
267
+ buf.append(_ESCAPES[esc])
268
+ i += 2
269
+ elif ch == quote:
270
+ i += 1
271
+ break
272
+ else:
273
+ buf.append(ch)
274
+ i += 1
275
+ toks.append(_Tok("STR", "".join(buf), start))
276
+ elif c == "`":
277
+ i += 1
278
+ buf = []
279
+ while True:
280
+ if i >= n:
281
+ raise _error("unterminated backquoted column name", start, text)
282
+ if text[i] == "`":
283
+ if i + 1 < n and text[i + 1] == "`":
284
+ buf.append("`")
285
+ i += 2
286
+ continue
287
+ i += 1
288
+ break
289
+ buf.append(text[i])
290
+ i += 1
291
+ name = "".join(buf)
292
+ if not name:
293
+ raise _error("empty column name", start, text)
294
+ toks.append(_Tok("QIDENT", name, start))
295
+ elif c.isalpha() or c == "_":
296
+ while i < n and (text[i].isalnum() or text[i] == "_"):
297
+ i += 1
298
+ word = text[start:i]
299
+ toks.append(_Tok("KW" if word in _KEYWORDS else "IDENT", word, start))
300
+ elif text.startswith(_OPS2, i):
301
+ toks.append(_Tok("OP", text[i : i + 2], start))
302
+ i += 2
303
+ elif c in _OPS1:
304
+ toks.append(_Tok("OP", c, start))
305
+ i += 1
306
+ elif c == "=":
307
+ raise _error("unexpected '=' (use '==' for equality)", i, text)
308
+ else:
309
+ raise _error(f"unexpected character {c!r}", i, text)
310
+ toks.append(_Tok("EOF", None, n))
311
+ return toks
312
+
313
+
314
+ # ---------------------------------------------------------------------------------------------
315
+ # Parser
316
+ # ---------------------------------------------------------------------------------------------
317
+
318
+
319
+ def _depth(node: Node) -> int:
320
+ return getattr(node, "_depth", 1)
321
+
322
+
323
+ def _mk(node: Node, *children: Node) -> Node:
324
+ d = 1 + max((_depth(c) for c in children), default=0)
325
+ if d > MAX_DEPTH:
326
+ raise _error(f"expression nesting deeper than {MAX_DEPTH}", node.pos) # type: ignore[attr-defined]
327
+ object.__setattr__(node, "_depth", d)
328
+ return node
329
+
330
+
331
+ class _Parser:
332
+ def __init__(self, text: str) -> None:
333
+ self.text = text
334
+ self.toks = _tokenize(text)
335
+ self.i = 0
336
+ self.nesting = 0
337
+
338
+ # -- helpers --------------------------------------------------------------------------
339
+ def peek(self) -> _Tok:
340
+ return self.toks[self.i]
341
+
342
+ def advance(self) -> _Tok:
343
+ tok = self.toks[self.i]
344
+ self.i += 1
345
+ return tok
346
+
347
+ def at_op(self, *ops: str) -> bool:
348
+ t = self.peek()
349
+ return t.kind == "OP" and t.value in ops
350
+
351
+ def at_kw(self, kw: str) -> bool:
352
+ t = self.peek()
353
+ return t.kind == "KW" and t.value == kw
354
+
355
+ def expect_op(self, op: str, context: str) -> _Tok:
356
+ if not self.at_op(op):
357
+ raise self.err(f"expected '{op}' {context}, found {self.describe(self.peek())}")
358
+ return self.advance()
359
+
360
+ def describe(self, tok: _Tok) -> str:
361
+ if tok.kind == "EOF":
362
+ return "end of expression"
363
+ if tok.kind == "STR":
364
+ return f"string {tok.value!r}"
365
+ if tok.kind == "QIDENT":
366
+ return f"`{tok.value}`"
367
+ return f"'{tok.value}'"
368
+
369
+ def err(self, msg: str, pos: int | None = None) -> ExpressionError:
370
+ return _error(msg, self.peek().pos if pos is None else pos, self.text)
371
+
372
+ def enter(self, pos: int) -> None:
373
+ self.nesting += 1
374
+ if self.nesting > MAX_DEPTH:
375
+ raise _error(f"expression nesting deeper than {MAX_DEPTH}", pos, self.text)
376
+
377
+ def leave(self) -> None:
378
+ self.nesting -= 1
379
+
380
+ # -- grammar --------------------------------------------------------------------------
381
+ def parse(self) -> Node:
382
+ if self.peek().kind == "EOF":
383
+ raise self.err("empty expression")
384
+ node = self.expr()
385
+ if self.peek().kind != "EOF":
386
+ raise self.err(f"unexpected {self.describe(self.peek())}")
387
+ return node
388
+
389
+ def expr(self) -> Node:
390
+ return self.implies()
391
+
392
+ def implies(self) -> Node:
393
+ operands = [self.or_expr()]
394
+ positions: list[int] = []
395
+ while self.at_kw("implies"):
396
+ positions.append(self.advance().pos)
397
+ operands.append(self.or_expr())
398
+ node = operands[-1]
399
+ for left, pos in zip(reversed(operands[:-1]), reversed(positions)):
400
+ node = _mk(Binary("implies", left, node, pos), left, node)
401
+ return node
402
+
403
+ def or_expr(self) -> Node:
404
+ node = self.and_expr()
405
+ while self.at_kw("or"):
406
+ pos = self.advance().pos
407
+ right = self.and_expr()
408
+ node = _mk(Binary("or", node, right, pos), node, right)
409
+ return node
410
+
411
+ def and_expr(self) -> Node:
412
+ node = self.not_expr()
413
+ while self.at_kw("and"):
414
+ pos = self.advance().pos
415
+ right = self.not_expr()
416
+ node = _mk(Binary("and", node, right, pos), node, right)
417
+ return node
418
+
419
+ def not_expr(self) -> Node:
420
+ if self.at_kw("not"):
421
+ pos = self.advance().pos
422
+ self.enter(pos)
423
+ operand = self.not_expr()
424
+ self.leave()
425
+ return _mk(Unary("not", operand, pos), operand)
426
+ return self.comparison()
427
+
428
+ def comparison(self) -> Node:
429
+ left = self.additive()
430
+ if self.at_op(*_COMPARISONS):
431
+ tok = self.advance()
432
+ right = self.additive()
433
+ node = _mk(Binary(tok.value, left, right, tok.pos), left, right)
434
+ elif self.at_kw("in"):
435
+ tok = self.advance()
436
+ node = self.in_list(left, tok.pos)
437
+ else:
438
+ return left
439
+ if self.at_op(*_COMPARISONS) or self.at_kw("in"):
440
+ raise self.err("comparisons cannot be chained; combine them with 'and'")
441
+ return node
442
+
443
+ def in_list(self, operand: Node, pos: int) -> Node:
444
+ self.expect_op("[", "after 'in'")
445
+ items: list[Literal] = []
446
+ if self.at_op("]"):
447
+ raise self.err("'in' list must not be empty")
448
+ while True:
449
+ items.append(self.list_literal())
450
+ if self.at_op(","):
451
+ self.advance()
452
+ continue
453
+ self.expect_op("]", "to close 'in' list")
454
+ break
455
+ return _mk(InList(operand, tuple(items), pos), operand)
456
+
457
+ def list_literal(self) -> Literal:
458
+ tok = self.peek()
459
+ if self.at_op("-"):
460
+ self.advance()
461
+ num = self.peek()
462
+ if num.kind != "NUM":
463
+ raise self.err("'in' list items must be literals")
464
+ self.advance()
465
+ return Literal(-num.value, "int" if isinstance(num.value, int) else "float", tok.pos)
466
+ lit = self.literal()
467
+ if lit is None:
468
+ raise self.err(f"'in' list items must be literals, found {self.describe(tok)}")
469
+ return lit
470
+
471
+ def literal(self) -> Literal | None:
472
+ tok = self.peek()
473
+ if tok.kind == "NUM":
474
+ self.advance()
475
+ return Literal(tok.value, "int" if isinstance(tok.value, int) else "float", tok.pos)
476
+ if tok.kind == "STR":
477
+ self.advance()
478
+ return Literal(tok.value, "str", tok.pos)
479
+ if tok.kind == "KW" and tok.value in ("true", "false"):
480
+ self.advance()
481
+ return Literal(tok.value == "true", "bool", tok.pos)
482
+ if tok.kind == "KW" and tok.value == "null":
483
+ self.advance()
484
+ return Literal(None, "null", tok.pos)
485
+ return None
486
+
487
+ def additive(self) -> Node:
488
+ node = self.term()
489
+ while self.at_op("+", "-"):
490
+ tok = self.advance()
491
+ right = self.term()
492
+ node = _mk(Binary(tok.value, node, right, tok.pos), node, right)
493
+ return node
494
+
495
+ def term(self) -> Node:
496
+ node = self.unary()
497
+ while self.at_op("*", "/", "%"):
498
+ tok = self.advance()
499
+ right = self.unary()
500
+ node = _mk(Binary(tok.value, node, right, tok.pos), node, right)
501
+ return node
502
+
503
+ def unary(self) -> Node:
504
+ if self.at_op("-"):
505
+ pos = self.advance().pos
506
+ self.enter(pos)
507
+ operand = self.unary()
508
+ self.leave()
509
+ return _mk(Unary("-", operand, pos), operand)
510
+ return self.atom()
511
+
512
+ def atom(self) -> Node:
513
+ tok = self.peek()
514
+ lit = self.literal()
515
+ if lit is not None:
516
+ return lit
517
+ if tok.kind == "QIDENT":
518
+ self.advance()
519
+ return Column(tok.value, tok.pos)
520
+ if tok.kind == "IDENT":
521
+ self.advance()
522
+ if self.at_op("("):
523
+ return self.call(tok)
524
+ return Column(tok.value, tok.pos)
525
+ if self.at_op("("):
526
+ self.advance()
527
+ self.enter(tok.pos)
528
+ node = self.expr()
529
+ self.leave()
530
+ self.expect_op(")", "to close '('")
531
+ return node
532
+ if tok.kind == "EOF":
533
+ raise self.err("unexpected end of expression")
534
+ raise self.err(f"unexpected {self.describe(tok)}")
535
+
536
+ def call(self, name_tok: _Tok) -> Node:
537
+ name = name_tok.value
538
+ if name not in FUNCTIONS:
539
+ known = ", ".join(sorted(FUNCTIONS))
540
+ raise _error(f"unknown function '{name}' (known: {known})", name_tok.pos, self.text)
541
+ self.advance() # "("
542
+ self.enter(name_tok.pos)
543
+ args: list[Node] = []
544
+ if not self.at_op(")"):
545
+ while True:
546
+ args.append(self.expr())
547
+ if self.at_op(","):
548
+ self.advance()
549
+ continue
550
+ break
551
+ self.expect_op(")", f"to close call to '{name}'")
552
+ self.leave()
553
+ lo, hi = FUNCTIONS[name]
554
+ if len(args) < lo or (hi is not None and len(args) > hi):
555
+ want = f"{lo}" if lo == hi else (f"at least {lo}" if hi is None else f"{lo} to {hi}")
556
+ raise _error(
557
+ f"function '{name}' takes {want} argument(s), got {len(args)}",
558
+ name_tok.pos,
559
+ self.text,
560
+ )
561
+ if name == "round" and len(args) == 2:
562
+ nd = args[1]
563
+ if not (isinstance(nd, Literal) and nd.kind == "int" and 0 <= nd.value <= 15): # type: ignore[operator]
564
+ raise _error(
565
+ "round(x, n): n must be an integer literal between 0 and 15",
566
+ getattr(nd, "pos", name_tok.pos),
567
+ self.text,
568
+ )
569
+ if name == "fiscal_year":
570
+ m = args[1]
571
+ if not (isinstance(m, Literal) and m.kind == "int" and 1 <= m.value <= 12): # type: ignore[operator]
572
+ raise _error(
573
+ "fiscal_year(d, m): m (the month the fiscal year starts in) must be an "
574
+ "integer literal between 1 and 12",
575
+ getattr(m, "pos", name_tok.pos),
576
+ self.text,
577
+ )
578
+ if name in _TABLE_FUNCTIONS:
579
+ self.check_table(name, args, name_tok.pos)
580
+ return _mk(Call(name, tuple(args), name_tok.pos), *args)
581
+
582
+ def check_table(self, name: str, args: list[Node], pos: int) -> None:
583
+ """The literal table of ``lookup`` / ``step``: literals only, distinct keys, increasing
584
+ cut points, values of one kind."""
585
+ for a in args[1:]:
586
+ if not (isinstance(a, Literal) or _is_num_literal(a)):
587
+ raise _error(f"{name}(): every argument after the first must be a literal",
588
+ getattr(a, "pos", pos), self.text)
589
+ if name == "step":
590
+ if len(args) % 2:
591
+ raise _error("step(x, v0, c1, v1, ..., cn, vn) takes an even number of "
592
+ f"arguments, got {len(args)}", pos, self.text)
593
+ values, cuts = args[1::2], args[2::2]
594
+ if not all(_is_num_literal(c) for c in cuts):
595
+ raise _error("step(): the cut points must be numeric literals", pos, self.text)
596
+ nums = [_num_value(c) for c in cuts]
597
+ if any(b <= a for a, b in zip(nums, nums[1:])):
598
+ raise _error("step(): the cut points must be strictly increasing", pos,
599
+ self.text)
600
+ else:
601
+ pairs = args[1:] if len(args) % 2 else args[1:-1]
602
+ keys, values = pairs[0::2], [*pairs[1::2], *([] if len(args) % 2 else [args[-1]])]
603
+ kinds = {"num" if _is_num_literal(k) else _literal_kind(k) # type: ignore[arg-type]
604
+ for k in keys}
605
+ if not kinds <= {"num"} and not kinds <= {"str"}:
606
+ raise _error("lookup(): the keys must be all numbers or all strings", pos,
607
+ self.text)
608
+ seen = [_num_value(k) if _is_num_literal(k) else k.value # type: ignore[attr-defined]
609
+ for k in keys]
610
+ if len(set(seen)) != len(seen):
611
+ raise _error("lookup(): the keys must be distinct", pos, self.text)
612
+ vkinds = {"num" if _is_num_literal(v) else _literal_kind(v) # type: ignore[arg-type]
613
+ for v in values} - {"null"}
614
+ if len(vkinds) > 1:
615
+ raise _error(f"{name}(): the values must be of one kind (numbers, strings or "
616
+ f"booleans), got {sorted(vkinds)}", pos, self.text)
617
+
618
+
619
+ def parse(text: str) -> Node:
620
+ """Parse expression text into an immutable AST. Raises :class:`ExpressionError`."""
621
+ if not isinstance(text, str):
622
+ raise _error(f"expression must be a string, got {type(text).__name__}", None)
623
+ if len(text) > MAX_LENGTH:
624
+ raise _error(f"expression is {len(text)} characters long; the limit is {MAX_LENGTH}", MAX_LENGTH)
625
+ return _Parser(text).parse()
626
+
627
+
628
+ def _as_node(text_or_node: str | Node) -> Node:
629
+ if isinstance(text_or_node, Node):
630
+ return text_or_node
631
+ return parse(text_or_node)
632
+
633
+
634
+ def _children(node: Node) -> tuple[Node, ...]:
635
+ if isinstance(node, Unary):
636
+ return (node.operand,)
637
+ if isinstance(node, Binary):
638
+ return (node.left, node.right)
639
+ if isinstance(node, InList):
640
+ return (node.operand, *node.items)
641
+ if isinstance(node, Call):
642
+ return node.args
643
+ return ()
644
+
645
+
646
+ def referenced_columns(text_or_node: str | Node) -> set[str]:
647
+ """Return the set of column names an expression references."""
648
+ out: set[str] = set()
649
+ stack = [_as_node(text_or_node)]
650
+ while stack:
651
+ node = stack.pop()
652
+ if isinstance(node, Column):
653
+ out.add(node.name)
654
+ stack.extend(_children(node))
655
+ return out
656
+
657
+
658
+ # ---------------------------------------------------------------------------------------------
659
+ # Unparse (canonical text)
660
+ # ---------------------------------------------------------------------------------------------
661
+
662
+
663
+ def _prec(node: Node) -> int:
664
+ if isinstance(node, Binary):
665
+ return _PREC[node.op]
666
+ if isinstance(node, InList):
667
+ return _PREC["in"]
668
+ if isinstance(node, Unary):
669
+ return _PREC["not"] if node.op == "not" else _PREC["neg"]
670
+ if isinstance(node, Literal) and node.kind in ("int", "float") and node.value < 0: # type: ignore[operator]
671
+ return _PREC["neg"]
672
+ return _ATOM_PREC
673
+
674
+
675
+ def _literal_text(lit: Literal) -> str:
676
+ if lit.kind == "null":
677
+ return "null"
678
+ if lit.kind == "bool":
679
+ return "true" if lit.value else "false"
680
+ if lit.kind == "str":
681
+ s = str(lit.value)
682
+ for raw, esc in (("\\", "\\\\"), ("'", "\\'"), ("\n", "\\n"), ("\t", "\\t"), ("\r", "\\r"), ("\0", "\\0")):
683
+ s = s.replace(raw, esc)
684
+ return f"'{s}'"
685
+ if lit.kind == "float":
686
+ v = float(lit.value) # type: ignore[arg-type]
687
+ if v != v or v in (float("inf"), float("-inf")):
688
+ raise _error(f"float literal {v} cannot be written as expression text", lit.pos)
689
+ return repr(v)
690
+ return str(lit.value)
691
+
692
+
693
+ def _column_text(name: str) -> str:
694
+ if (
695
+ name
696
+ and (name[0].isalpha() or name[0] == "_")
697
+ and all(ch.isalnum() or ch == "_" for ch in name)
698
+ and name.isascii()
699
+ and name not in _KEYWORDS
700
+ ):
701
+ return name
702
+ return "`" + name.replace("`", "``") + "`"
703
+
704
+
705
+ def unparse(text_or_node: str | Node) -> str:
706
+ """Render an AST as canonical expression text with minimal parentheses.
707
+
708
+ ``parse(unparse(node)) == node`` for every AST produced by :func:`parse`.
709
+ """
710
+ node = _as_node(text_or_node)
711
+
712
+ def wrap(child: Node, need: bool) -> str:
713
+ s = render(child)
714
+ return f"({s})" if need else s
715
+
716
+ def render(n: Node) -> str:
717
+ if isinstance(n, Literal):
718
+ return _literal_text(n)
719
+ if isinstance(n, Column):
720
+ return _column_text(n.name)
721
+ if isinstance(n, Call):
722
+ return f"{n.name}({', '.join(render(a) for a in n.args)})"
723
+ if isinstance(n, InList):
724
+ items = ", ".join(_literal_text(i) for i in n.items)
725
+ return f"{wrap(n.operand, _prec(n.operand) <= _PREC['in'])} in [{items}]"
726
+ if isinstance(n, Unary):
727
+ p = _prec(n)
728
+ if n.op == "not":
729
+ return f"not {wrap(n.operand, _prec(n.operand) < p)}"
730
+ return f"-{wrap(n.operand, _prec(n.operand) < p)}"
731
+ if isinstance(n, Binary):
732
+ p = _PREC[n.op]
733
+ lp, rp = _prec(n.left), _prec(n.right)
734
+ if n.op == "implies":
735
+ left_paren, right_paren = lp <= p, rp < p
736
+ elif p == _PREC["=="]:
737
+ left_paren, right_paren = lp <= p, rp <= p
738
+ else:
739
+ left_paren, right_paren = lp < p, rp <= p
740
+ return f"{wrap(n.left, left_paren)} {n.op} {wrap(n.right, right_paren)}"
741
+ raise _error(f"unknown node type {type(n).__name__}", None)
742
+
743
+ return render(node)
744
+
745
+
746
+ # ---------------------------------------------------------------------------------------------
747
+ # Type checking
748
+ # ---------------------------------------------------------------------------------------------
749
+
750
+ # value kinds: num bool str cat date datetime null any
751
+ _TEMPORAL = ("date", "datetime")
752
+
753
+
754
+ def _kind_from_schema(col: ColumnSchema) -> str:
755
+ lt = col.logical_type
756
+ if lt in (LogicalType.CONTINUOUS, LogicalType.DISCRETE):
757
+ return "num"
758
+ if lt == LogicalType.BOOLEAN:
759
+ return "bool"
760
+ if lt == LogicalType.CATEGORICAL:
761
+ # integer/float coded categories are numbers in the data (compare as numbers)
762
+ return "num" if col.physical_dtype.startswith(_NUMERIC_DTYPES) else "cat"
763
+ if lt == LogicalType.DATETIME:
764
+ return "date" if (col.is_date or col.datetime_unit == "d") else "datetime"
765
+ return "str"
766
+
767
+
768
+ _NUMERIC_DTYPES = ("Int", "UInt", "Float", "Decimal")
769
+
770
+
771
+ @dataclass(frozen=True)
772
+ class _Meta:
773
+ """Physical facts the value kinds do not carry."""
774
+
775
+ unsigned: frozenset[str] = frozenset() # unsigned integer columns
776
+ tz: dict[str, str] = field(default_factory=dict) # tz-aware datetime column -> zone
777
+ #: Float32 columns: numeric literals compared with them are rounded to float32 first, so
778
+ #: ``x <= 1.1`` holds for the stored value ``float32(1.1)`` (a float64 comparison does not)
779
+ float32: frozenset[str] = frozenset()
780
+
781
+
782
+ def _meta_from_columns(columns: dict[str, ColumnSchema]) -> _Meta:
783
+ return _Meta(
784
+ unsigned=frozenset(n for n, c in columns.items()
785
+ if c.physical_dtype.startswith("UInt")
786
+ and _kind_from_schema(c) == "num"),
787
+ tz={n: c.timezone for n, c in columns.items()
788
+ if c.timezone and _kind_from_schema(c) == "datetime"},
789
+ float32=frozenset(n for n, c in columns.items()
790
+ if c.physical_dtype == "Float32" and _kind_from_schema(c) == "num"))
791
+
792
+
793
+ def _meta_from_frame(schema: dict[str, pl.DataType]) -> _Meta:
794
+ return _Meta(
795
+ unsigned=frozenset(n for n, dt in schema.items() if dt.is_unsigned_integer()),
796
+ tz={n: dt.time_zone for n, dt in schema.items()
797
+ if isinstance(dt, pl.Datetime) and dt.time_zone},
798
+ float32=frozenset(n for n, dt in schema.items() if dt == pl.Float32))
799
+
800
+
801
+ def _kind_from_dtype(dtype: pl.DataType) -> str:
802
+ if dtype.is_numeric():
803
+ return "num"
804
+ if dtype == pl.Boolean:
805
+ return "bool"
806
+ if dtype == pl.String:
807
+ return "str"
808
+ if isinstance(dtype, pl.Categorical | pl.Enum):
809
+ return "cat"
810
+ if dtype == pl.Date:
811
+ return "date"
812
+ if isinstance(dtype, pl.Datetime):
813
+ return "datetime"
814
+ if dtype == pl.Null:
815
+ return "null"
816
+ return "any"
817
+
818
+
819
+ def _literal_kind(lit: Literal) -> str:
820
+ return {"int": "num", "float": "num", "str": "str", "bool": "bool", "null": "null"}[lit.kind]
821
+
822
+
823
+ _KIND_LABELS = {"cat": "categorical", "str": "string", "num": "numeric", "bool": "boolean"}
824
+
825
+
826
+ def _describe(node: Node, kind: str) -> str:
827
+ label = _KIND_LABELS.get(kind, kind)
828
+ if isinstance(node, Column):
829
+ return f"{label} column '{node.name}'"
830
+ return f"{label} value"
831
+
832
+
833
+ def _parse_temporal(lit: Literal, kind: str) -> _dt.date | _dt.datetime:
834
+ s = str(lit.value)
835
+ try:
836
+ if kind == "date":
837
+ if len(s) == 10:
838
+ return _dt.date.fromisoformat(s)
839
+ return _dt.datetime.fromisoformat(s)
840
+ return _dt.datetime.fromisoformat(s)
841
+ except ValueError:
842
+ raise _error(
843
+ f"string {s!r} is not an ISO date/datetime and cannot be compared with a {kind} value",
844
+ lit.pos,
845
+ ) from None
846
+
847
+
848
+ class _Checker:
849
+ """Infers value kinds bottom-up and records how temporal string literals are coerced."""
850
+
851
+ def __init__(self, kinds: dict[str, str] | None, text: str | None,
852
+ meta: _Meta | None = None) -> None:
853
+ self.kinds = kinds
854
+ self.text = text
855
+ self.meta = meta or _Meta()
856
+ # id(Literal) -> converted python value (ISO strings compared with temporal values)
857
+ self.coerce: dict[int, Any] = {}
858
+ # id(Literal) -> time zone of the tz-aware datetime value it is compared with
859
+ self.coerce_tz: dict[int, str] = {}
860
+
861
+ def tz_of(self, node: Node) -> str | None:
862
+ if isinstance(node, Column):
863
+ return self.meta.tz.get(node.name)
864
+ if isinstance(node, Call) and node.name in ("min", "max", "coalesce"):
865
+ for a in node.args:
866
+ tz = self.tz_of(a)
867
+ if tz:
868
+ return tz
869
+ return None
870
+
871
+ def err(self, msg: str, node: Node) -> ExpressionError:
872
+ return _error(msg, getattr(node, "pos", None), self.text)
873
+
874
+ def kind(self, node: Node) -> str:
875
+ if isinstance(node, Literal):
876
+ return _literal_kind(node)
877
+ if isinstance(node, Column):
878
+ if self.kinds is None:
879
+ return "any"
880
+ if node.name not in self.kinds:
881
+ known = ", ".join(sorted(self.kinds)[:20])
882
+ raise self.err(f"unknown column '{node.name}' (known: {known})", node)
883
+ return self.kinds[node.name]
884
+ if isinstance(node, Unary):
885
+ k = self.kind(node.operand)
886
+ if node.op == "not":
887
+ self.require(node.operand, k, ("bool",), "'not'")
888
+ return "bool"
889
+ self.require_numeric(node.operand, k, "unary '-'")
890
+ return "num"
891
+ if isinstance(node, Binary):
892
+ return self.binary(node)
893
+ if isinstance(node, InList):
894
+ return self.in_list(node)
895
+ if isinstance(node, Call):
896
+ return self.call(node)
897
+ raise self.err(f"unknown node type {type(node).__name__}", node)
898
+
899
+ def require(self, node: Node, k: str, allowed: tuple[str, ...], what: str) -> None:
900
+ if k not in (*allowed, "null", "any"):
901
+ want = " or ".join(allowed)
902
+ raise self.err(f"{what} expects {want}, got {_describe(node, k)}", node)
903
+
904
+ def require_numeric(self, node: Node, k: str, what: str) -> None:
905
+ if k in ("str", "cat"):
906
+ raise self.err(f"arithmetic on {_describe(node, k)} is not allowed ({what})", node)
907
+ self.require(node, k, ("num",), what)
908
+
909
+ def binary(self, node: Binary) -> str:
910
+ lk, rk = self.kind(node.left), self.kind(node.right)
911
+ op = node.op
912
+ if op in _ARITH:
913
+ self.require_numeric(node.left, lk, f"'{op}'")
914
+ self.require_numeric(node.right, rk, f"'{op}'")
915
+ return "num"
916
+ if op in ("and", "or", "implies"):
917
+ self.require(node.left, lk, ("bool",), f"'{op}'")
918
+ self.require(node.right, rk, ("bool",), f"'{op}'")
919
+ return "bool"
920
+ # comparison
921
+ for side, k in ((node.left, lk), (node.right, rk)):
922
+ if k == "null" and isinstance(side, Literal):
923
+ raise self.err(
924
+ f"comparison '{op}' with null is always null; use is_null()/is_not_null()",
925
+ side,
926
+ )
927
+ self.compatible(node.left, lk, node.right, rk, op)
928
+ if op not in ("==", "!="):
929
+ for side, k in ((node.left, lk), (node.right, rk)):
930
+ if k == "bool":
931
+ raise self.err(f"ordering comparison '{op}' on {_describe(side, k)}", side)
932
+ return "bool"
933
+
934
+ def compatible(self, a: Node, ak: str, b: Node, bk: str, op: str) -> None:
935
+ if "any" in (ak, bk) or "null" in (ak, bk) or ak == bk:
936
+ return
937
+ pair = {ak, bk}
938
+ if pair <= {"str", "cat"}:
939
+ return
940
+ if pair <= {"date", "datetime"}:
941
+ return
942
+ for lit, lk, other, other_k in ((a, ak, b, bk), (b, bk, a, ak)):
943
+ if lk == "str" and other_k in _TEMPORAL and isinstance(lit, Literal):
944
+ self.coerce[id(lit)] = _parse_temporal(lit, other_k)
945
+ tz = self.tz_of(other) if other_k == "datetime" else None
946
+ if tz and isinstance(self.coerce[id(lit)], _dt.datetime):
947
+ self.coerce_tz[id(lit)] = tz
948
+ return
949
+ raise self.err(
950
+ f"cannot compare {_describe(a, ak)} with {_describe(b, bk)} using '{op}'", b
951
+ )
952
+
953
+ def in_list(self, node: InList) -> str:
954
+ k = self.kind(node.operand)
955
+ for item in node.items:
956
+ if item.kind == "null":
957
+ raise self.err("null is not allowed in an 'in' list; use is_null()", item)
958
+ self.compatible(node.operand, k, item, _literal_kind(item), "in")
959
+ return "bool"
960
+
961
+ def call(self, node: Call) -> str:
962
+ name = node.name
963
+ kinds = [self.kind(a) for a in node.args]
964
+ what = f"{name}()"
965
+ if name in ("is_null", "is_not_null"):
966
+ return "bool"
967
+ if name in ("abs", "floor", "ceil", "log", "exp", "sqrt", "round"):
968
+ self.require_numeric(node.args[0], kinds[0], what)
969
+ return "num"
970
+ if name in ("year", "month", "day", "quarter", "weekday", "week", "fiscal_year"):
971
+ self.require(node.args[0], kinds[0], _TEMPORAL, what)
972
+ return "num"
973
+ if name in _TABLE_FUNCTIONS:
974
+ if name == "step":
975
+ self.require_numeric(node.args[0], kinds[0], what)
976
+ values = node.args[1::2]
977
+ else:
978
+ pairs = node.args[1:] if len(node.args) % 2 else node.args[1:-1]
979
+ key_kind = "num" if _is_num_literal(pairs[0]) else "str"
980
+ allowed = ("num",) if key_kind == "num" else ("str", "cat")
981
+ if kinds[0] not in (*allowed, "null", "any"):
982
+ raise self.err(f"lookup(): the keys are {_KIND_LABELS[key_kind]} literals "
983
+ f"but the first argument is a {_describe(node.args[0], kinds[0])}",
984
+ node.args[0])
985
+ values = (*pairs[1::2], *(() if len(node.args) % 2 else (node.args[-1],)))
986
+ vkinds = {"num" if _is_num_literal(v) else _literal_kind(v) # type: ignore[arg-type]
987
+ for v in values} - {"null"}
988
+ return vkinds.pop() if vkinds else "null"
989
+ if name == "date_diff_days":
990
+ for a, k in zip(node.args, kinds):
991
+ self.require(a, k, _TEMPORAL, what)
992
+ return "num"
993
+ # min / max / coalesce: arguments must share a kind
994
+ concrete = [k for k in kinds if k not in ("null", "any")]
995
+ if name in ("min", "max"):
996
+ for a, k in zip(node.args, kinds):
997
+ if k in ("str", "cat", "bool"):
998
+ raise self.err(f"{what} expects numeric or temporal values, got {_describe(a, k)}", a)
999
+ for a, k in zip(node.args, kinds):
1000
+ if concrete and not self._same_family(k, concrete[0]):
1001
+ raise self.err(
1002
+ f"{what} arguments must have the same type; got {_describe(a, k)} "
1003
+ f"alongside {concrete[0]}",
1004
+ a,
1005
+ )
1006
+ if not concrete:
1007
+ return "any" if "any" in kinds else "null"
1008
+ return concrete[0]
1009
+
1010
+ @staticmethod
1011
+ def _same_family(k: str, ref: str) -> bool:
1012
+ if k in ("null", "any") or k == ref or {k, ref} == {"cat", "str"}:
1013
+ return True
1014
+ fam = {"num": "num", "cat": "cat", "str": "str", "bool": "bool", "date": "t", "datetime": "t"}
1015
+ return fam.get(k) == fam.get(ref)
1016
+
1017
+
1018
+ def _kinds_from_columns(columns: dict[str, ColumnSchema]) -> dict[str, str]:
1019
+ return {name: _kind_from_schema(col) for name, col in columns.items()}
1020
+
1021
+
1022
+ def check(text: str, columns: dict[str, ColumnSchema]) -> Node:
1023
+ """Parse and type-check ``text`` against ``columns``; returns the AST.
1024
+
1025
+ Flags unknown columns and functions, wrong arity, arithmetic on string/categorical values,
1026
+ non-boolean operands of logical operators, incompatible comparisons (including categorical
1027
+ vs numeric) and comparisons with a ``null`` literal.
1028
+ """
1029
+ node = _as_node(text)
1030
+ _Checker(_kinds_from_columns(columns), text if isinstance(text, str) else None,
1031
+ _meta_from_columns(columns)).kind(node)
1032
+ return node
1033
+
1034
+
1035
+ # ---------------------------------------------------------------------------------------------
1036
+ # Compilation to Polars
1037
+ # ---------------------------------------------------------------------------------------------
1038
+
1039
+ _US_PER_DAY = 86_400_000_000
1040
+
1041
+
1042
+ class _Compiler:
1043
+ def __init__(self, checker: _Checker) -> None:
1044
+ self.checker = checker
1045
+
1046
+ def kind(self, node: Node) -> str:
1047
+ return self.checker.kind(node)
1048
+
1049
+ def compile(self, node: Node) -> pl.Expr:
1050
+ if isinstance(node, Literal):
1051
+ return self.literal(node)
1052
+ if isinstance(node, Column):
1053
+ return pl.col(node.name)
1054
+ if isinstance(node, Unary):
1055
+ inner = self.compile(node.operand)
1056
+ if node.op == "not":
1057
+ return ~(inner.cast(pl.Boolean) if _is_null_lit(node.operand) else inner)
1058
+ if self.unsigned(node.operand):
1059
+ inner = inner.cast(pl.Int64)
1060
+ return -inner
1061
+ if isinstance(node, Binary):
1062
+ return self.binary(node)
1063
+ if isinstance(node, InList):
1064
+ operand = self.compile(node.operand)
1065
+ values = [self.checker.coerce.get(id(i), i.value) for i in node.items]
1066
+ if all(i.kind in ("int", "float") for i in node.items):
1067
+ # Polars' is_in is dtype-strict; compare numerics on a common Float64 footing
1068
+ # (items rounded to float32 first for a Float32 column, see ``float32_column``)
1069
+ nums = [float(v) for v in values if v is not None]
1070
+ if self.float32_column(node.operand):
1071
+ nums = [float(np.float32(v)) for v in nums]
1072
+ return operand.cast(pl.Float64).is_in(nums)
1073
+ if any(id(i) in self.checker.coerce_tz for i in node.items):
1074
+ # tz-aware items: materialise them with the column's zone attached
1075
+ tz_items = pl.concat([pl.select(self.literal(i)).to_series()
1076
+ for i in node.items])
1077
+ return operand.is_in(tz_items)
1078
+ return operand.is_in(values)
1079
+ if isinstance(node, Call):
1080
+ return self.call(node)
1081
+ raise _error(f"unknown node type {type(node).__name__}", None)
1082
+
1083
+ def float32_column(self, node: Node) -> bool:
1084
+ """True when ``node`` is a Float32 column."""
1085
+ return isinstance(node, Column) and node.name in self.checker.meta.float32
1086
+
1087
+ def _float32_pair(self, node: Binary, left: pl.Expr, right: pl.Expr
1088
+ ) -> tuple[pl.Expr, pl.Expr]:
1089
+ """Compare a Float32 column with a numeric literal in float32: the literal is rounded
1090
+ to the column's precision (``x <= 1.1`` must hold for a stored ``float32(1.1)``)."""
1091
+ if self.float32_column(node.left) and _is_num_literal(node.right):
1092
+ right = right.cast(pl.Float32)
1093
+ elif self.float32_column(node.right) and _is_num_literal(node.left):
1094
+ left = left.cast(pl.Float32)
1095
+ return left, right
1096
+
1097
+ def unsigned(self, node: Node) -> bool:
1098
+ """True when ``node`` evaluates to an unsigned integer dtype."""
1099
+ if isinstance(node, Column):
1100
+ return node.name in self.checker.meta.unsigned
1101
+ if isinstance(node, Call) and node.name in ("abs", "min", "max", "coalesce"):
1102
+ args = [a for a in node.args if not _is_null_lit(a)]
1103
+ return bool(args) and all(self.unsigned(a) for a in args)
1104
+ return False
1105
+
1106
+ def literal(self, lit: Literal) -> pl.Expr:
1107
+ if id(lit) in self.checker.coerce:
1108
+ value = self.checker.coerce[id(lit)]
1109
+ tz = self.checker.coerce_tz.get(id(lit))
1110
+ if tz is None:
1111
+ return pl.lit(value)
1112
+ if value.tzinfo is None: # naive ISO text: read it in the column's time zone
1113
+ return pl.lit(value).dt.replace_time_zone(tz, ambiguous="earliest")
1114
+ return pl.lit(value).dt.convert_time_zone(tz)
1115
+ if lit.kind == "int":
1116
+ if not _INT64_MIN <= int(lit.value) <= _INT64_MAX: # type: ignore[arg-type]
1117
+ raise _error("integer literal is outside the int64 range", lit.pos)
1118
+ return pl.lit(lit.value, dtype=pl.Int64)
1119
+ if lit.kind == "float":
1120
+ return pl.lit(lit.value, dtype=pl.Float64)
1121
+ if lit.kind == "str":
1122
+ return pl.lit(lit.value, dtype=pl.String)
1123
+ if lit.kind == "bool":
1124
+ return pl.lit(lit.value, dtype=pl.Boolean)
1125
+ return pl.lit(None)
1126
+
1127
+ def binary(self, node: Binary) -> pl.Expr:
1128
+ op = node.op
1129
+ left, right = self.compile(node.left), self.compile(node.right)
1130
+ if op in _ARITH:
1131
+ # unsigned arithmetic would wrap around (UInt8 3 - 5 == 254)
1132
+ wide = pl.Float64 if op == "/" else pl.Int64
1133
+ if self.unsigned(node.left):
1134
+ left = left.cast(wide)
1135
+ if self.unsigned(node.right):
1136
+ right = right.cast(wide)
1137
+ if op in ("and", "or", "implies"):
1138
+ # make untyped nulls boolean so Kleene logic applies
1139
+ if _is_null_lit(node.left):
1140
+ left = left.cast(pl.Boolean)
1141
+ if _is_null_lit(node.right):
1142
+ right = right.cast(pl.Boolean)
1143
+ if op in _COMPARE:
1144
+ left, right = self._float32_pair(node, left, right)
1145
+ if op == "+":
1146
+ return left + right
1147
+ if op == "-":
1148
+ return left - right
1149
+ if op == "*":
1150
+ return left * right
1151
+ if op == "/":
1152
+ return left / right
1153
+ if op == "%":
1154
+ # Floor-modulo. With a tiny float divisor, x / y can round across an integer and
1155
+ # Polars then returns a remainder on the wrong side of zero (3 % 1e-05 gives
1156
+ # -4.4e-16). Move such a result back to the divisor's side, as floor-modulo requires.
1157
+ # A zero remainder takes the divisor's sign (-0.0 % 1 is +0.0), as in Python.
1158
+ rem = left % right
1159
+ wrong_side = ((right > 0) & (rem < 0)) | ((right < 0) & (rem > 0))
1160
+ return (pl.when(wrong_side).then(rem + right)
1161
+ .when(rem == 0).then(right.sign() * 0)
1162
+ .otherwise(rem))
1163
+ if op == "==":
1164
+ return left == right
1165
+ if op == "!=":
1166
+ return left != right
1167
+ if op == "<":
1168
+ return left < right
1169
+ if op == "<=":
1170
+ return left <= right
1171
+ if op == ">":
1172
+ return left > right
1173
+ if op == ">=":
1174
+ return left >= right
1175
+ if op == "and":
1176
+ return left & right
1177
+ if op == "or":
1178
+ return left | right
1179
+ if op == "implies":
1180
+ return (~left) | right
1181
+ raise _error(f"unknown operator '{op}'", node.pos)
1182
+
1183
+ def call(self, node: Call) -> pl.Expr:
1184
+ name = node.name
1185
+ args = [self.compile(a) for a in node.args]
1186
+ if name == "abs":
1187
+ return args[0].abs()
1188
+ if name == "round":
1189
+ nd = node.args[1].value if len(node.args) == 2 else 0 # type: ignore[attr-defined]
1190
+ return args[0].cast(pl.Float64).round(int(nd))
1191
+ if name == "floor":
1192
+ return args[0].cast(pl.Float64).floor()
1193
+ if name == "ceil":
1194
+ return args[0].cast(pl.Float64).ceil()
1195
+ if name == "log":
1196
+ return args[0].cast(pl.Float64).log()
1197
+ if name == "exp":
1198
+ return args[0].cast(pl.Float64).exp()
1199
+ if name == "sqrt":
1200
+ return args[0].cast(pl.Float64).sqrt()
1201
+ if name == "min":
1202
+ return pl.min_horizontal(*args)
1203
+ if name == "max":
1204
+ return pl.max_horizontal(*args)
1205
+ if name == "coalesce":
1206
+ return pl.coalesce(*args)
1207
+ if name == "is_null":
1208
+ return args[0].is_null()
1209
+ if name == "is_not_null":
1210
+ return args[0].is_not_null()
1211
+ if name == "year":
1212
+ return args[0].dt.year().cast(pl.Int64)
1213
+ if name == "month":
1214
+ return args[0].dt.month().cast(pl.Int64)
1215
+ if name == "day":
1216
+ return args[0].dt.day().cast(pl.Int64)
1217
+ if name == "quarter":
1218
+ return args[0].dt.quarter().cast(pl.Int64)
1219
+ if name == "weekday":
1220
+ return args[0].dt.weekday().cast(pl.Int64)
1221
+ if name == "week":
1222
+ return args[0].dt.week().cast(pl.Int64)
1223
+ if name == "fiscal_year":
1224
+ start = int(node.args[1].value) # type: ignore[attr-defined]
1225
+ year = args[0].dt.year().cast(pl.Int64)
1226
+ if start == 1:
1227
+ return year
1228
+ return year + (args[0].dt.month() >= start).cast(pl.Int64)
1229
+ if name == "lookup":
1230
+ x = args[0]
1231
+ if self.kind(node.args[0]) == "cat":
1232
+ x = x.cast(pl.String)
1233
+ has_default = len(args) % 2 == 0
1234
+ pairs = args[1:-1] if has_default else args[1:]
1235
+ default = args[-1] if has_default else pl.lit(None)
1236
+ chain: Any = pl.when(x == pairs[0]).then(pairs[1])
1237
+ for key, value in zip(pairs[2::2], pairs[3::2]):
1238
+ chain = chain.when(x == key).then(value)
1239
+ return pl.when(x.is_null()).then(None).otherwise(chain.otherwise(default))
1240
+ if name == "step":
1241
+ x = args[0].cast(pl.Float64)
1242
+ values, cuts = args[1::2], args[2::2]
1243
+ chain = pl.when(x < cuts[0]).then(values[0])
1244
+ for cut, value in zip(cuts[1:], values[1:]):
1245
+ chain = chain.when(x < cut).then(value)
1246
+ return pl.when(x.is_null() | x.is_nan()).then(None).otherwise(
1247
+ chain.otherwise(values[-1]))
1248
+ if name == "date_diff_days":
1249
+ a, b = args
1250
+ ka, kb = self.kind(node.args[0]), self.kind(node.args[1])
1251
+ if {ka, kb} == {"date", "datetime"}:
1252
+ a = a.cast(pl.Datetime("us")) if ka == "date" else a
1253
+ b = b.cast(pl.Datetime("us")) if kb == "date" else b
1254
+ return (a - b).dt.total_microseconds() / _US_PER_DAY
1255
+ raise _error(f"unknown function '{name}'", node.pos)
1256
+
1257
+
1258
+ def _is_null_lit(node: Node) -> bool:
1259
+ return isinstance(node, Literal) and node.kind == "null"
1260
+
1261
+
1262
+ _COMPARE = frozenset({"==", "!=", "<", "<=", ">", ">="})
1263
+
1264
+
1265
+ def _is_num_literal(node: Node) -> bool:
1266
+ """A numeric literal, possibly negated (``-1.5``)."""
1267
+ if isinstance(node, Unary) and node.op == "-":
1268
+ return _is_num_literal(node.operand)
1269
+ return isinstance(node, Literal) and node.kind in ("int", "float")
1270
+
1271
+
1272
+ def _num_value(node: Node) -> float:
1273
+ """The value of a numeric literal (see :func:`_is_num_literal`)."""
1274
+ if isinstance(node, Unary):
1275
+ return -_num_value(node.operand)
1276
+ return float(node.value) # type: ignore[attr-defined]
1277
+
1278
+
1279
+ def _compile(node: Node, kinds: dict[str, str] | None, text: str | None,
1280
+ meta: _Meta | None = None) -> pl.Expr:
1281
+ checker = _Checker(kinds, text, meta)
1282
+ checker.kind(node) # type-check and collect temporal literal coercions
1283
+ return _Compiler(checker).compile(node)
1284
+
1285
+
1286
+ def to_polars(node_or_text: str | Node, columns: dict[str, ColumnSchema] | None = None) -> pl.Expr:
1287
+ """Compile an expression to a native Polars expression.
1288
+
1289
+ With ``columns`` the expression is fully type-checked first (and ISO date strings compared
1290
+ with temporal columns become date literals); without, only operand kinds that are evident
1291
+ from literals are checked.
1292
+ """
1293
+ node = _as_node(node_or_text)
1294
+ kinds = _kinds_from_columns(columns) if columns is not None else None
1295
+ meta = _meta_from_columns(columns) if columns is not None else None
1296
+ text = node_or_text if isinstance(node_or_text, str) else None
1297
+ return _compile(node, kinds, text, meta)
1298
+
1299
+
1300
+ def evaluate(text: str | Node, df: pl.DataFrame) -> pl.Series:
1301
+ """Evaluate an expression against ``df`` and return the result as a Series named ``result``.
1302
+
1303
+ Column kinds are taken from the frame's dtypes, so the expression is type-checked against
1304
+ ``df`` (unknown columns raise :class:`ExpressionError`). Scalar results are broadcast to
1305
+ the frame height.
1306
+ """
1307
+ node = _as_node(text)
1308
+ kinds = {name: _kind_from_dtype(dtype) for name, dtype in df.schema.items()}
1309
+ expr = _compile(node, kinds, text if isinstance(text, str) else None,
1310
+ _meta_from_frame(dict(df.schema)))
1311
+ try:
1312
+ out = df.select(expr.alias("result")).to_series()
1313
+ except pl.exceptions.PolarsError as exc:
1314
+ raise _error(f"evaluation failed: {exc}", None) from exc
1315
+ if out.len() == 1 and df.height != 1:
1316
+ out = out.new_from_index(0, df.height)
1317
+ return out