summaryrefslogtreecommitdiffstats
path: root/src/prompt_toolkit/filters/base.py
blob: fd57cca6e901eea36799cd91ba171764e56895b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
from abc import ABCMeta, abstractmethod
from typing import Callable, Dict, Iterable, List, Tuple, Union

__all__ = ["Filter", "Never", "Always", "Condition", "FilterOrBool"]


class Filter(metaclass=ABCMeta):
    """
    Base class for any filter to activate/deactivate a feature, depending on a
    condition.

    The return value of ``__call__`` will tell if the feature should be active.
    """

    @abstractmethod
    def __call__(self) -> bool:
        """
        The actual call to evaluate the filter.
        """
        return True

    def __and__(self, other: "Filter") -> "Filter":
        """
        Chaining of filters using the & operator.
        """
        return _and_cache[self, other]

    def __or__(self, other: "Filter") -> "Filter":
        """
        Chaining of filters using the | operator.
        """
        return _or_cache[self, other]

    def __invert__(self) -> "Filter":
        """
        Inverting of filters using the ~ operator.
        """
        return _invert_cache[self]

    def __bool__(self) -> None:
        """
        By purpose, we don't allow bool(...) operations directly on a filter,
        because the meaning is ambiguous.

        Executing a filter has to be done always by calling it. Providing
        defaults for `None` values should be done through an `is None` check
        instead of for instance ``filter1 or Always()``.
        """
        raise ValueError(
            "The truth value of a Filter is ambiguous. "
            "Instead, call it as a function."
        )


class _AndCache(Dict[Tuple[Filter, Filter], "_AndList"]):
    """
    Cache for And operation between filters.
    (Filter classes are stateless, so we can reuse them.)

    Note: This could be a memory leak if we keep creating filters at runtime.
          If that is True, the filters should be weakreffed (not the tuple of
          filters), and tuples should be removed when one of these filters is
          removed. In practise however, there is a finite amount of filters.
    """

    def __missing__(self, filters: Tuple[Filter, Filter]) -> Filter:
        a, b = filters
        assert isinstance(b, Filter), "Expecting filter, got %r" % b

        if isinstance(b, Always) or isinstance(a, Never):
            return a
        elif isinstance(b, Never) or isinstance(a, Always):
            return b

        result = _AndList(filters)
        self[filters] = result
        return result


class _OrCache(Dict[Tuple[Filter, Filter], "_OrList"]):
    """Cache for Or operation between filters."""

    def __missing__(self, filters: Tuple[Filter, Filter]) -> Filter:
        a, b = filters
        assert isinstance(b, Filter), "Expecting filter, got %r" % b

        if isinstance(b, Always) or isinstance(a, Never):
            return b
        elif isinstance(b, Never) or isinstance(a, Always):
            return a

        result = _OrList(filters)
        self[filters] = result
        return result


class _InvertCache(Dict[Filter, "_Invert"]):
    """Cache for inversion operator."""

    def __missing__(self, filter: Filter) -> Filter:
        result = _Invert(filter)
        self[filter] = result
        return result


_and_cache = _AndCache()
_or_cache = _OrCache()
_invert_cache = _InvertCache()


class _AndList(Filter):
    """
    Result of &-operation between several filters.
    """

    def __init__(self, filters: Iterable[Filter]) -> None:
        self.filters: List[Filter] = []

        for f in filters:
            if isinstance(f, _AndList):  # Turn nested _AndLists into one.
                self.filters.extend(f.filters)
            else:
                self.filters.append(f)

    def __call__(self) -> bool:
        return all(f() for f in self.filters)

    def __repr__(self) -> str:
        return "&".join(repr(f) for f in self.filters)


class _OrList(Filter):
    """
    Result of |-operation between several filters.
    """

    def __init__(self, filters: Iterable[Filter]) -> None:
        self.filters: List[Filter] = []

        for f in filters:
            if isinstance(f, _OrList):  # Turn nested _OrLists into one.
                self.filters.extend(f.filters)
            else:
                self.filters.append(f)

    def __call__(self) -> bool:
        return any(f() for f in self.filters)

    def __repr__(self) -> str:
        return "|".join(repr(f) for f in self.filters)


class _Invert(Filter):
    """
    Negation of another filter.
    """

    def __init__(self, filter: Filter) -> None:
        self.filter = filter

    def __call__(self) -> bool:
        return not self.filter()

    def __repr__(self) -> str:
        return "~%r" % self.filter


class Always(Filter):
    """
    Always enable feature.
    """

    def __call__(self) -> bool:
        return True

    def __invert__(self) -> "Never":
        return Never()


class Never(Filter):
    """
    Never enable feature.
    """

    def __call__(self) -> bool:
        return False

    def __invert__(self) -> Always:
        return Always()


class Condition(Filter):
    """
    Turn any callable into a Filter. The callable is supposed to not take any
    arguments.

    This can be used as a decorator::

        @Condition
        def feature_is_active():  # `feature_is_active` becomes a Filter.
            return True

    :param func: Callable which takes no inputs and returns a boolean.
    """

    def __init__(self, func: Callable[[], bool]) -> None:
        self.func = func

    def __call__(self) -> bool:
        return self.func()

    def __repr__(self) -> str:
        return "Condition(%r)" % self.func


# Often used as type annotation.
FilterOrBool = Union[Filter, bool]