Coverage for src/scixplorer/expr.py: 99%
237 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-18 23:06 +0000
1"""Immutable expression trees describing search predicates.
3Expressions are built by operator overloading on field handles (see
4:mod:`scixplorer.fields`) and interpreted by :mod:`scixplorer.solr` (compile to a Solr query)
5and :mod:`scixplorer.evaluate` (evaluate in Python). Every node is a frozen, hashable
6dataclass that compares structurally.
7"""
9from __future__ import annotations
11from collections.abc import Callable, Iterator
12from dataclasses import dataclass
13from enum import Enum
14from typing import TYPE_CHECKING, Any, Literal
16from .exceptions import QueryError
18if TYPE_CHECKING:
19 from .fields import Field
20 from .model import Collection, Relation
22__all__ = [
23 "EVERYTHING",
24 "NOTHING",
25 "And",
26 "Constant",
27 "Expr",
28 "Func",
29 "In",
30 "InLibrary",
31 "Like",
32 "Match",
33 "Not",
34 "Or",
35 "Order",
36 "Quantified",
37 "Range",
38 "Raw",
39 "Related",
40 "SolrLiteral",
41 "Wildcard",
42 "days_ago",
43 "escape_pattern",
44 "format_pattern",
45 "now",
46 "parse_pattern",
47 "simplify",
48 "transform",
49 "walk",
50]
52BOOL_ERROR = (
53 "{name} cannot be used as a truth value. Combine expressions with & (and), "
54 "| (or) and ~ (not) instead of the keywords and/or/not, wrap each comparison "
55 "in parentheses, e.g. (Document.year == 2020) & (Document.author == 'Kewley, L'), "
56 "and use .in_(values) instead of the `in` operator."
57)
60class Expr:
61 """Base class of all expression nodes.
63 ``&``, ``|`` and ``~`` build :class:`And`, :class:`Or` and :class:`Not`.
64 Expressions deliberately have no truth value, so that ``and``/``or``/``not``
65 and chained comparisons fail loudly instead of silently dropping a clause.
66 """
68 __slots__ = ()
70 def __and__(self, other: object) -> Expr:
71 if not isinstance(other, Expr):
72 return NotImplemented
73 return And(_flatten(And, (self, other)))
75 def __or__(self, other: object) -> Expr:
76 if not isinstance(other, Expr):
77 return NotImplemented
78 return Or(_flatten(Or, (self, other)))
80 def __invert__(self) -> Expr:
81 if isinstance(self, Not):
82 return self.operand
83 if isinstance(self, Constant):
84 return NOTHING if self.value else EVERYTHING
85 return Not(self)
87 def __bool__(self) -> bool:
88 raise TypeError(BOOL_ERROR.format(name="A query expression"))
91def _flatten(kind: type[And] | type[Or], operands: tuple[Expr, ...]) -> tuple[Expr, ...]:
92 """Splice the operands of any ``kind`` node into a flat tuple."""
93 flat: list[Expr] = []
94 for operand in operands:
95 if isinstance(operand, kind):
96 flat.extend(operand.operands)
97 else:
98 flat.append(operand)
99 return tuple(flat)
102def _expr_tuple(owner: str, items: Any) -> tuple[Expr, ...]:
103 operands: tuple[Any, ...] = tuple(items)
104 for item in operands:
105 if not isinstance(item, Expr):
106 raise TypeError(f"{owner} operands must be expressions, not {item!r}")
107 return operands
110@dataclass(frozen=True, slots=True)
111class And(Expr):
112 """True when every operand is true. An empty ``And`` is always true."""
114 operands: tuple[Expr, ...]
116 def __post_init__(self) -> None:
117 object.__setattr__(self, "operands", _expr_tuple("And", self.operands))
120@dataclass(frozen=True, slots=True)
121class Or(Expr):
122 """True when any operand is true. An empty ``Or`` is always false."""
124 operands: tuple[Expr, ...]
126 def __post_init__(self) -> None:
127 object.__setattr__(self, "operands", _expr_tuple("Or", self.operands))
130@dataclass(frozen=True, slots=True)
131class Not(Expr):
132 """Negation of ``operand``."""
134 operand: Expr
136 def __post_init__(self) -> None:
137 if not isinstance(self.operand, Expr):
138 raise TypeError(f"Not operand must be an expression, not {self.operand!r}")
141@dataclass(frozen=True, slots=True)
142class Match(Expr):
143 """``field`` matches ``value``; ``exact`` disables ADS's expansion (synonyms, name variants)."""
145 field: Field[Any, Any]
146 value: Any
147 exact: bool = False
150@dataclass(frozen=True, slots=True)
151class Like(Expr):
152 """Wildcard match: ``*`` is any run of characters, ``?`` is one character.
154 A backslash makes the next character literal (``\\*``, ``\\?``, ``\\\\``).
155 """
157 field: Field[Any, Any]
158 pattern: str
160 def __post_init__(self) -> None:
161 if not isinstance(self.pattern, str): 161 ↛ 162line 161 didn't jump to line 162 because the condition on line 161 was never true
162 raise TypeError(f"Like pattern must be a str, not {self.pattern!r}")
163 if not self.pattern:
164 raise QueryError("Like pattern must not be empty")
165 parse_pattern(self.pattern)
168@dataclass(frozen=True, slots=True)
169class Range(Expr):
170 """``lo <= field <= hi`` (bounds exclusive where requested); ``None`` is unbounded."""
172 field: Field[Any, Any]
173 lo: Any
174 hi: Any
175 include_lo: bool = True
176 include_hi: bool = True
178 def __post_init__(self) -> None:
179 if self.lo is None and self.hi is None:
180 raise QueryError("Range needs at least one bound")
183@dataclass(frozen=True, slots=True)
184class In(Expr):
185 """``field`` matches any of ``values``; ``exact`` as for :class:`Match`."""
187 field: Field[Any, Any]
188 values: tuple[Any, ...]
189 exact: bool = False
191 def __post_init__(self) -> None:
192 if isinstance(self.values, (str, bytes)):
193 raise TypeError("In values must be a collection of values, not a single string")
194 object.__setattr__(self, "values", tuple(self.values))
197@dataclass(frozen=True, slots=True)
198class Func(Expr):
199 """A Solr function or second-order operator, e.g. ``citations(...)`` or ``pos(...)``.
201 Arguments are expressions, ints, strs (emitted verbatim) or :class:`Order`.
202 """
204 name: str
205 args: tuple[Any, ...]
207 def __post_init__(self) -> None:
208 args = tuple(self.args)
209 for arg in args:
210 if isinstance(arg, bool) or not isinstance(arg, (Expr, int, str, Order)):
211 raise TypeError(f"{self.name}() argument must be an Expr, int, str or Order, not {arg!r}")
212 object.__setattr__(self, "args", args)
215@dataclass(frozen=True, slots=True)
216class Related(Expr):
217 """Rows whose related object(s) through ``relation`` satisfy ``predicate``.
219 ``predicate`` is an expression over the fields of the related model.
220 """
222 relation: Relation[Any]
223 predicate: Expr
225 def __post_init__(self) -> None:
226 if not isinstance(self.predicate, Expr):
227 raise TypeError(f"Related predicate must be an expression, not {self.predicate!r}")
230@dataclass(frozen=True, slots=True)
231class Quantified(Expr):
232 """Rows for which ``any`` (or ``all``) of their records in ``collection`` satisfy ``predicate``.
234 A record is one entry of a set of index-aligned arrays on the row, such as
235 one author of a document (see :class:`~scixplorer.model.Collection`); ``predicate``
236 is an expression over the fields of the record model, so everything in it
237 is about one record. ``positions`` (1-indexed, inclusive, as for ``pos()``)
238 restricts the records considered. ``all`` requires at least one record.
239 """
241 collection: Collection[Any, Any]
242 predicate: Expr
243 quantifier: Literal["any", "all"] = "any"
244 positions: tuple[int, int] | None = None
246 def __post_init__(self) -> None:
247 if not isinstance(self.predicate, Expr):
248 raise TypeError(f"Quantified predicate must be an expression, not {self.predicate!r}")
249 if self.quantifier not in ("any", "all"):
250 raise ValueError(f"Quantified quantifier must be 'any' or 'all', not {self.quantifier!r}")
251 if self.positions is not None:
252 start, end = self.positions
253 if not (isinstance(start, int) and isinstance(end, int) and 1 <= start <= end):
254 raise ValueError(f"Quantified positions must be 1 <= start <= end, not {self.positions!r}")
257@dataclass(frozen=True, slots=True)
258class InLibrary(Expr):
259 """The document belongs to the ADS library with id ``library_id``."""
261 library_id: str
264@dataclass(frozen=True, slots=True)
265class Raw(Expr):
266 """Verbatim Solr query syntax, for anything the expression language lacks."""
268 query: str
271@dataclass(frozen=True, slots=True)
272class Constant(Expr):
273 """Always true (:data:`EVERYTHING`) or always false (:data:`NOTHING`)."""
275 value: bool
278EVERYTHING = Constant(True)
279NOTHING = Constant(False)
282@dataclass(frozen=True, slots=True)
283class Order:
284 """A sort key: ``field`` ascending, or descending if ``descending``."""
286 field: Field[Any, Any]
287 descending: bool = False
290@dataclass(frozen=True, slots=True)
291class SolrLiteral:
292 """A value emitted verbatim and unquoted, such as ``NOW-7DAYS``."""
294 text: str
297def now() -> SolrLiteral:
298 """The current time, as evaluated by Solr."""
299 return SolrLiteral("NOW")
302def days_ago(n: int) -> SolrLiteral:
303 """The time ``n`` days before now, as evaluated by Solr."""
304 if isinstance(n, bool) or not isinstance(n, int):
305 raise TypeError(f"days_ago() needs an int, not {n!r}")
306 if n < 0:
307 raise ValueError(f"days_ago() needs a non-negative number of days, not {n}")
308 return now() if n == 0 else SolrLiteral(f"NOW-{n}DAYS")
311class Wildcard(Enum):
312 """Wildcard tokens of a :class:`Like` pattern."""
314 ANY = "*"
315 ONE = "?"
318def parse_pattern(pattern: str, *, percent: bool = False) -> tuple[str | Wildcard, ...]:
319 """Split a wildcard pattern into literal strings and :class:`Wildcard` tokens.
321 A backslash makes the following character literal; adjacent literal
322 characters are merged into one string. With ``percent=True`` an unescaped
323 ``%`` is read as ``*``. This is the only parser of pattern syntax: the Solr
324 compiler and the Python evaluator both use it.
325 """
326 tokens: list[str | Wildcard] = []
327 literal: list[str] = []
328 chars = iter(pattern)
329 for char in chars:
330 if char == "\\":
331 escaped = next(chars, None)
332 if escaped is None:
333 raise QueryError(f"Pattern {pattern!r} ends with an unpaired backslash")
334 literal.append(escaped)
335 continue
336 if char == "%" and percent:
337 char = "*"
338 if char in "*?":
339 if literal:
340 tokens.append("".join(literal))
341 literal.clear()
342 tokens.append(Wildcard(char))
343 else:
344 literal.append(char)
345 if literal:
346 tokens.append("".join(literal))
347 return tuple(tokens)
350def format_pattern(tokens: tuple[str | Wildcard, ...]) -> str:
351 """Render tokens from :func:`parse_pattern` back to canonical pattern syntax."""
352 return "".join(
353 token.value if isinstance(token, Wildcard) else escape_pattern(token) for token in tokens
354 )
357def escape_pattern(text: str) -> str:
358 """Escape ``text`` so that it matches itself literally inside a pattern."""
359 return text.replace("\\", "\\\\").replace("*", "\\*").replace("?", "\\?")
362def walk(expr: Expr) -> Iterator[Expr]:
363 """Yield ``expr`` and every nested expression, in pre-order."""
364 yield expr
365 for child in _children(expr):
366 yield from walk(child)
369def _children(expr: Expr) -> tuple[Expr, ...]:
370 if isinstance(expr, (And, Or)):
371 return expr.operands
372 if isinstance(expr, Not):
373 return (expr.operand,)
374 if isinstance(expr, Func):
375 return tuple(arg for arg in expr.args if isinstance(arg, Expr))
376 if isinstance(expr, (Related, Quantified)):
377 return (expr.predicate,)
378 return ()
381def transform(expr: Expr, fn: Callable[[Expr], Expr]) -> Expr:
382 """Rebuild ``expr`` bottom-up: transform the children, then apply ``fn`` to the node."""
383 if isinstance(expr, (And, Or)):
384 expr = type(expr)(tuple(transform(operand, fn) for operand in expr.operands))
385 elif isinstance(expr, Not):
386 expr = Not(transform(expr.operand, fn))
387 elif isinstance(expr, Func):
388 args = tuple(transform(arg, fn) if isinstance(arg, Expr) else arg for arg in expr.args)
389 expr = Func(expr.name, args)
390 elif isinstance(expr, Related):
391 expr = Related(expr.relation, transform(expr.predicate, fn))
392 elif isinstance(expr, Quantified):
393 expr = Quantified(expr.collection, transform(expr.predicate, fn), expr.quantifier, expr.positions)
394 return fn(expr)
397def simplify(expr: Expr) -> Expr:
398 """Return an equivalent, simpler expression.
400 Flattens nested ``And``/``Or``, drops duplicate operands, folds constants,
401 rewrites ``In`` with zero or one values, unwraps single-operand groups and
402 removes double negation, throughout the tree.
404 A :class:`Quantified` node's predicate is simplified like any subtree. If it
405 becomes a constant: no record satisfies ``NOTHING``, so ``any`` and ``all``
406 of it are ``NOTHING``; every record satisfies ``EVERYTHING``, so both mean
407 "there is at least one record (at those positions)", which is kept as
408 ``any(EVERYTHING)`` (not folded to ``EVERYTHING``: a row may have no records).
409 """
410 return transform(expr, _simplify_node)
413def _simplify_node(expr: Expr) -> Expr:
414 if isinstance(expr, (And, Or)):
415 return _simplify_group(expr)
416 if isinstance(expr, Not):
417 if isinstance(expr.operand, (Not, Constant)):
418 return ~expr.operand
419 return expr
420 if isinstance(expr, In):
421 if not expr.values:
422 return NOTHING
423 if len(expr.values) == 1:
424 return Match(expr.field, expr.values[0], expr.exact)
425 if isinstance(expr, Quantified):
426 if expr.predicate == NOTHING:
427 return NOTHING
428 if expr.predicate == EVERYTHING and expr.quantifier == "all":
429 return Quantified(expr.collection, EVERYTHING, "any", expr.positions)
430 return expr
433def _simplify_group(expr: And | Or) -> Expr:
434 kind = type(expr)
435 absorbing, identity = (NOTHING, EVERYTHING) if kind is And else (EVERYTHING, NOTHING)
436 operands: dict[Expr, None] = {}
437 for operand in _flatten(kind, expr.operands):
438 if operand == absorbing:
439 return absorbing
440 if operand != identity:
441 operands.setdefault(operand)
442 if not operands:
443 return identity
444 if len(operands) == 1:
445 return next(iter(operands))
446 return kind(tuple(operands))