Source

Pyrolog / prolog / interpreter / shape.py

  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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
from pypy.rlib import jit, objectmodel, debug, unroll, rerased, rarithmetic
from prolog.interpreter import term
from prolog.interpreter.graphviz import _dot, view
# a Callable implementation that tries to save memory

erase, unerase = rerased.new_erasing_pair("pyrolog")

# XXX tune this
MAX_DEPTH = 6
MAX_SIZE = 6
SHAPED_CALLABLE_SIZE = 6

class Shape(object):
    _attrs_ = []
    def __init__(self):
        pass

    def resolve(self, shaped_callable, index):
        raise NotImplementedError("abstract base class")

    def num_storage_vars(self):
        return 0

    def depth(self):
        return 1

    def get_path(self, index):
        raise NotImplementedError("abstract base class")

    def str(self):
        return ""

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

    _dot = _dot

INEFFICIENT = Shape()
SEEN_ONCE = Shape()

class WrapShape(Shape):
    _immutable_fields_ = ["w_obj"]
    def __init__(self, w_obj):
        Shape.__init__(self)
        self.w_obj = w_obj

    def resolve(self, shaped_callable, index):
        return self.w_obj

    def replace(self, i, shape):
        assert 0, "cannot happen"

    def str(self):
        return "WrapShape(%s)" % (self.w_obj, )

class InStorageShape(Shape):

    def __init__(self):
        Shape.__init__(self)

    @staticmethod
    def build():
        return InStorageShape._singleton

    def resolve(self, shaped_callable, index):
        return unerase(shaped_callable.get_raw_storage(index))

    def write(self, shaped_callable, i, val):
        shaped_callable.set_raw_storage(i, erase(val))

    def num_storage_vars(self):
        return 1

    def replace(self, i, shape):
        assert i == 0
        return shape

    def str(self):
        return "InStorageShape()"
InStorageShape._singleton = InStorageShape()

class InStorageIntShape(InStorageShape):
    @staticmethod
    def build():
        return InStorageIntShape._singleton

    def resolve(self, shaped_callable, index):
        val = rerased.unerase_int(shaped_callable.get_raw_storage(index))
        return term.Number(val)

    def write(self, shaped_callable, i, obj):
        if obj is None:
            val = -41 # need an initialization value
        else:
            assert isinstance(obj, term.Number)
            val = obj.num
        r_val = rerased.erase_int(val)
        shaped_callable.set_raw_storage(i, r_val)

    def str(self):
        return "InStorageIntShape()"
InStorageIntShape._singleton = InStorageIntShape()

class InStorageAtomShape(InStorageShape):
    @staticmethod
    def build():
        return InStorageAtomShape._singleton

    def resolve(self, shaped_callable, index):
        result = unerase(shaped_callable.get_raw_storage(index))
        # XXX use new JIT interface here instead
        assert isinstance(result, term.Atom)
        return result

    def write(self, shaped_callable, i, val):
        assert val is None or isinstance(val, term.Atom)
        shaped_callable.set_raw_storage(i, erase(val))

    def str(self):
        return "InStorageAtomShape()"
InStorageAtomShape._singleton = InStorageAtomShape()

# XXX introduce a Var Shape

def can_be_tagged(obj):
    val = obj.num
    # bit sucky
    try:
        rerased.erase_int(val)
    except OverflowError:
        return False
    return True

def shape_eq((sig1, children1), (sig2, children2)):
    return sig1 is sig2 and children1 == children2

def shape_hash((sig, children)):
    x = objectmodel.compute_identity_hash(sig)
    for item in children:
        y = objectmodel.compute_identity_hash(item)
        x = rarithmetic.intmask((1000003 * x) ^ y)
    return x

class SharingShape(Shape):
    _immutable_fields_ = ["signature", "children[*]", "_num_storage_vars", "paths[*]", "storage[*]"]
    _cache = objectmodel.r_dict(shape_eq, shape_hash)
    _transitions = None

    def __init__(self, signature, children):
        Shape.__init__(self)
        self.signature = signature
        self.children = children
        children = debug.make_sure_not_resized(children)
        _num_storage_vars = 0
        paths = []
        storage = []
        for i in range(len(children)):
            child = children[i]
            _num_storage_vars += child.num_storage_vars()
            if isinstance(child, InStorageShape):
                paths.append(term.VarInTermPath([i]))
                storage.append(child)
            elif isinstance(child, SharingShape):
                for subpath in child.paths:
                    if subpath is not None:
                        paths.append(term.VarInTermPath([i] + subpath.path))
                storage.extend(child.storage)
        self._num_storage_vars = _num_storage_vars
        assert len(paths) == _num_storage_vars
        assert len(storage) == _num_storage_vars
        self.paths = paths[:]
        self.storage = storage[:]

    @staticmethod
    def build(signature, children):
        key = signature, children
        res = SharingShape._cache.get(key, None)
        if res is None:
            SharingShape._cache[key] = res = SharingShape(signature, children)
        return res

    @staticmethod
    @jit.elidable
    def build_flat(signature, numargs):
        children = [InStorageShape.build()] * numargs
        return SharingShape.build(signature, children)


    @jit.unroll_safe
    def resolve(self, shaped_callable, index):
        storage = [shaped_callable.get_storage(i)
                      for i in range(index, index + self.num_storage_vars())]
        return shaped_callable.new(self, storage).compress()

    @jit.unroll_safe
    def _find_storage_index(self, argument_index):
        storage_index = 0
        for j in range(argument_index):
            storage_index += self.children[j].num_storage_vars()
        return storage_index

    def resolve_at(self, argument_index, shaped_callable):
        return self.children[argument_index].resolve(shaped_callable,
                self._find_storage_index(argument_index))

    @jit.unroll_safe
    def resolve_indicator(self, indicator, shaped_callable):
        storage_index = 0
        for j in range(len(indicator.path)):
            # to make the JIT know that the read is constant-foldable
            i = indicator.path[j]
            storage_index += self._find_storage_index(i)
            assert isinstance(self, SharingShape)
            self = self.children[i]
        return self.resolve(shaped_callable, storage_index)

    def get_path(self, index):
        return self.paths[index]

    @staticmethod
    def build_potentially_wrap(signature, children):
        unwrapped = [None] * len(children)
        for i in range(len(children)):
            child = children[i]
            if not isinstance(child, WrapShape):
                return SharingShape.build(signature, children)
            unwrapped[i] = child.w_obj
        return WrapShape(term.Callable.build(signature.name, unwrapped,
                                        signature=signature))

    def num_storage_vars(self):
        return self._num_storage_vars

    @jit.elidable
    def replace(self, i, shape):
        for j in range(len(self.children)):
            child = self.children[j]
            num = child.num_storage_vars()
            if i < num:
                child = child.replace(i, shape)
                break
            else:
                i -= num
        else:
            assert 0, "cannot happen"
        children = self.children[:j] + [child] + self.children[j + 1:]
        return SharingShape.build(self.signature, children)

    def depth(self):
        depth = 0
        for child in self.children:
            depth = max(depth, child.depth())
        return depth + 1

    @jit.elidable_promote('all')
    def get_transition(self, i, shape):
        if self._transitions is None:
            self._transitions = {}
        key = (i, shape)
        newshape = self._transitions.get(key, None)
        # XXX tune heuristics
        if newshape is None:
            self._transitions[key] = SEEN_ONCE
            return None
        elif newshape is SEEN_ONCE:
            newshape = self.replace(i, shape)
            if (newshape.depth() <= MAX_DEPTH and
                    newshape.num_storage_vars() <= MAX_SIZE):
                self._transitions[key] = newshape
            else:
                self._transitions[key] = INEFFICIENT
                return None
        elif newshape is INEFFICIENT:
            return None
        assert isinstance(newshape, SharingShape)
        return newshape

    def str(self):
        return "SharingShape(%s, [%s])" % (self.signature.string(), ", ".join([child.str() for child in self.children]))

    def _dot(self, seen):
        if self in seen:
            return
        for line in Shape._dot(self, seen):
            yield line
        for i, child in enumerate(self.children):
            yield "%s -> %s [label=%s]" % (id(self), id(child), i)
            for line in child._dot(seen):
                yield line


# _____________________________________________________________________

class ShapedCallableBase(term.Callable):
    _attrs_ = []

    def get_shape(self):
        raise NotImplementedError("abstract base class")

    def get_storage(self, i):
        raise NotImplementedError("abstract base class")

    def get_storage_using_shape(self, i, shape):
        raise NotImplementedError("abstract base class")

    def set_storage(self, i, val):
        raise NotImplementedError("abstract base class")

    def size_storage(self):
        raise NotImplementedError("abstract base class")

    def new(self, shape, storage):
        raise NotImplementedError("abstract base class")

    @jit.unroll_safe
    def get_mode(self):
        mode = 0x345678
        for i in range(self.size_storage()):
            child = self.get_storage(i)
            y = 0
            if isinstance(child, term.VarInTerm):
                parent = child.parent
                shape = parent.get_shape()
                indicator = child.indicator
                if isinstance(indicator, term.VarInTermIndex):
                    y = objectmodel.compute_identity_hash(shape)
                else:
                    y = 0
            mode = rarithmetic.intmask((1000003 * mode) ^ y)
        return mode

UNROLL_N = unroll.unrolling_iterable(range(SHAPED_CALLABLE_SIZE))
UNROLL_R = unroll.unrolling_iterable(range(SHAPED_CALLABLE_SIZE)[::-1])

class ShapedCallableMixin:
    TYPE_STANDARD_ORDER = term.Term.TYPE_STANDARD_ORDER
    _mixin_ = True

    rest_storage = None

    def __init__(self, shape, storage):
        assert isinstance(shape, SharingShape)
        self.shape = shape
        assert shape.num_storage_vars() == len(storage)
        self.set_full_storage(storage)

    def get_shape(self):
        return jit.promote(self.shape)

    def set_shape(self, shape):
        self.shape = shape

    def get_raw_storage(self, i):
        for n in UNROLL_N:
            if i == n:
                return getattr(self, "a%s" % n)
        return self.rest_storage[i - SHAPED_CALLABLE_SIZE]

    def set_raw_storage(self, i, r_val):
        for n in UNROLL_N:
            if i == n:
                setattr(self, "a%s" % n, r_val)
                break
        else:
            self.rest_storage[i - SHAPED_CALLABLE_SIZE] = r_val

    def get_storage(self, i):
        return self.get_storage_using_shape(i, self.get_shape())

    def get_storage_using_shape(self, i, shape):
        jit.promote(i)
        return shape.storage[i].resolve(self, i)

    def set_storage(self, i, val):
        jit.promote(i)
        self.get_shape().storage[i].write(self, i, val)

    def size_storage(self):
        return self.get_shape().num_storage_vars()


    @jit.unroll_safe
    def get_full_storage(self):
        size = self.size_storage()
        return [self.get_storage(i) for i in range(size)]

        # this is very much over the top, but it was fun to do
        result = [None] * min(size, SHAPED_CALLABLE_SIZE)
        if size == 0:
            return result
        for n in UNROLL_N:
            if size == n + 1:
                break
        else:
            result = result + self.rest_storage
            n = SHAPED_CALLABLE_SIZE - 1
        for i in UNROLL_R:
            if n == i:
                result[i] = self.get_storage(i)
                n = i - 1
        return result

    @jit.unroll_safe
    def set_full_storage(self, storage):
        additional_size = max(0, len(storage) - SHAPED_CALLABLE_SIZE)
        if additional_size:
            self.rest_storage = [erase(None)] * additional_size
        else:
            self.rest_storage = None
        for i in range(len(storage)):
            self.set_storage(i, storage[i])
        return

        # this is very much over the top, but it was fun to do
        size = self.size_storage()
        if size == 0:
            return
        # the trick: "promote" size
        for n in UNROLL_N:
            if size == n + 1:
                break
        else:
            self.rest_storage = storage[SHAPED_CALLABLE_SIZE:]
            n = SHAPED_CALLABLE_SIZE - 1
        for i in UNROLL_R:
            if n == i:
                setattr(self, "a%s" % i, storage[i])
                n = i - 1

    # _____________________________________________________________________
    # callable interface

    def signature(self):
        return self.get_shape().signature

    def argument_at(self, i):
        return self.get_shape().resolve_at(i, self)

    def argument_count(self):
        return self.signature().numargs

    @objectmodel.specialize.arg(3)
    @jit.look_inside_iff(lambda self, other, heap, occurs_check:
        jit.isvirtual(self) or jit.isvirtual(other) or
        jit.isconstant(self) or jit.isconstant(other))
    def basic_unify(self, other, heap, occurs_check):
        if (isinstance(other, ShapedCallableBase) and
                self.get_shape() is other.get_shape()):
            for i in range(self.size_storage()):
                self.get_storage(i).unify(other.get_storage(i), heap, occurs_check)
            return
        return term.Callable.basic_unify(self, other, heap, occurs_check)

    @jit.unroll_safe
    def copy_and_basic_unify(self, other, heap, env):
        if (isinstance(other, ShapedCallableBase) and
                self.get_shape() is other.get_shape()):
            for i in range(self.size_storage()):
                self.get_storage(i).unify_and_standardize_apart(
                        other.get_storage(i), heap, env)
            return
        return term.Callable.copy_and_basic_unify(self, other, heap, env)

    def copy(self, heap, memo):
        from prolog.interpreter.term import _term_copy
        return self._copy_term(_term_copy, heap, memo)

    @jit.unroll_safe
    def copy_standardize_apart(self, heap, env):
        storage = [None] * self.size_storage()
        result = ShapedCallableMutable(self.get_shape(), storage)
        newinstance = False
        needmutable = False
        i = 0
        for i in range(self.size_storage()):
            arg = self.get_storage(i)
            cloned = arg.copy_standardize_apart_as_child_of(heap, env, result, i)
            newinstance = newinstance | (isinstance(arg, term.NumberedVar) or cloned is not arg)
            needmutable = needmutable | isinstance(cloned, term.VarInTerm)
            result.set_storage(i, cloned)
        if newinstance:
            if not needmutable:
                result = result._make_immutable()
            return result.compress()
        else:
            return self

    def enumerate_vars(self, memo):
        from prolog.interpreter.term import _term_enumerate_vars
        return self._copy_term(_term_enumerate_vars, None, memo)

    @objectmodel.specialize.arg(1)
    @jit.unroll_safe
    def _copy_term(self, copy_individual, heap, *extraargs):
        args = [None] * self.size_storage()
        newinstance = False
        i = 0
        while i < self.size_storage():
            arg = self.get_storage(i)
            cloned = copy_individual(arg, i, heap, *extraargs)
            newinstance = newinstance | (cloned is not arg)
            args[i] = cloned
            i += 1
        if newinstance:
            # XXX what about the variable shunting in Callable.build?
            return self.new(self.get_shape(), args)
        else:
            return self

    def contains_var(self, var, heap):
        for i in range(self.size_storage()):
            arg = self.get_storage(i)
            if arg.contains_var(var, heap):
                return True
        return False

    # _____________________________________________________________________
    # shape-specific interface

    @jit.unroll_safe
    def _replace_child(self, index, obj, new_shape):
        assert isinstance(obj, ShapedCallableBase)
        newsize = obj.size_storage() + self.size_storage() - 1
        assert newsize == new_shape.num_storage_vars()
        offset = obj.size_storage() - 1
        old_shape = self.shape
        self.set_shape(new_shape)
        if offset < 0:
            for i in range(index + 1, self.size_storage()):
                self.move_child(i, i + offset, old_shape)
        else:
            if offset > 0:
                for i in range(old_shape.num_storage_vars() - 1, index, -1):
                    self.move_child(i, i + offset, old_shape)
            for i in range(obj.size_storage()):
                child = obj.get_storage(i)
                # XXX whew, subtle logic here
                if isinstance(child, term.VarInTerm):
                    deref = child.getbinding()
                    if deref is None:
                        self = self._make_mutable()
                        child.parent = self
                        child.indicator = term.VarInTermIndex.build(i + index)
                    else:
                        child = deref
                self.set_raw_storage(i + index, obj.get_raw_storage(i))
        return self

    def move_child(self, index, newindex, old_shape):
        child = self.get_storage_using_shape(index, old_shape)
        if isinstance(child, term.VarInTerm):
            child = child.move(self, index, newindex)
            self.set_storage(newindex, child)
        else:
            self.set_raw_storage(newindex, self.get_raw_storage(index))

    def replace_child(self, index, obj):
        shape = self.get_shape()
        if isinstance(obj, ShapedCallableBase):
            new_shape = shape.get_transition(index, obj.get_shape())
            if new_shape is not None:
                assert new_shape.num_storage_vars() <= SHAPED_CALLABLE_SIZE
                return self._replace_child(index, obj, new_shape)
        elif isinstance(obj, term.Number) and can_be_tagged(obj):
            new_shape = shape.replace(index, InStorageIntShape.build())
            self.set_shape(new_shape)
            # new shape will take care to store unwrapped
            self.set_storage(index, obj)
        elif isinstance(obj, term.Atom):
            new_shape = shape.replace(index, InStorageAtomShape.build())
            self.set_shape(new_shape)
            self.set_storage(index, obj)
        return None

    @staticmethod
    def build(shape, storage):
        if isinstance(shape, WrapShape):
            assert not storage
            return shape.w_obj
        result = ShapedCallable(shape, storage)
        return result.compress()

    @jit.unroll_safe
    def compress(self):
        i = 0
        while i < self.size_storage():
            child = self.get_storage(i)
            newresult = self.replace_child(i, child)
            if not newresult:
                i += 1
            else:
                self = newresult
        assert self.get_shape().num_storage_vars() == self.size_storage()
        return self

    _dot = _dot

for i in range(SHAPED_CALLABLE_SIZE):
    setattr(ShapedCallableMixin, "a%s" % i, erase(None))

class ShapedCallableMutable(ShapedCallableMixin, ShapedCallableBase):
    def _make_immutable(self):
        return ShapedCallable(self.get_shape(), self.get_full_storage())

    def _make_mutable(self):
        return self

    def new(self, shape, storage):
        return ShapedCallableMutable(shape, storage)


class ShapedCallable(ShapedCallableMixin, ShapedCallableBase):
    _immutable_fields_ = ["shape", "rest_storage[*]"] + ["a%s" % i for i in range(SHAPED_CALLABLE_SIZE)]

    @jit.unroll_safe
    def _make_mutable(self):
        result = objectmodel.instantiate(ShapedCallableMutable)
        result.shape = self.shape
        for i in range(SHAPED_CALLABLE_SIZE):
            result.set_raw_storage(i, self.get_raw_storage(i))
        result.rest_storage = self.rest_storage
        return result

    def new(self, shape, storage):
        return ShapedCallable(shape, storage)


# _____________________________________________________________________

def make_standardizer(w_obj):
    memo = []
    shape = term_with_numbered_vars_to_shape(w_obj, memo)
    if isinstance(shape, SharingShape):
        w_obj = ShapedCallable(shape, memo[:])
    elif isinstance(shape, WrapShape):
        w_obj = shape.w_obj
    else:
        assert 0, "should be unreachable"
    return Standardizer(w_obj)

def term_with_numbered_vars_to_shape(w_obj, memo):
    from prolog.interpreter import term
    if isinstance(w_obj, term.NumberedVar):
        memo.append(w_obj)
        return InStorageShape.build()
    elif isinstance(w_obj, term.Callable):
        argshapes = [term_with_numbered_vars_to_shape(w_arg, memo)
                        for w_arg in w_obj.arguments()]
        return SharingShape.build_potentially_wrap(w_obj.signature(), argshapes)
    return WrapShape(w_obj)

class Standardizer(object):
    _immutable_fields_ = ["w_obj"]
    def __init__(self, w_obj):
        self.w_obj = w_obj

    def make_shaped_callable(self, heap, env):
        return self.w_obj.copy_standardize_apart(heap, env)

# _____________________________________________________________________