aboutsummaryrefslogtreecommitdiffhomepage
path: root/pyecsca/ec/context.py
blob: 175da9dc2c0e3623ddb275f040a3e88c4f109c5f (plain) (blame)
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
"""
Provides classes for tracing the execution of operations.

The operations include key generation, scalar multiplication, formula execution and individual operation evaluation.
These operations are traced in `Context` classes using `Actions`. Different contexts trace actions differently.

A :py:class:`DefaultContext` traces actions into a tree as they are executed (a scalar
multiplication actions has as its children an ordered list of the individual formula executions it has done).

A :py:class:`PathContext` works like a :py:class:`DefaultContext` that only traces an action on a particular path
in the tree.
"""
from abc import abstractmethod, ABC
from collections import OrderedDict
from copy import deepcopy
from typing import List, Optional, ContextManager, Any, Tuple, Sequence, Callable

from public import public


@public
class Action:
    """
    An Action.

    Can be entered:
    >>> with Action() as action:
    ...     print(action.inside)
    True

    """

    inside: bool

    def __init__(self):
        self.inside = False

    def __enter__(self):
        if current is not None:
            current.enter_action(self)
        self.inside = True
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if current is not None:
            current.exit_action(self)
        self.inside = False


@public
class ResultAction(Action):
    """
    An action that has a result.

    >>> with ResultAction() as action:
    ...     r = action.exit("result")
    >>> action.result == r
    True
    """

    _result: Any = None
    _has_result: bool = False

    @property
    def result(self) -> Any:
        if not self._has_result:
            raise AttributeError("No result set")
        return self._result

    def exit(self, result: Any):
        if not self.inside:
            raise RuntimeError("Result set outside of action scope")
        if self._has_result:
            return
        self._has_result = True
        self._result = result
        return result

    def __exit__(self, exc_type, exc_val, exc_tb):
        if (
                not self._has_result
                and exc_type is None
                and exc_val is None
                and exc_tb is None
        ):
            raise RuntimeError("Result unset on action exit")
        super().__exit__(exc_type, exc_val, exc_tb)


@public
class Tree(OrderedDict):
    """
    A recursively-implemented tree.

    >>> tree = Tree()
    >>> tree["a"] = Tree()
    >>> tree["a"]["1"] = Tree()
    >>> tree["a"]["2"] = Tree()
    >>> tree # doctest: +NORMALIZE_WHITESPACE
    a
        1
        2
    <BLANKLINE>
    """

    def get_by_key(self, path: List) -> Any:
        """
        Get the value in the tree at a position given by the path.

        >>> one = Tree()
        >>> tree = Tree()
        >>> tree["a"] = Tree()
        >>> tree["a"]["1"] = Tree()
        >>> tree["a"]["2"] = one
        >>> tree.get_by_key(["a", "2"]) == one
        True

        :param path: The path to get.
        :return: The value in the tree.
        """
        if len(path) == 0:
            return self
        value = self[path[0]]
        if len(path) == 1:
            return value
        elif isinstance(value, Tree):
            return value.get_by_key(path[1:])
        else:
            raise ValueError

    def get_by_index(self, path: List[int]) -> Tuple[Any, Any]:
        """
        Get the key and value in the tree at a position given by the path of indices.

        The nodes inside a level of a tree are ordered by insertion order.

        >>> one = Tree()
        >>> tree = Tree()
        >>> tree["a"] = Tree()
        >>> tree["a"]["1"] = Tree()
        >>> tree["a"]["2"] = one
        >>> key, value = tree.get_by_index([0, 1])
        >>> key
        '2'
        >>> value == one
        True

        :param path: The path to get.
        :return: The key and value.
        """
        if len(path) == 0:
            raise ValueError
        key = list(self.keys())[path[0]]
        value = self[key]
        if len(path) == 1:
            return key, value
        elif isinstance(value, Tree):
            return value.get_by_index(path[1:])
        else:
            raise ValueError

    def repr(self, depth: int = 0) -> str:
        """
        Construct a textual representation of the tree. Useful for visualization and debugging.

        :param depth:
        :return: The resulting textual representation.
        """
        result = ""
        for key, value in self.items():
            if isinstance(value, Tree):
                result += "\t" * depth + str(key) + "\n"
                result += value.repr(depth + 1)
            else:
                result += "\t" * depth + str(key) + ":" + str(value) + "\n"
        return result

    def walk(self, callback: Callable[[Any], None]) -> None:
        """
        Walk the tree, depth-first, with the callback.

        >>> tree = Tree()
        >>> tree["a"] = Tree()
        >>> tree["a"]["1"] = Tree()
        >>> tree["a"]["2"] = Tree()
        >>> tree.walk(lambda key: print(key))
        a
        1
        2

        :param callback: The callback to call for all values in the tree.
        """
        for key, val in self.items():
            callback(key)
            if isinstance(val, Tree):
                val.walk(callback)

    def __repr__(self):
        return self.repr()


@public
class Context(ABC):
    """
    Context is an object that traces actions which happen.

    There is always one context active, see functions :py:func:`getcontext`,
    :py:func:`setcontext` and :py:func:`resetcontext`. Also, the :py:func:`local`
    contextmanager.
    """

    @abstractmethod
    def enter_action(self, action: Action) -> None:
        """
        Enter into an action (i.e. start executing it).

        :param action: The action.
        """
        raise NotImplementedError

    @abstractmethod
    def exit_action(self, action: Action) -> None:
        """
        Exit from an action (i.e. stop executing it).

        :param action: The action.
        """
        raise NotImplementedError

    def __str__(self):
        return self.__class__.__name__


@public
class DefaultContext(Context):
    """
    Context that traces executions of actions in a tree.

    >>> with local(DefaultContext()) as ctx:
    ...     with Action() as one_action:
    ...         with ResultAction() as other_action:
    ...             r = other_action.exit("some result")
    ...         with Action() as yet_another:
    ...             pass
    >>> ctx.actions # doctest: +NORMALIZE_WHITESPACE, +ELLIPSIS
    <context.Action ...
        <context.ResultAction ...
        <context.Action ...
    <BLANKLINE>
    >>> root, subtree = ctx.actions.get_by_index([0])
    >>> for action in subtree: # doctest: +ELLIPSIS
    ...     print(action)
    <context.ResultAction ...
    <context.Action ...
    """

    actions: Tree
    current: List[Action]

    def __init__(self):
        self.actions = Tree()
        self.current = []

    def enter_action(self, action: Action) -> None:
        self.actions.get_by_key(self.current)[action] = Tree()
        self.current.append(action)

    def exit_action(self, action: Action) -> None:
        if len(self.current) < 1 or self.current[-1] != action:
            raise ValueError
        self.current.pop()

    def __repr__(self):
        return f"{self.__class__.__name__}({self.actions!r}, current={self.current!r})"


@public
class PathContext(Context):
    """Context that traces targeted actions."""

    path: List[int]
    current: List[int]
    current_depth: int
    value: Any

    def __init__(self, path: Sequence[int]):
        """
        Create a :py:class:`PathContext`.

        :param path: The path of an action in the execution tree that will be captured.
        """
        self.path = list(path)
        self.current = []
        self.current_depth = 0
        self.value = None

    def enter_action(self, action: Action) -> None:
        if self.current_depth == len(self.current):
            self.current.append(0)
        else:
            self.current[self.current_depth] += 1
        self.current_depth += 1
        if self.path == self.current[: self.current_depth]:
            self.value = action

    def exit_action(self, action: Action) -> None:
        if self.current_depth != len(self.current):
            self.current.pop()
        self.current_depth -= 1

    def __repr__(self):
        return (
            f"{self.__class__.__name__}({self.current!r}, depth={self.current_depth!r})"
        )


current: Optional[Context] = None


class _ContextManager:
    def __init__(self, new_context):
        # TODO: Is this deepcopy a good idea?
        self.new_context = deepcopy(new_context)

    def __enter__(self) -> Optional[Context]:
        global current  # This is OK, skipcq: PYL-W0603
        self.old_context = current
        current = self.new_context
        return current

    def __exit__(self, t, v, tb):
        global current  # This is OK, skipcq: PYL-W0603
        current = self.old_context


@public
def local(ctx: Optional[Context] = None) -> ContextManager:
    """
    Use a local context.

    Use it like a contextmanager, the context is active during its execution.

    >>> with local(DefaultContext()) as ctx:
    ...     with Action() as action:
    ...         pass
    >>> list(ctx.actions)[0] == action
    True

    :param ctx: If none, current context is copied.
    :return: A context manager.
    """
    return _ContextManager(ctx)