astnodes.py 19.3 KB
Newer Older
1
import sympy as sp
2
from sympy.tensor import IndexedBase
3
from pystencils.field import Field
Martin Bauer's avatar
Martin Bauer committed
4
from pystencils.data_types import TypedSymbol, create_type, cast_func
Martin Bauer's avatar
Martin Bauer committed
5
from pystencils.sympyextensions import fast_subs
Martin Bauer's avatar
Martin Bauer committed
6
7
8
from typing import List, Set, Optional, Union, Any

NodeOrExpr = Union['Node', sp.Expr]
9
10


11
class Node:
Martin Bauer's avatar
Martin Bauer committed
12
    """Base class for all AST nodes."""
Martin Bauer's avatar
Martin Bauer committed
13

Martin Bauer's avatar
Martin Bauer committed
14
    def __init__(self, parent: Optional['Node'] = None):
15
16
        self.parent = parent

Martin Bauer's avatar
Martin Bauer committed
17
18
19
    @property
    def args(self) -> List[NodeOrExpr]:
        """Returns all arguments/children of this node."""
Martin Bauer's avatar
Martin Bauer committed
20
        raise NotImplementedError()
21
22

    @property
Martin Bauer's avatar
Martin Bauer committed
23
24
    def symbols_defined(self) -> Set[sp.Symbol]:
        """Set of symbols which are defined by this node."""
Martin Bauer's avatar
Martin Bauer committed
25
        raise NotImplementedError()
26
27

    @property
Martin Bauer's avatar
Martin Bauer committed
28
29
    def undefined_symbols(self) -> Set[sp.Symbol]:
        """Symbols which are used but are not defined inside this node."""
30
        raise NotImplementedError()
31

Martin Bauer's avatar
Martin Bauer committed
32
    def subs(self, subs_dict) -> None:
Martin Bauer's avatar
Martin Bauer committed
33
        """Inplace! substitute, similar to sympy's but modifies the AST inplace."""
34
        for a in self.args:
Martin Bauer's avatar
Martin Bauer committed
35
            a.subs(subs_dict)
36

37
38
39
40
    @property
    def func(self):
        return self.__class__

Martin Bauer's avatar
Martin Bauer committed
41
42
    def atoms(self, arg_type) -> Set[Any]:
        """Returns a set of all descendants recursively, which are an instance of the given type."""
43
44
        result = set()
        for arg in self.args:
Martin Bauer's avatar
Martin Bauer committed
45
            if isinstance(arg, arg_type):
46
                result.add(arg)
Martin Bauer's avatar
Martin Bauer committed
47
            result.update(arg.atoms(arg_type))
48
49
50
        return result


51
class Conditional(Node):
Martin Bauer's avatar
Martin Bauer committed
52
53
54
55
56
57
58
59
60
61
62
    """Conditional that maps to a 'if' statement in C/C++.

    Try to avoid using this node inside of loops, since currently this construction can not be vectorized.
    Consider using assignments with sympy.Piecewise in this case.

    Args:
        condition_expr: sympy relational expression
        true_block: block which is run if conditional is true
        false_block: optional block which is run if conditional is false
    """

Martin Bauer's avatar
Martin Bauer committed
63
64
    def __init__(self, condition_expr: sp.Basic, true_block: Union['Block', 'SympyAssignment'],
                 false_block: Optional['Block'] = None) -> None:
Martin Bauer's avatar
Martin Bauer committed
65
66
67
        super(Conditional, self).__init__(parent=None)

        assert condition_expr.is_Boolean or condition_expr.is_Relational
Martin Bauer's avatar
Martin Bauer committed
68
        self.condition_expr = condition_expr
Martin Bauer's avatar
Martin Bauer committed
69
70

        def handle_child(c):
71
72
73
74
75
76
77
            if c is None:
                return None
            if not isinstance(c, Block):
                c = Block([c])
            c.parent = self
            return c

Martin Bauer's avatar
Martin Bauer committed
78
79
        self.true_block = handle_child(true_block)
        self.false_block = handle_child(false_block)
80

Martin Bauer's avatar
Martin Bauer committed
81
82
    def subs(self, subs_dict):
        self.true_block.subs(subs_dict)
Martin Bauer's avatar
Martin Bauer committed
83
        if self.false_block:
Martin Bauer's avatar
Martin Bauer committed
84
85
            self.false_block.subs(subs_dict)
        self.condition_expr = self.condition_expr.subs(subs_dict)
86
87
88

    @property
    def args(self):
Martin Bauer's avatar
Martin Bauer committed
89
90
91
        result = [self.condition_expr, self.true_block]
        if self.false_block:
            result.append(self.false_block)
92
93
94
        return result

    @property
Martin Bauer's avatar
Martin Bauer committed
95
    def symbols_defined(self):
96
97
98
        return set()

    @property
Martin Bauer's avatar
Martin Bauer committed
99
    def undefined_symbols(self):
Martin Bauer's avatar
Martin Bauer committed
100
101
102
103
        result = self.true_block.undefined_symbols
        if self.false_block:
            result.update(self.false_block.undefined_symbols)
        result.update(self.condition_expr.atoms(sp.Symbol))
104
105
106
        return result

    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
107
        return 'if:({!s}) '.format(self.condition_expr)
108
109

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
110
        return 'if:({!r}) '.format(self.condition_expr)
111

112
113
114
115
116
117
118
119
    def replace_by_true_block(self):
        """Replaces the conditional by its True block"""
        self.parent.replace(self, [self.true_block])

    def replace_by_false_block(self):
        """Replaces the conditional by its False block"""
        self.parent.replace(self, [self.false_block] if self.false_block else [])

120

121
122
123
class KernelFunction(Node):

    class Argument:
Martin Bauer's avatar
Martin Bauer committed
124
        def __init__(self, name, dtype, symbol, kernel_function_node):
Martin Bauer's avatar
Martin Bauer committed
125
            from pystencils.transformations import symbol_name_to_variable_name
126
            self.name = name
127
            self.dtype = dtype
Martin Bauer's avatar
Martin Bauer committed
128
129
130
131
            self.is_field_ptr_argument = False
            self.is_field_shape_argument = False
            self.is_field_stride_argument = False
            self.is_field_argument = False
Martin Bauer's avatar
Martin Bauer committed
132
            self.field_name = ""
133
            self.coordinate = None
134
            self.symbol = symbol
135
136

            if name.startswith(Field.DATA_PREFIX):
Martin Bauer's avatar
Martin Bauer committed
137
138
                self.is_field_ptr_argument = True
                self.is_field_argument = True
Martin Bauer's avatar
Martin Bauer committed
139
                self.field_name = name[len(Field.DATA_PREFIX):]
140
            elif name.startswith(Field.SHAPE_PREFIX):
Martin Bauer's avatar
Martin Bauer committed
141
142
                self.is_field_shape_argument = True
                self.is_field_argument = True
Martin Bauer's avatar
Martin Bauer committed
143
                self.field_name = name[len(Field.SHAPE_PREFIX):]
144
            elif name.startswith(Field.STRIDE_PREFIX):
Martin Bauer's avatar
Martin Bauer committed
145
146
                self.is_field_stride_argument = True
                self.is_field_argument = True
Martin Bauer's avatar
Martin Bauer committed
147
                self.field_name = name[len(Field.STRIDE_PREFIX):]
148

149
            self.field = None
Martin Bauer's avatar
Martin Bauer committed
150
            if self.is_field_argument:
Martin Bauer's avatar
Martin Bauer committed
151
152
                field_map = {symbol_name_to_variable_name(f.name): f for f in kernel_function_node.fields_accessed}
                self.field = field_map[self.field_name]
153

154
155
        def __lt__(self, other):
            def score(l):
Martin Bauer's avatar
Martin Bauer committed
156
                if l.is_field_ptr_argument:
157
                    return -4
Martin Bauer's avatar
Martin Bauer committed
158
                elif l.is_field_shape_argument:
159
                    return -3
Martin Bauer's avatar
Martin Bauer committed
160
                elif l.is_field_stride_argument:
161
162
163
164
165
166
167
168
169
170
                    return -2
                return 0

            if score(self) < score(other):
                return True
            elif score(self) == score(other):
                return self.name < other.name
            else:
                return False

171
172
173
        def __repr__(self):
            return '<{0} {1}>'.format(self.dtype, self.name)

Martin Bauer's avatar
Martin Bauer committed
174
    def __init__(self, body, ghost_layers=None, function_name="kernel", backend=""):
175
176
        super(KernelFunction, self).__init__()
        self._body = body
177
        body.parent = self
178
        self._parameters = None
Martin Bauer's avatar
Martin Bauer committed
179
        self.function_name = function_name
180
        self._body.parent = self
Martin Bauer's avatar
Martin Bauer committed
181
        self.compile = None
Martin Bauer's avatar
Martin Bauer committed
182
        self.ghost_layers = ghost_layers
183
        # these variables are assumed to be global, so no automatic parameter is generated for them
Martin Bauer's avatar
Martin Bauer committed
184
        self.global_variables = set()
185
        self.backend = backend
186
187

    @property
Martin Bauer's avatar
Martin Bauer committed
188
    def symbols_defined(self):
189
190
191
        return set()

    @property
Martin Bauer's avatar
Martin Bauer committed
192
    def undefined_symbols(self):
193
194
195
196
        return set()

    @property
    def parameters(self):
Martin Bauer's avatar
Martin Bauer committed
197
        self._update_parameters()
198
199
200
201
202
203
204
205
        return self._parameters

    @property
    def body(self):
        return self._body

    @property
    def args(self):
Jan Hoenig's avatar
Jan Hoenig committed
206
        return [self._body]
207

208
    @property
Martin Bauer's avatar
Martin Bauer committed
209
    def fields_accessed(self):
210
        """Set of Field instances: fields which are accessed inside this kernel function"""
Martin Bauer's avatar
Martin Bauer committed
211
        return set(o.field for o in self.atoms(ResolvedFieldAccess))
212

Martin Bauer's avatar
Martin Bauer committed
213
    def _update_parameters(self):
Martin Bauer's avatar
Martin Bauer committed
214
        undefined_symbols = self._body.undefined_symbols - self.global_variables
Martin Bauer's avatar
Martin Bauer committed
215
        self._parameters = [KernelFunction.Argument(s.name, s.dtype, s, self) for s in undefined_symbols]
216
217

        self._parameters.sort()
218

219
    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
220
        self._update_parameters()
Martin Bauer's avatar
Martin Bauer committed
221
        return '{0} {1}({2})\n{3}'.format(type(self).__name__, self.function_name, self.parameters,
Michael Kuron's avatar
Michael Kuron committed
222
                                          ("\t" + "\t".join(str(self.body).splitlines(True))))
223
224

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
225
        self._update_parameters()
Martin Bauer's avatar
Martin Bauer committed
226
        return '{0} {1}({2})'.format(type(self).__name__, self.function_name, self.parameters)
227

228
229

class Block(Node):
Martin Bauer's avatar
Martin Bauer committed
230
231
232
    def __init__(self, nodes: List[Node]):
        super(Block, self).__init__()
        self._nodes = nodes
233
        self.parent = None
234
235
236
237
238
239
240
        for n in self._nodes:
            n.parent = self

    @property
    def args(self):
        return self._nodes

Martin Bauer's avatar
Martin Bauer committed
241
242
243
244
245
246
247
248
249
250
251
252
    def subs(self, subs_dict) -> None:
        new_args = []
        for a in self.args:
            if isinstance(a, SympyAssignment) and a.is_declaration and a.rhs in subs_dict.keys():
                subs_dict[a.lhs] = subs_dict[a.rhs]
            else:
                new_args.append(a)
        self._nodes = new_args

        for a in self.args:
            a.subs(subs_dict)

Martin Bauer's avatar
Martin Bauer committed
253
    def insert_front(self, node):
254
255
256
        node.parent = self
        self._nodes.insert(0, node)

Martin Bauer's avatar
Martin Bauer committed
257
258
259
    def insert_before(self, new_node, insert_before):
        new_node.parent = self
        idx = self._nodes.index(insert_before)
260
261

        # move all assignment (definitions to the top)
Martin Bauer's avatar
Martin Bauer committed
262
        if isinstance(new_node, SympyAssignment) and new_node.is_declaration:
Martin Bauer's avatar
Martin Bauer committed
263
264
265
266
267
268
            while idx > 0:
                pn = self._nodes[idx - 1]
                if isinstance(pn, LoopOverCoordinate) or isinstance(pn, Conditional):
                    idx -= 1
                else:
                    break
Martin Bauer's avatar
Martin Bauer committed
269
        self._nodes.insert(idx, new_node)
Martin Bauer's avatar
Martin Bauer committed
270

271
    def append(self, node):
272
273
274
275
276
277
278
        if isinstance(node, list) or isinstance(node, tuple):
            for n in node:
                n.parent = self
                self._nodes.append(n)
        else:
            node.parent = self
            self._nodes.append(node)
279

Martin Bauer's avatar
Martin Bauer committed
280
    def take_child_nodes(self):
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
        tmp = self._nodes
        self._nodes = []
        return tmp

    def replace(self, child, replacements):
        idx = self._nodes.index(child)
        del self._nodes[idx]
        if type(replacements) is list:
            for e in replacements:
                e.parent = self
            self._nodes = self._nodes[:idx] + replacements + self._nodes[idx:]
        else:
            replacements.parent = self
            self._nodes.insert(idx, replacements)

    @property
Martin Bauer's avatar
Martin Bauer committed
297
    def symbols_defined(self):
298
299
        result = set()
        for a in self.args:
Martin Bauer's avatar
Martin Bauer committed
300
            result.update(a.symbols_defined)
301
302
303
        return result

    @property
Martin Bauer's avatar
Martin Bauer committed
304
    def undefined_symbols(self):
305
        result = set()
Martin Bauer's avatar
Martin Bauer committed
306
        defined_symbols = set()
307
        for a in self.args:
Martin Bauer's avatar
Martin Bauer committed
308
309
            result.update(a.undefined_symbols)
            defined_symbols.update(a.symbols_defined)
Martin Bauer's avatar
Martin Bauer committed
310
        return result - defined_symbols
311

312
    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
313
        return "Block " + ''.join('{!s}\n'.format(node) for node in self._nodes)
314
315

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
316
        return "Block"
317

318
319

class PragmaBlock(Block):
Martin Bauer's avatar
Martin Bauer committed
320
321
    def __init__(self, pragma_line, nodes):
        super(PragmaBlock, self).__init__(nodes)
Martin Bauer's avatar
Martin Bauer committed
322
        self.pragma_line = pragma_line
Martin Bauer's avatar
Martin Bauer committed
323
        for n in nodes:
Martin Bauer's avatar
Martin Bauer committed
324
325
326
            n.parent = self

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
327
        return self.pragma_line
328
329
330
331
332


class LoopOverCoordinate(Node):
    LOOP_COUNTER_NAME_PREFIX = "ctr"

Martin Bauer's avatar
Martin Bauer committed
333
334
    def __init__(self, body, coordinate_to_loop_over, start, stop, step=1):
        super(LoopOverCoordinate, self).__init__(parent=None)
335
        self.body = body
336
        body.parent = self
Martin Bauer's avatar
Martin Bauer committed
337
        self.coordinate_to_loop_over = coordinate_to_loop_over
338
339
340
341
        self.start = start
        self.stop = stop
        self.step = step
        self.body.parent = self
Martin Bauer's avatar
Martin Bauer committed
342
        self.prefix_lines = []
343

Martin Bauer's avatar
Martin Bauer committed
344
    def new_loop_with_different_body(self, new_body):
Martin Bauer's avatar
Martin Bauer committed
345
346
        result = LoopOverCoordinate(new_body, self.coordinate_to_loop_over, self.start, self.stop, self.step)
        result.prefix_lines = [l for l in self.prefix_lines]
347
348
        return result

Martin Bauer's avatar
Martin Bauer committed
349
350
    def subs(self, subs_dict):
        self.body.subs(subs_dict)
351
        if hasattr(self.start, "subs"):
Martin Bauer's avatar
Martin Bauer committed
352
            self.start = self.start.subs(subs_dict)
353
        if hasattr(self.stop, "subs"):
Martin Bauer's avatar
Martin Bauer committed
354
            self.stop = self.stop.subs(subs_dict)
355
        if hasattr(self.step, "subs"):
Martin Bauer's avatar
Martin Bauer committed
356
            self.step = self.step.subs(subs_dict)
357

358
359
    @property
    def args(self):
360
361
        result = [self.body]
        for e in [self.start, self.stop, self.step]:
Martin Bauer's avatar
Martin Bauer committed
362
363
            if hasattr(e, "args"):
                result.append(e)
364
365
        return result

366
367
368
369
370
371
372
373
374
375
    def replace(self, child, replacement):
        if child == self.body:
            self.body = replacement
        elif child == self.start:
            self.start = replacement
        elif child == self.step:
            self.step = replacement
        elif child == self.stop:
            self.stop = replacement

376
    @property
Martin Bauer's avatar
Martin Bauer committed
377
378
    def symbols_defined(self):
        return {self.loop_counter_symbol}
379
380

    @property
Martin Bauer's avatar
Martin Bauer committed
381
382
    def undefined_symbols(self):
        result = self.body.undefined_symbols
Martin Bauer's avatar
Martin Bauer committed
383
384
385
        for possible_symbol in [self.start, self.stop, self.step]:
            if isinstance(possible_symbol, Node) or isinstance(possible_symbol, sp.Basic):
                result.update(possible_symbol.atoms(sp.Symbol))
Martin Bauer's avatar
Martin Bauer committed
386
        return result - {self.loop_counter_symbol}
387

Martin Bauer's avatar
Martin Bauer committed
388
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
389
390
    def get_loop_counter_name(coordinate_to_loop_over):
        return "%s_%s" % (LoopOverCoordinate.LOOP_COUNTER_NAME_PREFIX, coordinate_to_loop_over)
Martin Bauer's avatar
Martin Bauer committed
391

392
    @property
Martin Bauer's avatar
Martin Bauer committed
393
    def loop_counter_name(self):
Martin Bauer's avatar
Martin Bauer committed
394
        return LoopOverCoordinate.get_loop_counter_name(self.coordinate_to_loop_over)
Martin Bauer's avatar
Martin Bauer committed
395

396
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
397
    def is_loop_counter_symbol(symbol):
398
399
400
        prefix = LoopOverCoordinate.LOOP_COUNTER_NAME_PREFIX
        if not symbol.name.startswith(prefix):
            return None
Martin Bauer's avatar
Martin Bauer committed
401
        if symbol.dtype != create_type('int'):
402
            return None
Martin Bauer's avatar
Martin Bauer committed
403
        coordinate = int(symbol.name[len(prefix) + 1:])
404
405
        return coordinate

Martin Bauer's avatar
Martin Bauer committed
406
    @staticmethod
Martin Bauer's avatar
Martin Bauer committed
407
408
    def get_loop_counter_symbol(coordinate_to_loop_over):
        return TypedSymbol(LoopOverCoordinate.get_loop_counter_name(coordinate_to_loop_over), 'int')
409
410

    @property
Martin Bauer's avatar
Martin Bauer committed
411
    def loop_counter_symbol(self):
Martin Bauer's avatar
Martin Bauer committed
412
        return LoopOverCoordinate.get_loop_counter_symbol(self.coordinate_to_loop_over)
413
414

    @property
Martin Bauer's avatar
Martin Bauer committed
415
    def is_outermost_loop(self):
Martin Bauer's avatar
Martin Bauer committed
416
417
        from pystencils.transformations import get_next_parent_of_type
        return get_next_parent_of_type(self, LoopOverCoordinate) is None
418
419

    @property
Martin Bauer's avatar
Martin Bauer committed
420
    def is_innermost_loop(self):
Martin Bauer's avatar
Martin Bauer committed
421
        return len(self.atoms(LoopOverCoordinate)) == 0
422

423
    def __str__(self):
Martin Bauer's avatar
Martin Bauer committed
424
425
426
        return 'for({!s}={!s}; {!s}<{!s}; {!s}+={!s})\n{!s}'.format(self.loop_counter_name, self.start,
                                                                    self.loop_counter_name, self.stop,
                                                                    self.loop_counter_name, self.step,
427
                                                                    ("\t" + "\t".join(str(self.body).splitlines(True))))
428
429

    def __repr__(self):
Martin Bauer's avatar
Martin Bauer committed
430
431
432
        return 'for({!s}={!s}; {!s}<{!s}; {!s}+={!s})'.format(self.loop_counter_name, self.start,
                                                              self.loop_counter_name, self.stop,
                                                              self.loop_counter_name, self.step)
433

434
435

class SympyAssignment(Node):
Martin Bauer's avatar
Martin Bauer committed
436
437
    def __init__(self, lhs_symbol, rhs_expr, is_const=True):
        super(SympyAssignment, self).__init__(parent=None)
Martin Bauer's avatar
Martin Bauer committed
438
        self._lhs_symbol = lhs_symbol
Martin Bauer's avatar
Martin Bauer committed
439
        self.rhs = rhs_expr
Martin Bauer's avatar
Martin Bauer committed
440
441
442
443
444
        self._is_declaration = True
        is_cast = self._lhs_symbol.func == cast_func
        if isinstance(self._lhs_symbol, Field.Access) or isinstance(self._lhs_symbol, ResolvedFieldAccess) or is_cast:
            self._is_declaration = False
        self._is_const = is_const
445
446
447

    @property
    def lhs(self):
Martin Bauer's avatar
Martin Bauer committed
448
        return self._lhs_symbol
449
450

    @lhs.setter
Martin Bauer's avatar
Martin Bauer committed
451
    def lhs(self, new_value):
Martin Bauer's avatar
Martin Bauer committed
452
453
454
455
456
        self._lhs_symbol = new_value
        self._is_declaration = True
        is_cast = self._lhs_symbol.func == cast_func
        if isinstance(self._lhs_symbol, Field.Access) or isinstance(self._lhs_symbol, sp.Indexed) or is_cast:
            self._is_declaration = False
457

Martin Bauer's avatar
Martin Bauer committed
458
459
460
    def subs(self, subs_dict):
        self.lhs = fast_subs(self.lhs, subs_dict)
        self.rhs = fast_subs(self.rhs, subs_dict)
461

462
463
    @property
    def args(self):
Martin Bauer's avatar
Martin Bauer committed
464
        return [self._lhs_symbol, self.rhs]
465
466

    @property
Martin Bauer's avatar
Martin Bauer committed
467
    def symbols_defined(self):
Martin Bauer's avatar
Martin Bauer committed
468
        if not self._is_declaration:
469
            return set()
Martin Bauer's avatar
Martin Bauer committed
470
        return {self._lhs_symbol}
471
472

    @property
Martin Bauer's avatar
Martin Bauer committed
473
    def undefined_symbols(self):
474
        result = self.rhs.atoms(sp.Symbol)
475
        # Add loop counters if there a field accesses
Martin Bauer's avatar
Martin Bauer committed
476
        loop_counters = set()
477
478
479
        for symbol in result:
            if isinstance(symbol, Field.Access):
                for i in range(len(symbol.offsets)):
Martin Bauer's avatar
Martin Bauer committed
480
481
                    loop_counters.add(LoopOverCoordinate.get_loop_counter_symbol(i))
        result.update(loop_counters)
Martin Bauer's avatar
Martin Bauer committed
482
        result.update(self._lhs_symbol.atoms(sp.Symbol))
483
484
485
        return result

    @property
Martin Bauer's avatar
Martin Bauer committed
486
    def is_declaration(self):
Martin Bauer's avatar
Martin Bauer committed
487
        return self._is_declaration
488
489

    @property
Martin Bauer's avatar
Martin Bauer committed
490
    def is_const(self):
Martin Bauer's avatar
Martin Bauer committed
491
        return self._is_const
492

Jan Hoenig's avatar
Jan Hoenig committed
493
494
    def replace(self, child, replacement):
        if child == self.lhs:
495
496
            replacement.parent = self
            self.lhs = replacement
Jan Hoenig's avatar
Jan Hoenig committed
497
498
499
500
501
502
        elif child == self.rhs:
            replacement.parent = self
            self.rhs = replacement
        else:
            raise ValueError('%s is not in args of %s' % (replacement, self.__class__))

503
    def __repr__(self):
504
        return repr(self.lhs) + " ← " + repr(self.rhs)
505

Martin Bauer's avatar
Martin Bauer committed
506
507
508
    def _repr_html_(self):
        printed_lhs = sp.latex(self.lhs)
        printed_rhs = sp.latex(self.rhs)
509
        return "${printed_lhs} \leftarrow {printed_rhs}$".format(printed_lhs=printed_lhs, printed_rhs=printed_rhs)
Martin Bauer's avatar
Martin Bauer committed
510

511

Martin Bauer's avatar
Martin Bauer committed
512
class ResolvedFieldAccess(sp.Indexed):
Martin Bauer's avatar
Martin Bauer committed
513
    def __new__(cls, base, linearized_index, field, offsets, idx_coordinate_values):
Martin Bauer's avatar
Martin Bauer committed
514
515
        if not isinstance(base, IndexedBase):
            base = IndexedBase(base, shape=(1,))
Martin Bauer's avatar
Martin Bauer committed
516
        obj = super(ResolvedFieldAccess, cls).__new__(cls, base, linearized_index)
Martin Bauer's avatar
Martin Bauer committed
517
518
        obj.field = field
        obj.offsets = offsets
Martin Bauer's avatar
Martin Bauer committed
519
        obj.idx_coordinate_values = idx_coordinate_values
Martin Bauer's avatar
Martin Bauer committed
520
521
522
523
524
        return obj

    def _eval_subs(self, old, new):
        return ResolvedFieldAccess(self.args[0],
                                   self.args[1].subs(old, new),
Martin Bauer's avatar
Martin Bauer committed
525
                                   self.field, self.offsets, self.idx_coordinate_values)
Martin Bauer's avatar
Martin Bauer committed
526

Martin Bauer's avatar
Martin Bauer committed
527
528
529
530
531
    def fast_subs(self, substitutions):
        if self in substitutions:
            return substitutions[self]
        return ResolvedFieldAccess(self.args[0].subs(substitutions),
                                   self.args[1].subs(substitutions),
Martin Bauer's avatar
Martin Bauer committed
532
                                   self.field, self.offsets, self.idx_coordinate_values)
Martin Bauer's avatar
Martin Bauer committed
533
534

    def _hashable_content(self):
Martin Bauer's avatar
Martin Bauer committed
535
        super_class_contents = super(ResolvedFieldAccess, self)._hashable_content()
Martin Bauer's avatar
Martin Bauer committed
536
        return super_class_contents + tuple(self.offsets) + (repr(self.idx_coordinate_values), hash(self.field))
Martin Bauer's avatar
Martin Bauer committed
537
538

    @property
Martin Bauer's avatar
Martin Bauer committed
539
    def typed_symbol(self):
Martin Bauer's avatar
Martin Bauer committed
540
541
542
543
        return self.base.label

    def __str__(self):
        top = super(ResolvedFieldAccess, self).__str__()
Martin Bauer's avatar
Martin Bauer committed
544
        return "%s (%s)" % (top, self.typed_symbol.dtype)
Martin Bauer's avatar
Martin Bauer committed
545
546

    def __getnewargs__(self):
Martin Bauer's avatar
Martin Bauer committed
547
        return self.base, self.indices[0], self.field, self.offsets, self.idx_coordinate_values
Martin Bauer's avatar
Martin Bauer committed
548
549


550
class TemporaryMemoryAllocation(Node):
Martin Bauer's avatar
Martin Bauer committed
551
552
553
    def __init__(self, typed_symbol, size):
        super(TemporaryMemoryAllocation, self).__init__(parent=None)
        self.symbol = typed_symbol
554
555
556
        self.size = size

    @property
Martin Bauer's avatar
Martin Bauer committed
557
558
    def symbols_defined(self):
        return {self.symbol}
559
560

    @property
Martin Bauer's avatar
Martin Bauer committed
561
    def undefined_symbols(self):
562
563
564
565
        if isinstance(self.size, sp.Basic):
            return self.size.atoms(sp.Symbol)
        else:
            return set()
566
567
568

    @property
    def args(self):
569
        return [self.symbol]
570
571
572


class TemporaryMemoryFree(Node):
Martin Bauer's avatar
Martin Bauer committed
573
574
575
    def __init__(self, typed_symbol):
        super(TemporaryMemoryFree, self).__init__(parent=None)
        self.symbol = typed_symbol
576
577

    @property
Martin Bauer's avatar
Martin Bauer committed
578
    def symbols_defined(self):
579
580
581
        return set()

    @property
Martin Bauer's avatar
Martin Bauer committed
582
    def undefined_symbols(self):
583
584
585
586
587
        return set()

    @property
    def args(self):
        return []