"""Power Fx value semantics for code generated by Power Migrate from canvas apps. This module is copied verbatim into every generated package, so it has no dependencies beyond the standard library and imports nothing from the tool. Values are plain Python objects: ``None`` (Blank), ``float``/``int``, ``str``, ``bool``, ``datetime.date`` (Date), ``datetime.datetime`` (DateTime, naive and in the app's time zone), ``datetime.timedelta`` (Time), ``Option`` (an enumeration member such as ``SortOrder.Descending``), ``Color``, ``dict`` (record) and ``list`` of records (table). A single-column table is a list of ``{"Value": ...}`` records, as in Power Fx itself. Errors are ``FxError`` values that propagate through every function and operator; ``Unsupported`` is an error no ``IfError`` catches, so an unconverted formula can never pass for a result. Semantics were settled against Microsoft's open-source Power Fx interpreter (``tests/test_powerfx_runtime.py`` cross-checks every function over grids of inputs): Blank is 0 in arithmetic and false in logic, ``Round`` rounds the decimal spelling half away from zero, blanks sort last, text sorts culture-aware, and ``Text`` formats with the invariant culture unless a language is given. """ from __future__ import annotations import calendar import datetime as _dt import functools as _functools import json import math import random as _random import re import uuid as _uuid from decimal import ROUND_DOWN, ROUND_HALF_UP, ROUND_UP, Decimal from typing import Any, Callable, Iterable # --------------------------------------------------------------------------- # Values # --------------------------------------------------------------------------- ERROR_KINDS = {"Validation": 11, "Unknown": 12, "Div0": 13, "NotSupported": 20, "Numeric": 24, "InvalidArgument": 25, "NotFound": 12} class FxError: """A Power Fx error value. Compares equal by kind.""" __slots__ = ("kind", "message") def __init__(self, kind: str, message: str = ""): self.kind = kind self.message = message @property def code(self) -> int: return ERROR_KINDS.get(self.kind, 12) def __eq__(self, other: object) -> bool: return isinstance(other, FxError) and other.kind == self.kind def __hash__(self) -> int: return hash(("FxError", self.kind)) def __repr__(self) -> str: return f"FxError({self.kind}: {self.message})" if self.message else f"FxError({self.kind})" class Unsupported(FxError): """An unconverted formula or feature. Propagates through everything; ``IfError`` does not catch it.""" __slots__ = ("reason",) def __init__(self, reason: str): super().__init__("Unsupported", reason) self.reason = reason def __repr__(self) -> str: return f"Unsupported({self.reason})" def UNSUPPORTED(reason: str) -> Unsupported: return Unsupported(reason) def div0() -> FxError: return FxError("Div0", "division by zero") def invalid(message: str) -> FxError: return FxError("InvalidArgument", message) class Option: """A member of an enumeration: ``SortOrder.Descending``, ``DisplayMode.Edit``, ``Color.Red`` is a Color instead.""" __slots__ = ("set_name", "name") def __init__(self, set_name: str, name: str): self.set_name = set_name self.name = name def __eq__(self, other: object) -> bool: return isinstance(other, Option) and (other.set_name, other.name) == (self.set_name, self.name) def __hash__(self) -> int: return hash((self.set_name, self.name)) def __repr__(self) -> str: return f"{self.set_name}.{self.name}" class Color: """An ARGB colour. ``RGBA``, ``ColorValue`` and ``ColorFade`` build them; equality is by value.""" __slots__ = ("argb",) def __init__(self, argb: int): self.argb = argb & 0xFFFFFFFF @classmethod def from_rgba(cls, r: int, g: int, b: int, a: int) -> "Color": return cls((a << 24) | (r << 16) | (g << 8) | b) @property def a(self) -> int: return (self.argb >> 24) & 0xFF @property def r(self) -> int: return (self.argb >> 16) & 0xFF @property def g(self) -> int: return (self.argb >> 8) & 0xFF @property def b(self) -> int: return self.argb & 0xFF def __eq__(self, other: object) -> bool: return isinstance(other, Color) and other.argb == self.argb def __hash__(self) -> int: return hash(("Color", self.argb)) def __repr__(self) -> str: return f"Color(#{self.argb:08X})" BLANK = None Record = dict Table = list def is_error(v: Any) -> bool: return isinstance(v, FxError) def first_error(*values: Any) -> FxError | None: """The first error among ``values``, Unsupported first of all.""" found = None for v in values: if isinstance(v, Unsupported): return v if isinstance(v, FxError) and found is None: found = v return found def is_blank(v: Any) -> bool: """``IsBlank``: Blank or empty text. Errors are not blank.""" return v is None or v == "" def is_number(v: Any) -> bool: return isinstance(v, (int, float)) and not isinstance(v, bool) def is_table(v: Any) -> bool: return isinstance(v, list) def is_record(v: Any) -> bool: return isinstance(v, dict) # --------------------------------------------------------------------------- # Coercion # --------------------------------------------------------------------------- _THOUSANDS = re.compile(r"(?<=\d),(?=\d{3}(?:\D|$))") def parse_number(text: str, language: str | None = None) -> float | FxError: """``Value`` of text: invariant separators, thousands commas allowed, blank text is Blank (handled by the caller).""" lang = _culture(language) if isinstance(lang, FxError): return lang s = text.strip() if lang["group"] != ",": s = s.replace(lang["group"], "").replace(lang["decimal"], ".") percent = s.endswith("%") if percent: s = s[:-1].strip() s = s.replace(",", "") if lang["group"] == "," else s negative = False if s.startswith("(") and s.endswith(")"): s, negative = s[1:-1].strip(), True if s == "" or " " in s or s.lower() in ("nan", "inf", "infinity", "-inf", "+inf"): return invalid(f"The value '{text}' cannot be converted to a number.") try: value = float(s) except ValueError: return invalid(f"The value '{text}' cannot be converted to a number.") if math.isnan(value) or math.isinf(value): return invalid(f"The value '{text}' cannot be converted to a number.") value = -value if negative else value return value / 100 if percent else value def to_number(v: Any) -> float | FxError: """A number for arithmetic: Blank is 0, text is parsed, booleans are 1 and 0.""" if v is None: return 0.0 if isinstance(v, FxError): return v if isinstance(v, bool): return 1.0 if v else 0.0 if isinstance(v, (int, float)): if math.isnan(v) or math.isinf(v): return FxError("Numeric", "non-finite number") return float(v) if isinstance(v, str): if v.strip() == "": return 0.0 if v == "" else invalid(f"The value '{v}' cannot be converted to a number.") return parse_number(v) if isinstance(v, _dt.datetime): return _datetime_serial(v) if isinstance(v, _dt.date): return _datetime_serial(_dt.datetime(v.year, v.month, v.day)) if isinstance(v, _dt.timedelta): return v.total_seconds() / 86400.0 return invalid(f"{type(v).__name__} cannot be converted to a number") _SERIAL_BASE = _dt.datetime(1899, 12, 30) def _datetime_serial(d: _dt.datetime) -> float: """``Value`` of a date or date/time: days since 1899-12-30, the Excel serial, as the interpreter gives.""" return (d - _SERIAL_BASE).total_seconds() / 86400.0 def to_bool(v: Any) -> bool | FxError: """A boolean for logic: Blank is false; text and numbers go through ``Boolean``.""" if v is None: return False if isinstance(v, bool): return v if isinstance(v, FxError): return v if isinstance(v, str): low = v.lower() # exactly "true" or "false" in any case; " true " is not (interpreter-verified) if low == "true": return True if low == "false" or v == "": return False # Boolean("") is Blank, false in logic return invalid("The value could not be interpreted as a boolean.") if isinstance(v, (int, float)): return v != 0 return invalid("The value could not be interpreted as a boolean.") def number_to_text(x: float) -> str: """Shortest round-trip spelling, as .NET prints a double: ``0.30000000000000004``, ``1E-05``, ``1234567890123456``.""" if isinstance(x, bool): return "true" if x else "false" if x != x: return "NaN" if x in (math.inf, -math.inf): return "Infinity" if x > 0 else "-Infinity" # .NET's spelling; arithmetic here never yields one, it errors first if x == 0: return "-0" if math.copysign(1.0, x) < 0 else "0" r = repr(float(x)) mantissa, _, exponent = r.partition("e") exp = int(exponent) if exponent else 0 sign = "-" if mantissa.startswith("-") else "" digits = mantissa.lstrip("-") int_part, _, frac_part = digits.partition(".") frac_part = frac_part.rstrip("0") if frac_part == "" and int_part.rstrip("0") == "": return sign + "0" # the decimal exponent of the leading digit all_digits = (int_part + frac_part).lstrip("0") lead = exp + len(int_part) - 1 if int_part != "0" else exp - (len(frac_part) - len(frac_part.lstrip("0")) + 1) all_digits = all_digits.rstrip("0") or "0" if -5 < lead < 17: point = lead + 1 # digits before the decimal point if point <= 0: return sign + "0." + "0" * (-point) + all_digits if point >= len(all_digits): return sign + all_digits + "0" * (point - len(all_digits)) return sign + all_digits[:point] + "." + all_digits[point:] m = all_digits[0] + ("." + all_digits[1:] if len(all_digits) > 1 else "") return f"{sign}{m}E{'+' if lead >= 0 else '-'}{abs(lead):02d}" def to_text(v: Any) -> str | FxError: """``Text`` of a value with no format: Blank is empty, numbers spell shortest, dates use the invariant culture.""" if v is None: return "" if isinstance(v, FxError): return v if isinstance(v, bool): return "true" if v else "false" if isinstance(v, str): return v if isinstance(v, (int, float)): return number_to_text(float(v)) if isinstance(v, _dt.datetime): return v.strftime("%m/%d/%Y %H:%M") if isinstance(v, _dt.date): return v.strftime("%m/%d/%Y") if isinstance(v, _dt.timedelta): return _format_time(v, "hh:mm") if isinstance(v, Option): if v.set_name == "SortOrder": return v.name.lower() if v.set_name == "MatchOptions": codes = MATCH_OPTION_CODES.get(v.name) return codes if codes is not None else invalid(f"unknown MatchOptions.{v.name}") if v.set_name == "Match": pattern = MATCH_PATTERNS.get(v.name) return pattern if pattern is not None else invalid(f"Match.{v.name} is not in the runtime yet") return v.name if isinstance(v, Color): name = _COLOR_NAME_BY_ARGB.get(v.argb) return name if name else invalid("a colour without a name cannot be converted to text") return invalid(f"{type(v).__name__} cannot be converted to text") # --------------------------------------------------------------------------- # Operators # --------------------------------------------------------------------------- def _arith(a: Any, b: Any, fn: Callable[[float, float], Any]) -> Any: err = first_error(a, b) if err is not None: return err x = to_number(a) if isinstance(x, FxError): return x y = to_number(b) if isinstance(y, FxError): return y try: result = fn(x, y) except ZeroDivisionError: return div0() except (OverflowError, ValueError): return FxError("Numeric", "the result is not a finite number") if isinstance(result, float) and (math.isnan(result) or math.isinf(result)): return FxError("Numeric", "the result is not a finite number") return result def _is_date(v: Any) -> bool: return isinstance(v, _dt.date) def _as_datetime(v: _dt.date) -> _dt.datetime: return v if isinstance(v, _dt.datetime) else _dt.datetime(v.year, v.month, v.day) def add(a: Any, b: Any) -> Any: err = first_error(a, b) if err is not None: return err if _is_date(a) or _is_date(b): if _is_date(a) and _is_date(b): return invalid("two dates cannot be added") d, n = (a, b) if _is_date(a) else (b, a) if isinstance(n, _dt.timedelta): return _as_datetime(d) + n days = to_number(n) if isinstance(days, FxError): return days try: if isinstance(d, _dt.datetime): return d + _dt.timedelta(days=days) return d + _dt.timedelta(days=math.trunc(days)) except (ValueError, OverflowError): return invalid("Argument out of range.") if isinstance(a, _dt.timedelta) or isinstance(b, _dt.timedelta): if isinstance(a, _dt.timedelta) and isinstance(b, _dt.timedelta): return _wrap_time(a + b) t, n = (a, b) if isinstance(a, _dt.timedelta) else (b, a) days = to_number(n) if isinstance(days, FxError): return days return _wrap_time(t + _dt.timedelta(days=days)) return _arith(a, b, lambda x, y: x + y) def _wrap_time(t: _dt.timedelta) -> _dt.timedelta: """A Time stays within one day, as ``Time(25, 0, 0)`` is 01:00.""" return _dt.timedelta(seconds=t.total_seconds() % 86400.0) def sub(a: Any, b: Any) -> Any: err = first_error(a, b) if err is not None: return err if _is_date(a) and _is_date(b): delta = _as_datetime(a) - _as_datetime(b) return delta.total_seconds() / 86400.0 if _is_date(a): if isinstance(b, _dt.timedelta): return _as_datetime(a) - b days = to_number(b) if isinstance(days, FxError): return days try: if isinstance(a, _dt.datetime): return a - _dt.timedelta(days=days) return a - _dt.timedelta(days=math.trunc(days)) except (ValueError, OverflowError): return invalid("Argument out of range.") if isinstance(a, _dt.timedelta) and isinstance(b, _dt.timedelta): return _wrap_time(a - b) if isinstance(a, _dt.timedelta): days = to_number(b) return days if isinstance(days, FxError) else _wrap_time(a - _dt.timedelta(days=days)) return _arith(a, b, lambda x, y: x - y) def mul(a: Any, b: Any) -> Any: err = first_error(a, b) if err is not None: return err return _arith(a, b, lambda x, y: x * y) # a Time is a fraction of a day here, so the result is a number def div(a: Any, b: Any) -> Any: err = first_error(a, b) if err is not None: return err return _arith(a, b, lambda x, y: x / y) def power(a: Any, b: Any) -> Any: def _pow(x: float, y: float) -> float: if x == 0 and y < 0: raise ZeroDivisionError result = math.pow(x, y) return result return _arith(a, b, _pow) def neg(a: Any) -> Any: if isinstance(a, FxError): return a if isinstance(a, _dt.timedelta): return -a x = to_number(a) return x if isinstance(x, FxError) else -x def pct(a: Any) -> Any: if isinstance(a, FxError): return a x = to_number(a) return x if isinstance(x, FxError) else x / 100.0 def concat(*parts: Any) -> Any: """The ``&`` operator and ``Concatenate``: Blank is empty text.""" err = first_error(*parts) if err is not None: return err out = [] for p in parts: t = to_text(p) if isinstance(t, FxError): return t out.append(t) return "".join(out) _PUNCTUATION_ORDER = {ch: i for i, ch in enumerate("\t\n\r _-,;:!?.'\"()[]{}@*/\\&#%`^+<=>|~$")} def _collation(s: str) -> tuple: """A primary key close to the invariant culture's collation: whitespace, then punctuation, digits, letters without accents or case.""" import unicodedata primary = [] for ch in s: if ch.isalpha(): base = unicodedata.normalize("NFD", ch)[0].casefold() primary.append((3, ord(base))) elif ch.isdigit(): primary.append((2, ord(ch))) elif ch.isspace(): primary.append((0, 32)) else: primary.append((1, _PUNCTUATION_ORDER.get(ch, 100 + ord(ch)))) return tuple(primary) def _text_key(s: str) -> tuple: """Invariant-culture ordering: letters compare without accents or case first, then accents, then lower before upper.""" import unicodedata return (_collation(s), unicodedata.normalize("NFD", s).casefold(), s.swapcase()) def compare(a: Any, b: Any) -> int | None | FxError: """-1, 0 or 1; None when the values cannot be ordered (a Blank on either side orders as nothing).""" err = first_error(a, b) if err is not None: return err if a is None or b is None: return None if isinstance(a, bool) or isinstance(b, bool): if isinstance(a, bool) and isinstance(b, bool): return (a > b) - (a < b) return invalid("booleans compare only with booleans") if is_number(a) and is_number(b): return (a > b) - (a < b) if _is_date(a) and _is_date(b): x, y = _as_datetime(a), _as_datetime(b) return (x > y) - (x < y) if isinstance(a, _dt.timedelta) and isinstance(b, _dt.timedelta): return (a > b) - (a < b) if isinstance(a, str) and isinstance(b, str): ka, kb = _text_key(a), _text_key(b) return (ka > kb) - (ka < kb) return invalid(f"{type(a).__name__} and {type(b).__name__} cannot be compared") def eq(a: Any, b: Any) -> Any: err = first_error(a, b) if err is not None: return err if a is None or b is None: return a is None and b is None if isinstance(a, bool) or isinstance(b, bool): return isinstance(a, bool) and isinstance(b, bool) and a == b if is_number(a) and is_number(b): return float(a) == float(b) if _is_date(a) and _is_date(b): return _as_datetime(a) == _as_datetime(b) if isinstance(a, (str, _dt.timedelta, Option, Color)) or isinstance(b, (str, _dt.timedelta, Option, Color)): return type(a) is type(b) and a == b if isinstance(a, dict) and isinstance(b, dict): return a.keys() == b.keys() and all(eq(a[k], b[k]) is True for k in a) if isinstance(a, list) and isinstance(b, list): return len(a) == len(b) and all(eq(x, y) is True for x, y in zip(a, b)) return False def ne(a: Any, b: Any) -> Any: r = eq(a, b) return r if isinstance(r, FxError) else not r def _blank_like(other: Any) -> Any: """What a Blank orders as against ``other``: 0, the blank date, an empty time or empty text.""" if _is_date(other): return _BLANK_DATE if isinstance(other, _dt.timedelta): return _dt.timedelta(0) if isinstance(other, str): return "" if isinstance(other, bool): return False return 0.0 def _ordered(a: Any, b: Any, test: Callable[[int], bool]) -> Any: err = first_error(a, b) if err is not None: return err if a is None and b is None: return test(0) if a is None: a = _blank_like(b) elif b is None: b = _blank_like(a) c = compare(a, b) if isinstance(c, FxError): return c if c is None: return False return test(c) def lt(a: Any, b: Any) -> Any: return _ordered(a, b, lambda c: c < 0) def le(a: Any, b: Any) -> Any: return _ordered(a, b, lambda c: c <= 0) def gt(a: Any, b: Any) -> Any: return _ordered(a, b, lambda c: c > 0) def ge(a: Any, b: Any) -> Any: return _ordered(a, b, lambda c: c >= 0) def and_(a: Callable[[], Any] | Any, *rest: Callable[[], Any] | Any) -> Any: """``&&``/``And`` with short-circuit: later operands may be thunks.""" for operand in (a, *rest): v = operand() if callable(operand) else operand t = to_bool(v) if isinstance(t, FxError): return t if not t: return False return True def or_(a: Callable[[], Any] | Any, *rest: Callable[[], Any] | Any) -> Any: for operand in (a, *rest): v = operand() if callable(operand) else operand t = to_bool(v) if isinstance(t, FxError): return t if t: return True return False def not_(a: Any) -> Any: t = to_bool(a) return t if isinstance(t, FxError) else not t def in_(needle: Any, haystack: Any, exact: bool = False) -> Any: """``in`` and ``exactin``: substring of text (case-insensitive unless exact) or membership of a table.""" err = first_error(needle, haystack) if err is not None: return err if isinstance(haystack, list): for row in haystack: candidate = row if isinstance(row, dict) and not isinstance(needle, dict): candidate = row.get("Value") if "Value" in row else (next(iter(row.values())) if len(row) == 1 else row) if candidate is None and needle is None: return True # Blank in [1, Blank()] is true (interpreter-verified) if isinstance(candidate, str) and isinstance(needle, str) and not exact: if candidate.casefold() == needle.casefold(): return True elif eq(candidate, needle) is True: return True return False h = to_text(haystack) # a Blank on either side is empty text: Blank in Blank is true, "a" in Blank false (interpreter-verified) n = to_text(needle) if isinstance(h, FxError) or isinstance(n, FxError): return h if isinstance(h, FxError) else n return (n in h) if exact else (n.casefold() in h.casefold()) # --------------------------------------------------------------------------- # Records, tables and scopes # --------------------------------------------------------------------------- def field(record: Any, name: str) -> Any: """``record.name``: Blank of a Blank record, the field, or Blank for a column the record does not carry.""" if record is None: return None if isinstance(record, FxError): return record if isinstance(record, dict): return record.get(name) if isinstance(record, list): return [row if isinstance(row, FxError) else {name: (row.get(name) if isinstance(row, dict) else None)} for row in record] # Table.Column, the single-column projection; an error row stays one return invalid(f"'.{name}' on a {type(record).__name__}") def scoped(name: str, *scopes: Any) -> Any: """A bare name inside a record scope: the innermost record that carries it, else ``_MISSING``.""" for record in scopes: if isinstance(record, FxError): return record # an error row: every column of it is the error if isinstance(record, dict) and name in record: return record[name] return _MISSING class _Missing: __slots__ = () def __repr__(self) -> str: return "MISSING" _MISSING = _Missing() def resolve(name: str, fallback: Callable[[], Any], *scopes: Any) -> Any: """A bare name: a column of the enclosing record scopes, else the global ``fallback``.""" v = scoped(name, *scopes) return fallback() if v is _MISSING else v def _rows(table: Any) -> list[dict] | FxError | None: if table is None: return None if isinstance(table, FxError): return table if isinstance(table, list): return table if isinstance(table, dict): return invalid("a record where a table was expected") return invalid(f"{type(table).__name__} where a table was expected") def column_table(values: Iterable[Any]) -> list[dict]: return [{"Value": v} for v in values] def table(*items: Any) -> Any: """``Table(...)`` and the ``[...]`` literal: records stay records, scalars become a Value column, a Blank is a row. An error stays in its cell (``[1/0, "x"]`` has two rows), as the interpreter has it. Records with different fields make one table with every column, Blank where a record lacks one (``Table({a:1},{b:2})``). A Blank item is a Blank row: ``[1, Blank()]`` has two rows and ``Table({a:1}, Blank())`` an empty record (interpreter-verified). """ records = any(isinstance(item, dict) for item in items) out: list[dict] = [] for item in items: if isinstance(item, Unsupported): return item if item is None: out.append({} if records else {"Value": None}) continue out.append(item if isinstance(item, dict) else {"Value": item}) return _rectangular(out) def _rectangular(rows: list) -> list: """Every record carries every column, in first-seen order, Blank where it had none (interpreter-verified).""" columns: dict[str, None] = {} # the columns in first-seen order for row in rows: if isinstance(row, dict): for k in row: if k not in columns: columns[k] = None if all(not isinstance(row, dict) or len(row) == len(columns) for row in rows): return rows return [{k: row.get(k) for k in columns} if isinstance(row, dict) else row for row in rows] def record(**fields: Any) -> Any: err = next((v for v in fields.values() if isinstance(v, Unsupported)), None) return err if err is not None else dict(fields) # an error stays in its field def record_of(pairs: Iterable[tuple[str, Any]]) -> Any: """A record literal whose field names may be anything (``{'Order Date': ...}``).""" pairs = list(pairs) err = next((v for _, v in pairs if isinstance(v, Unsupported)), None) return err if err is not None else dict(pairs) # an error stays in its field: {a: 1/0, b: 2}.b is 2 def _pred(fn: Callable[[dict], Any], row: dict) -> bool | FxError: v = fn(row) if isinstance(v, FxError): return v t = to_bool(v) return t if isinstance(t, FxError) else t def filter_(table: Any, *predicates: Callable[[dict], Any]) -> Any: rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows if rows is not None else [] out = [] for row in rows: keep: Any = True for p in predicates: t = _pred(p, row) if isinstance(t, Unsupported): return t if isinstance(t, FxError): keep = t # the row becomes an error row; the table itself is not an error break if not t: keep = False break if keep is not False: out.append(row if keep is True else keep) return out def lookup(table: Any, predicate: Callable[[dict], Any], reduction: Callable[[dict], Any] | None = None) -> Any: rows = _rows(table) if rows is None: return None if isinstance(rows, FxError): return rows for row in rows: t = _pred(predicate, row) if isinstance(t, FxError): return t if t: return reduction(row) if reduction is not None else row return None def _sort_key(v: Any) -> tuple: if v is None: return (1, 0) if isinstance(v, bool): return (0, 0, int(v)) if is_number(v): return (0, 0, float(v)) if _is_date(v): return (0, 0, _as_datetime(v)) # naive datetimes compare directly; timestamp() would depend on the local zone if isinstance(v, _dt.timedelta): return (0, 0, v.total_seconds()) if isinstance(v, str): return (0, 1, *_text_key(v)) return (0, 2, repr(v)) def _introsort(items: list, compare: Callable[[Any, Any], int]) -> list: """.NET's ``Array.Sort`` with a comparer (introsort: insertion sort below 17 items, a three-element special case, median-of-three quicksort, heapsort past the depth limit), so rows with equal keys land where the interpreter puts them.""" keys = list(items) def swap_if_greater(i: int, j: int) -> None: if i != j and compare(keys[i], keys[j]) > 0: keys[i], keys[j] = keys[j], keys[i] def insertion(lo: int, hi: int) -> None: for i in range(lo, hi): t = keys[i + 1] j = i while j >= lo and compare(t, keys[j]) < 0: keys[j + 1] = keys[j] j -= 1 keys[j + 1] = t def down_heap(i: int, n: int, lo: int) -> None: d = keys[lo + i - 1] while i <= n // 2: child = 2 * i if child < n and compare(keys[lo + child - 1], keys[lo + child]) < 0: child += 1 if not compare(d, keys[lo + child - 1]) < 0: break keys[lo + i - 1] = keys[lo + child - 1] i = child keys[lo + i - 1] = d def heapsort(lo: int, hi: int) -> None: n = hi - lo + 1 for i in range(n // 2, 0, -1): down_heap(i, n, lo) for i in range(n, 1, -1): keys[lo], keys[lo + i - 1] = keys[lo + i - 1], keys[lo] down_heap(1, i - 1, lo) def partition(lo: int, hi: int) -> int: middle = lo + (hi - lo) // 2 swap_if_greater(lo, middle) swap_if_greater(lo, hi) swap_if_greater(middle, hi) pivot = keys[middle] keys[middle], keys[hi - 1] = keys[hi - 1], keys[middle] left, right = lo, hi - 1 while left < right: left += 1 while compare(keys[left], pivot) < 0: left += 1 right -= 1 while compare(pivot, keys[right]) < 0: right -= 1 if left >= right: break keys[left], keys[right] = keys[right], keys[left] if left != hi - 1: keys[left], keys[hi - 1] = keys[hi - 1], keys[left] return left def intro(lo: int, hi: int, depth: int) -> None: while hi > lo: size = hi - lo + 1 if size <= 16: if size == 2: swap_if_greater(lo, hi) elif size == 3: swap_if_greater(lo, hi - 1) swap_if_greater(lo, hi) swap_if_greater(hi - 1, hi) else: insertion(lo, hi) return if depth == 0: heapsort(lo, hi) return depth -= 1 p = partition(lo, hi) intro(p + 1, hi, depth) hi = p - 1 if len(keys) > 1: intro(0, len(keys) - 1, 2 * len(keys).bit_length()) return keys def sort(table: Any, key: Callable[[dict], Any], descending: Any = None) -> Any: """``Sort``: blanks last whatever the direction. Power Fx does not define the order of rows whose keys are equal. The interpreter sorts with .NET's ``Array.Sort``, which is not stable, so ``_introsort`` reproduces that algorithm and the generated code orders ties exactly as the reference does (``SortByColumns`` is stable in the interpreter, and here). The canvas player sorts stably (JavaScript), and apps rely on it: with ``SORT_STABLE`` set, ties keep their order. """ rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows if rows is not None else [] desc = isinstance(descending, Option) and descending.name == "Descending" keyed = [] for row in rows: k = key(row) if isinstance(k, FxError): return k keyed.append((None if k is None else _sort_key(k), row)) def compare(a: tuple, b: tuple) -> int: ka, kb = a[0], b[0] if ka is None or kb is None: return 0 if ka is kb else (1 if ka is None else -1) # a blank key sorts last in both directions c = (ka > kb) - (ka < kb) return -c if desc else c if SORT_STABLE: return [row for _, row in sorted(keyed, key=_functools.cmp_to_key(compare))] return [row for _, row in _introsort(keyed, compare)] #: Order ties as the canvas player does (stable) rather than as the interpreter does (.NET Array.Sort). A host #: that stands in for the player sets this; the reconciliation leaves it off, since the interpreter is its reference. SORT_STABLE = False def sort_by_columns(table: Any, *args: Any) -> Any: rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows if rows is not None else [] specs: list[tuple[str, bool]] = [] i = 0 while i < len(args): name = args[i] if isinstance(name, FxError): return name order = args[i + 1] if i + 1 < len(args) else None desc = isinstance(order, Option) and order.name == "Descending" specs.append((str(name), desc)) i += 2 err = next((r for r in rows if isinstance(r, FxError)), None) if err is not None: return err out = list(rows) for name, desc in reversed(specs): present = [r for r in out if r.get(name) is not None] blanks = [r for r in out if r.get(name) is None] present.sort(key=lambda r: _sort_key(r.get(name)), reverse=desc) out = present + blanks return out def first(table: Any) -> Any: rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows return rows[0] if rows else None def last(table: Any) -> Any: rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows return rows[-1] if rows else None def first_n(table: Any, n: Any = 1) -> Any: rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows if rows is not None else [] k = to_number(n) if isinstance(k, FxError): return k return rows[: max(0, math.trunc(k))] def last_n(table: Any, n: Any = 1) -> Any: rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows if rows is not None else [] k = to_number(n) if isinstance(k, FxError): return k k = max(0, math.trunc(k)) return rows[-k:] if k else [] def index(table: Any, n: Any) -> Any: rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows k = to_number(n) if isinstance(k, FxError): return k i = math.trunc(k) if i < 1 or i > len(rows): return invalid("Argument out of range") return rows[i - 1] def count_rows(table: Any) -> Any: rows = _rows(table) if rows is None: return 0 if isinstance(rows, FxError): return rows err = next((r for r in rows if isinstance(r, FxError)), None) return err if err is not None else len(rows) # a table with an error row has no count def _values(table_or_values: Any, fn: Callable[[dict], Any] | None, extra: tuple[Any, ...]) -> list[Any] | FxError: """The numbers an aggregate sees: ``Sum(table, expr)`` or ``Sum(a, b, c)``.""" if fn is not None: rows = _rows(table_or_values) if rows is None: return [] if isinstance(rows, FxError): return rows out = [] for row in rows: v = fn(row) if isinstance(v, FxError): return v out.append(v) return out values = [table_or_values, *extra] if len(values) == 1 and isinstance(values[0], list): return [row.get("Value") if isinstance(row, dict) else row for row in values[0]] err = first_error(*values) return err if err is not None else values def _numbers(values: list[Any]) -> list[float] | FxError: out = [] for v in values: if v is None: continue x = to_number(v) if isinstance(x, FxError): return x out.append(x) return out def sum_(table: Any, fn: Callable[[dict], Any] | None = None, *extra: Any) -> Any: values = _values(table, fn, extra) if isinstance(values, FxError): return values nums = _numbers(values) if isinstance(nums, FxError): return nums if not nums: return None return math.fsum(nums) def average(table: Any, fn: Callable[[dict], Any] | None = None, *extra: Any) -> Any: values = _values(table, fn, extra) if isinstance(values, FxError): return values nums = _numbers(values) if isinstance(nums, FxError): return nums if not nums: return div0() return math.fsum(nums) / len(nums) def _extreme(table: Any, fn: Callable[[dict], Any] | None, extra: tuple[Any, ...], pick: Callable[[Any, Any], bool]) -> Any: values = _values(table, fn, extra) if isinstance(values, FxError): return values present = [] for v in values: if v is None: continue if isinstance(v, str) or isinstance(v, bool): n = to_number(v) if isinstance(n, FxError): return n v = n present.append(v) if not present: return None best = present[0] for v in present[1:]: c = compare(v, best) if isinstance(c, FxError): return c if c is not None and pick(c, 0): best = v return best def max_(table: Any, fn: Callable[[dict], Any] | None = None, *extra: Any) -> Any: return _extreme(table, fn, extra, lambda c, _: c > 0) def min_(table: Any, fn: Callable[[dict], Any] | None = None, *extra: Any) -> Any: return _extreme(table, fn, extra, lambda c, _: c < 0) def _only_column(row: Any) -> Any: """The value in a one-column table's row, whatever the column is called.""" if isinstance(row, dict): if "Value" in row: return row["Value"] return next(iter(row.values())) if len(row) == 1 else row return row def count(table: Any) -> Any: """``Count``: rows of a one-column table whose value is a number.""" rows = _rows(table) if rows is None: return 0 if isinstance(rows, FxError): return rows return sum(1 for row in rows if is_number(_only_column(row))) def count_a(table: Any) -> Any: rows = _rows(table) if rows is None: return 0 if isinstance(rows, FxError): return rows return sum(1 for row in rows if not is_blank(_only_column(row))) def count_if(table: Any, *predicates: Callable[[dict], Any]) -> Any: kept = filter_(table, *predicates) return kept if isinstance(kept, FxError) else len(kept) def _variance(table: Any, fn: Callable[[dict], Any] | None, extra: tuple[Any, ...]) -> Any: values = _values(table, fn, extra) if isinstance(values, FxError): return values nums = _numbers(values) if isinstance(nums, FxError): return nums if not nums: return div0() # Welford's running update, which is what the interpreter's answers match to the last digit mean = 0.0 m2 = 0.0 for k, x in enumerate(nums, start=1): delta = x - mean mean += delta / k m2 += delta * (x - mean) return m2 / len(nums) def var_p(table: Any, fn: Callable[[dict], Any] | None = None, *extra: Any) -> Any: return _variance(table, fn, extra) def stdev_p(table: Any, fn: Callable[[dict], Any] | None = None, *extra: Any) -> Any: v = _variance(table, fn, extra) return v if isinstance(v, FxError) else math.sqrt(v) def concat_rows(table: Any, fn: Callable[[dict], Any], separator: Any = "") -> Any: rows = _rows(table) if rows is None: return "" if isinstance(rows, FxError): return rows sep = to_text(separator) if isinstance(sep, FxError): return sep parts = [] for row in rows: t = to_text(fn(row)) if isinstance(t, FxError): return t parts.append(t) return sep.join(parts) def distinct(table: Any, fn: Callable[[dict], Any]) -> Any: rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows if rows is not None else [] seen: list[Any] = [] for row in rows: v = fn(row) if isinstance(v, FxError): return v if isinstance(v, (dict, list)): return invalid("Only primitive values are allowed for the operation.") # Distinct over a record or table column, as the interpreter has it if not any(eq(v, s) is True for s in seen): seen.append(v) return column_table(seen) def group_by(table: Any, *names: Any) -> Any: """``GroupBy(table, col1, ..., group)``: one row per distinct combination of the named columns, in first-seen order; the other columns of each row go into ``group`` as a table. Values group by equality of their JSON form. The interpreter does not support GroupBy, so this follows the documented behaviour and stays unchecked by it. """ rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows if rows is not None else [] err = first_error(*names) if err is not None: return err if len(names) < 2: return invalid("GroupBy needs at least one column and the name of the group column") keys, group = [str(n) for n in names[:-1]], str(names[-1]) out: list[dict] = [] index: dict[tuple, dict] = {} for row in rows: if isinstance(row, FxError): return row if not isinstance(row, dict): return invalid("GroupBy: a table of records was expected") k = tuple(json.dumps(json_ready(row.get(c)), sort_keys=True) for c in keys) if k not in index: index[k] = {**{c: row.get(c) for c in keys}, group: []} out.append(index[k]) index[k][group].append({c: v for c, v in row.items() if c not in keys}) return out def ungroup(table: Any, name: Any) -> Any: """``Ungroup(table, group)``: every row of each row's ``group`` table, with the outer row's other columns added back. The interpreter does not support Ungroup; a Blank group contributes no rows (unverified). """ rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows if rows is not None else [] if isinstance(name, FxError): return name group = str(name) out: list[dict] = [] for row in rows: if isinstance(row, FxError): return row if not isinstance(row, dict): return invalid("Ungroup: a table of records was expected") inner = row.get(group) if inner is None: continue if isinstance(inner, FxError): return inner if not isinstance(inner, list): return invalid(f"Ungroup: {group} does not hold a table") outer = {k: v for k, v in row.items() if k != group} for r in inner: if isinstance(r, FxError): out.append(r) elif isinstance(r, dict): out.append({**outer, **r}) else: return invalid(f"Ungroup: {group} holds something that is not a table of records") return out def add_columns(table: Any, *pairs: Any) -> Any: rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows if rows is not None else [] out = [] for row in rows: if isinstance(row, FxError): out.append(row) # an error row stays one continue new = dict(row) for i in range(0, len(pairs), 2): v = pairs[i + 1](row) if isinstance(v, Unsupported): return v new[str(pairs[i])] = v # an error stays in its cell; the table is still produced out.append(new) return out def drop_columns(table: Any, *names: Any) -> Any: rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows if rows is not None else [] drop = {str(n) for n in names} return [row if isinstance(row, FxError) else {k: v for k, v in row.items() if k not in drop} for row in rows] def show_columns(table: Any, *names: Any) -> Any: rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows if rows is not None else [] keep = [str(n) for n in names] return [row if isinstance(row, FxError) else {k: row.get(k) for k in keep} for row in rows] def rename_columns(table: Any, *pairs: Any) -> Any: rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows if rows is not None else [] mapping = {str(pairs[i]): str(pairs[i + 1]) for i in range(0, len(pairs), 2)} return [row if isinstance(row, FxError) else {mapping.get(k, k): v for k, v in row.items()} for row in rows] def for_all(table: Any, fn: Callable[[dict], Any]) -> Any: """``ForAll``: records make a table, scalars a Value column. A scalar result that errors fails the whole table; an error inside a record result stays in its field. A Blank scalar keeps its row (interpreter-verified). A Blank record is dropped: the interpreter cannot evaluate that case, so it is unverified. """ rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows if rows is not None else [] values = [] for row in rows: v = fn(row) if isinstance(v, FxError): return v values.append(v) if any(isinstance(v, dict) for v in values): return _rectangular([v for v in values if v is not None]) # If(..., {a: 1}, {b: 2}) rows share every column return [{"Value": v} for v in values] def with_(rec: Any, fn: Callable[[dict], Any]) -> Any: if isinstance(rec, FxError) or rec is None: return rec return fn(rec if isinstance(rec, dict) else {}) def search(table: Any, text: Any, *columns: Any) -> Any: rows = _rows(table) if rows is None or isinstance(rows, FxError): return rows if rows is not None else [] if isinstance(text, FxError): return text needle = to_text(text) if isinstance(needle, FxError): return needle if needle == "": return list(rows) needle = needle.casefold() out = [] for row in rows: for col in columns: v = row.get(str(col)) if isinstance(row, dict) else None if isinstance(v, str) and needle in v.casefold(): out.append(row) break return out def sequence(n: Any, start: Any = 1, step: Any = 1) -> Any: err = first_error(n, start, step) if err is not None: return err k = to_number(n) s = to_number(start) d = to_number(step) for v in (k, s, d): if isinstance(v, FxError): return v k = math.trunc(k) if k < 0: return invalid("Sequence needs a count of zero or more") return column_table(s + i * d for i in range(k)) def split(text: Any, separator: Any) -> Any: err = first_error(text, separator) if err is not None: return err t = to_text(text) s = to_text(separator) if isinstance(t, FxError) or isinstance(s, FxError): return t if isinstance(t, FxError) else s if s == "": return column_table(list(t)) # each character; empty text gives no rows (interpreter-verified) return column_table(t.split(s)) # empty text gives one empty row # --------------------------------------------------------------------------- # Logic # --------------------------------------------------------------------------- def if_(*args: Callable[[], Any] | Any) -> Any: """``If(c1, v1, c2, v2, ..., else)``: arguments may be thunks so only the chosen branch is evaluated.""" i = 0 while i + 1 < len(args): cond = args[i]() if callable(args[i]) else args[i] t = to_bool(cond) if isinstance(t, FxError): return t if t: v = args[i + 1] return v() if callable(v) else v i += 2 if i < len(args): v = args[i] return v() if callable(v) else v return None def switch(value: Any, *args: Callable[[], Any] | Any) -> Any: if isinstance(value, FxError): return value i = 0 while i + 1 < len(args): match = args[i]() if callable(args[i]) else args[i] if isinstance(match, FxError): return match if eq(value, match) is True: v = args[i + 1] return v() if callable(v) else v i += 2 if i < len(args): v = args[i] return v() if callable(v) else v return None def coalesce(*args: Callable[[], Any] | Any) -> Any: for a in args: v = a() if callable(a) else a if isinstance(v, FxError): return v if not is_blank(v): return v return None def is_blank_fn(v: Any) -> Any: if isinstance(v, FxError): return v return is_blank(v) def is_empty(v: Any) -> Any: if isinstance(v, FxError): return v if v is None: return True rows = _rows(v) return rows if isinstance(rows, FxError) else len(rows) == 0 def is_error_fn(v: Any) -> Any: if isinstance(v, Unsupported): return v return isinstance(v, FxError) def if_error(*args: Callable[[], Any] | Any) -> Any: """``IfError(v1, r1, v2, r2, ..., default)``; an Unsupported marker is never caught.""" i = 0 last_value: Any = None while i + 1 < len(args): v = args[i]() if callable(args[i]) else args[i] if isinstance(v, Unsupported): return v if isinstance(v, FxError): r = args[i + 1] return r() if callable(r) else r last_value = v i += 2 if i < len(args): v = args[i] return v() if callable(v) else v return last_value def boolean(v: Any) -> Any: if isinstance(v, FxError): return v if v is None: return None if v == "": return None return to_bool(v) def is_numeric(v: Any) -> Any: if isinstance(v, FxError): return v if isinstance(v, bool): return False if is_number(v): return True if isinstance(v, str): return not isinstance(parse_number(v), FxError) and v.strip() != "" return False def value(v: Any, language: Any = None) -> Any: """``Value``: text to number; Blank and empty text give Blank.""" err = first_error(v, language) if err is not None: return err if v is None: return None if isinstance(v, str): if v.strip() == "": return None return parse_number(v, None if language is None else str(language)) return to_number(v) # --------------------------------------------------------------------------- # Text # --------------------------------------------------------------------------- def _text_arg(v: Any) -> str | FxError: if isinstance(v, FxError): return v return to_text(v) def _int_arg(v: Any) -> int | FxError: x = to_number(v) return x if isinstance(x, FxError) else math.trunc(x) def len_(v: Any) -> Any: if isinstance(v, list): return invalid("Len of a table") t = _text_arg(v) return t if isinstance(t, FxError) else len(t.encode("utf-16-le")) // 2 # UTF-16 code units: Len(UniChar(128512)) is 2, as in the interpreter def upper(v: Any) -> Any: t = _text_arg(v) return t if isinstance(t, FxError) else "".join(_upper_char(c) for c in t) def lower(v: Any) -> Any: t = _text_arg(v) return t if isinstance(t, FxError) else "".join(_lower_char(c) for c in t) def proper(v: Any) -> Any: """Capitalise each letter that follows a non-letter other than an apostrophe; lower the rest.""" t = _text_arg(v) if isinstance(t, FxError): return t out = [] seen_letter_in_word = False for ch in t: if ch.isalpha(): out.append(_upper_char(ch) if not seen_letter_in_word else _lower_char(ch)) seen_letter_in_word = True else: out.append(ch) if not (ch.isdigit() or ch == "'"): seen_letter_in_word = False return "".join(out) def _upper_char(ch: str) -> str: u = ch.upper() return u if len(u) == 1 else ch # the invariant culture maps one character to one: ß stays ß def _lower_char(ch: str) -> str: low = ch.lower() return low if len(low) == 1 else ch _WHITESPACE = "\t\n\x0b\x0c\r \x85\xa0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000" # what .NET calls white space; U+200B is not _SPACE_RUN = re.compile(r"[ \t]+") def trim(v: Any) -> Any: """``Trim``: white space off both ends; inside, each run of spaces and tabs becomes one space and line breaks stay (interpreter-verified).""" t = _text_arg(v) return t if isinstance(t, FxError) else _SPACE_RUN.sub(" ", t.strip(_WHITESPACE)) def trim_ends(v: Any) -> Any: t = _text_arg(v) return t if isinstance(t, FxError) else t.strip(_WHITESPACE) def left(text: Any, n: Any) -> Any: err = first_error(text, n) if err is not None: return err t = to_text(text) k = _int_arg(n) if isinstance(t, FxError) or isinstance(k, FxError): return t if isinstance(t, FxError) else k if k < 0: return invalid("Argument out of range.") return t[:k] def right(text: Any, n: Any) -> Any: err = first_error(text, n) if err is not None: return err t = to_text(text) k = _int_arg(n) if isinstance(t, FxError) or isinstance(k, FxError): return t if isinstance(t, FxError) else k if k < 0: return invalid("Argument out of range.") return t[-k:] if k else "" def mid(text: Any, start: Any, n: Any = None) -> Any: err = first_error(text, start, n) if err is not None: return err t = to_text(text) s = _int_arg(start) if isinstance(t, FxError) or isinstance(s, FxError): return t if isinstance(t, FxError) else s if s < 1: return invalid("Argument out of range.") if n is None: return t[s - 1 :] k = _int_arg(n) if isinstance(k, FxError): return k if k < 0: return invalid("Argument out of range.") return t[s - 1 : s - 1 + k] def find(needle: Any, haystack: Any, start: Any = 1) -> Any: err = first_error(needle, haystack, start) if err is not None: return err n = to_text(needle) h = to_text(haystack) s = _int_arg(start) for v in (n, h, s): if isinstance(v, FxError): return v if s < 1 or s > len(h) + 1: return invalid("Argument out of range.") i = h.find(n, s - 1) return None if i < 0 else i + 1 def substitute(text: Any, old: Any, new: Any, instance: Any = None) -> Any: err = first_error(text, old, new, instance) if err is not None: return err t, o, n = to_text(text), to_text(old), to_text(new) for v in (t, o, n): if isinstance(v, FxError): return v if o == "": return t if instance is None: return t.replace(o, n) k = _int_arg(instance) if isinstance(k, FxError): return k if k < 1: return invalid("Argument out of range.") pos = -1 for _ in range(k): pos = t.find(o, pos + 1) if pos < 0: return t return t[:pos] + n + t[pos + len(o) :] def replace(text: Any, start: Any, n: Any, new: Any) -> Any: err = first_error(text, start, n, new) if err is not None: return err t, s, k, r = to_text(text), _int_arg(start), _int_arg(n), to_text(new) for v in (t, s, k, r): if isinstance(v, FxError): return v if s < 1 or k < 0: return invalid("Argument out of range.") return t[: s - 1] + r + t[s - 1 + k :] def starts_with(text: Any, prefix: Any) -> Any: err = first_error(text, prefix) if err is not None: return err t, p = to_text(text), to_text(prefix) if isinstance(t, FxError) or isinstance(p, FxError): return t if isinstance(t, FxError) else p return t.casefold().startswith(p.casefold()) def ends_with(text: Any, suffix: Any) -> Any: err = first_error(text, suffix) if err is not None: return err t, p = to_text(text), to_text(suffix) if isinstance(t, FxError) or isinstance(p, FxError): return t if isinstance(t, FxError) else p return t.casefold().endswith(p.casefold()) # Match and MatchOptions members are text in Power Fx (they concatenate with &). The patterns are the interpreter's own # spellings, translated to Python's dialect where \p{...} classes have no direct form. MATCH_PATTERNS = { "Any": ".", "Comma": ",", "Digit": "\\d", "Hyphen": "-", "LeftParen": "\\(", "Letter": "\\p{L}", "MultipleDigits": "\\d+", "MultipleLetters": "\\p{L}+", "MultipleNonSpaces": "\\S+", "MultipleSpaces": "\\s+", "NonSpace": "\\S", "OptionalDigits": "\\d*", "OptionalLetters": "\\p{L}*", "OptionalNonSpaces": "\\S*", "OptionalSpaces": "\\s*", "Period": "\\.", "RightParen": "\\)", "Space": "\\s", "Tab": "\\t", "Email": "(?:[^\\s@<>,;:\\\\\"]+)@(?:(?:[^\\s.@<>,;:\\\\\"]+)\\.)+(?:[^\\s.@<>,;:\\\\\"]+)", } MATCH_OPTION_CODES = {"Contains": "c", "IgnoreCase": "i", "Multiline": "m", "BeginsWith": "^c", "EndsWith": "c$", "Complete": "^c$", "FreeSpacing": "x", "DotAll": "s", "NumberedSubMatches": "N"} _UNICODE_CLASSES = {"L": "[^\\W\\d_]", "Lu": "[A-Z\\u00C0-\\u00DE]", "Ll": "[a-z\\u00DF-\\u00FF]", "N": "\\d", "Nd": "\\d", "P": "[!-/:-@\\[-`{-~]", "S": "[$+<=>^`|~]", "Z": "\\s", "Zs": " "} def _python_regex(pattern: str) -> str: """The .NET pattern in Python's dialect: \\p{L} classes become their nearest character class.""" def repl(m: "re.Match[str]") -> str: cls = _UNICODE_CLASSES.get(m.group(2)) if cls is None: return m.group(0) if m.group(1) == "P": # the negated class: undo a negation or add one if cls.startswith("[^"): return "[" + cls[2:] return "[^" + cls[1:] if cls.startswith("[") else "[^" + cls + "]" return cls out = re.sub(r"\\([pP])\{(\w+)\}", repl, pattern) out = re.sub(r"\(\?<([A-Za-z_]\w*)>", r"(?P<\1>", out) # a .NET named group return re.sub(r"\\k<([A-Za-z_]\w*)>", r"(?P=\1)", out) # a .NET named back-reference def _regex(pattern: Any, options: Any) -> tuple[Any, bool, str, str, bool] | FxError: """(compiled pattern, complete, anchor-start, anchor-end, numbered) from a pattern and MatchOptions text. Every match function looks for a sub-match unless the options say Complete, BeginsWith or EndsWith, which is how the interpreter answers (``IsMatch("abc", "b")`` is true). """ if isinstance(pattern, FxError) or isinstance(options, FxError): return pattern if isinstance(pattern, FxError) else options text_pattern = to_text(pattern) if isinstance(text_pattern, FxError): return text_pattern codes = to_text(options) if options is not None else "" if isinstance(codes, FxError): return codes flags = 0 if "i" in codes: flags |= re.IGNORECASE if "m" in codes: flags |= re.MULTILINE if "x" in codes: flags |= re.VERBOSE if "s" in codes: flags |= re.DOTALL starts, ends = "^" in codes, "$" in codes # "i^c$" is IgnoreCase & Complete: the anchors sit anywhere in the codes try: compiled = re.compile(_python_regex(text_pattern), flags) except re.error as exc: return invalid(f"the regular expression is not valid: {exc}") return compiled, starts and ends, starts, ends, "N" in codes def _search(compiled: Any, text: str, complete: bool, starts: bool, ends: bool) -> Any: if complete: return compiled.fullmatch(text) if starts: return compiled.match(text) if ends: for m in compiled.finditer(text): if m.end() == len(text): return m return None return compiled.search(text) def is_match(text_value: Any, pattern: Any, options: Any = None) -> Any: err = first_error(text_value, pattern, options) if err is not None: return err spec = _regex(pattern, options) if isinstance(spec, FxError): return spec compiled, complete, starts, ends, _ = spec t = to_text(text_value) if isinstance(t, FxError): return t return _search(compiled, t, complete, starts, ends) is not None def _match_record(m: Any, numbered: bool) -> dict[str, Any]: record: dict[str, Any] = {"FullMatch": m.group(0), "StartMatch": float(m.start() + 1)} if numbered: record["SubMatches"] = column_table(g if g is not None else "" for g in m.groups()) for name, value in m.groupdict().items(): record[name] = value if value is not None else "" return record def match(text_value: Any, pattern: Any, options: Any = None) -> Any: err = first_error(text_value, pattern, options) if err is not None: return err spec = _regex(pattern, options) if isinstance(spec, FxError): return spec compiled, complete, starts, ends, numbered = spec t = to_text(text_value) if isinstance(t, FxError): return t m = _search(compiled, t, complete, starts, ends) return _match_record(m, numbered) if m else None def match_all(text_value: Any, pattern: Any, options: Any = None) -> Any: err = first_error(text_value, pattern, options) if err is not None: return err spec = _regex(pattern, options) if isinstance(spec, FxError): return spec compiled, complete, starts, ends, numbered = spec t = to_text(text_value) if isinstance(t, FxError): return t if complete or starts or ends: m = _search(compiled, t, complete, starts, ends) return [_match_record(m, numbered)] if m else [] return [_match_record(m, numbered) for m in compiled.finditer(t)] def encode_url(v: Any) -> Any: """``EncodeUrl``: percent-encode everything but unreserved characters, as the interpreter does.""" import urllib.parse t = _text_arg(v) return t if isinstance(t, FxError) else urllib.parse.quote(t, safe="-_.~") def char(n: Any) -> Any: k = _int_arg(n) if isinstance(k, FxError): return k if k < 1 or k > 255: return invalid("Argument out of range.") return chr(k) def uni_char(n: Any) -> Any: """``UniChar``: 1 to 1,114,111, truncated; a surrogate code point is an error (interpreter-verified).""" k = _int_arg(n) if isinstance(k, FxError): return k if k < 1 or k > 0x10FFFF: return invalid(f"Input value {k} falls outside the allowable range.") if 0xD800 <= k <= 0xDFFF: return invalid(f"Input value {k} is an invalid input.") return chr(k) # --------------------------------------------------------------------------- # Numbers # --------------------------------------------------------------------------- def _decimal(x: float) -> Decimal: return Decimal(repr(float(x))) def _round_decimal(x: float, digits: int, mode: str) -> float: if x == 0: return 0.0 # a negative zero rounds to plain zero; Round(-0.4, 0) still gives -0 d = _decimal(x) q = Decimal(1).scaleb(-digits) return float(d.quantize(q, rounding=mode)) if digits >= -28 else x def _num1(v: Any) -> float | FxError: if isinstance(v, FxError): return v return to_number(v) def round_(x: Any, digits: Any = 0) -> Any: err = first_error(x, digits) if err is not None: return err v, d = _num1(x), _int_arg(digits) if isinstance(v, FxError) or isinstance(d, FxError): return v if isinstance(v, FxError) else d return _round_decimal(v, d, ROUND_HALF_UP) def round_up(x: Any, digits: Any = 0) -> Any: err = first_error(x, digits) if err is not None: return err v, d = _num1(x), _int_arg(digits) if isinstance(v, FxError) or isinstance(d, FxError): return v if isinstance(v, FxError) else d return _round_decimal(v, d, ROUND_UP) def round_down(x: Any, digits: Any = 0) -> Any: err = first_error(x, digits) if err is not None: return err v, d = _num1(x), _int_arg(digits) if isinstance(v, FxError) or isinstance(d, FxError): return v if isinstance(v, FxError) else d return _round_decimal(v, d, ROUND_DOWN) def int_(x: Any) -> Any: v = _num1(x) if isinstance(v, FxError): return v return v if v == 0 else float(math.floor(v)) # Int(-0) stays -0, as the interpreter has it def trunc(x: Any, digits: Any = 0) -> Any: return round_down(x, digits) def abs_(x: Any) -> Any: v = _num1(x) return v if isinstance(v, FxError) else abs(v) def sqrt(x: Any) -> Any: v = _num1(x) if isinstance(v, FxError): return v if v < 0: return FxError("Numeric", "The function 'Sqrt' returned a non-finite number.") return math.sqrt(v) def mod(a: Any, b: Any) -> Any: err = first_error(a, b) if err is not None: return err x, y = _num1(a), _num1(b) if isinstance(x, FxError) or isinstance(y, FxError): return x if isinstance(x, FxError) else y if y == 0: return div0() r = math.fmod(x, y) if r != 0 and (r < 0) != (y < 0): r += y return r def exp(x: Any) -> Any: v = _num1(x) if isinstance(v, FxError): return v try: return math.exp(v) except OverflowError: return FxError("Numeric", "overflow") def ln(x: Any) -> Any: v = _num1(x) if isinstance(v, FxError): return v if v <= 0: return FxError("Numeric", "The function 'Ln' returned a non-finite number.") return math.log(v) def log(x: Any, base: Any = 10) -> Any: err = first_error(x, base) if err is not None: return err v, b = _num1(x), _num1(base) if isinstance(v, FxError) or isinstance(b, FxError): return v if isinstance(v, FxError) else b if v <= 0 or b <= 0 or b == 1: return FxError("Numeric", "The function 'Log' returned a non-finite number.") return math.log(v) / math.log(b) def power_fn(x: Any, y: Any) -> Any: return power(x, y) def _unary_math(fn: Callable[[float], float]) -> Callable[[Any], Any]: def wrapped(x: Any) -> Any: v = _num1(x) if isinstance(v, FxError): return v try: result = fn(v) except (ValueError, OverflowError, ZeroDivisionError): return FxError("Numeric", "the result is not a finite number") if math.isnan(result) or math.isinf(result): return FxError("Numeric", "the result is not a finite number") return result return wrapped sin, cos, tan = _unary_math(math.sin), _unary_math(math.cos), _unary_math(math.tan) asin, acos, atan = _unary_math(math.asin), _unary_math(math.acos), _unary_math(math.atan) degrees, radians = _unary_math(math.degrees), _unary_math(math.radians) cot = _unary_math(lambda v: 1.0 / math.tan(v)) acot = _unary_math(lambda v: math.pi / 2 - math.atan(v)) def atan2(x: Any, y: Any) -> Any: """``Atan2(x, y)``: the x coordinate comes first, as in Excel and Power Fx; the origin is a division by zero (interpreter-verified).""" err = first_error(x, y) if err is not None: return err a, b = _num1(x), _num1(y) if isinstance(a, FxError) or isinstance(b, FxError): return a if isinstance(a, FxError) else b if a == 0 and b == 0: return div0() return math.atan2(b, a) def pi() -> float: return math.pi # --------------------------------------------------------------------------- # Dates and times # --------------------------------------------------------------------------- _UNIT_NAMES = {"Milliseconds", "Seconds", "Minutes", "Hours", "Days", "Months", "Quarters", "Years"} def _unit(u: Any) -> str | FxError: if u is None: return "Days" if isinstance(u, FxError): return u if isinstance(u, Option): return u.name if u.name in _UNIT_NAMES else invalid(f"unknown time unit {u.name}") if isinstance(u, str) and u in _UNIT_NAMES: return u return invalid("unknown time unit") def _date_arg(v: Any) -> _dt.datetime | None | FxError: if isinstance(v, FxError): return v if v is None: return None if isinstance(v, _dt.datetime): return v if isinstance(v, _dt.date): return _dt.datetime(v.year, v.month, v.day) if isinstance(v, _dt.timedelta): return _dt.datetime(1899, 12, 30) + v if isinstance(v, str): return date_time_value(v) if is_number(v): return _dt.datetime(1899, 12, 30) + _dt.timedelta(days=float(v)) return invalid("a date was expected") _BLANK_DATE = _dt.datetime(1899, 12, 30) def date(year: Any, month: Any, day: Any) -> Any: err = first_error(year, month, day) if err is not None: return err y, m, d = _int_arg(year), _int_arg(month), _int_arg(day) for v in (y, m, d): if isinstance(v, FxError): return v total_months = y * 12 + (m - 1) y2, m2 = divmod(total_months, 12) try: base = _dt.date(y2, m2 + 1, 1) + _dt.timedelta(days=d - 1) except (ValueError, OverflowError): return invalid("date out of range") return base def time(hours: Any, minutes: Any, seconds: Any, milliseconds: Any = 0) -> Any: err = first_error(hours, minutes, seconds, milliseconds) if err is not None: return err parts = [_int_arg(v) for v in (hours, minutes, seconds, milliseconds)] for v in parts: if isinstance(v, FxError): return v h, m, s, ms = parts return _wrap_time(_dt.timedelta(hours=h, minutes=m, seconds=s, milliseconds=ms)) def date_time(year: Any, month: Any, day: Any, hours: Any = 0, minutes: Any = 0, seconds: Any = 0, milliseconds: Any = 0) -> Any: d = date(year, month, day) if isinstance(d, FxError): return d parts = [_int_arg(v) for v in (hours, minutes, seconds, milliseconds)] for v in parts: if isinstance(v, FxError): return v h, m, s, ms = parts return _dt.datetime(d.year, d.month, d.day) + _dt.timedelta(hours=h, minutes=m, seconds=s, milliseconds=ms) # 25 hours rolls into the next day def _add_months(d: _dt.datetime, months: int) -> _dt.datetime: total = d.year * 12 + (d.month - 1) + months y, m0 = divmod(total, 12) last_day = calendar.monthrange(y, m0 + 1)[1] return d.replace(year=y, month=m0 + 1, day=min(d.day, last_day)) def date_add(value: Any, n: Any, unit: Any = None) -> Any: err = first_error(value, n, unit) if err is not None: return err d = _date_arg(value) if isinstance(d, FxError): return d k = to_number(n) if isinstance(k, FxError): return k u = _unit(unit) if isinstance(u, FxError): return u was_date = isinstance(value, _dt.date) and not isinstance(value, _dt.datetime) if d is None: return None try: if u in ("Months", "Quarters", "Years"): months = int(k) * {"Months": 1, "Quarters": 3, "Years": 12}[u] out = _add_months(d, months) else: seconds = k * {"Milliseconds": 0.001, "Seconds": 1, "Minutes": 60, "Hours": 3600, "Days": 86400}[u] out = d + _dt.timedelta(seconds=seconds) except (ValueError, OverflowError): return invalid("Argument out of range.") return out.date() if was_date else out def date_diff(start: Any, end: Any, unit: Any = None) -> Any: err = first_error(start, end, unit) if err is not None: return err a, b = _date_arg(start), _date_arg(end) if isinstance(a, FxError) or isinstance(b, FxError): return a if isinstance(a, FxError) else b u = _unit(unit) if isinstance(u, FxError): return u a = a or _BLANK_DATE b = b or _BLANK_DATE if u == "Years": return float(b.year - a.year) if u == "Quarters": return float((b.year - a.year) * 4 + ((b.month - 1) // 3 - (a.month - 1) // 3)) if u == "Months": return float((b.year - a.year) * 12 + (b.month - a.month)) if u == "Days": return float((b.date() - a.date()).days) per = {"Milliseconds": 0.001, "Seconds": 1, "Minutes": 60, "Hours": 3600}[u] # both ends are truncated to the unit first, so 15:04 to 16:03 is one hour ta = math.floor((a - _SERIAL_BASE).total_seconds() / per) tb = math.floor((b - _SERIAL_BASE).total_seconds() / per) return float(tb - ta) def _part(value: Any, fn: Callable[[_dt.datetime], Any], blank: float = 0.0) -> Any: d = _date_arg(value) if isinstance(d, FxError): return d if d is None: return blank # the blank date reads as "0 January 1900": Year 1900, Month 1, Day 0, a Saturday return fn(d) def year(v: Any) -> Any: return _part(v, lambda d: float(d.year), 1900.0) def month(v: Any) -> Any: return _part(v, lambda d: float(d.month), 1.0) def day(v: Any) -> Any: return _part(v, lambda d: float(d.day), 0.0) def hour(v: Any) -> Any: if isinstance(v, _dt.timedelta): return float(int(v.total_seconds() // 3600) % 24) return _part(v, lambda d: float(d.hour)) def minute(v: Any) -> Any: if isinstance(v, _dt.timedelta): return float(int(v.total_seconds() // 60) % 60) return _part(v, lambda d: float(d.minute)) def second(v: Any) -> Any: if isinstance(v, _dt.timedelta): return float(int(v.total_seconds()) % 60) return _part(v, lambda d: float(d.second)) _START_OF_WEEK = {"Sunday": 1, "Monday": 2, "Tuesday": 3, "Wednesday": 4, "Thursday": 5, "Friday": 6, "Saturday": 7} def weekday(v: Any, start: Any = None) -> Any: """``Weekday``: 1 for Sunday by default; ``StartOfWeek`` members shift the week; the Zero variants count from 0.""" err = first_error(v, start) if err is not None: return err d = _date_arg(v) if isinstance(d, FxError): return d d = d or _BLANK_DATE sunday_based = (d.weekday() + 1) % 7 # Sunday 0 .. Saturday 6 if start is None: return float(sunday_based + 1) if isinstance(start, Option): name = start.name zero = name.endswith("Zero") name = name[:-4] if zero else name first_day = _START_OF_WEEK.get(name) if first_day is None: return invalid("unknown start of week") shifted = (sunday_based - (first_day - 1)) % 7 return float(shifted if zero else shifted + 1) k = _int_arg(start) if isinstance(k, FxError): return k codes = {1: 1, 2: 2, 3: 2, 11: 2, 12: 3, 13: 4, 14: 5, 15: 6, 16: 7, 17: 1} if k not in codes: return invalid("unknown start of week") shifted = (sunday_based - (codes[k] - 1)) % 7 return float(shifted if k == 3 else shifted + 1) def week_num(v: Any, start: Any = None) -> Any: err = first_error(v, start) if err is not None: return err d = _date_arg(v) if isinstance(d, FxError): return d d = d or _BLANK_DATE first_day = 1 if isinstance(start, Option): first_day = _START_OF_WEEK.get(start.name.replace("Zero", ""), 1) elif start is not None: k = _int_arg(start) if isinstance(k, FxError): return k first_day = {1: 1, 2: 2, 11: 2, 12: 3, 13: 4, 14: 5, 15: 6, 16: 7, 17: 1}.get(k, 1) jan1 = _dt.date(d.year, 1, 1) jan1_index = ((jan1.weekday() + 1) % 7 - (first_day - 1)) % 7 # days since the week started, for 1 Jan return float(((d.date() - jan1).days + jan1_index) // 7 + 1) def edate(v: Any, months: Any) -> Any: return date_add(v, months, Option("TimeUnit", "Months")) def eomonth(v: Any, months: Any) -> Any: err = first_error(v, months) if err is not None: return err d = _date_arg(v) if isinstance(d, FxError): return d k = _int_arg(months) if isinstance(k, FxError): return k try: moved = _add_months(d or _BLANK_DATE, k) return _dt.date(moved.year, moved.month, calendar.monthrange(moved.year, moved.month)[1]) except (ValueError, OverflowError): return invalid("Argument out of range.") _DATE_FORMATS = ( "%Y-%m-%d", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%dT%H:%M:%S.%f", "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M", "%m/%d/%Y", "%m/%d/%Y %H:%M", "%m/%d/%Y %H:%M:%S", "%m/%d/%Y %I:%M %p", "%m/%d/%Y %I:%M:%S %p", "%B %d, %Y", "%b %d, %Y", "%d %B %Y", "%d %b %Y", ) def date_time_value(text: Any, language: Any = None) -> Any: """``DateTimeValue``/``DateValue`` parsing: ISO 8601 and the invariant culture's spellings; ``en-GB`` reads day first.""" err = first_error(text, language) if err is not None: return err if text is None: return None if isinstance(text, _dt.date): return _as_datetime(text) s = to_text(text) if isinstance(s, FxError): return s s = s.strip() if s == "": return None iso = s.replace("Z", "+00:00") if s.endswith("Z") else s try: parsed = _dt.datetime.fromisoformat(iso) if parsed.tzinfo is not None: parsed = parsed.astimezone(_dt.timezone.utc).replace(tzinfo=None) return parsed except ValueError: pass formats = list(_DATE_FORMATS) if language and str(language).lower() in ("en-gb", "en-au", "en-nz", "en-ie", "fr-fr", "de-de", "es-es", "it-it"): formats = ["%d/%m/%Y", "%d/%m/%Y %H:%M", "%d/%m/%Y %H:%M:%S", "%d.%m.%Y"] + formats for fmt in formats: try: return _dt.datetime.strptime(s, fmt) except ValueError: continue return invalid(f"The value '{s}' cannot be converted to a date.") def date_value(text: Any, language: Any = None) -> Any: d = date_time_value(text, language) if d is None or isinstance(d, FxError): return d return d.date() def time_value(text: Any, language: Any = None) -> Any: err = first_error(text, language) if err is not None: return err if text is None: return None s = to_text(text) if isinstance(s, FxError): return s s = s.strip() if s == "": return None for fmt in ("%H:%M:%S", "%H:%M", "%I:%M %p", "%I:%M:%S %p", "%H:%M:%S.%f"): try: t = _dt.datetime.strptime(s, fmt) return _dt.timedelta(hours=t.hour, minutes=t.minute, seconds=t.second, microseconds=t.microsecond) except ValueError: continue d = date_time_value(s, language) if isinstance(d, FxError) or d is None: return invalid(f"The value '{s}' cannot be converted to a time.") return _dt.timedelta(hours=d.hour, minutes=d.minute, seconds=d.second, microseconds=d.microsecond) class Clock: """``Now``/``Today`` read the clock the generated model is run with; a frozen clock keeps runs reproducible.""" def __init__(self, now: _dt.datetime | None = None): self.fixed = now def now(self) -> _dt.datetime: return self.fixed if self.fixed is not None else _dt.datetime.now() CLOCK = Clock() def now() -> _dt.datetime: return CLOCK.now().replace(microsecond=(CLOCK.now().microsecond // 1000) * 1000) def today() -> _dt.date: return CLOCK.now().date() def is_today(v: Any) -> Any: d = _date_arg(v) if isinstance(d, FxError): return d return d is not None and d.date() == today() def guid(text: Any = None) -> Any: """``GUID()`` makes a new identifier (the interpreter: 36 lower-case characters, never equal to another call); ``GUID(text)`` reads one, 32 hex digits with optional hyphens and braces, and spells it the canonical way.""" if isinstance(text, FxError): return text if text is None: return str(_uuid.uuid4()) s = str(text).strip() if s.startswith("{") and s.endswith("}"): s = s[1:-1] digits = s.replace("-", "") if len(digits) != 32 or any(c not in "0123456789abcdefABCDEF" for c in digits): return invalid(f"The value '{text}' cannot be converted to a GUID.") d = digits.lower() return f"{d[:8]}-{d[8:12]}-{d[12:16]}-{d[16:20]}-{d[20:]}" RNG = _random.Random() # ``Shuffle``'s source of randomness; seed it for a reproducible run def shuffle(table: Any) -> Any: """``Shuffle(table)``: the rows in a random order (the interpreter: Blank stays Blank, an empty table stays empty).""" if isinstance(table, FxError) or table is None: return table if not isinstance(table, list): return invalid("Shuffle needs a table.") rows = list(table) RNG.shuffle(rows) return rows def patch_record(base: Any, *changes: Any) -> Any: """``Patch(record, changes...)`` outside a data source: the changes merged into the record, later ones winning. The interpreter ignores a Blank change and reads a Blank base as an empty record; a Patch on a data source is a write and is the generated Context's job (``ctx.patch``), never this function's. """ for v in (base, *changes): if isinstance(v, FxError): return v if base is not None and not isinstance(base, dict): return invalid("Patch outside a data source needs a record as its first argument.") merged = dict(base or {}) for change in changes: if change is None: continue if not isinstance(change, dict): return invalid("The changes given to Patch must be records.") merged.update(change) return merged # --------------------------------------------------------------------------- # Text formatting # --------------------------------------------------------------------------- # Separators and the named date/time patterns of the cultures the runtime formats for (the .NET patterns the # interpreter uses; other languages are reported as not translated rather than approximated). _CULTURES: dict[str, dict[str, Any]] = { "": {"decimal": ".", "group": ",", "short_date": "MM/dd/yyyy", "long_date": "dddd, dd MMMM yyyy", "short_time": "HH:mm", "long_time": "HH:mm:ss"}, "en-us": {"decimal": ".", "group": ",", "short_date": "M/d/yyyy", "long_date": "dddd, MMMM d, yyyy", "short_time": "h:mm tt", "long_time": "h:mm:ss tt"}, "en-gb": {"decimal": ".", "group": ",", "short_date": "dd/MM/yyyy", "long_date": "dd MMMM yyyy", "short_time": "HH:mm", "long_time": "HH:mm:ss"}, "en-au": {"decimal": ".", "group": ",", "short_date": "d/MM/yyyy", "long_date": "dddd, d MMMM yyyy", "short_time": "h:mm tt", "long_time": "h:mm:ss tt"}, "en-ie": {"decimal": ".", "group": ",", "short_date": "dd/MM/yyyy", "long_date": "dd MMMM yyyy", "short_time": "HH:mm", "long_time": "HH:mm:ss"}, "de-de": {"decimal": ",", "group": ".", "short_date": "dd.MM.yyyy", "long_date": None, "short_time": "HH:mm", "long_time": "HH:mm:ss"}, } _MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] _DAYS = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] def _culture(language: Any) -> dict[str, Any] | FxError: if isinstance(language, FxError): return language key = (str(language) if language is not None else "").strip().lower() culture = _CULTURES.get(key) if culture is None: return UNSUPPORTED(f"Text with language '{language}' is not translated: only the invariant culture, en-US, en-GB, en-AU, en-IE and de-DE are") return culture _LOCALE_PREFIX = re.compile(r"^\[\$-([A-Za-z0-9-]+)\]") def text(v: Any, fmt: Any = None, language: Any = None) -> Any: """``Text``: a number or date with an Excel-style format, or the default spelling.""" err = first_error(v, fmt, language) if err is not None: return err culture = _culture(language) if isinstance(culture, FxError): return culture if fmt is None: return None if v is None else to_text(v) if v is None: v = 0.0 if isinstance(fmt, Option) and fmt.set_name == "DateTimeFormat": d = _date_arg(v) if isinstance(d, FxError) or d is None: return d if isinstance(d, FxError) else "" return _format_named(d, fmt.name, culture) f = to_text(fmt) if isinstance(f, FxError): return f f = _LOCALE_PREFIX.sub("", f) if isinstance(v, (bool, str)): return invalid("The second argument of the 'Text' function is only supported for numeric and date/time values.") if f == "": return "" if isinstance(v, _dt.timedelta): return _format_time(v, f) if _looks_like_date_format(f) else _format_number(v.total_seconds() / 86400.0, f, culture) if _is_date(v): if _looks_like_date_format(f): return _format_date(_as_datetime(v), f, culture) return _format_number(_datetime_serial(_as_datetime(v)), f, culture) if not is_number(v): return invalid("The second argument of the 'Text' function is only supported for numeric and date/time values.") if _looks_like_date_format(f): d = _date_arg(v) return d if isinstance(d, FxError) else _format_date(d, f, culture) return _format_number(float(v), f, culture) def _tokens(fmt: str) -> list[tuple[str, str]]: """(kind, text): kind is 'lit' for literal text or 'fmt' for format characters.""" out: list[tuple[str, str]] = [] i = 0 while i < len(fmt): ch = fmt[i] if ch == '"': j = fmt.find('"', i + 1) if j < 0: j = len(fmt) out.append(("lit", fmt[i + 1 : j])) i = j + 1 elif ch == "\\" and i + 1 < len(fmt): out.append(("lit", fmt[i + 1])) i += 2 else: out.append(("fmt", ch)) i += 1 return out def _looks_like_date_format(fmt: str) -> bool: chars = "".join(t for kind, t in _tokens(fmt) if kind == "fmt").lower() chars = re.sub(r"(?<=s)\.0+", "", chars) # ss.000 is a fraction of a second, not a number placeholder has_date = any(c in chars for c in "ymdhs") or "am/pm" in chars or "a/p" in chars has_number = any(c in chars for c in "0#%") return has_date and not has_number def _format_named(d: _dt.datetime, name: str, culture: dict[str, Any]) -> str | FxError: if culture is not _CULTURES[""]: # .NET takes these patterns from the platform (ICU on Linux, NLS on Windows) and they differ, so there is # no single answer to reproduce; the invariant culture's patterns are fixed return UNSUPPORTED("DateTimeFormat names with a language are not translated: their patterns vary by platform in the interpreter itself") short_date, long_date = culture["short_date"], culture["long_date"] short_time, long_time = culture["short_time"], culture["long_time"] patterns = { "ShortDate": short_date, "LongDate": long_date, "ShortTime": short_time, "ShortTime24": "HH:mm", "LongTime": long_time, "LongTime24": "HH:mm:ss", "ShortDateTime": f"{short_date} {short_time}", "ShortDateTime24": f"{short_date} HH:mm", "LongDateTime": f"{long_date} {long_time}", "LongDateTime24": f"{long_date} HH:mm:ss", "UTC": "yyyy-MM-ddTHH:mm:ss.fffZ", } pattern = patterns.get(name) if pattern is None: return invalid(f"unknown DateTimeFormat {name}") return _format_net(d, pattern) def _format_net(d: _dt.datetime, pattern: str) -> str: """A .NET custom date pattern (case-sensitive tokens), used for the named formats.""" out = [] i = 0 while i < len(pattern): ch = pattern[i] j = i while j < len(pattern) and pattern[j] == ch: j += 1 run = pattern[i:j] n = len(run) if ch == "y": out.append(f"{d.year % 100:02d}" if n <= 2 else f"{d.year:04d}") elif ch == "M": out.append(_MONTHS[d.month - 1] if n >= 4 else _MONTHS[d.month - 1][:3] if n == 3 else f"{d.month:0{n}d}") elif ch == "d": out.append(_DAYS[d.weekday()] if n >= 4 else _DAYS[d.weekday()][:3] if n == 3 else f"{d.day:0{n}d}") elif ch == "H": out.append(f"{d.hour:0{n}d}") elif ch == "h": out.append(f"{(d.hour % 12) or 12:0{n}d}") elif ch == "m": out.append(f"{d.minute:0{n}d}") elif ch == "s": out.append(f"{d.second:0{n}d}") elif ch == "f": out.append(f"{d.microsecond // 1000:03d}"[:n]) elif ch == "t": out.append("AM" if d.hour < 12 else "PM") else: out.append(run) i = j return "".join(out) def _format_date(d: _dt.datetime, fmt: str, culture: dict[str, Any]) -> str | FxError: """An Excel-style date format: ``dd mmm yyyy``, ``h:mm AM/PM``, ``yyyy-mm-ddThh:mm:ss.000``.""" tokens = _tokens(fmt) out: list[str] = [] twelve_hour = "am/pm" in fmt.lower() or "a/p" in fmt.lower() i = 0 last_time_token = "" while i < len(tokens): kind, t = tokens[i] if kind == "lit": out.append(t) i += 1 continue low = t.lower() rest = "".join(x for k, x in tokens[i:] if k == "fmt") rest_low = rest.lower() if rest_low.startswith("am/pm"): marker = "AM" if d.hour < 12 else "PM" out.append(marker if rest[:5] == "AM/PM" else marker.lower()) i += 5 continue if rest_low.startswith("a/p"): marker = "A" if d.hour < 12 else "P" out.append(marker if rest[0] == "A" else marker.lower()) i += 3 continue if low in "ymdhs": j = i while j < len(tokens) and tokens[j][0] == "fmt" and tokens[j][1].lower() == low: j += 1 n = j - i if low == "y": out.append(f"{d.year % 100:02d}" if n <= 2 else f"{d.year:04d}") elif low == "d": out.append(_DAYS[d.weekday()] if n >= 4 else _DAYS[d.weekday()][:3] if n == 3 else f"{d.day:0{n}d}") last_time_token = "" elif low == "h": hour = (d.hour % 12 or 12) if twelve_hour else d.hour out.append(f"{hour:0{min(n, 2)}d}") last_time_token = "h" elif low == "s": out.append(f"{d.second:0{min(n, 2)}d}") last_time_token = "s" elif low == "m": following = "".join(x for k, x in tokens[j:] if k == "fmt").lower().lstrip(":. ") minutes = last_time_token == "h" or following.startswith("s") or (n <= 2 and following.startswith("ss")) if minutes: out.append(f"{d.minute:0{min(n, 2)}d}") last_time_token = "m" else: out.append(_MONTHS[d.month - 1] if n >= 4 else _MONTHS[d.month - 1][:3] if n == 3 else f"{d.month:0{n}d}") i = j continue if t == "." and i + 1 < len(tokens) and tokens[i + 1] == ("fmt", "0") and last_time_token in ("s", "m", "h"): j = i + 1 while j < len(tokens) and tokens[j] == ("fmt", "0"): j += 1 digits = j - i - 1 out.append("." + f"{d.microsecond // 1000:03d}"[:digits].ljust(digits, "0")) i = j continue out.append(t) i += 1 return "".join(out) def _format_time(t: _dt.timedelta, fmt: str) -> str | FxError: base = _BLANK_DATE + t return _format_date(base, fmt, _CULTURES[""]) def _format_number(x: float, fmt: str, culture: dict[str, Any]) -> str | FxError: sections = _split_sections(fmt) if x < 0 and len(sections) >= 2 and sections[1] != "": section, x = sections[1], -x elif x == 0 and len(sections) >= 3: section = sections[2] else: section = sections[0] return _apply_number_section(x, section, culture) def _split_sections(fmt: str) -> list[str]: sections, current, quoted, i = [], [], False, 0 while i < len(fmt): ch = fmt[i] if ch == '"': quoted = not quoted elif ch == "\\" and i + 1 < len(fmt): current.append(fmt[i : i + 2]) i += 2 continue elif ch == ";" and not quoted: sections.append("".join(current)) current = [] i += 1 continue current.append(ch) i += 1 sections.append("".join(current)) return sections def _apply_number_section(x: float, section: str, culture: dict[str, Any]) -> str | FxError: tokens = _tokens(section) fmt_chars = [t for k, t in tokens if k == "fmt"] percent = fmt_chars.count("%") scale = 100.0**percent # trailing commas after the last digit placeholder scale by thousands digits_idx = [i for i, (k, t) in enumerate(tokens) if k == "fmt" and t in "0#?"] if not digits_idx: return "".join(t for k, t in tokens if k == "lit" or t not in "0#?,.%E+-") last_digit = digits_idx[-1] trailing_commas = 0 j = last_digit + 1 while j < len(tokens) and tokens[j] == ("fmt", ","): trailing_commas += 1 j += 1 scale /= 1000.0**trailing_commas # a comma between the integer digits and the decimal point scales as well ("0,.0") for i, tok in enumerate(tokens): if tok == ("fmt", ",") and i < last_digit and not any(t == ("fmt", ".") for t in tokens[:i]): after = tokens[i + 1 : last_digit + 1] if after and all(t[0] == "lit" or t[1] not in "0#?" for t in after[: next((k for k, t in enumerate(after) if t == ("fmt", ".")), len(after))]): scale /= 1000.0 # scientific notation sci = None for i in range(len(tokens) - 1): if tokens[i] == ("fmt", "E") or tokens[i] == ("fmt", "e"): if i + 1 < len(tokens) and tokens[i + 1][0] == "fmt" and tokens[i + 1][1] in "+-": sci = i break value = x * scale # split integer and fraction placeholders first_digit = digits_idx[0] dot = next((i for i, tok in enumerate(tokens) if tok == ("fmt", ".") and first_digit < i < (sci if sci is not None else len(tokens))), None) int_tokens = tokens[first_digit : (dot if dot is not None else (sci if sci is not None else last_digit + 1))] frac_tokens = tokens[dot + 1 : (sci if sci is not None else last_digit + 1)] if dot is not None else [] int_places = sum(1 for k, t in int_tokens if k == "fmt" and t in "0#?") int_zeros = sum(1 for k, t in int_tokens if k == "fmt" and t == "0") grouping = any(tok == ("fmt", ",") for tok in int_tokens) frac_places = sum(1 for k, t in frac_tokens if k == "fmt" and t in "0#?") frac_zeros = sum(1 for k, t in frac_tokens if k == "fmt" and t == "0") exponent = 0 if sci is not None: exp_tokens = tokens[sci + 2 :] exp_digits = sum(1 for k, t in exp_tokens if k == "fmt" and t == "0") if value != 0: exponent = int(math.floor(math.log10(abs(value)))) exponent -= (int_places - 1) if int_places > 1 else 0 value = value / (10**exponent) d = _decimal(value).quantize(Decimal(1).scaleb(-frac_places), rounding=ROUND_HALF_UP) negative = d.is_signed() d = abs(d) int_part, _, frac_part = f"{d:f}".partition(".") if int_part == "0" and int_zeros == 0 and int_places > 0 and frac_places > 0: int_part = "" elif int_part == "0" and int_zeros == 0 and int_places > 0 and frac_places == 0: int_part = "" int_part = int_part.rjust(int_zeros, "0") if grouping and int_part: groups = [] while len(int_part) > 3: groups.insert(0, int_part[-3:]) int_part = int_part[:-3] groups.insert(0, int_part) int_part = culture["group"].join(groups) frac_part = (frac_part or "").ljust(frac_places, "0")[:frac_places] while len(frac_part) > frac_zeros and frac_part.endswith("0"): frac_part = frac_part[:-1] # assemble: literals before the digits, the number, literals after out: list[str] = [] for k, t in tokens[:first_digit]: if k == "lit": out.append(t) elif t not in "0#?,.%E+-": out.append(t) elif t == "%": out.append("%") number = int_part if frac_part or (dot is not None and frac_zeros > 0): number += culture["decimal"] + frac_part elif dot is not None and frac_places == 0 and any(tok == ("fmt", ".") for tok in tokens): number += culture["decimal"] if False else "" if sci is not None: sign_token = tokens[sci + 1][1] exp_text = f"{abs(exponent):0{max(1, sum(1 for k, t in tokens[sci + 2 :] if k == 'fmt' and t == '0'))}d}" sign = "-" if exponent < 0 else ("+" if sign_token == "+" else "") number += tokens[sci][1] + sign + exp_text tail_start = sci + 2 while tail_start < len(tokens) and tokens[tail_start] == ("fmt", "0"): tail_start += 1 else: tail_start = last_digit + 1 + trailing_commas out.append(("-" if negative else "") + number) for k, t in tokens[tail_start:]: if k == "lit": out.append(t) elif t == "%": out.append("%") elif t not in "0#?,.E+-": out.append(t) return "".join(out) # --------------------------------------------------------------------------- # Colours # --------------------------------------------------------------------------- _NAMED_COLORS: dict[str, int] = { "aliceblue": 0xFFF0F8FF, "antiquewhite": 0xFFFAEBD7, "aqua": 0xFF00FFFF, "aquamarine": 0xFF7FFFD4, "azure": 0xFFF0FFFF, "beige": 0xFFF5F5DC, "bisque": 0xFFFFE4C4, "black": 0xFF000000, "blanchedalmond": 0xFFFFEBCD, "blue": 0xFF0000FF, "blueviolet": 0xFF8A2BE2, "brown": 0xFFA52A2A, "burlywood": 0xFFDEB887, "cadetblue": 0xFF5F9EA0, "chartreuse": 0xFF7FFF00, "chocolate": 0xFFD2691E, "coral": 0xFFFF7F50, "cornflowerblue": 0xFF6495ED, "cornsilk": 0xFFFFF8DC, "crimson": 0xFFDC143C, "cyan": 0xFF00FFFF, "darkblue": 0xFF00008B, "darkcyan": 0xFF008B8B, "darkgoldenrod": 0xFFB8860B, "darkgray": 0xFFA9A9A9, "darkgreen": 0xFF006400, "darkgrey": 0xFFA9A9A9, "darkkhaki": 0xFFBDB76B, "darkmagenta": 0xFF8B008B, "darkolivegreen": 0xFF556B2F, "darkorange": 0xFFFF8C00, "darkorchid": 0xFF9932CC, "darkred": 0xFF8B0000, "darksalmon": 0xFFE9967A, "darkseagreen": 0xFF8FBC8F, "darkslateblue": 0xFF483D8B, "darkslategray": 0xFF2F4F4F, "darkslategrey": 0xFF2F4F4F, "darkturquoise": 0xFF00CED1, "darkviolet": 0xFF9400D3, "deeppink": 0xFFFF1493, "deepskyblue": 0xFF00BFFF, "dimgray": 0xFF696969, "dimgrey": 0xFF696969, "dodgerblue": 0xFF1E90FF, "firebrick": 0xFFB22222, "floralwhite": 0xFFFFFAF0, "forestgreen": 0xFF228B22, "fuchsia": 0xFFFF00FF, "gainsboro": 0xFFDCDCDC, "ghostwhite": 0xFFF8F8FF, "gold": 0xFFFFD700, "goldenrod": 0xFFDAA520, "gray": 0xFF808080, "green": 0xFF008000, "greenyellow": 0xFFADFF2F, "grey": 0xFF808080, "honeydew": 0xFFF0FFF0, "hotpink": 0xFFFF69B4, "indianred": 0xFFCD5C5C, "indigo": 0xFF4B0082, "ivory": 0xFFFFFFF0, "khaki": 0xFFF0E68C, "lavender": 0xFFE6E6FA, "lavenderblush": 0xFFFFF0F5, "lawngreen": 0xFF7CFC00, "lemonchiffon": 0xFFFFFACD, "lightblue": 0xFFADD8E6, "lightcoral": 0xFFF08080, "lightcyan": 0xFFE0FFFF, "lightgoldenrodyellow": 0xFFFAFAD2, "lightgray": 0xFFD3D3D3, "lightgreen": 0xFF90EE90, "lightgrey": 0xFFD3D3D3, "lightpink": 0xFFFFB6C1, "lightsalmon": 0xFFFFA07A, "lightseagreen": 0xFF20B2AA, "lightskyblue": 0xFF87CEFA, "lightslategray": 0xFF778899, "lightslategrey": 0xFF778899, "lightsteelblue": 0xFFB0C4DE, "lightyellow": 0xFFFFFFE0, "lime": 0xFF00FF00, "limegreen": 0xFF32CD32, "linen": 0xFFFAF0E6, "magenta": 0xFFFF00FF, "maroon": 0xFF800000, "mediumaquamarine": 0xFF66CDAA, "mediumblue": 0xFF0000CD, "mediumorchid": 0xFFBA55D3, "mediumpurple": 0xFF9370DB, "mediumseagreen": 0xFF3CB371, "mediumslateblue": 0xFF7B68EE, "mediumspringgreen": 0xFF00FA9A, "mediumturquoise": 0xFF48D1CC, "mediumvioletred": 0xFFC71585, "midnightblue": 0xFF191970, "mintcream": 0xFFF5FFFA, "mistyrose": 0xFFFFE4E1, "moccasin": 0xFFFFE4B5, "navajowhite": 0xFFFFDEAD, "navy": 0xFF000080, "oldlace": 0xFFFDF5E6, "olive": 0xFF808000, "olivedrab": 0xFF6B8E23, "orange": 0xFFFFA500, "orangered": 0xFFFF4500, "orchid": 0xFFDA70D6, "palegoldenrod": 0xFFEEE8AA, "palegreen": 0xFF98FB98, "paleturquoise": 0xFFAFEEEE, "palevioletred": 0xFFDB7093, "papayawhip": 0xFFFFEFD5, "peachpuff": 0xFFFFDAB9, "peru": 0xFFCD853F, "pink": 0xFFFFC0CB, "plum": 0xFFDDA0DD, "powderblue": 0xFFB0E0E6, "purple": 0xFF800080, "red": 0xFFFF0000, "rosybrown": 0xFFBC8F8F, "royalblue": 0xFF4169E1, "saddlebrown": 0xFF8B4513, "salmon": 0xFFFA8072, "sandybrown": 0xFFF4A460, "seagreen": 0xFF2E8B57, "seashell": 0xFFFFF5EE, "sienna": 0xFFA0522D, "silver": 0xFFC0C0C0, "skyblue": 0xFF87CEEB, "slateblue": 0xFF6A5ACD, "slategray": 0xFF708090, "slategrey": 0xFF708090, "snow": 0xFFFFFAFA, "springgreen": 0xFF00FF7F, "steelblue": 0xFF4682B4, "tan": 0xFFD2B48C, "teal": 0xFF008080, "thistle": 0xFFD8BFD8, "tomato": 0xFFFF6347, "transparent": 0x00FFFFFF, "turquoise": 0xFF40E0D0, "violet": 0xFFEE82EE, "wheat": 0xFFF5DEB3, "white": 0xFFFFFFFF, "whitesmoke": 0xFFF5F5F5, "yellow": 0xFFFFFF00, "yellowgreen": 0xFF9ACD32, } _COLOR_DISPLAY = {name: name[0].upper() + name[1:] for name in _NAMED_COLORS} _COLOR_NAME_BY_ARGB: dict[int, str] = {} for _name, _argb in _NAMED_COLORS.items(): _COLOR_NAME_BY_ARGB.setdefault(_argb, _COLOR_DISPLAY[_name]) def color_enum(name: str) -> Any: """``Color.Red`` and friends.""" argb = _NAMED_COLORS.get(name.lower()) return Color(argb) if argb is not None else invalid(f"unknown colour {name}") def _channel(v: Any) -> int | FxError: x = to_number(v) if isinstance(x, FxError): return x if x < 0 or x > 255: return invalid("Argument out of range.") return math.trunc(x) def rgba(r: Any, g: Any, b: Any, a: Any) -> Any: err = first_error(r, g, b, a) if err is not None: return err rc, gc, bc = _channel(r), _channel(g), _channel(b) alpha = to_number(a) for v in (rc, gc, bc, alpha): if isinstance(v, FxError): return v if alpha < 0 or alpha > 1: return invalid("Argument out of range.") ac = int(math.ceil(alpha * 255 - 0.5)) if alpha * 255 - math.floor(alpha * 255) != 0.5 else int(round(alpha * 255)) return Color.from_rgba(rc, gc, bc, ac) def color_value(v: Any) -> Any: if isinstance(v, FxError): return v if v is None: return None s = str(v).strip() if s.startswith("#"): h = s[1:] if len(h) == 6: return Color(0xFF000000 | int(h, 16)) if len(h) == 8: return Color((int(h[6:8], 16) << 24) | int(h[:6], 16)) return invalid(f"'{s}' is not a colour") argb = _NAMED_COLORS.get(s.lower()) return Color(argb) if argb is not None else invalid(f"'{s}' is not a colour") def color_fade(c: Any, amount: Any) -> Any: err = first_error(c, amount) if err is not None: return err if c is None: c = Color.from_rgba(0, 0, 0, 0) # a blank colour fades as transparent black (interpreter-verified) if not isinstance(c, Color): return invalid("ColorFade needs a colour") p = to_number(amount) if isinstance(p, FxError): return p if p < -1.0 or p > 1.0: return invalid("Argument out of range.") def fade(channel: int) -> int: return int(channel + (255 - channel) * p) if p > 0 else int(channel * (1 + p)) return Color.from_rgba(fade(c.r), fade(c.g), fade(c.b), c.a) # --------------------------------------------------------------------------- # The function table the generator relies on # --------------------------------------------------------------------------- #: Power Fx function name -> runtime callable. Scoped table functions take callables for their per-record arguments. FUNCTIONS: dict[str, Callable[..., Any]] = { "If": if_, "Switch": switch, "Coalesce": coalesce, "IsBlank": is_blank_fn, "IsEmpty": is_empty, "IsError": is_error_fn, "IfError": if_error, "IsNumeric": is_numeric, "Boolean": boolean, "Value": value, "Text": text, "Blank": lambda: None, "Not": not_, "And": and_, "Or": or_, "Len": len_, "Upper": upper, "Lower": lower, "Proper": proper, "Trim": trim, "TrimEnds": trim_ends, "Left": left, "Right": right, "Mid": mid, "Find": find, "Substitute": substitute, "Replace": replace, "StartsWith": starts_with, "EndsWith": ends_with, "Char": char, "UniChar": uni_char, "Concatenate": concat, "Split": split, "EncodeUrl": encode_url, "IsMatch": is_match, "Match": match, "MatchAll": match_all, "Round": round_, "RoundUp": round_up, "RoundDown": round_down, "Int": int_, "Trunc": trunc, "Abs": abs_, "Sqrt": sqrt, "Mod": mod, "Exp": exp, "Ln": ln, "Log": log, "Power": power_fn, "Sin": sin, "Cos": cos, "Tan": tan, "Asin": asin, "Acos": acos, "Atan": atan, "Atan2": atan2, "Cot": cot, "Acot": acot, "Degrees": degrees, "Radians": radians, "Pi": pi, "Sum": sum_, "Average": average, "Max": max_, "Min": min_, "Count": count, "CountA": count_a, "CountRows": count_rows, "CountIf": count_if, "StdevP": stdev_p, "VarP": var_p, "Sequence": sequence, "Date": date, "Time": time, "DateTime": date_time, "DateAdd": date_add, "DateDiff": date_diff, "DateValue": date_value, "DateTimeValue": date_time_value, "TimeValue": time_value, "Now": now, "Today": today, "Year": year, "Month": month, "Day": day, "Hour": hour, "Minute": minute, "Second": second, "Weekday": weekday, "WeekNum": week_num, "EDate": edate, "EOMonth": eomonth, "IsToday": is_today, "Filter": filter_, "LookUp": lookup, "Sort": sort, "SortByColumns": sort_by_columns, "Search": search, "First": first, "FirstN": first_n, "Last": last, "LastN": last_n, "Index": index, "Distinct": distinct, "GroupBy": group_by, "Ungroup": ungroup, "AddColumns": add_columns, "DropColumns": drop_columns, "ShowColumns": show_columns, "RenameColumns": rename_columns, "ForAll": for_all, "Table": table, "With": with_, "Concat": concat_rows, "RGBA": rgba, "ColorValue": color_value, "ColorFade": color_fade, "GUID": guid, "Patch": patch_record, "Shuffle": shuffle, } #: Functions whose later arguments are evaluated per record of the first (the generator wraps them in lambdas). SCOPED = { "Filter": (1,), "LookUp": (1, 2), "Sort": (1,), "Search": (), "Sum": (1,), "Average": (1,), "Max": (1,), "Min": (1,), "CountIf": (1,), "StdevP": (1,), "VarP": (1,), "Distinct": (1,), "AddColumns": "pairs", "ForAll": (1,), "With": (1,), "Concat": (1,), } #: Functions whose arguments are evaluated lazily (thunks), so untaken branches never run. LAZY = {"If", "Switch", "Coalesce", "IfError", "And", "Or"} #: Enumerations the generated code spells as Option values; Color members are Color values. ENUMS = { "SortOrder", "DisplayMode", "ScreenTransition", "Font", "FontWeight", "Align", "VerticalAlign", "BorderStyle", "Layout", "TextMode", "TextFormat", "ImagePosition", "Transition", "Direction", "LayoutDirection", "LayoutMode", "LayoutOverflow", "AlignInContainer", "LayoutAlignItems", "LayoutJustifyContent", "Icon", "FormMode", "NotificationType", "DateTimeFormat", "TimeUnit", "StartOfWeek", "MatchOptions", "Match", "ListItemTemplate", "TextPosition", "VirtualKeyboardMode", "Zoom", "LabelPosition", "BarcodeType", "PenMode", "RemoveFlags", "SelectedState", "GridStyle", "Overflow", "ScreenSize", "Orientation", "ErrorKind", "JSONFormat", "TraceSeverity", "TraceOptions", "OperatingSystem", "TableStyle", "Locale", "Live", "TextRole", "LoadingSpinner", "DateTimeZone", "LayoutWrap", } def option(set_name: str, name: str) -> Any: if set_name == "Color": return color_enum(name) return Option(set_name, name) def json_ready(v: Any) -> Any: """A JSON-serialisable form of a value, in the oracle's spelling, for reports and reconciliation.""" if v is None or isinstance(v, (bool, str)): return v if isinstance(v, (int, float)): return float(v) if isinstance(v, Unsupported): return {"$unsupported": v.reason} if isinstance(v, FxError): return {"$error": v.kind} if isinstance(v, _dt.datetime): return {"$datetime": v.strftime("%Y-%m-%dT%H:%M:%S.") + f"{v.microsecond // 1000:03d}"} if isinstance(v, _dt.date): return {"$date": v.strftime("%Y-%m-%d")} if isinstance(v, _dt.timedelta): total = round(v.total_seconds(), 3) # to the millisecond first, so .9996 s carries into the seconds magnitude = abs(total) # a Time is wrapped into a day, so this is defensive; divmod would floor a negative h, rem = divmod(int(magnitude), 3600) m, s = divmod(rem, 60) sign = "-" if total < 0 else "" ms = int(round((magnitude - int(magnitude)) * 1000)) return {"$time": f"{sign}{h:02d}:{m:02d}:{s:02d}.{ms:03d}"} if isinstance(v, Option): return {"$option": v.name, "set": v.set_name} if isinstance(v, Color): return {"$color": f"#{v.argb:08X}"} if isinstance(v, dict): return {k: json_ready(x) for k, x in v.items()} if isinstance(v, list): return [json_ready(x) for x in v] return str(v) def from_json(v: Any, schema: Any = None) -> Any: """The inverse of :func:`json_ready` for inputs: tagged dates, records and tables become runtime values.""" if v is None: return None if isinstance(v, bool): return v if isinstance(v, (int, float)): return float(v) if isinstance(v, str): if schema == "date": return _dt.date.fromisoformat(v) if schema == "datetime": return _dt.datetime.fromisoformat(v) if schema == "time": return time_value(v) return v if isinstance(v, dict): if "$option" in v and set(v) <= {"$option", "set"}: set_name = v.get("set", "") return color_enum(v["$option"]) if set_name == "Color" else Option(set_name, v["$option"]) if len(v) == 1 and next(iter(v)).startswith("$"): tag, inner = next(iter(v.items())) if tag == "$date": return _dt.date.fromisoformat(inner) if tag == "$datetime": return _dt.datetime.fromisoformat(inner.replace("Z", "")) if tag == "$time": return time_value(inner) if tag == "$color": return color_value(inner) if tag == "$option": return Option("", inner) if tag == "$error": return FxError(inner) sub = schema if isinstance(schema, dict) else {} return {k: from_json(x, sub.get(k)) for k, x in v.items()} if isinstance(v, list): row_schema = schema[0] if isinstance(schema, list) and schema else None return [from_json(x, row_schema) if isinstance(x, dict) else {"Value": from_json(x, row_schema.get("Value") if isinstance(row_schema, dict) else None)} for x in v] return v __all__ = [ "BLANK", "CLOCK", "Clock", "Color", "ENUMS", "FUNCTIONS", "FxError", "LAZY", "Option", "SCOPED", "UNSUPPORTED", "Unsupported", "add", "and_", "concat", "div", "eq", "field", "from_json", "ge", "gt", "in_", "is_blank", "is_error", "json_ready", "le", "lt", "mul", "ne", "neg", "not_", "option", "or_", "pct", "power", "record", "record_of", "resolve", "scoped", "sub", "table", "to_bool", "to_number", "to_text", ]