Pyrolog / prolog / interpreter / continuation.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
import py
import time
from pypy.rlib import jit
from pypy.rlib.objectmodel import we_are_translated, specialize
from prolog.interpreter import error
from prolog.interpreter import helper
from prolog.interpreter.term import Term, Atom, Var, Callable
from prolog.interpreter.function import Function, Rule
from prolog.interpreter.heap import Heap
from prolog.interpreter.signature import Signature

Signature.register_extr_attr("function", engine=True)

# ___________________________________________________________________
# JIT stuff

def get_printable_location(rulechain):
    if rulechain:
        s = rulechain.rule.signature.string()
    else:
        s = "No rulechain"
    return s

def get_jitcell_at(where, rule):
    # XXX can be vastly simplified
    return rule.jit_cells.get(where, None)

def set_jitcell_at(newcell, where, rule):
    # XXX can be vastly simplified
    rule.jit_cells[where] = newcell

predsig = Signature.getsignature(":-", 2)
callsig = Signature.getsignature(":-", 1)

jitdriver = jit.JitDriver(
        greens=["rulechain"],
        reds=["scont", "fcont", "heap", "engine"],
        get_printable_location=get_printable_location,
        #get_jitcell_at=get_jitcell_at,
        #set_jitcell_at=set_jitcell_at,
        )

# ___________________________________________________________________
# end JIT stuff


def driver(scont, fcont, heap, engine):
    rulechain = None
    while not scont.is_done():
        #view(scont, fcont, heap)
        if isinstance(scont, UserCallContinuation) and scont.rulechain.rule.bodyshape is not None:
            rulechain = scont.rulechain
            jitdriver.can_enter_jit(rulechain=rulechain, scont=scont, fcont=fcont,
                                    heap=heap, engine=engine)
        try:
            jitdriver.jit_merge_point(rulechain=rulechain, scont=scont, fcont=fcont,
                                      heap=heap, engine=engine)
            scont, fcont, heap  = scont.activate(fcont, heap, engine)
        except error.UnificationFailed:
            if not we_are_translated():
                if fcont.is_done():
                    raise
            if scont.candiscard():
                scont.discard()
            scont, fcont, heap = fcont.fail(heap, engine)
        except error.CatchableError, e:
            scont, fcont, heap = engine.throw(e.term, scont, fcont, heap)
    assert isinstance(scont, DoneContinuation)
    if scont.failed:
        raise error.UnificationFailed

class Engine(object):
    def __init__(self):
        self.heap = Heap()
        self.parser = None
        self.operations = None
        from prolog.builtin.statistics import Clocks
        self.clocks = Clocks()
        self.clocks.startup()
    # _____________________________________________________
    # database functionality

    def get_function(self, signature):
        return signature.get_extra_engine_local("function", self)

    def add_rule(self, rule, end=True, fromassert=True):
        #import pdb; pdb.set_trace()
        if helper.is_term(rule):
            assert isinstance(rule, Callable)
            if rule.signature().eq(predsig):
                rule = Rule(rule.argument_at(0), rule.argument_at(1))
            else:
                rule = Rule(rule, None)
        elif isinstance(rule, Atom):
            rule = Rule(rule, None)
        else:
            error.throw_type_error("callable", rule)
            assert 0, "unreachable" # make annotator happy
        signature = rule.signature
        if self.get_builtin(signature):
            error.throw_permission_error(
                "modify", "static_procedure", rule.head.get_prolog_signature())
        function = self.lookup_function(signature, new_is_dynamic=fromassert)
        function.add_rule(rule, end, fromassert)

    @jit.purefunction_promote("0")
    def get_builtin(self, signature):
        from prolog import builtin # for the side-effects
        return signature.get_extra("builtin")

    def lookup_function(self, signature, new_is_dynamic=False):
        # redirection needed because purefunction_promote does not support
        # default args
        return self._lookup_function(signature, new_is_dynamic)

    @jit.purefunction_promote("0")
    def _lookup_function(self, signature, new_is_dynamic):
        assert signature.cached
        function = self.get_function(signature)
        if function is None:
            function = Function()
            function.dynamic = new_is_dynamic
            signature.set_extra_engine_local("function", function, self)
        return function

    # _____________________________________________________
    # parsing-related functionality

    def _build_and_run(self, tree):
        from prolog.interpreter.parsing import TermBuilder
        builder = TermBuilder()
        term = builder.build_query(tree)
        if isinstance(term, Callable) and term.signature().eq(callsig):
            self.run(term.argument_at(0))
        else:
            self.add_rule(term, fromassert=False)
        return self.parser

    def runstring(self, s):
        from prolog.interpreter.parsing import parse_file
        trees = parse_file(s, self.parser, Engine._build_and_run, self)

    def parse(self, s):
        from prolog.interpreter.parsing import parse_file, TermBuilder
        builder = TermBuilder()
        trees = parse_file(s, self.parser, None, self)
        terms = builder.build_many(trees)
        return terms, builder.varname_to_var

    def getoperations(self):
        from prolog.interpreter.parsing import default_operations
        if self.operations is None:
            return default_operations
        return self.operations

    # _____________________________________________________
    # Prolog execution

    def run_query(self, query, continuation=None):
        if continuation is None:
            continuation = DoneContinuation()
        scont, fcont, heap = self.call(query, continuation, DoneContinuation(), Heap())
        driver(scont, fcont, heap, self)
    run = run_query

    def call(self, query, scont, fcont, heap):
        if not isinstance(query, Callable):
            raise error.throw_type_error('callable', query)
        signature = query.signature()
        builtin = self.get_builtin(signature)
        if builtin is not None:
            return self.continue_(BuiltinContinuation(scont, builtin, query), fcont, heap)

        # do a real call
        function = self.lookup_function(signature)
        startrulechain = jit.hint(function.get_rulechain(), promote=True)
        if startrulechain is None:
            return error.throw_existence_error(
                "procedure", query.get_prolog_signature())
        rulechain = startrulechain.find_rulechain(query)
        if rulechain is None:
            raise error.UnificationFailed
        rulechain = rulechain.find_applicable_rule(query)
        if rulechain is None:
            raise error.UnificationFailed
        scont = UserCallContinuation(scont, query,
                                     rulechain)
        return self.continue_(scont, fcont, heap)

    # _____________________________________________________
    # error handling

    @jit.unroll_safe
    def throw(self, exc, scont, fcont, heap):
        # XXX write tests for catching non-ground things
        while not scont.is_done():
            if not isinstance(scont, CatchingDelimiter):
                scont = scont.nextcont
                continue
            heap = heap.revert_upto(scont.heap)
            try:
                scont.catcher.unify(exc, heap)
            except error.UnificationFailed:
                scont = scont.nextcont
            else:
                # XXX discard the heap?
                return self.call(
                    scont.recover, scont.nextcont, scont.fcont, heap)
        raise error.UncaughtError(exc)


    @specialize.argtype(0)
    def continue_(engine, scont, fcont, heap):
        if scont.is_done() or isinstance(scont, UserCallContinuation) and scont.rulechain.rule.bodyshape is not None:
            return scont, fcont, heap
        try:
            return scont.activate(fcont, heap, engine)
        except error.UnificationFailed:
            if not we_are_translated():
                if fcont.is_done():
                    raise
            if scont.candiscard():
                scont.discard()
            return fcont.fail(heap, engine)
        except error.CatchableError, e:
            return engine.throw(e.term, scont, fcont, heap)
    continue_._always_inline_ = True

    def __freeze__(self):
        return True

# ___________________________________________________________________
# Continuation classes

class Continuation(object):
    """ Represents a continuation of the Prolog computation. This can be seen
    as an RPython-compatible way to express closures. """

    def __init__(self, nextcont):
        self.nextcont = nextcont
        if nextcont is not None:
            self._candiscard = nextcont.candiscard()
        else:
            self._candiscard = False

    def candiscard(self):
        return self._candiscard

    def activate(self, fcont, heap, engine):
        """ Follow the continuation. heap is the heap that should be used while
        doing so, fcont the failure continuation that should be activated in
        case this continuation fails. This method can only be called once, i.e.
        it can destruct this object.

        The method should return a triple (next cont, failure cont, heap)"""
        raise NotImplementedError("abstract base class")

    def is_done(self):
        return False

    def discard(self):
        """ Discard the information stored in a Continuation. This will be used
        if a SuccessContinuation will no longer be activatable, since
        backtracking occurred. """
        if self.nextcont is not None:
            self.nextcont.discard()

    def _dot(self, seen):
        if self in seen:
            return
        seen.add(self)
        yield '%s [label="%s", shape=box]' % (id(self), repr(self)[:50])
        if self.nextcont is not None:
            yield "%s -> %s [label=nextcont]" % (id(self), id(self.nextcont))
            for line in self.nextcont._dot(seen):
                yield line

def view(*objects):
    from dotviewer import graphclient
    content = ["digraph G{"]
    seen = set()
    for obj in objects:
        content.extend(obj._dot(seen))
    content.append("}")
    p = py.test.ensuretemp("prolog").join("temp.dot")
    p.write("\n".join(content))
    graphclient.display_dot_file(str(p))

class FailureContinuation(Continuation):
    """ A continuation that can represent failures. It has a .fail method that
    is called to prepare it for being used as a failure continuation.

    NB: a Continuation can be used both as a failure continuation and as a
    success continuation."""

    def fail(self, heap, engine):
        """ Needs to be called to prepare the object as being used as a failure
        continuation. After fail has been called, the continuation will usually
        be activated. Particularly useful for objects that are both a regular
        and a failure continuation, to distinguish the two cases. """
        # returns (next cont, failure cont, heap)
        raise NotImplementedError("abstract base class")

    def cut(self, heap):
        """ Cut away choice points till the next correct cut delimiter.
        Slightly subtle. """
        return self

class DoneContinuation(FailureContinuation):
    def __init__(self):
        Continuation.__init__(self, None)
        self.failed = False

    def activate(self, fcont, heap, engine):
        assert 0, "unreachable"

    def fail(self, heap, engine):
        self.failed = True
        return self, self, heap

    def is_done(self):
        return True


class BodyContinuation(Continuation):
    """ Represents a bit of Prolog code that is still to be called. """
    def __init__(self, nextcont, body):
        Continuation.__init__(self, nextcont)
        self.body = body

    def activate(self, fcont, heap, engine):
        return engine.call(self.body, self.nextcont, fcont, heap)

    def __repr__(self):
        return "<BodyContinuation %r>" % (self.body, )

class BuiltinContinuation(Continuation):
    """ Rerpresents the call to a builtin. """
    def __init__(self, nextcont, builtin, query):
        Continuation.__init__(self, nextcont)
        self.builtin = builtin
        self.query = query

    def activate(self, fcont, heap, engine):
        return self.builtin.call(engine, self.query, self.nextcont, fcont, heap)

    def __repr__(self):
        return "<BuiltinContinuation %r, %r>" % (self.builtin, self.query, )

class ChoiceContinuation(FailureContinuation):
    """ An abstract base class for Continuations that represent a choice point,
    i.e. a point to which the execution can backtrack to."""

    def __init__(self, *args):
        FailureContinuation.__init__(self, *args)
        self.undoheap = None
        self.orig_fcont = None

    #def activate(self, fcont, heap, engine):
    #    this method needs to be structured as follows:
    #    <some code>
    #    if <has more solutions>:
    #        fcont, heap = self.prepare_more_solutions(fcont, heap)
    #    <construct cont> # must not raise UnificationFailed!
    #    return cont, fcont, heap

    def prepare_more_solutions(self, fcont, heap):
        self.undoheap = heap
        heap = heap.branch()
        self.orig_fcont = fcont
        fcont = self
        return fcont, heap

    def fail(self, heap, engine):
        assert self.undoheap is not None
        heap = heap.revert_upto(self.undoheap, discard_choicepoint=True)
        return engine.continue_(self, self.orig_fcont, heap)

    def cut(self, heap):
        heap = self.undoheap.discard(heap)
        return self.orig_fcont.cut(heap)

    def discard(self):
        # don't propagate the discarding, as a ChoiceContinuation can both be a
        # success and a failure continuation at the same time
        pass

    def _dot(self, seen):
        if self in seen:
            return
        for line in FailureContinuation._dot(self, seen):
            yield line
        seen.add(self)
        if self.orig_fcont is not None:
            yield "%s -> %s [label=orig_fcont]" % (id(self), id(self.orig_fcont))
            for line in self.orig_fcont._dot(seen):
                yield line
        if self.undoheap is not None:
            yield "%s -> %s [label=heap]" % (id(self), id(self.undoheap))
            for line in self.undoheap._dot(seen):
                yield line

class UserCallContinuation(ChoiceContinuation):
    def __init__(self, nextcont, query, rulechain):
        ChoiceContinuation.__init__(self, nextcont)
        self.query = query
        signature = query.signature()
        self.rulechain = rulechain

    def activate(self, fcont, heap, engine):
        rulechain = jit.hint(self.rulechain, promote=True)
        rule = rulechain.rule
        nextcont = self.nextcont
        if rule.contains_cut:
            nextcont, fcont = CutDelimiter.insert_cut_delimiter(nextcont, fcont)
        query = self.query
        restchain = rulechain.find_next_applicable_rule(query)
        if restchain is not None:
            fcont, heap = self.prepare_more_solutions(fcont, heap)
            self.rulechain = restchain

        cont = RuleContinuation(nextcont, rule, query)
        return cont, fcont, heap

    def __repr__(self):
        return "<UserCallContinuation query=%r rule=%r>" % (
                self.query, self.rulechain)


class RuleContinuation(Continuation):
    """ A Continuation that represents the application of a rule, i.e.:
        - standardizing apart of the rule
        - unifying the rule head with the query
        - calling the body of the rule
    """

    def __init__(self, nextcont, rule, query):
        Continuation.__init__(self, nextcont)
        self._rule = rule
        self.query = query

    def activate(self, fcont, heap, engine):
        nextcont = self.nextcont
        rule = jit.hint(self._rule, promote=True)
        nextcall = rule.clone_and_unify_head(heap, self.query)
        if nextcall is not None:
            return engine.call(nextcall, nextcont, fcont, heap)
        else:
            cont = nextcont
        return cont, fcont, heap

    def __repr__(self):
        return "<RuleContinuation rule=%r query=%r>" % (self._rule, self.query)

class CutScopeNotifier(Continuation):
    def __init__(self, nextcont):
        Continuation.__init__(self, nextcont)
        self.cutcell = CutCell()

    def candiscard(self):
        return not self.cutcell.discarded

    def activate(self, fcont, heap, engine):
        self.cutcell.activated = True
        return self.nextcont, fcont, heap

    def discard(self):
        assert not self.cutcell.activated
        self.cutcell.discarded = True


class CutCell(object):
    def __init__(self):
        self.activated = False
        self.discarded = False

class CutDelimiter(FailureContinuation):
    def __init__(self, nextcont, cutcell):
        FailureContinuation.__init__(self, nextcont)
        self.cutcell = cutcell

    def candiscard(self):
        return not self.cutcell.discarded

    @staticmethod
    def insert_cut_delimiter(nextcont, fcont):
        if isinstance(fcont, CutDelimiter):
            if fcont.cutcell.activated or fcont.cutcell.discarded:
                fcont = fcont.nextcont
                if isinstance(nextcont, CutScopeNotifier) and nextcont.cutcell.discarded:
                    nextcont = nextcont.nextcont
            elif (isinstance(nextcont, CutScopeNotifier) and
                    nextcont.cutcell is fcont.cutcell):
                assert not fcont.cutcell.activated
                return nextcont, fcont
        scont = CutScopeNotifier(nextcont)
        fcont = CutDelimiter(fcont, scont.cutcell)
        return scont, fcont

    def activate(self, *args):
        raise NotImplementedError("unreachable")

    def fail(self, heap, engine):
        nextcont = self.nextcont
        assert isinstance(nextcont, FailureContinuation)
        return nextcont.fail(heap, engine)

    def cut(self, heap):
        if not self.cutcell.activated:
            return self
        nextcont = self.nextcont
        assert isinstance(nextcont, FailureContinuation)
        return nextcont.cut(heap)

    def __repr__(self):
        return "<CutDelimiter activated=%r, discarded=%r>" % (self.cutcell.activated, self.cutcell.discarded)

    def _dot(self, seen):
        if self in seen:
            return
        for line in FailureContinuation._dot(self, seen):
            yield line
        seen.add(self)
        yield "%s -> %s [label=nextcont]" % (id(self), id(self.nextcont))
        for line in self.nextcont._dot(seen):
            yield line


class CatchingDelimiter(Continuation):
    def __init__(self, nextcont, fcont, catcher, recover, heap):
        Continuation.__init__(self, nextcont)
        self.catcher = catcher
        self.recover = recover
        self.fcont = fcont
        self.heap = heap

    def activate(self, fcont, heap, engine):
        return self.nextcont, fcont, heap
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.