File: ast_nodes.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (435 lines) | stat: -rw-r--r-- 13,784 bytes parent folder | download
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
# type: ignore
import abc
from abc import abstractmethod
from collections import deque

from moto.dynamodb.models import DynamoType


class Node(metaclass=abc.ABCMeta):
    def __init__(self, children=None):
        self.type = self.__class__.__name__
        assert children is None or isinstance(children, list)
        self.children = children
        self.parent = None

        if isinstance(children, list):
            for child in children:
                if isinstance(child, Node):
                    child.set_parent(self)

    def set_parent(self, parent_node):
        self.parent = parent_node

    def normalize(self):
        """
        Flatten the Add-/Delete-/Remove-/Set-Action children within this Node
        """
        if self.type == "UpdateExpression":
            # We can have multiple REMOVE attr[idx] expressions, such as attr[i] and attr[i+2]
            # If we remove attr[i] first, attr[i+2] suddenly refers to a different item
            # So we sort them in reverse order - we can remove attr[i+2] first, attr[i] still refers to the same item

            # Behaviour that is unknown, for now:
            # What happens if we SET and REMOVE on the same list - what takes precedence?
            # We're assuming this is executed in original order

            remove_actions = []
            sorted_actions = []
            possible_clauses = [
                UpdateExpressionAddAction,
                UpdateExpressionDeleteAction,
                UpdateExpressionRemoveAction,
                UpdateExpressionSetAction,
            ]
            for action in self.find_clauses(possible_clauses):
                if isinstance(action, UpdateExpressionRemoveAction):
                    # Keep these separate for now
                    remove_actions.append(action)
                else:
                    if len(remove_actions) > 0:
                        # Remove-actions were found earlier
                        # Now that we have other action-types, that means we've found all possible Remove-actions
                        # Sort them appropriately
                        sorted_actions.extend(sorted(remove_actions, reverse=True))
                        remove_actions.clear()
                    # Add other actions by insertion order
                    sorted_actions.append(action)
            # Remove actions were found last
            if len(remove_actions) > 0:
                sorted_actions.extend(sorted(remove_actions, reverse=True))

            self.children = sorted_actions

    def find_clauses(self, clause_types):
        clauses = []
        for child in self.children or []:
            if type(child) in clause_types:
                clauses.append(child)
            elif isinstance(child, Expression):
                clauses.extend(child.find_clauses(clause_types))
            elif isinstance(child, UpdateExpressionFunction):
                clauses.extend(child.find_clauses(clause_types))
        return clauses


class LeafNode(Node):
    """A LeafNode is a Node where none of the children are Nodes themselves."""

    def __init__(self, children=None):
        super().__init__(children)


class Expression(Node, metaclass=abc.ABCMeta):
    """
    Abstract Syntax Tree representing the expression

    For the Grammar start here and jump down into the classes at the righ-hand side to look further. Nodes marked with
    a star are abstract and won't appear in the final AST.

    Expression* => UpdateExpression
    Expression* => ConditionExpression
    """


class UpdateExpression(Expression):
    """
    UpdateExpression => UpdateExpressionClause*
    UpdateExpression => UpdateExpressionClause* UpdateExpression
    """


class UpdateExpressionClause(UpdateExpression, metaclass=abc.ABCMeta):
    """
    UpdateExpressionClause* => UpdateExpressionSetClause
    UpdateExpressionClause* => UpdateExpressionRemoveClause
    UpdateExpressionClause* => UpdateExpressionAddClause
    UpdateExpressionClause* => UpdateExpressionDeleteClause
    """


class UpdateExpressionSetClause(UpdateExpressionClause):
    """
    UpdateExpressionSetClause => SET SetActions
    """


class UpdateExpressionSetActions(UpdateExpressionClause):
    """
    UpdateExpressionSetClause => SET SetActions

    SetActions => SetAction
    SetActions => SetAction , SetActions

    """


class UpdateExpressionSetAction(UpdateExpressionClause):
    """
    SetAction => Path = Value
    """


class UpdateExpressionAction(UpdateExpressionClause):
    def get_value(self):
        expression_path = self.children[0]
        expression_selector = expression_path.children[-1]
        return expression_selector.children[0]


class UpdateExpressionRemoveActions(UpdateExpressionClause):
    """
    UpdateExpressionSetClause => REMOVE RemoveActions

    RemoveActions => RemoveAction
    RemoveActions => RemoveAction , RemoveActions
    """


class UpdateExpressionRemoveAction(UpdateExpressionAction):
    """
    RemoveAction => Path
    """

    def __lt__(self, other):
        self_value = self.get_value()
        other_value = other.get_value()
        if isinstance(self_value, int) and isinstance(other_value, int):
            return self_value < other_value
        else:
            return str(self_value) < str(other_value)


class UpdateExpressionAddActions(UpdateExpressionClause):
    """
    UpdateExpressionAddClause => ADD RemoveActions

    AddActions => AddAction
    AddActions => AddAction , AddActions
    """


class UpdateExpressionAddAction(UpdateExpressionAction):
    """
    AddAction => Path Value
    """


class UpdateExpressionDeleteActions(UpdateExpressionClause):
    """
    UpdateExpressionDeleteClause => DELETE RemoveActions

    DeleteActions => DeleteAction
    DeleteActions => DeleteAction , DeleteActions
    """


class UpdateExpressionDeleteAction(UpdateExpressionAction):
    """
    DeleteAction => Path Value
    """


class UpdateExpressionPath(UpdateExpressionClause):
    def to_str(self):
        return "".join(x.to_str() for x in self.children)


class UpdateExpressionValue(UpdateExpressionClause):
    """
    Value => Operand
    Value => Operand + Value
    Value => Operand - Value
    """


class UpdateExpressionGroupedValue(UpdateExpressionClause):
    """
    GroupedValue => ( Value )
    """


class UpdateExpressionRemoveClause(UpdateExpressionClause):
    """
    UpdateExpressionRemoveClause => REMOVE RemoveActions
    """


class UpdateExpressionAddClause(UpdateExpressionClause):
    """
    UpdateExpressionAddClause => ADD AddActions
    """


class UpdateExpressionDeleteClause(UpdateExpressionClause):
    """
    UpdateExpressionDeleteClause => DELETE DeleteActions
    """


class ExpressionPathDescender(Node):
    """Node identifying descender into nested structure (.) in expression"""

    def to_str(self):
        return "."


class ExpressionSelector(LeafNode):
    """Node identifying selector [selection_index] in expresion"""

    def __init__(self, selection_index):
        try:
            super().__init__(children=[int(selection_index)])
        except ValueError:
            raise AssertionError(
                "Expression selector must be an int, this is a bug in the moto library."
            )

    def get_index(self):
        return self.children[0]

    def to_str(self):
        return f"[{self.get_index()}]"


class ExpressionAttribute(LeafNode):
    """An attribute identifier as used in the DDB item"""

    def __init__(self, attribute):
        super().__init__(children=[attribute])

    def get_attribute_name(self):
        return self.children[0]

    def to_str(self):
        return self.get_attribute_name()


class ExpressionAttributeName(LeafNode):
    """An ExpressionAttributeName is an alias for an attribute identifier"""

    def __init__(self, attribute_name):
        super().__init__(children=[attribute_name])

    def get_attribute_name_placeholder(self):
        return self.children[0]

    def to_str(self):
        return self.get_attribute_name_placeholder()


class ExpressionAttributeValue(LeafNode):
    """An ExpressionAttributeValue is an alias for an value"""

    def __init__(self, value):
        super().__init__(children=[value])

    def get_value_name(self):
        return self.children[0]


class ExpressionValueOperator(LeafNode):
    """An ExpressionValueOperator is an operation that works on 2 values"""

    def __init__(self, value):
        super().__init__(children=[value])

    def get_operator(self):
        return self.children[0]


class UpdateExpressionFunction(Node):
    """
    A Node representing a function of an Update Expression. The first child is the function name the others are the
    arguments.
    """

    def get_function_name(self):
        return self.children[0]

    def get_nth_argument(self, n=1):
        """Return nth element where n is a 1-based index."""
        assert n >= 1
        return self.children[n]


class DDBTypedValue(Node):
    """
    A node representing a DDBTyped value. This can be any structure as supported by DyanmoDB. The node only has 1 child
    which is the value of type `DynamoType`.
    """

    def __init__(self, value):
        assert isinstance(value, DynamoType), "DDBTypedValue must be of DynamoType"
        super().__init__(children=[value])

    def get_value(self):
        return self.children[0]


class NoneExistingPath(LeafNode):
    """A placeholder for Paths that did not exist in the Item."""

    def __init__(self, creatable=False):
        super().__init__(children=[creatable])

    def is_creatable(self):
        """Can this path be created if need be. For example path creating element in a dictionary or creating a new
        attribute under root level of an item."""
        return self.children[0]


class DepthFirstTraverser:
    """
    Helper class that allows depth first traversal and to implement custom processing for certain AST nodes. The
    processor of a node must return the new resulting node. This node will be placed in the tree. Processing of a
    node using this traverser should therefore only transform child nodes.  The returned node will get the same parent
    as the node before processing had.
    """

    @abstractmethod
    def _processing_map(self):
        """
        A map providing a processing function per node class type to a function that takes in a Node object and
        processes it. A Node can only be processed by a single function and they are considered in order. Therefore if
        multiple classes from a single class hierarchy strain are used the more specific classes have to be put before
        the less specific ones. That requires overriding `nodes_to_be_processed`. If no multiple classes form a single
        class hierarchy strain are used the default implementation of `nodes_to_be_processed` should be OK.
        Returns:
            dict: Mapping a Node Class to a processing function.
        """
        pass

    def nodes_to_be_processed(self):
        """Cached accessor for getting Node types that need to be processed."""
        return tuple(k for k in self._processing_map().keys())

    def process(self, node):
        """Process a Node"""
        for class_key, processor in self._processing_map().items():
            if isinstance(node, class_key):
                return processor(node)

    def pre_processing_of_child(self, parent_node, child_id):
        """Hook that is called pre-processing of the child at position `child_id`"""
        pass

    def traverse_node_recursively(self, node, child_id=-1):
        """
        Traverse nodes depth first processing nodes bottom up (if root node is considered the top).

        Args:
            node(Node): The node which is the last node to be processed but which allows to identify all the
                             work (which is in the children)
            child_id(int): The index in the list of children from the parent that this node corresponds to

        Returns:
            Node: The node of the new processed AST
        """
        if isinstance(node, Node):
            parent_node = node.parent
            if node.children is not None:
                for i, child_node in enumerate(node.children):
                    self.pre_processing_of_child(node, i)
                    self.traverse_node_recursively(child_node, i)
            # noinspection PyTypeChecker
            if isinstance(node, self.nodes_to_be_processed()):
                node = self.process(node)
                node.parent = parent_node
                if parent_node:
                    parent_node.children[child_id] = node
        return node

    def traverse(self, node):
        return self.traverse_node_recursively(node)


class NodeDepthLeftTypeFetcher:
    """Helper class to fetch a node of a specific type. Depth left-first traversal"""

    def __init__(self, node_type, root_node):
        assert issubclass(node_type, Node)
        self.node_type = node_type
        self.root_node = root_node
        self.queue = deque()
        self.add_nodes_left_to_right_depth_first(self.root_node)

    def add_nodes_left_to_right_depth_first(self, node):
        if isinstance(node, Node) and node.children is not None:
            for child_node in node.children:
                self.add_nodes_left_to_right_depth_first(child_node)
                self.queue.append(child_node)
        self.queue.append(node)

    def __iter__(self):
        return self

    def next(self):
        return self.__next__()

    def __next__(self):
        while len(self.queue) > 0:
            candidate = self.queue.popleft()
            if isinstance(candidate, self.node_type):
                return candidate
        raise StopIteration