|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import re |
| 4 | +from collections.abc import Callable |
| 5 | +from operator import attrgetter |
| 6 | +from typing import TYPE_CHECKING, Any, Generic, Literal, Protocol, final, overload |
| 7 | + |
| 8 | +from narwhals._plan._guards import is_function_expr |
| 9 | +from narwhals._plan.compliant.typing import FrameT_contra, R_co |
| 10 | +from narwhals._typing_compat import TypeVar |
| 11 | + |
| 12 | +if TYPE_CHECKING: |
| 13 | + from typing_extensions import Never, TypeAlias |
| 14 | + |
| 15 | + from narwhals._plan.compliant.typing import Ctx |
| 16 | + from narwhals._plan.expressions import ExprIR, FunctionExpr |
| 17 | + from narwhals._plan.typing import ExprIRT, FunctionT |
| 18 | + |
| 19 | +__all__ = ["Dispatcher", "get_dispatch_name"] |
| 20 | + |
| 21 | + |
| 22 | +Node = TypeVar("Node", bound="ExprIR | FunctionExpr[Any]") |
| 23 | +Node_contra = TypeVar( |
| 24 | + "Node_contra", bound="ExprIR | FunctionExpr[Any]", contravariant=True |
| 25 | +) |
| 26 | +Raiser: TypeAlias = Callable[..., "Never"] |
| 27 | + |
| 28 | + |
| 29 | +class Binder(Protocol[Node_contra]): |
| 30 | + def __call__( |
| 31 | + self, ctx: Ctx[FrameT_contra, R_co], / |
| 32 | + ) -> BoundMethod[Node_contra, FrameT_contra, R_co]: ... |
| 33 | + |
| 34 | + |
| 35 | +class BoundMethod(Protocol[Node_contra, FrameT_contra, R_co]): |
| 36 | + def __call__(self, node: Node_contra, frame: FrameT_contra, name: str, /) -> R_co: ... |
| 37 | + |
| 38 | + |
| 39 | +@final |
| 40 | +class Dispatcher(Generic[Node]): |
| 41 | + """Translate class definitions into error-wrapped method calls. |
| 42 | +
|
| 43 | + Operates over `ExprIR` and `Function` nodes. |
| 44 | +
|
| 45 | + By default, we dispatch to the compliant-level by calling a method that is the |
| 46 | + **snake_case**-equivalent of the class name: |
| 47 | +
|
| 48 | + class BinaryExpr(ExprIR): ... |
| 49 | +
|
| 50 | + class CompliantExpr(Protocol): |
| 51 | + def binary_expr(self, *args: Any): ... |
| 52 | + """ |
| 53 | + |
| 54 | + __slots__ = ("_bind", "_name") |
| 55 | + _bind: Binder[Node] |
| 56 | + _name: str |
| 57 | + |
| 58 | + @property |
| 59 | + def name(self) -> str: |
| 60 | + return self._name |
| 61 | + |
| 62 | + def __repr__(self) -> str: |
| 63 | + return f"{type(self).__name__}<{self.name}>" |
| 64 | + |
| 65 | + def bind( |
| 66 | + self, ctx: Ctx[FrameT_contra, R_co], / |
| 67 | + ) -> BoundMethod[Node, FrameT_contra, R_co]: |
| 68 | + """Retrieve the implementation of this expression from `ctx`. |
| 69 | +
|
| 70 | + Binds an instance method, most commonly via: |
| 71 | +
|
| 72 | + expr: CompliantExpr |
| 73 | + method = getattr(expr, "method_name") |
| 74 | + """ |
| 75 | + try: |
| 76 | + return self._bind(ctx) |
| 77 | + except AttributeError: |
| 78 | + raise self._not_implemented_error(ctx, "compliant") from None |
| 79 | + |
| 80 | + def __call__( |
| 81 | + self, |
| 82 | + node: Node, |
| 83 | + ctx: Ctx[FrameT_contra, R_co], |
| 84 | + frame: FrameT_contra, |
| 85 | + name: str, |
| 86 | + /, |
| 87 | + ) -> R_co: |
| 88 | + """Evaluate this expression in `frame`, using implementation(s) provided by `ctx`.""" |
| 89 | + method = self.bind(ctx) |
| 90 | + if result := method(node, frame, name): |
| 91 | + return result |
| 92 | + raise self._not_implemented_error(ctx, "context") |
| 93 | + |
| 94 | + @staticmethod |
| 95 | + def from_expr_ir(tp: type[ExprIRT], /) -> Dispatcher[ExprIRT]: |
| 96 | + if not tp.__expr_ir_config__.allow_dispatch: |
| 97 | + return Dispatcher._no_dispatch(tp) |
| 98 | + return Dispatcher._from_type(tp) |
| 99 | + |
| 100 | + @staticmethod |
| 101 | + def from_function(tp: type[FunctionT], /) -> Dispatcher[FunctionExpr[FunctionT]]: |
| 102 | + return Dispatcher._from_type(tp) |
| 103 | + |
| 104 | + @staticmethod |
| 105 | + @overload |
| 106 | + def _from_type(tp: type[ExprIRT], /) -> Dispatcher[ExprIRT]: ... |
| 107 | + @staticmethod |
| 108 | + @overload |
| 109 | + def _from_type(tp: type[FunctionT], /) -> Dispatcher[FunctionExpr[FunctionT]]: ... |
| 110 | + @staticmethod |
| 111 | + def _from_type(tp: type[ExprIRT | FunctionT], /) -> Dispatcher[Any]: |
| 112 | + obj = Dispatcher.__new__(Dispatcher) |
| 113 | + obj._name = _method_name(tp) |
| 114 | + getter = attrgetter(obj._name) |
| 115 | + is_namespaced = tp.__expr_ir_config__.is_namespaced |
| 116 | + obj._bind = _via_namespace(getter) if is_namespaced else getter |
| 117 | + return obj |
| 118 | + |
| 119 | + @staticmethod |
| 120 | + def _no_dispatch(tp: type[ExprIRT], /) -> Dispatcher[ExprIRT]: |
| 121 | + obj = Dispatcher.__new__(Dispatcher) |
| 122 | + obj._name = tp.__name__ |
| 123 | + obj._bind = obj._make_no_dispatch_error() |
| 124 | + return obj |
| 125 | + |
| 126 | + def _make_no_dispatch_error(self) -> Callable[[Any], Raiser]: |
| 127 | + def _no_dispatch_error(node: Node, *_: Any) -> Never: |
| 128 | + msg = ( |
| 129 | + f"{self.name!r} should not appear at the compliant-level.\n\n" |
| 130 | + f"Make sure to expand all expressions first, got:\n{node!r}" |
| 131 | + ) |
| 132 | + raise TypeError(msg) |
| 133 | + |
| 134 | + def getter(_: Any, /) -> Raiser: |
| 135 | + return _no_dispatch_error |
| 136 | + |
| 137 | + return getter |
| 138 | + |
| 139 | + def _not_implemented_error( |
| 140 | + self, ctx: object, /, missing: Literal["compliant", "context"] |
| 141 | + ) -> NotImplementedError: |
| 142 | + if missing == "context": |
| 143 | + msg = f"`{self.name}` is not yet implemented for {type(ctx).__name__!r}" |
| 144 | + else: |
| 145 | + msg = ( |
| 146 | + f"`{self.name}` has not been implemented at the compliant-level.\n" |
| 147 | + f"Hint: Try adding `CompliantExpr.{self.name}()` or `CompliantNamespace.{self.name}()`" |
| 148 | + ) |
| 149 | + return NotImplementedError(msg) |
| 150 | + |
| 151 | + |
| 152 | +def _via_namespace(getter: Callable[[Any], Any], /) -> Callable[[Any], Any]: |
| 153 | + def _(ctx: Any, /) -> Any: |
| 154 | + return getter(ctx.__narwhals_namespace__()) |
| 155 | + |
| 156 | + return _ |
| 157 | + |
| 158 | + |
| 159 | +def _pascal_to_snake_case(s: str) -> str: |
| 160 | + """Convert a PascalCase string to snake_case. |
| 161 | +
|
| 162 | + Adapted from https://github.com/pydantic/pydantic/blob/f7a9b73517afecf25bf898e3b5f591dffe669778/pydantic/alias_generators.py#L43-L62 |
| 163 | + """ |
| 164 | + # Handle the sequence of uppercase letters followed by a lowercase letter |
| 165 | + snake = _PATTERN_UPPER_LOWER.sub(_re_repl_snake, s) |
| 166 | + # Insert an underscore between a lowercase letter and an uppercase letter |
| 167 | + return _PATTERN_LOWER_UPPER.sub(_re_repl_snake, snake).lower() |
| 168 | + |
| 169 | + |
| 170 | +_PATTERN_UPPER_LOWER = re.compile(r"([A-Z]+)([A-Z][a-z])") |
| 171 | +_PATTERN_LOWER_UPPER = re.compile(r"([a-z])([A-Z])") |
| 172 | + |
| 173 | + |
| 174 | +def _re_repl_snake(match: re.Match[str], /) -> str: |
| 175 | + return f"{match.group(1)}_{match.group(2)}" |
| 176 | + |
| 177 | + |
| 178 | +def _method_name(tp: type[ExprIRT | FunctionT]) -> str: |
| 179 | + config = tp.__expr_ir_config__ |
| 180 | + name = config.override_name or _pascal_to_snake_case(tp.__name__) |
| 181 | + return f"{ns}.{name}" if (ns := getattr(config, "accessor_name", "")) else name |
| 182 | + |
| 183 | + |
| 184 | +def get_dispatch_name(expr: ExprIR, /) -> str: |
| 185 | + """Return the synthesized method name for `expr`.""" |
| 186 | + return ( |
| 187 | + repr(expr.function) if is_function_expr(expr) else expr.__expr_ir_dispatch__.name |
| 188 | + ) |
0 commit comments