View source with raw comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Benoit Desouter <Benoit.Desouter@UGent.be>
    4                   Jan Wielemaker (SWI-Prolog port)
    5                   Fabrizio Riguzzi (mode directed tabling)
    6    Copyright (c) 2016-2025, Benoit Desouter,
    7                             Jan Wielemaker,
    8                             Fabrizio Riguzzi
    9                             SWI-Prolog Solutions b.v.
   10    All rights reserved.
   11
   12    Redistribution and use in source and binary forms, with or without
   13    modification, are permitted provided that the following conditions
   14    are met:
   15
   16    1. Redistributions of source code must retain the above copyright
   17       notice, this list of conditions and the following disclaimer.
   18
   19    2. Redistributions in binary form must reproduce the above copyright
   20       notice, this list of conditions and the following disclaimer in
   21       the documentation and/or other materials provided with the
   22       distribution.
   23
   24    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   25    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   26    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   27    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   28    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   29    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   30    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   31    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   32    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   33    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   34    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   35    POSSIBILITY OF SUCH DAMAGE.
   36*/
   37
   38:- module('$tabling',
   39          [ (table)/1,                  % :PI ...
   40            untable/1,                  % :PI ...
   41
   42            (tnot)/1,                   % :Goal
   43            not_exists/1,               % :Goal
   44            undefined/0,
   45            answer_count_restraint/0,
   46            radial_restraint/0,
   47
   48            current_table/2,            % :Variant, ?Table
   49            abolish_all_tables/0,
   50            abolish_private_tables/0,
   51            abolish_shared_tables/0,
   52            abolish_table_subgoals/1,   % :Subgoal
   53            abolish_module_tables/1,    % +Module
   54            abolish_nonincremental_tables/0,
   55            abolish_nonincremental_tables/1, % +Options
   56            abolish_monotonic_tables/0,
   57
   58            start_tabling/3,            % +Closure, +Wrapper, :Worker
   59            start_subsumptive_tabling/3,% +Closure, +Wrapper, :Worker
   60            start_abstract_tabling/3,   % +Closure, +Wrapper, :Worker
   61            start_moded_tabling/5,      % +Closure, +Wrapper, :Worker,
   62                                        % :Variant, ?ModeArgs
   63
   64            '$tbl_answer'/4,            % +Trie, -Return, -ModeArgs, -Delay
   65
   66            '$wrap_tabled'/2,		% :Head, +Mode
   67            '$moded_wrap_tabled'/5,	% :Head, +Opts, +ModeTest, +Varnt, +Moded
   68            '$wfs_call'/2,              % :Goal, -Delays
   69
   70            '$set_table_wrappers'/1,    % :Head
   71            '$start_monotonic'/2        % :Head, :Wrapped
   72          ]).   73
   74:- meta_predicate
   75    table(:),
   76    untable(:),
   77    tnot(0),
   78    not_exists(0),
   79    tabled_call(0),
   80    start_tabling(+, +, 0),
   81    start_abstract_tabling(+, +, 0),
   82    start_moded_tabling(+, +, 0, +, ?),
   83    current_table(:, -),
   84    abolish_table_subgoals(:),
   85    '$wfs_call'(0, :).

Tabled execution (SLG WAM)

This library handled tabled execution of predicates using the characteristics if the SLG WAM. The required suspension is realised using delimited continuations implemented by reset/3 and shift/1. The table space and work lists are part of the SWI-Prolog core.

author
- Benoit Desouter, Jan Wielemaker and Fabrizio Riguzzi
   97% Enable debugging using debug(tabling(Topic)) when compiled with
   98% -DO_DEBUG
   99goal_expansion(tdebug(Topic, Fmt, Args), Expansion) :-
  100    (   current_prolog_flag(prolog_debug, true)
  101    ->  Expansion = debug(tabling(Topic), Fmt, Args)
  102    ;   Expansion = true
  103    ).
  104goal_expansion(tdebug(Goal), Expansion) :-
  105    (   current_prolog_flag(prolog_debug, true)
  106    ->  Expansion = (   debugging(tabling(_))
  107                    ->  (   Goal
  108                        ->  true
  109                        ;   print_message(error,
  110                                          format('goal_failed: ~q', [Goal]))
  111                        )
  112                    ;   true
  113                    )
  114    ;   Expansion = true
  115    ).
  116
  117:- if(current_prolog_flag(prolog_debug, true)).  118:- set_prolog_flag(optimise_debug, false).  119:- autoload(library(debug), [debug/3, debugging/1]).  120
  121wl_goal(tnot(WorkList), ~(Goal), Skeleton) :-
  122    !,
  123    '$tbl_wkl_table'(WorkList, ATrie),
  124    trie_goal(ATrie, Goal, Skeleton).
  125wl_goal(WorkList, Goal, Skeleton) :-
  126    '$tbl_wkl_table'(WorkList, ATrie),
  127    trie_goal(ATrie, Goal, Skeleton).
  128
  129trie_goal(ATrie, Goal, Skeleton) :-
  130    '$tbl_table_status'(ATrie, _Status, M:Variant, Skeleton),
  131    (   M:'$table_mode'(Goal0, Variant, _Moded)
  132    ->  true
  133    ;   Goal0 = Variant                 % dynamic IDG nodes
  134    ),
  135    unqualify_goal(M:Goal0, user, Goal).
  136
  137delay_goals(List, Goal) :-
  138    delay_goals(List, user, Goal).
  139
  140user_goal(Goal, UGoal) :-
  141    unqualify_goal(Goal, user, UGoal).
  142
  143:- multifile
  144    prolog:portray/1.  145
  146user:portray(ATrie) :-
  147    '$is_answer_trie'(ATrie, _),
  148    trie_goal(ATrie, Goal, _Skeleton),
  149    (   '$idg_falsecount'(ATrie, FalseCount)
  150    ->  (   '$idg_forced'(ATrie)
  151        ->  format('~q [fc=~d/F] for ~p', [ATrie, FalseCount, Goal])
  152        ;   format('~q [fc=~d] for ~p', [ATrie, FalseCount, Goal])
  153        )
  154    ;   format('~q for ~p', [ATrie, Goal])
  155    ).
  156user:portray(Cont) :-
  157    compound(Cont),
  158    compound_name_arguments(Cont, '$cont$', [_Context, Clause, PC | Args]),
  159    clause_property(Clause, file(File)),
  160    file_base_name(File, Base),
  161    clause_property(Clause, line_count(Line)),
  162    clause_property(Clause, predicate(PI)),
  163    format('~q at ~w:~d @PC=~w, ~p', [PI, Base, Line, PC, Args]).
  164
  165:- endif.
 table :PredicateIndicators
Prepare the given PredicateIndicators for tabling. This predicate is normally used as a directive, but SWI-Prolog also allows runtime conversion of non-tabled predicates to tabled predicates by calling table/1. The example below prepares the predicate edge/2 and the non-terminal statement//1 for tabled execution.
:- table edge/2, statement//1.

In addition to using predicate indicators, a predicate can be declared for mode directed tabling using a term where each argument declares the intended mode. For example:

:- table connection(_,_,min).

Mode directed tabling is discussed in the general introduction section about tabling.

  190table(M:PIList) :-
  191    setup_call_cleanup(
  192        '$set_source_module'(OldModule, M),
  193        expand_term((:- table(PIList)), Clauses),
  194        '$set_source_module'(OldModule)),
  195    dyn_tabling_list(Clauses, M).
  196
  197dyn_tabling_list([], _).
  198dyn_tabling_list([H|T], M) :-
  199    dyn_tabling(H, M),
  200    dyn_tabling_list(T, M).
  201
  202dyn_tabling(M:Clause, _) :-
  203    !,
  204    dyn_tabling(Clause, M).
  205dyn_tabling((:- multifile(PI)), M) :-
  206    !,
  207    multifile(M:PI),
  208    dynamic(M:PI).
  209dyn_tabling(:- initialization(Wrap, now), M) :-
  210    !,
  211    M:Wrap.
  212dyn_tabling('$tabled'(Head, TMode), M) :-
  213    (   clause(M:'$tabled'(Head, OMode), true, Ref),
  214        (   OMode \== TMode
  215        ->  erase(Ref),
  216            fail
  217        ;   true
  218        )
  219    ->  true
  220    ;   assertz(M:'$tabled'(Head, TMode))
  221    ).
  222dyn_tabling('$table_mode'(Head, Variant, Moded), M) :-
  223    (   clause(M:'$table_mode'(Head, Variant0, Moded0), true, Ref)
  224    ->  (   t(Head, Variant, Moded) =@= t(Head, Variant0, Moded0)
  225        ->  true
  226        ;   erase(Ref),
  227            assertz(M:'$table_mode'(Head, Variant, Moded))
  228        )
  229    ;   assertz(M:'$table_mode'(Head, Variant, Moded))
  230    ).
  231dyn_tabling(('$table_update'(Head, S0, S1, S2) :- Body), M) :-
  232    (   clause(M:'$table_update'(Head, S00, S10, S20), Body0, Ref)
  233    ->  (   t(Head, S0, S1, S2, Body) =@= t(Head, S00, S10, S20, Body0)
  234        ->  true
  235        ;   erase(Ref),
  236            assertz(M:('$table_update'(Head, S0, S1, S2) :- Body))
  237        )
  238    ;   assertz(M:('$table_update'(Head, S0, S1, S2) :- Body))
  239    ).
 untable(M:PIList) is det
Remove tabling for the predicates in PIList. This can be used to undo the effect of table/1 at runtime. In addition to removing the tabling instrumentation this also removes possibly associated tables using abolish_table_subgoals/1.
Arguments:
PIList- is a comma-list that is compatible ith table/1.
  250untable(M:PIList) :-
  251    untable(PIList, M).
  252
  253untable(Var, _) :-
  254    var(Var),
  255    !,
  256    '$instantiation_error'(Var).
  257untable(M:Spec, _) :-
  258    !,
  259    '$must_be'(atom, M),
  260    untable(Spec, M).
  261untable((A,B), M) :-
  262    !,
  263    untable(A, M),
  264    untable(B, M).
  265untable(Name//Arity, M) :-
  266    atom(Name), integer(Arity), Arity >= 0,
  267    !,
  268    Arity1 is Arity+2,
  269    untable(Name/Arity1, M).
  270untable(Name/Arity, M) :-
  271    !,
  272    functor(Head, Name, Arity),
  273    (   '$get_predicate_attribute'(M:Head, tabled, 1)
  274    ->  abolish_table_subgoals(M:Head),
  275        dynamic(M:'$tabled'/2),
  276        dynamic(M:'$table_mode'/3),
  277        retractall(M:'$tabled'(Head, _TMode)),
  278        retractall(M:'$table_mode'(Head, _Variant, _Moded)),
  279        unwrap_predicate(M:Name/Arity, table),
  280        '$set_predicate_attribute'(M:Head, tabled, false),
  281        '$set_predicate_attribute'(M:Head, tabled_variant, false),
  282        '$set_predicate_attribute'(M:Head, opaque, false),
  283        '$set_predicate_attribute'(M:Head, incremental, false),
  284        '$set_predicate_attribute'(M:Head, monotonic, false),
  285        '$set_predicate_attribute'(M:Head, lazy, false)
  286    ;   true
  287    ).
  288untable(Head, M) :-
  289    callable(Head),
  290    !,
  291    functor(Head, Name, Arity),
  292    untable(Name/Arity, M).
  293untable(TableSpec, _) :-
  294    '$type_error'(table_declaration, TableSpec).
  295
  296untable_reconsult(PI) :-
  297    print_message(informational, untable(PI)),
  298    untable(PI).
  299
  300:- initialization
  301   prolog_listen(untable, untable_reconsult).  302
  303
  304'$wrap_tabled'(Head, Options) :-
  305    get_dict(mode, Options, subsumptive),
  306    !,
  307    set_pattributes(Head, Options),
  308    '$set_predicate_attribute'(Head, tabled_variant, false),
  309    '$wrap_predicate'(Head, table, Closure, Wrapped,
  310                      start_subsumptive_tabling(Closure, Head, Wrapped)).
  311'$wrap_tabled'(Head, Options) :-
  312    get_dict(subgoal_abstract, Options, _Abstract),
  313    !,
  314    set_pattributes(Head, Options),
  315    '$set_predicate_attribute'(Head, tabled_variant, false),
  316    '$wrap_predicate'(Head, table, Closure, Wrapped,
  317                      start_abstract_tabling(Closure, Head, Wrapped)).
  318'$wrap_tabled'(Head, Options) :-
  319    !,
  320    set_pattributes(Head, Options),
  321    '$set_predicate_attribute'(Head, tabled_variant, true),
  322    '$wrap_predicate'(Head, table, Closure, Wrapped,
  323                      start_tabling(Closure, Head, Wrapped)).
 set_pattributes(:Head, +Options) is det
Set all tabling attributes for Head. These have been collected using table_options/3 from the :- table Head as (Attr1,...) directive.
  330set_pattributes(Head, Options) :-
  331    '$set_predicate_attribute'(Head, tabled, true),
  332    (   tabled_attribute(Attr),
  333        get_dict(Attr, Options, Value),
  334        '$set_predicate_attribute'(Head, Attr, Value),
  335        fail
  336    ;   current_prolog_flag(table_monotonic, lazy),
  337        '$set_predicate_attribute'(Head, lazy, true),
  338        fail
  339    ;   true
  340    ).
  341
  342tabled_attribute(incremental).
  343tabled_attribute(dynamic).
  344tabled_attribute(tshared).
  345tabled_attribute(max_answers).
  346tabled_attribute(subgoal_abstract).
  347tabled_attribute(answer_abstract).
  348tabled_attribute(monotonic).
  349tabled_attribute(opaque).
  350tabled_attribute(lazy).
 start_tabling(:Closure, :Wrapper, :Implementation)
Execute Implementation using tabling. This predicate should not be called directly. The table/1 directive causes a predicate to be translated into a renamed implementation and a wrapper that involves this predicate.
Arguments:
Closure- is the wrapper closure to find the predicate quickly. It is also allowed to pass nothing. In that cases the predicate is looked up using Wrapper. We suggest to pass 0 in this case.
Compatibility
- This interface may change or disappear without notice from future versions.
  366start_tabling(Closure, Wrapper, Worker) :-
  367    '$tbl_variant_table'(Closure, Wrapper, Trie, Status, Skeleton, IsMono),
  368    (   IsMono == true
  369    ->  shift(dependency(Skeleton, Trie, Mono)),
  370        (   Mono == true
  371        ->  tdebug(monotonic, 'Monotonic new answer: ~p', [Skeleton])
  372        ;   start_tabling_2(Closure, Wrapper, Worker, Trie, Status, Skeleton)
  373        )
  374    ;   Status == complete                      % common cases of
  375    ->  trie_gen_compiled(Trie, Skeleton)       % start_tabling_2/6
  376    ;   Status = fresh(SCC, WorkList)
  377    ->  create_table(Trie, SCC, WorkList, Skeleton, Wrapper, Worker)
  378    ;   start_tabling_2(Closure, Wrapper, Worker, Trie, Status, Skeleton)
  379    ).
  380
  381start_tabling_2(Closure, Wrapper, Worker, Trie, Status, Skeleton) :-
  382    tdebug(deadlock, 'Got table ~p, status ~p', [Trie, Status]),
  383    (   Status == complete
  384    ->  trie_gen_compiled(Trie, Skeleton)
  385    ;   Status = fresh(SCC, WorkList)
  386    ->  create_table(Trie, SCC, WorkList, Skeleton, Wrapper, Worker)
  387    ;   Status == invalid
  388    ->  reeval(Trie, Wrapper, Skeleton)
  389    ;   Status = fresh_shared(SCC, WorkList)
  390    ->  catch(create_table(Trie, SCC, WorkList, Skeleton, Wrapper, Worker),
  391              deadlock,
  392              restart_tabling(Closure, Wrapper, Worker))
  393    ;   % = run_follower, but never fresh and Status is a worklist
  394        shift_for_copy(call_info(Skeleton, Status))
  395    ).
 create_table(+Trie, +SCC, +WorkList, ?Skeleton, +Wrapper, +Worker)
Run the leader for the fresh table Trie. Only a shared table is run inside catch/3 for a deadlock exception, which is raised when claiming a shared table. The tables we own are shared tables and restarting a private table cannot release them.
  404create_table(Trie, SCC, WorkList, Skeleton, Wrapper, Worker) :-
  405    tdebug(wl_goal(WorkList, Goal, _)),
  406    tdebug(schedule, 'Created component ~d for ~p', [SCC, Goal]),
  407    '$tbl_leader'(SCC,
  408                  run_leader(Skeleton, Worker, SCC, WorkList, LStatus, Clause),
  409                  Wrapper, _OldCurrent, Trie),
  410    tdebug(schedule, 'Leader ~p done, status = ~p', [Goal, LStatus]),
  411    done_leader(LStatus, Skeleton, Clause).
 $tbl_leader(+SCC, :Goal, +Wrapper, -OldCurrent, +Trie)
Run Goal, the leader of the new component SCC for the fresh table Trie, with Trie as current IDG node. This acts as
setup_call_catcher_cleanup(
    '$idg_set_current'(OldCurrent, Trie),
    Goal,
    Catcher,
    tbl_leader_finished(OldCurrent, Catcher, SCC, Wrapper))

where the cleanup is the C function tbl_leader_finished(). It restores the IDG node, destroys SCC if the leader completed the root component and discards the tables of SCC if Goal raised an exception. '$call_cleanup' compiles to the VM instructions of setup_call_catcher_cleanup/4, where callCleanupHandler() detects this predicate by its arity. The setup need not be atomic: the current IDG node is a backtrackable assignment, so an exception before the cleanup is active restores it.

  433'$tbl_leader'(_SCC, _Goal, _Wrapper, OldCurrent, Trie) :-
  434    '$idg_set_current'(OldCurrent, Trie),
  435    '$call_cleanup'.
 restart_tabling(+Closure, +Wrapper, +Worker)
We were aborted due to a deadlock. Simply retry. We sleep a very tiny amount to give the thread against which we have deadlocked the opportunity to grab our table. Without, it is common that we re-grab the table within our time slice and before the kernel managed to wakeup the other thread.
  445restart_tabling(Closure, Wrapper, Worker) :-
  446    tdebug(user_goal(Wrapper, Goal)),
  447    tdebug(deadlock, 'Deadlock running ~p; retrying', [Goal]),
  448    sleep(0.000001),
  449    start_tabling(Closure, Wrapper, Worker).
  450
  451restart_abstract_tabling(Closure, Wrapper, Worker) :-
  452    tdebug(user_goal(Wrapper, Goal)),
  453    tdebug(deadlock, 'Deadlock running ~p; retrying', [Goal]),
  454    sleep(0.000001),
  455    start_abstract_tabling(Closure, Wrapper, Worker).
 start_subsumptive_tabling(:Closure, :Wrapper, :Implementation)
(*) We should not use trie_gen_compiled/2 here as this will enumerate all answers while '$tbl_answer_update_dl'/2 uses the available trie indexing to only fetch the relevant answer(s).
To be done
- In the end '$tbl_answer_update_dl'/2 is problematic with incremental and shared tabling as we do not get the consistent update view from the compiled result.
  467start_subsumptive_tabling(Closure, Wrapper, Worker) :-
  468    (   '$tbl_existing_variant_table'(Closure, Wrapper, Trie, Status, Skeleton)
  469    ->  '$idg_add_edge'(Trie),
  470        mon_consumer(Wrapper, Trie, Skeleton,
  471                     start_tabling_2(Closure, Wrapper, Worker,
  472                                     Trie, Status, Skeleton))
  473    ;   more_general_table(Wrapper, ATrie),
  474        '$tbl_table_status'(ATrie, complete, Wrapper, Skeleton)
  475    ->  '$idg_add_edge'(ATrie),
  476        mon_consumer(Wrapper, ATrie, Skeleton,
  477                     '$tbl_answer_update_dl'(ATrie, Skeleton)) % see (*)
  478    ;   more_general_table(Wrapper, ATrie),
  479        '$tbl_table_status'(ATrie, Status, GenWrapper, GenSkeleton)
  480    ->  (   Status == invalid
  481        ->  forall(reeval(ATrie, GenWrapper, GenSkeleton), true),
  482            start_subsumptive_tabling(Closure, Wrapper, Worker)
  483        ;   wrapper_skeleton(GenWrapper, GenSkeleton, Wrapper, Skeleton),
  484            mon_consumer(Wrapper, ATrie, Skeleton,
  485                         ( shift_for_copy(call_info(GenSkeleton, Skeleton, Status)),
  486                           unify_subsumptive(Skeleton, GenSkeleton)
  487                         ))
  488        )
  489    ;   start_tabling(Closure, Wrapper, Worker)
  490    ).
 wrapper_skeleton(+GenWrapper, +GenSkeleton, +Wrapper, -Skeleton)
Skeleton is a specialized version of GenSkeleton for the subsumed new consumer.
  497wrapper_skeleton(GenWrapper, GenSkeleton, Wrapper, Skeleton) :-
  498    copy_term(GenWrapper+GenSkeleton, Wrapper+Skeleton),
  499    tdebug(call_subsumption, 'GenSkeleton+Skeleton = ~p',
  500           [GenSkeleton+Skeleton]).
  501
  502unify_subsumptive(X,X).
 mon_consumer(+Wrapper, +Trie, +Skeleton, :Goal)
Call Goal, which produces the answers of Trie that unify with Skeleton, for a call to Wrapper that is answered from an existing table: an existing variant of a subsumptive call, a more general table or an abstract table. If Wrapper is monotonic and we collect monotonic dependencies, first record that the caller depends on Trie, as start_tabling/3 does for a variant table, so that answers propagated to Trie later also reach the caller. Skeleton may be more specific than the answers of Trie. Propagation unifies it with each new answer, passing only the answers this call can use.
  516mon_consumer(Wrapper, Trie, Skeleton, Goal) :-
  517    '$get_predicate_attribute'(Wrapper, monotonic, 1),
  518    '$tbl_collect_mono_dep',
  519    !,
  520    shift(dependency(Skeleton, Trie, Mono)),
  521    (   Mono == true
  522    ->  tdebug(monotonic, 'Monotonic new answer: ~p', [Skeleton])
  523    ;   call(Goal)
  524    ).
  525mon_consumer(_, _, _, Goal) :-
  526    call(Goal).
 start_abstract_tabling(:Closure, :Wrapper, :Worker)
Deal with table p/1 as subgoal_abstract(N). This is a merge between variant and subsumptive tabling. If the goal is not abstracted this is simple variant tabling. If the goal is abstracted we must solve the more general goal and use answers from the abstract table.

Wrapper is e.g., user:p(s(s(s(X))),Y) Worker is e.g., call(<closure>(p/2)(s(s(s(X))),Y))

  539start_abstract_tabling(Closure, Wrapper, Worker) :-
  540    '$tbl_abstract_table'(Closure, Wrapper, Trie, _Abstract, Status, Skeleton),
  541    tdebug(abstract, 'Wrapper=~p, Worker=~p, Skel=~p',
  542           [Wrapper, Worker, Skeleton]),
  543    mon_consumer(Wrapper, Trie, Skeleton,
  544                 start_abstract_tabling_2(Closure, Wrapper, Worker,
  545                                          Trie, Status, Skeleton)).
  546
  547start_abstract_tabling_2(Closure, Wrapper, Worker, Trie, Status, Skeleton) :-
  548    (   is_most_general_term(Skeleton)           % TBD: Fill and test Abstract
  549    ->  start_tabling_2(Closure, Wrapper, Worker, Trie, Status, Skeleton)
  550    ;   Status == complete
  551    ->  '$tbl_answer_update_dl'(Trie, Skeleton)
  552    ;   fresh_status(Status, SCC, WorkList)
  553    ->  '$tbl_table_status'(Trie, _, GenWrapper, GenSkeleton),
  554        abstract_worker(Worker, GenWrapper, GenWorker),
  555        catch(create_abstract_table(Trie, SCC, WorkList, Skeleton, GenSkeleton,
  556                                    GenWrapper, GenWorker),
  557              deadlock,
  558              restart_abstract_tabling(Closure, Wrapper, Worker))
  559    ;   Status == invalid
  560    ->  '$tbl_table_status'(Trie, _, GenWrapper, GenSkeleton),
  561        forall(reeval(Trie, GenWrapper, GenSkeleton), true),
  562        '$tbl_answer_update_dl'(Trie, Skeleton)
  563    ;   shift_for_copy(call_info(GenSkeleton, Skeleton, Status)),
  564        unify_subsumptive(Skeleton, GenSkeleton)
  565    ).
  566
  567create_abstract_table(Trie, SCC, WorkList, Skeleton, GenSkeleton, Wrapper,
  568                      Worker) :-
  569    tdebug(wl_goal(WorkList, Goal, _)),
  570    tdebug(schedule, 'Created component ~d for ~p', [SCC, Goal]),
  571    '$tbl_leader'(SCC,
  572                  run_leader(GenSkeleton, Worker, SCC, WorkList, LStatus,
  573                             _Clause),
  574                  Wrapper, _OldCurrent, Trie),
  575    tdebug(schedule, 'Leader ~p done, status = ~p', [Goal, LStatus]),
  576    Skeleton = GenSkeleton,
  577    done_abstract_leader(LStatus, GenSkeleton, Trie).
  578
  579abstract_worker(_:call(Term), _M:GenWrapper, call(GenTerm)) :-
  580    functor(Term, Closure, _),
  581    GenWrapper =.. [_|Args],
  582    GenTerm =.. [Closure|Args].
 fresh_status(+Status, -SCC, -WorkList) is semidet
True when Status is the status of a fresh table, i.e., we must run its leader.
  589fresh_status(fresh(SCC, WorkList), SCC, WorkList).
  590fresh_status(fresh_shared(SCC, WorkList), SCC, WorkList).
  591
  592:- '$hide'((done_abstract_leader/3)).  593
  594done_abstract_leader(merged, _, _) :-
  595    !.
  596done_abstract_leader(_, Skeleton, Trie) :-
  597    '$tbl_answer_update_dl'(Trie, Skeleton).
 done_leader(+Status, +Skeleton, +Clause)
Called on completion of a table. Generates the answers from the complete table. The last cases deals with leaders that are merged into a higher SCC (and thus no longer a leader). If the leader completed the root component, the component was destroyed by the cleanup of '$tbl_leader'/5.

The answer trie is only compiled if it is deep or has conditional answers (Status is clause). Otherwise the first call to trie_gen_compiled/2 compiles it. Many tables are never called again after their leader completes.

  612:- '$hide'((done_leader/3, '$tbl_leader'/5)).  613
  614done_leader(true, _, _).                        % single answer, unified
  615done_leader(false, _, _) :-                     % no answers
  616    fail.
  617done_leader(trie, Skeleton, Trie) :-
  618    trie_gen(Trie, Skeleton).
  619done_leader(clause, Skeleton, Clause) :-
  620    trie_gen_compiled(Clause, Skeleton).
  621done_leader(merged, _, _).
 run_leader(+Skeleton, +Worker, +SCC, +WorkList, -Status, -Clause) is det
Run the leader of a (new) SCC, storing instantiated copies of Wrapper into Trie. Status is the status of the SCC when this predicate terminates. It is true, false, trie or clause if local completion finished (see '$tbl_leader_complete'/4 and done_leader/3), or merged if running the completion finds an open (not completed) active goal that resides in a parent component. In this case, this SCC has been merged with this parent.

This inlines the activation of the leader and completion/3.

If the SCC is merged, the answers it already gathered are added to the worklist and we shift (suspend), turning our leader into an internal node for the upper SCC.

  640run_leader(Skeleton, Worker, SCC, Worklist, Status, Clause) :-
  641    tdebug(wl_goal(Worklist, Goal, Skeleton)),
  642    tdebug(schedule, '-> Activate component ~p for ~p', [SCC, Goal]),
  643    tdebug(activate, '~p: created wl=~p', [Skeleton, Worklist]),
  644    (   '$tbl_set_delay_list'([]),              % activate
  645        delim(Skeleton, Worker, Worklist, []),
  646        fail
  647    ;   tdebug(schedule, '-> Complete component ~p for ~p', [SCC, Goal]),
  648        '$tbl_pop_worklist'(SCC, WorkList1)     % completion
  649    ->  (   '$tbl_set_delay_list'([]),
  650            (   completion_step(WorkList1)
  651            ;   completion_(SCC)
  652            ),
  653            fail
  654        ;   true
  655        )
  656    ;   true
  657    ),
  658    '$tbl_leader_complete'(SCC, Skeleton, Status, Clause),
  659    tdebug(schedule, '-> Completed component ~p for ~p: ~p', [SCC, Goal, Status]),
  660    (   Status == merged
  661    ->  tdebug(merge, 'Turning leader ~p into follower', [Goal]),
  662        '$tbl_wkl_make_follower'(Worklist),
  663        shift_for_copy(call_info(Skeleton, Worklist))
  664    ;   true                                    % completed
  665    ).
 delim(+Skeleton, +Worker, +WorkList, +Delays)
Call WorkList and add all instances of Skeleton as answer to WorkList, conditional according to Delays.
Arguments:
Skeleton- is the return skeleton (ret/N term)
Worker- is either the (wrapped) tabled goal or a continuation
WorkList- is the work list associated with Worker (or its continuation).
Delays- is the current delay list. Note that the actual delay also include the internal global delay list. '$tbl_wkl_add_answer'/4 joins the two. For a dependency we join the two explicitly.
  681%   Without debugging, '$tbl_reset'/6 adds the answers.  It fails after
  682%   adding an answer, after pruning the choice points of Worker if the
  683%   answer completes the table.  It only exits if Worker suspends.  All
  684%   callers of delim/4 fail after it succeeds.
  685
  686:- if(current_prolog_flag(prolog_debug, true)).  687delim(Skeleton, Worker, WorkList, Delays) :-
  688    reset(Worker, SourceCall, Continuation),
  689    tdebug(wl_goal(WorkList, Goal, _)),
  690    (   Continuation == 0
  691    ->  tdebug('$tbl_add_global_delays'(Delays, AllDelays)),
  692        tdebug(delay_goals(AllDelays, Cond)),
  693        tdebug(answer, 'New answer ~p for ~p (delays = ~p)',
  694               [Skeleton, Goal, Cond]),
  695        '$tbl_wkl_add_answer'(WorkList, Skeleton, Delays, Complete),
  696        Complete == !,
  697        !
  698    ;   delim_suspended(SourceCall, Continuation, Skeleton, WorkList, Delays)
  699    ).
  700:- else.  701delim(Skeleton, Worker, WorkList, Delays) :-
  702    '$tbl_reset'(Worker, SourceCall, Continuation, WorkList, Skeleton, Delays),
  703    delim_suspended(SourceCall, Continuation, Skeleton, WorkList, Delays).
  704:- endif.  705
  706delim_suspended(SourceCall, Continuation, Skeleton, WorkList, Delays) :-
  707    (   SourceCall = call_info(SrcSkeleton, SourceWL)
  708    ->  '$tbl_add_global_delays'(Delays, AllDelays),
  709        tdebug(wl_goal(SourceWL, SrcGoal, _)),
  710        tdebug(wl_goal(WorkList, DstGoal, _)),
  711        tdebug(schedule, 'Suspended ~p, for solving ~p', [SrcGoal, DstGoal]),
  712        '$tbl_wkl_add_suspension'(
  713            SourceWL,
  714            dependency(SrcSkeleton, Continuation, Skeleton, WorkList, AllDelays))
  715    ;   SourceCall = call_info(SrcSkeleton, InstSkeleton, SourceWL)
  716    ->  '$tbl_add_global_delays'(Delays, AllDelays),
  717        tdebug(wl_goal(SourceWL, SrcGoal, _)),
  718        tdebug(wl_goal(WorkList, DstGoal, _)),
  719        tdebug(schedule, 'Suspended ~p, for solving ~p', [SrcGoal, DstGoal]),
  720        '$tbl_wkl_add_suspension'(
  721            SourceWL,
  722            InstSkeleton,
  723            dependency(SrcSkeleton, Continuation, Skeleton, WorkList, AllDelays))
  724    ;   '$tbl_wkl_table'(WorkList, ATrie),
  725        mon_assert_dep(SourceCall, Continuation, Skeleton, ATrie)
  726    ->  delim(Skeleton, Continuation, WorkList, Delays)
  727    ).
 start_moded_tabling(+Closure, :Wrapper, :Implementation, +Variant, +ModeArgs)
As start_tabling/2, but in addition separates the data stored in the answer trie in the Variant and ModeArgs.
  734'$moded_wrap_tabled'(Head, Options, ModeTest, WrapperNoModes, ModeArgs) :-
  735    set_pattributes(Head, Options),
  736    '$set_predicate_attribute'(Head, tabled_variant, false),
  737    '$wrap_predicate'(Head, table, Closure, Wrapped,
  738                      (   ModeTest,
  739                          start_moded_tabling(Closure, Head, Wrapped,
  740                                              WrapperNoModes, ModeArgs)
  741                      )).
  742
  743
  744start_moded_tabling(Closure, Wrapper, Worker, WrapperNoModes, ModeArgs) :-
  745    '$tbl_moded_variant_table'(Closure, WrapperNoModes, Trie,
  746                               Status, Skeleton, IsMono),
  747    (   IsMono == true
  748    ->  shift(dependency(Skeleton/ModeArgs, Trie, Mono)),
  749        (   Mono == true
  750        ->  tdebug(monotonic, 'Monotonic new answer: ~p', [Skeleton])
  751        ;   start_moded_tabling_2(Closure, Wrapper, Worker, ModeArgs,
  752                                  Trie, Status, Skeleton)
  753        )
  754    ;   start_moded_tabling_2(Closure, Wrapper, Worker, ModeArgs,
  755                              Trie, Status, Skeleton)
  756    ).
  757
  758start_moded_tabling_2(_Closure, Wrapper, Worker, ModeArgs,
  759                      Trie, Status, Skeleton) :-
  760    (   Status == complete
  761    ->  moded_gen_answer(Trie, Skeleton, ModeArgs)
  762    ;   fresh_status(Status, SCC, WorkList)
  763    ->  '$tbl_leader'(SCC,
  764                      moded_run_leader(Wrapper, Skeleton/ModeArgs,
  765                                       Worker, SCC, WorkList, LStatus),
  766                      Wrapper, _OldCurrent, Trie),
  767        tdebug(schedule, 'Leader ~p done, modeargs = ~p, status = ~p',
  768               [Wrapper, ModeArgs, LStatus]),
  769        moded_done_leader(LStatus, Skeleton, ModeArgs, Trie)
  770    ;   Status == invalid
  771    ->  reeval(Trie, Wrapper, Skeleton),
  772        moded_gen_answer(Trie, Skeleton, ModeArgs)
  773    ;   % = run_follower, but never fresh and Status is a worklist
  774        shift_for_copy(call_info(Skeleton/ModeArgs, Status))
  775    ).
  776
  777:- public
  778    moded_gen_answer/3.                         % XSB tables.pl
  779
  780moded_gen_answer(Trie, Skeleton, ModedArgs) :-
  781    trie_gen(Trie, Skeleton),
  782    '$tbl_answer_update_dl'(Trie, Skeleton, ModedArgs).
  783
  784'$tbl_answer'(ATrie, Skeleton, ModedArgs, Delay) :-
  785    trie_gen(ATrie, Skeleton),
  786    '$tbl_answer_c'(ATrie, Skeleton, ModedArgs, Delay).
  787
  788moded_done_leader(complete, Skeleton, ModeArgs, Trie) :-
  789    !,
  790    moded_gen_answer(Trie, Skeleton, ModeArgs).
  791moded_done_leader(final, Skeleton, ModeArgs, Trie) :-
  792    !,
  793    moded_gen_answer(Trie, Skeleton, ModeArgs).
  794moded_done_leader(_, _, _, _).
  795
  796moded_run_leader(Wrapper, SkeletonMA, Worker, SCC, Worklist, Status) :-
  797    tdebug(wl_goal(Worklist, Goal, _)),
  798    tdebug(schedule, '-> Activate component ~p for ~p', [SCC, Goal]),
  799    moded_activate(SkeletonMA, Worker, Worklist),
  800    tdebug(schedule, '-> Complete component ~p for ~p', [SCC, Goal]),
  801    completion(SCC, Status, _Clause),           % TBD: propagate
  802    tdebug(schedule, '-> Completed component ~p for ~p: ~p', [SCC, Goal, Status]),
  803    (   Status == merged
  804    ->  tdebug(merge, 'Turning leader ~p into follower', [Wrapper]),
  805        '$tbl_wkl_make_follower'(Worklist),
  806        shift_for_copy(call_info(SkeletonMA, Worklist))
  807    ;   true                                    % completed
  808    ).
  809
  810moded_activate(SkeletonMA, Worker, WorkList) :-
  811    (   reset_delays,
  812        delim(SkeletonMA, Worker, WorkList, []),
  813        fail
  814    ;   true
  815    ).
 update(+Flags, +Head, +Module, +A1, +A2, -A3, -Action) is semidet
Update the aggregated value for an answer. Iff this predicate succeeds, the aggregated value is updated to A3. If Del is unified with true, A1 should be deleted.
Arguments:
Flags- is a bit mask telling which of A1 and A2 are unconditional
Head- is the head of the predicate
Module- is the module of the predicate
A1- is the currently aggregated value
A2- is the newly produced value
Action- is one of
  • delete to replace the old answer with the new
  • keep to keep the old answer and add the new
  • done to stop the update process
  833:- public
  834    update/7.  835
  836% both unconditional
  837update(0b11, Wrapper, M, Agg, New, Next, delete) :-
  838    !,
  839    M:'$table_update'(Wrapper, Agg, New, Next),
  840    Agg \=@= Next.
  841% old unconditional, new conditional
  842update(0b10, Wrapper, M, Agg, New, Next, keep) :-
  843    !,
  844    M:'$table_update'(Wrapper, Agg, New, Next0),
  845    (   Next0 =@= Agg
  846    ->  Next = Agg
  847    ;   Next = Next0
  848    ).
  849% old conditional, new unconditional,
  850update(0b01, Wrapper, M, Agg, New, Next, keep) :-
  851    !,
  852    M:'$table_update'(Wrapper, New, Agg, Next0),
  853    (   Next0 =@= Agg
  854    ->  Next = Agg
  855    ;   Next = Next0
  856    ).
  857% both conditional
  858update(0b00, _Wrapper, _M, _Agg, New, New, keep) :-
  859    !.
 completion(+Component, -Status, -Clause) is det
Wakeup suspended goals until no new answers are generated. Status is one of merged, completed or final. If Status is not merged, Clause is the answer trie of the Component leader or a compiled representation of it. See done_leader/3.
  868completion(SCC, Status, Clause) :-
  869    (   '$tbl_pop_worklist'(SCC, WorkList)
  870    ->  (   '$tbl_set_delay_list'([]),          % reset_delays
  871            tdebug(wl_goal(WorkList, Goal, _)),
  872            tdebug(schedule, 'Complete ~p in ~p', [Goal, scc(SCC)]),
  873            (   completion_step(WorkList)
  874            ;   completion_(SCC)
  875            ),
  876            fail
  877        ;   true
  878        )
  879    ;   true
  880    ),
  881    '$tbl_table_complete_all'(SCC, Status, Clause),
  882    tdebug(schedule, 'SCC ~p: ~p', [scc(SCC), Status]).
  883
  884completion_(SCC) :-
  885    repeat,
  886    (   '$tbl_pop_worklist'(SCC, WorkList)
  887    ->  tdebug(wl_goal(WorkList, Goal, _)),
  888        tdebug(schedule, 'Complete ~p in ~p', [Goal, scc(SCC)]),
  889        completion_step(WorkList)
  890    ;   !
  891    ).
 $tbl_wkl_work(+WorkList, -Answer, -Continuation, -Wrapper, -TargetWorklist, -Delays) is nondet
True when Continuation needs to run with Answer and possible answers need to be added to TargetWorklist. The remaining arguments are there to restore variable bindings and restore the delay list.

The suspension added by '$tbl_wkl_add_suspension'/2 is a term dependency(SrcWrapper, Continuation, Wrapper, WorkList, Delays). Note that:

Arguments:
Answer- is the answer term from the answer cluster (node in the answer trie). For answer subsumption it is a term Ret/ModeArgs
Goal- to Delays are extracted from the dependency/5 term in the same order.
  922:- if(current_prolog_flag(prolog_debug, true)).  923completion_step(SourceWL) :-
  924    '$tbl_wkl_work'(SourceWL,
  925                    Answer, Continuation, TargetSkeleton, TargetWL, Delays),
  926    tdebug(wl_goal(SourceWL, SourceGoal, _)),
  927    tdebug(wl_goal(TargetWL, TargetGoal, _Skeleton)),
  928    tdebug('$tbl_add_global_delays'(Delays, AllDelays)),
  929    tdebug(delay_goals(AllDelays, Cond)),
  930    tdebug(schedule, 'Resuming ~p, calling ~p with ~p (delays = ~p)',
  931           [TargetGoal, SourceGoal, Answer, Cond]),
  932    delim(TargetSkeleton, Continuation, TargetWL, Delays),
  933    fail.
  934:- else.  935completion_step(SourceWL) :-                    % inlines delim/4
  936    '$tbl_wkl_work'(SourceWL,
  937                    _Answer, Continuation, TargetSkeleton, TargetWL, Delays),
  938    '$tbl_reset'(Continuation, SourceCall, Cont,
  939                 TargetWL, TargetSkeleton, Delays),
  940    delim_suspended(SourceCall, Cont, TargetSkeleton, TargetWL, Delays),
  941    fail.
  942:- endif.  943
  944
  945		 /*******************************
  946		 *     STRATIFIED NEGATION	*
  947		 *******************************/
 tnot(:Goal)
Tabled negation.

(*): Only variant tabling is allowed under tnot/1.

  955tnot(Goal0) :-
  956    '$tnot_implementation'(Goal0, Goal),        % verifies Goal is tabled
  957    (   '$tbl_existing_variant_table'(_, Goal, Trie, Status, Skeleton),
  958        Status \== invalid
  959    ->  '$idg_add_edge'(Trie),
  960        (   '$tbl_answer_dl'(Trie, _, true)
  961        ->  fail
  962        ;   '$tbl_answer_dl'(Trie, _, _)
  963        ->  tdebug(tnot, 'tnot: adding ~p to delay list', [Goal]),
  964            add_delay(Trie)
  965        ;   Status == complete
  966        ->  true
  967        ;   negation_suspend(Goal, Skeleton, Status)
  968        )
  969    ;   tdebug(tnot, 'tnot: ~p: fresh', [Goal]),
  970        (   '$wrapped_implementation'(Goal, table, Implementation), % see (*)
  971            functor(Implementation, Closure, _),
  972            start_tabling(Closure, Goal, Implementation),
  973            fail
  974        ;   '$tbl_existing_variant_table'(_, Goal, Trie, NewStatus, NewSkeleton),
  975            tdebug(tnot, 'tnot: fresh ~p now ~p', [Goal, NewStatus]),
  976            (   '$tbl_answer_dl'(Trie, _, true)
  977            ->  fail
  978            ;   '$tbl_answer_dl'(Trie, _, _)
  979            ->  add_delay(Trie)
  980            ;   NewStatus == complete
  981            ->  true
  982            ;   negation_suspend(Goal, NewSkeleton, NewStatus)
  983            )
  984        )
  985    ).
  986
  987floundering(Goal) :-
  988    format(string(Comment), 'Floundering goal in tnot/1: ~p', [Goal]),
  989    throw(error(instantiation_error, context(_Stack, Comment))).
 negation_suspend(+Goal, +Skeleton, +Worklist)
Suspend Worklist due to negation. This marks the worklist as dealing with a negative literal and suspend.

The completion step will resume negative worklists that have no solutions, causing this to succeed.

 1000negation_suspend(Wrapper, Skeleton, Worklist) :-
 1001    tdebug(tnot, 'negation_suspend ~p (wl=~p)', [Wrapper, Worklist]),
 1002    '$tbl_wkl_negative'(Worklist),
 1003    shift_for_copy(call_info(Skeleton, tnot(Worklist))),
 1004    tdebug(tnot, 'negation resume ~p (wl=~p)', [Wrapper, Worklist]),
 1005    '$tbl_wkl_is_false'(Worklist).
 not_exists(:P) is semidet
Tabled negation for non-ground goals. This predicate uses the tabled meta-predicate tabled_call/1. The tables for tabled_call/1 must be cleared if `the world changes' as well as to avoid aggregating too many variants.
 1014not_exists(Goal) :-
 1015    ground(Goal),
 1016    '$get_predicate_attribute'(Goal, tabled, 1),
 1017    !,
 1018    tnot(Goal).
 1019not_exists(Goal) :-
 1020    (   tabled_call(Goal), fail
 1021    ;   tnot(tabled_call(Goal))
 1022    ).
 1023
 1024		 /*******************************
 1025		 *           DELAY LISTS	*
 1026		 *******************************/
 1027
 1028add_delay(Delay) :-
 1029    '$tbl_delay_list'(DL0),
 1030    '$tbl_set_delay_list'([Delay|DL0]).
 1031
 1032reset_delays :-
 1033    '$tbl_set_delay_list'([]).
 $wfs_call(:Goal, :Delays)
Call Goal and provide WFS delayed goals as a conjunction in Delays. This predicate is the internal version of call_delays/2 from library(wfs).
 1041'$wfs_call'(Goal, M:Delays) :-
 1042    '$tbl_delay_list'(DL0),
 1043    reset_delays,
 1044    call(Goal),
 1045    '$tbl_delay_list'(DL1),
 1046    (   delay_goals(DL1, M, Delays)
 1047    ->  true
 1048    ;   Delays = undefined
 1049    ),
 1050    '$append'(DL0, DL1, DL),
 1051    '$tbl_set_delay_list'(DL).
 1052
 1053delay_goals([], _, true) :-
 1054    !.
 1055delay_goals([AT+AN|T], M, Goal) :-
 1056    !,
 1057    (   integer(AN)
 1058    ->  at_delay_goal(AT, M, G0, Answer, Moded),
 1059        (   '$tbl_is_trienode'(Moded)
 1060        ->  trie_term(AN, Answer)
 1061        ;   true                        % TBD: Generated moded answer
 1062        )
 1063    ;   AN = Skeleton/ModeArgs
 1064    ->  '$tbl_table_status'(AT, _, M1:GNoModes, Skeleton),
 1065        M1:'$table_mode'(G0plain, GNoModes, ModeArgs),
 1066        G0 = M1:G0plain
 1067    ;   '$tbl_table_status'(AT, _, G0, AN)
 1068    ),
 1069    GN = G0,
 1070    (   T == []
 1071    ->  Goal = GN
 1072    ;   Goal = (GN,GT),
 1073        delay_goals(T, M, GT)
 1074    ).
 1075delay_goals([AT|T], M, Goal) :-
 1076    atrie_goal(AT, G0),
 1077    unqualify_goal(G0, M, G1),
 1078    GN = tnot(G1),
 1079    (   T == []
 1080    ->  Goal = GN
 1081    ;   Goal = (GN,GT),
 1082        delay_goals(T, M, GT)
 1083    ).
 1084
 1085at_delay_goal(tnot(Trie), M, tnot(Goal), Skeleton, Moded) :-
 1086    is_trie(Trie),
 1087    !,
 1088    at_delay_goal(Trie, M, Goal, Skeleton, Moded).
 1089at_delay_goal(Trie, M, Goal, Skeleton, Moded) :-
 1090    is_trie(Trie),
 1091    !,
 1092    '$tbl_table_status'(Trie, _Status, M2:Variant, Skeleton),
 1093    M2:'$table_mode'(Goal0, Variant, Moded),
 1094    unqualify_goal(M2:Goal0, M, Goal).
 1095
 1096atrie_goal(Trie, M:Goal) :-
 1097    '$tbl_table_status'(Trie, _Status, M:Variant, _Skeleton),
 1098    M:'$table_mode'(Goal, Variant, _Moded).
 1099
 1100unqualify_goal(M:Goal, M, Goal0) :-
 1101    !,
 1102    Goal0 = Goal.
 1103unqualify_goal(Goal, _, Goal).
 1104
 1105
 1106                 /*******************************
 1107                 *            CLEANUP           *
 1108                 *******************************/
 abolish_all_tables
Remove all tables. This is normally used to free up the space or recompute the result after predicates on which the result for some tabled predicates depend.

Abolishes both local and shared tables. Possibly incomplete tables are marked for destruction upon completion. The dependency graphs for incremental and monotonic tabling are reclaimed as well.

 1120abolish_all_tables :-
 1121    (   '$tbl_abolish_local_tables'
 1122    ->  true
 1123    ;   true
 1124    ),
 1125    (   '$tbl_variant_table'(VariantTrie),
 1126        trie_gen(VariantTrie, _, Trie),
 1127        '$tbl_destroy_table'(Trie),
 1128        fail
 1129    ;   true
 1130    ).
 1131
 1132abolish_private_tables :-
 1133    (   '$tbl_abolish_local_tables'
 1134    ->  true
 1135    ;   (   '$tbl_local_variant_table'(VariantTrie),
 1136            trie_gen(VariantTrie, _, Trie),
 1137            '$tbl_destroy_table'(Trie),
 1138            fail
 1139        ;   true
 1140        )
 1141    ).
 1142
 1143abolish_shared_tables :-
 1144    (   '$tbl_global_variant_table'(VariantTrie),
 1145        trie_gen(VariantTrie, _, Trie),
 1146        '$tbl_destroy_table'(Trie),
 1147        fail
 1148    ;   true
 1149    ).
 abolish_table_subgoals(:Subgoal) is det
Abolish all tables that unify with SubGoal.
To be done
- : SubGoal must be callable. Should we allow for more general patterns?
 1158abolish_table_subgoals(SubGoal0) :-
 1159    '$tbl_implementation'(SubGoal0, M:SubGoal),
 1160    !,
 1161    '$must_be'(acyclic, SubGoal),
 1162    (   '$tbl_variant_table'(VariantTrie),
 1163        trie_gen(VariantTrie, M:SubGoal, Trie),
 1164        '$tbl_destroy_table'(Trie),
 1165        fail
 1166    ;   true
 1167    ).
 1168abolish_table_subgoals(_).
 abolish_module_tables(+Module) is det
Abolish all tables for predicates associated with the given module.
 1174abolish_module_tables(Module) :-
 1175    '$must_be'(atom, Module),
 1176    '$tbl_variant_table'(VariantTrie),
 1177    current_module(Module),
 1178    !,
 1179    forall(trie_gen(VariantTrie, Module:_, Trie),
 1180           '$tbl_destroy_table'(Trie)).
 1181abolish_module_tables(_).
 abolish_nonincremental_tables is det
Abolish all tables that are not related to incremental predicates.
 1187abolish_nonincremental_tables :-
 1188    (   '$tbl_variant_table'(VariantTrie),
 1189        trie_gen(VariantTrie, _, Trie),
 1190        '$tbl_table_status'(Trie, Status, Goal, _),
 1191        (   Status == complete
 1192        ->  true
 1193        ;   '$permission_error'(abolish, incomplete_table, Trie)
 1194        ),
 1195        \+ predicate_property(Goal, incremental),
 1196        '$tbl_destroy_table'(Trie),
 1197        fail
 1198    ;   true
 1199    ).
 abolish_nonincremental_tables(+Options)
Allow for skipping incomplete tables while abolishing.
To be done
- Mark tables for destruction such that they are abolished when completed.
 1208abolish_nonincremental_tables(Options) :-
 1209    (   Options = on_incomplete(Action)
 1210    ->  Action == skip
 1211    ;   '$option'(on_incomplete(skip), Options)
 1212    ),
 1213    !,
 1214    (   '$tbl_variant_table'(VariantTrie),
 1215        trie_gen(VariantTrie, _, Trie),
 1216        '$tbl_table_status'(Trie, complete, Goal, _),
 1217        \+ predicate_property(Goal, incremental),
 1218        '$tbl_destroy_table'(Trie),
 1219        fail
 1220    ;   true
 1221    ).
 1222abolish_nonincremental_tables(_) :-
 1223    abolish_nonincremental_tables.
 1224
 1225
 1226                 /*******************************
 1227                 *        EXAMINE TABLES        *
 1228                 *******************************/
 current_table(:Variant, -Trie) is nondet
True when Trie is the answer table for Variant. If Variant has an unbound module or goal, all possible answer tries are generated, otherwise Variant is considered a fully instantiated variant and the predicate is semidet.
 1237current_table(Variant, Trie) :-
 1238    ct_generate(Variant),
 1239    !,
 1240    current_table_gen(Variant, Trie).
 1241current_table(Variant, Trie) :-
 1242    current_table_lookup(Variant, Trie),
 1243    !.
 1244
 1245current_table_gen(M:Variant, Trie) :-
 1246    '$tbl_local_variant_table'(VariantTrie),
 1247    trie_gen(VariantTrie, M:NonModed, Trie),
 1248    M:'$table_mode'(Variant, NonModed, _Moded).
 1249current_table_gen(M:Variant, Trie) :-
 1250    '$tbl_global_variant_table'(VariantTrie),
 1251    trie_gen(VariantTrie, M:NonModed, Trie),
 1252    \+ '$tbl_table_status'(Trie, fresh), % shared tables are not destroyed
 1253    M:'$table_mode'(Variant, NonModed, _Moded).
 1254
 1255current_table_lookup(M:Variant, Trie) :-
 1256    M:'$table_mode'(Variant, NonModed, _Moded),
 1257    '$tbl_local_variant_table'(VariantTrie),
 1258    trie_lookup(VariantTrie, M:NonModed, Trie).
 1259current_table_lookup(M:Variant, Trie) :-
 1260    M:'$table_mode'(Variant, NonModed, _Moded),
 1261    '$tbl_global_variant_table'(VariantTrie),
 1262    trie_lookup(VariantTrie, NonModed, Trie),
 1263    \+ '$tbl_table_status'(Trie, fresh).
 1264
 1265ct_generate(M:Variant) :-
 1266    (   var(Variant)
 1267    ->  true
 1268    ;   var(M)
 1269    ).
 1270
 1271                 /*******************************
 1272                 *      WRAPPER GENERATION      *
 1273                 *******************************/
 1274
 1275:- multifile
 1276    system:term_expansion/2,
 1277    tabled/2. 1278:- dynamic
 1279    system:term_expansion/2. 1280
 1281wrappers(Spec, M) -->
 1282    { tabling_defaults(
 1283          [ (table_incremental=true)            - (incremental=true),
 1284            (table_shared=true)                 - (tshared=true),
 1285            (table_subsumptive=true)            - ((mode)=subsumptive),
 1286            call(subgoal_size_restraint(Level)) - (subgoal_abstract=Level)
 1287          ],
 1288          #{}, Defaults)
 1289    },
 1290    wrappers(Spec, M, Defaults).
 1291
 1292wrappers(Var, _, _) -->
 1293    { var(Var),
 1294      !,
 1295      '$instantiation_error'(Var)
 1296    }.
 1297wrappers(M:Spec, _, Opts) -->
 1298    !,
 1299    { '$must_be'(atom, M) },
 1300    wrappers(Spec, M, Opts).
 1301wrappers(Spec as Options, M, Opts0) -->
 1302    !,
 1303    { table_options(Options, Opts0, Opts) },
 1304    wrappers(Spec, M, Opts).
 1305wrappers((A,B), M, Opts) -->
 1306    !,
 1307    wrappers(A, M, Opts),
 1308    wrappers(B, M, Opts).
 1309wrappers(Name//Arity, M, Opts) -->
 1310    { atom(Name), integer(Arity), Arity >= 0,
 1311      !,
 1312      Arity1 is Arity+2
 1313    },
 1314    wrappers(Name/Arity1, M, Opts).
 1315wrappers(Name/Arity, Module, Opts) -->
 1316    { '$option'(mode(TMode), Opts, variant),
 1317      atom(Name), integer(Arity), Arity >= 0,
 1318      !,
 1319      functor(Head, Name, Arity),
 1320      '$tbl_trienode'(Reserved)
 1321    },
 1322    qualify(Module,
 1323            [ '$tabled'(Head, TMode),
 1324              '$table_mode'(Head, Head, Reserved)
 1325            ]),
 1326    [ (:- initialization('$wrap_tabled'(Module:Head, Opts), now))
 1327    ].
 1328wrappers(ModeDirectedSpec, Module, Opts) -->
 1329    { '$option'(mode(TMode), Opts, variant),
 1330      callable(ModeDirectedSpec),
 1331      !,
 1332      functor(ModeDirectedSpec, Name, Arity),
 1333      functor(Head, Name, Arity),
 1334      extract_modes(ModeDirectedSpec, Head, Variant, Modes, Moded),
 1335      updater_clauses(Modes, Head, UpdateClauses),
 1336      mode_check(Moded, ModeTest),
 1337      (   ModeTest == true
 1338      ->  WrapClause = '$wrap_tabled'(Module:Head, Opts),
 1339          TVariant = Head
 1340      ;   WrapClause = '$moded_wrap_tabled'(Module:Head, Opts, ModeTest,
 1341                                            Module:Variant, Moded),
 1342          TVariant = Variant
 1343      )
 1344    },
 1345    qualify(Module,
 1346            [ '$tabled'(Head, TMode),
 1347              '$table_mode'(Head, TVariant, Moded)
 1348            ]),
 1349    [ (:- initialization(WrapClause, now))
 1350    ],
 1351    qualify(Module, UpdateClauses).
 1352wrappers(TableSpec, _M, _Opts) -->
 1353    { '$type_error'(table_declaration, TableSpec)
 1354    }.
 1355
 1356qualify(Module, List) -->
 1357    { prolog_load_context(module, Module) },
 1358    !,
 1359    clist(List).
 1360qualify(Module, List) -->
 1361    qlist(List, Module).
 1362
 1363clist([])    --> [].
 1364clist([H|T]) --> [H], clist(T).
 1365
 1366qlist([], _)    --> [].
 1367qlist([H|T], M) --> [M:H], qlist(T, M).
 1368
 1369
 1370tabling_defaults([], Dict, Dict).
 1371tabling_defaults([Condition-(Opt=Value)|T], Dict0, Dict) :-
 1372    (   tabling_default(Condition)
 1373    ->  Dict1 = Dict0.put(Opt,Value)
 1374    ;   Dict1 = Dict0
 1375    ),
 1376    tabling_defaults(T, Dict1, Dict).
 1377
 1378tabling_default(Flag=FValue) :-
 1379    !,
 1380    current_prolog_flag(Flag, FValue).
 1381tabling_default(call(Term)) :-
 1382    call(Term).
 1383
 1384% Called from wrappers//2.
 1385
 1386subgoal_size_restraint(Level) :-
 1387    current_prolog_flag(max_table_subgoal_size_action, abstract),
 1388    current_prolog_flag(max_table_subgoal_size, Level).
 table_options(+Options, +OptDictIn, -OptDictOut)
Handler the ... as options ... construct.
 1394table_options(Options, _Opts0, _Opts) :-
 1395    var(Options),
 1396    '$instantiation_error'(Options).
 1397table_options((A,B), Opts0, Opts) :-
 1398    !,
 1399    table_options(A, Opts0, Opts1),
 1400    table_options(B, Opts1, Opts).
 1401table_options(subsumptive, Opts0, Opts1) :-
 1402    !,
 1403    put_dict(mode, Opts0, subsumptive, Opts1).
 1404table_options(variant, Opts0, Opts1) :-
 1405    !,
 1406    put_dict(mode, Opts0, variant, Opts1).
 1407table_options(incremental, Opts0, Opts1) :-
 1408    !,
 1409    put_dict(#{incremental:true,opaque:false}, Opts0, Opts1).
 1410table_options(monotonic, Opts0, Opts1) :-
 1411    !,
 1412    put_dict(monotonic, Opts0, true, Opts1).
 1413table_options(opaque, Opts0, Opts1) :-
 1414    !,
 1415    put_dict(#{incremental:false,opaque:true}, Opts0, Opts1).
 1416table_options(lazy, Opts0, Opts1) :-
 1417    !,
 1418    put_dict(lazy, Opts0, true, Opts1).
 1419table_options(dynamic, Opts0, Opts1) :-
 1420    !,
 1421    put_dict(dynamic, Opts0, true, Opts1).
 1422table_options(shared, Opts0, Opts1) :-
 1423    !,
 1424    put_dict(tshared, Opts0, true, Opts1).
 1425table_options(private, Opts0, Opts1) :-
 1426    !,
 1427    put_dict(tshared, Opts0, false, Opts1).
 1428table_options(max_answers(Count), Opts0, Opts1) :-
 1429    !,
 1430    restraint(max_answers, Count, Opts0, Opts1).
 1431table_options(subgoal_abstract(Size), Opts0, Opts1) :-
 1432    !,
 1433    restraint(subgoal_abstract, Size, Opts0, Opts1).
 1434table_options(answer_abstract(Size), Opts0, Opts1) :-
 1435    !,
 1436    restraint(answer_abstract, Size, Opts0, Opts1).
 1437table_options(Opt, _, _) :-
 1438    '$domain_error'(table_option, Opt).
 1439
 1440restraint(Name, Value0, Opts0, Opts) :-
 1441    '$table_option'(Value0, Value),
 1442    (   Value < 0
 1443    ->  Opts = Opts0
 1444    ;   put_dict(Name, Opts0, Value, Opts)
 1445    ).
 mode_check(+Moded, -TestCode)
Enforce the output arguments of a mode-directed tabled predicate to be unbound.
 1453mode_check(Moded, Check) :-
 1454    var(Moded),
 1455    !,
 1456    Check = (var(Moded)->true;'$uninstantiation_error'(Moded)).
 1457mode_check(Moded, true) :-
 1458    '$tbl_trienode'(Moded),
 1459    !.
 1460mode_check(Moded, (Test->true;'$tabling':instantiated_moded_arg(Vars))) :-
 1461    Moded =.. [s|Vars],
 1462    var_check(Vars, Test).
 1463
 1464var_check([H|T], Test) :-
 1465    (   T == []
 1466    ->  Test = var(H)
 1467    ;   Test = (var(H),Rest),
 1468        var_check(T, Rest)
 1469    ).
 1470
 1471:- public
 1472    instantiated_moded_arg/1. 1473
 1474instantiated_moded_arg(Vars) :-
 1475    '$member'(V, Vars),
 1476    \+ var(V),
 1477    '$uninstantiation_error'(V).
 extract_modes(+ModeSpec, +Head, -Variant, -Modes, -ModedAnswer) is det
Split Head into its variant and term that matches the moded arguments.
Arguments:
ModedAnswer- is a term that captures that value of all moded arguments of an answer. If there is only one, this is the value itself. If there are multiple, this is a term s(A1,A2,...)
 1489extract_modes(ModeSpec, Head, Variant, Modes, ModedAnswer) :-
 1490    compound(ModeSpec),
 1491    !,
 1492    compound_name_arguments(ModeSpec, Name, ModeSpecArgs),
 1493    compound_name_arguments(Head, Name, HeadArgs),
 1494    separate_args(ModeSpecArgs, HeadArgs, VariantArgs, Modes, ModedArgs),
 1495    length(ModedArgs, Count),
 1496    atomic_list_concat([$,Name,$,Count], VName),
 1497    Variant =.. [VName|VariantArgs],
 1498    (   ModedArgs == []
 1499    ->  '$tbl_trienode'(ModedAnswer)
 1500    ;   ModedArgs = [ModedAnswer]
 1501    ->  true
 1502    ;   ModedAnswer =.. [s|ModedArgs]
 1503    ).
 1504extract_modes(Atom, Atom, Variant, [], ModedAnswer) :-
 1505    atomic_list_concat([$,Atom,$,0], Variant),
 1506    '$tbl_trienode'(ModedAnswer).
 separate_args(+ModeSpecArgs, +HeadArgs, -NoModesArgs, -Modes, -ModeArgs) is det
Split the arguments in those that need to be part of the variant identity (NoModesArgs) and those that are aggregated (ModeArgs).
Arguments:
Args- seems a copy of ModeArgs, why?
 1516separate_args([], [], [], [], []).
 1517separate_args([HM|TM], [H|TA], [H|TNA], Modes, TMA):-
 1518    indexed_mode(HM),
 1519    !,
 1520    separate_args(TM, TA, TNA, Modes, TMA).
 1521separate_args([M|TM], [H|TA], TNA, [M|Modes], [H|TMA]):-
 1522    separate_args(TM, TA, TNA, Modes, TMA).
 1523
 1524indexed_mode(Mode) :-                           % XSB
 1525    var(Mode),
 1526    !.
 1527indexed_mode(index).                            % YAP
 1528indexed_mode(+).                                % B
 updater_clauses(+Modes, +Head, -Clauses)
Generates a clause to update the aggregated state. Modes is a list of predicate names we apply to the state.
 1535updater_clauses([], _, []) :- !.
 1536updater_clauses([P], Head, [('$table_update'(Head, S0, S1, S2) :- Body)]) :- !,
 1537    update_goal(P, S0,S1,S2, Body).
 1538updater_clauses(Modes, Head, [('$table_update'(Head, S0, S1, S2) :- Body)]) :-
 1539    length(Modes, Len),
 1540    functor(S0, s, Len),
 1541    functor(S1, s, Len),
 1542    functor(S2, s, Len),
 1543    S0 =.. [_|Args0],
 1544    S1 =.. [_|Args1],
 1545    S2 =.. [_|Args2],
 1546    update_body(Modes, Args0, Args1, Args2, true, Body).
 1547
 1548update_body([], _, _, _, Body, Body).
 1549update_body([P|TM], [A0|Args0], [A1|Args1], [A2|Args2], Body0, Body) :-
 1550    update_goal(P, A0,A1,A2, Goal),
 1551    mkconj(Body0, Goal, Body1),
 1552    update_body(TM, Args0, Args1, Args2, Body1, Body).
 1553
 1554update_goal(Var, _,_,_, _) :-
 1555    var(Var),
 1556    !,
 1557    '$instantiation_error'(Var).
 1558update_goal(lattice(M:PI), S0,S1,S2, M:Goal) :-
 1559    !,
 1560    '$must_be'(atom, M),
 1561    update_goal(lattice(PI), S0,S1,S2, Goal).
 1562update_goal(lattice(Name/Arity), S0,S1,S2, Goal) :-
 1563    !,
 1564    '$must_be'(oneof(integer, lattice_arity, [3]), Arity),
 1565    '$must_be'(atom, Name),
 1566    Goal =.. [Name,S0,S1,S2].
 1567update_goal(lattice(Head), S0,S1,S2, Goal) :-
 1568    compound(Head),
 1569    !,
 1570    compound_name_arity(Head, Name, Arity),
 1571    '$must_be'(oneof(integer, lattice_arity, [3]), Arity),
 1572    Goal =.. [Name,S0,S1,S2].
 1573update_goal(lattice(Name), S0,S1,S2, Goal) :-
 1574    !,
 1575    '$must_be'(atom, Name),
 1576    update_goal(lattice(Name/3), S0,S1,S2, Goal).
 1577update_goal(po(Name/Arity), S0,S1,S2, Goal) :-
 1578    !,
 1579    '$must_be'(oneof(integer, po_arity, [2]), Arity),
 1580    '$must_be'(atom, Name),
 1581    Call =.. [Name, S0, S1],
 1582    Goal = (Call -> S2 = S0 ; S2 = S1).
 1583update_goal(po(M:Name/Arity), S0,S1,S2, Goal) :-
 1584    !,
 1585    '$must_be'(atom, M),
 1586    '$must_be'(oneof(integer, po_arity, [2]), Arity),
 1587    '$must_be'(atom, Name),
 1588    Call =.. [Name, S0, S1],
 1589    Goal = (M:Call -> S2 = S0 ; S2 = S1).
 1590update_goal(po(M:Name), S0,S1,S2, Goal) :-
 1591    !,
 1592    '$must_be'(atom, M),
 1593    '$must_be'(atom, Name),
 1594    update_goal(po(M:Name/2), S0,S1,S2, Goal).
 1595update_goal(po(Name), S0,S1,S2, Goal) :-
 1596    !,
 1597    '$must_be'(atom, Name),
 1598    update_goal(po(Name/2), S0,S1,S2, Goal).
 1599update_goal(Alias, S0,S1,S2, Goal) :-
 1600    update_alias(Alias, Update),
 1601    !,
 1602    update_goal(Update, S0,S1,S2, Goal).
 1603update_goal(Mode, _,_,_, _) :-
 1604    '$domain_error'(tabled_mode, Mode).
 1605
 1606update_alias(first, lattice('$tabling':first/3)).
 1607update_alias(-,     lattice('$tabling':first/3)).
 1608update_alias(last,  lattice('$tabling':last/3)).
 1609update_alias(min,   lattice('$tabling':min/3)).
 1610update_alias(max,   lattice('$tabling':max/3)).
 1611update_alias(sum,   lattice('$tabling':sum/3)).
 1612
 1613mkconj(true, G,  G) :- !.
 1614mkconj(G1,   G2, (G1,G2)).
 1615
 1616
 1617		 /*******************************
 1618		 *          AGGREGATION		*
 1619		 *******************************/
 first(+S0, +S1, -S) is det
 last(+S0, +S1, -S) is det
 min(+S0, +S1, -S) is det
 max(+S0, +S1, -S) is det
 sum(+S0, +S1, -S) is det
Implement YAP tabling modes.
 1629:- public first/3, last/3, min/3, max/3, sum/3. 1630
 1631first(S, _, S).
 1632last(_, S, S).
 1633min(S0, S1, S) :- (S0 @< S1 -> S = S0 ; S = S1).
 1634max(S0, S1, S) :- (S0 @> S1 -> S = S0 ; S = S1).
 1635sum(S0, S1, S) :- S is S0+S1.
 1636
 1637
 1638		 /*******************************
 1639		 *      DYNAMIC PREDICATES	*
 1640		 *******************************/
 $set_table_wrappers(:Head)
Clear/add wrappers and notifications to trap dynamic predicates. This is required both for incremental and monotonic tabling.
 1647'$set_table_wrappers'(Pred) :-
 1648    (   '$get_predicate_attribute'(Pred, incremental, 1),
 1649        \+ '$get_predicate_attribute'(Pred, opaque, 1)
 1650    ->  wrap_incremental(Pred)
 1651    ;   unwrap_incremental(Pred)
 1652    ),
 1653    (   '$get_predicate_attribute'(Pred, monotonic, 1)
 1654    ->  wrap_monotonic(Pred)
 1655    ;   unwrap_monotonic(Pred)
 1656    ).
 1657
 1658		 /*******************************
 1659		 *       MONOTONIC TABLING	*
 1660		 *******************************/
 mon_assert_dep(+Dependency, +Continuation, +Skel, +ATrie) is det
Create a dependency for monotonic tabling. Skel and ATrie are the target trie for solutions of Continuation.
 1667mon_assert_dep(dependency(Dynamic), Cont, Skel, ATrie) :-
 1668    '$idg_add_mono_dyn_dep'(Dynamic,
 1669                            dependency(Dynamic, Cont, Skel),
 1670                            ATrie).
 1671mon_assert_dep(dependency(SrcSkel, SrcTrie, IsMono), Cont, Skel, ATrie) :-
 1672    '$idg_add_monotonic_dep'(SrcTrie,
 1673                             dependency(SrcSkel, IsMono, Cont, Skel),
 1674                             ATrie).
 monotonic_affects(+SrcTrie, +SrcReturn, -IsMono, -Continuation, -Return, -Atrie)
Dependency between two monotonic tables. If SrcReturn is added to SrcTrie we must add all answers for Return of Continuation to Atrie. IsMono shares with Continuation and is used in start_tabling/3 to distinguish normal tabled call from propagation.

A table with more than one monotonic dependency indexes them by their skeleton, so only the dependencies whose skeleton unifies with SrcReturn are visited rather than every dependency of SrcTrie.

 1688monotonic_affects(SrcTrie, SrcSkel, IsMono, Cont, Skel, ATrie) :-
 1689    (   '$idg_mono_index'(SrcTrie, Index)
 1690    ->  '$trie_gen_node'(Index, SrcSkel-ATrie, Leaf),
 1691        '$idg_mono_index_deps'(SrcTrie, Leaf, ATrie,
 1692                               dependency(SrcSkel, IsMono, Cont, Skel))
 1693    ;   '$idg_mono_affects_eager'(SrcTrie, ATrie,
 1694                                  dependency(SrcSkel, IsMono, Cont, Skel))
 1695    ).
 monotonic_dyn_affects(:Head, -Continuation, -Return, -ATrie)
Dynamic predicate that maintains the dependency from a monotonic
 1701monotonic_dyn_affects(Head, Cont, Skel, ATrie) :-
 1702    dyn_affected(Head, DTrie),
 1703    '$idg_mono_affects_eager'(DTrie, ATrie,
 1704                              dependency(Head, Cont, Skel)).
 wrap_monotonic(:Head)
Prepare the dynamic predicate Head for monotonic tabling. This traps calls to build the dependency graph and updates to propagate answers from new clauses through the dependency graph.
 1712wrap_monotonic(Head) :-
 1713    '$wrap_predicate'(Head, monotonic, _Closure, Wrapped,
 1714                      '$start_monotonic'(Head, Wrapped)),
 1715    '$pi_head'(PI, Head),
 1716    prolog_listen(PI, monotonic_update).
 unwrap_monotonic(+Head)
Remove the monotonic wrappers and dependencies.
 1722unwrap_monotonic(Head) :-
 1723    '$pi_head'(PI, Head),
 1724    (   unwrap_predicate(PI, monotonic)
 1725    ->  prolog_unlisten(PI, monotonic_update)
 1726    ;   true
 1727    ).
 $start_monotonic(+Head, +Wrapped)
This is called the monotonic wrapper around a dynamic predicate to collect the dependencies between the dynamic predicate and the monotonic tabled predicates.
 1735'$start_monotonic'(Head, Wrapped) :-
 1736    (   '$tbl_collect_mono_dep'
 1737    ->  shift(dependency(Head)),
 1738        tdebug(monotonic, 'Cont in $start_dynamic/2 with ~p', [Head]),
 1739        Wrapped,
 1740        tdebug(monotonic, '  --> ~p', [Head])
 1741    ;   Wrapped
 1742    ).
 monotonic_update(+Action, +ClauseRef)
Trap changes to the monotonic dynamic predicate and forward them.
 1748:- public monotonic_update/2. 1749monotonic_update(Action, ClauseRef) :-
 1750    (   atomic(ClauseRef)                       % avoid retractall, start(_)
 1751    ->  '$clause'(Head, _Body, ClauseRef, _Bindings),
 1752        mon_propagate(Action, Head, ClauseRef)
 1753    ;   true
 1754    ).
 mon_propagate(+Action, +Head, +ClauseRef)
Handle changes to a dynamic predicate as part of monotonic updates.
 1761mon_propagate(Action, Head, ClauseRef) :-
 1762    assert_action(Action),
 1763    !,
 1764    setup_call_cleanup(
 1765        '$tbl_propagate_start'(Old),
 1766        propagate_assert(Head),                 % eager monotonic dependencies
 1767        '$tbl_propagate_end'(Old)),
 1768    forall(dyn_affected(Head, ATrie),
 1769           '$mono_idg_changed'(ATrie, ClauseRef)). % lazy monotonic dependencies
 1770mon_propagate(retract, Head, _) :-
 1771    !,
 1772    mon_invalidate_dependents(Head).
 1773mon_propagate(rollback(Action), Head, _) :-
 1774    mon_propagate_rollback(Action, Head).
 1775
 1776mon_propagate_rollback(Action, _Head) :-
 1777    assert_action(Action),
 1778    !.
 1779mon_propagate_rollback(retract, Head) :-
 1780    mon_invalidate_dependents(Head).
 1781
 1782assert_action(asserta).
 1783assert_action(assertz).
 propagate_assert(+Head) is det
Propagate assertion of a dynamic clause with head Head.
 1789propagate_assert(Head) :-
 1790    tdebug(monotonic, 'Asserted ~p', [Head]),
 1791    (   monotonic_dyn_affects(Head, Cont, Skel, ATrie),
 1792        tdebug(monotonic, 'Propagating dyn ~p to ~p', [Head, ATrie]),
 1793        '$idg_set_current'(_, ATrie),
 1794        pdelim(Cont, Skel, ATrie),
 1795        fail
 1796    ;   true
 1797    ).
 incr_propagate_assert(+Head) is det
Propagate assertion of a dynamic clause with head Head, both through eager and dynamic tables.
 1804incr_propagate_assert(Head) :-
 1805    tdebug(monotonic, 'New dynamic answer ~p', [Head]),
 1806    (   dyn_affected(Head, DTrie),
 1807         '$idg_mono_affects'(DTrie, ATrie,
 1808                             dependency(Head, Cont, Skel)),
 1809        tdebug(monotonic, 'Propagating dyn ~p to ~p', [Head, ATrie]),
 1810        '$idg_set_current'(_, ATrie),
 1811        pdelim(Cont, Skel, ATrie),
 1812        fail
 1813    ;   true
 1814    ).
 propagate_answer(+SrcTrie, +SrcSkel) is det
Propagate the new answer SrcSkel to the answer table SrcTrie.
 1821propagate_answer(SrcTrie, SrcSkel) :-
 1822    (   monotonic_affects(SrcTrie, SrcSkel, true, Cont, Skel, ATrie),
 1823        tdebug(monotonic, 'Propagating tab ~p to ~p', [SrcTrie, ATrie]),
 1824        pdelim(Cont, Skel, ATrie),
 1825        fail
 1826    ;   true
 1827    ).
 pdelim(+Worker, +Skel, +ATrie)
Call Worker (a continuation) and add each binding it provides for Skel to ATrie. If a new answer is added to ATrie, using propagate_answer/2 to propagate this further. Note that we may hit new dependencies and thus we need to run this using reset/3.
To be done
- Not sure whether we need full tabling here. Need to think of test cases.
 1839pdelim(Worker, Skel, ATrie) :-
 1840    reset(Worker, Dep, Cont),
 1841    (   Cont == 0
 1842    ->  '$tbl_monotonic_add_answer'(ATrie, Skel),
 1843        propagate_answer(ATrie, Skel)
 1844    ;   mon_assert_dep(Dep, Cont, Skel, ATrie),
 1845        pdelim(Cont, Skel, ATrie)
 1846    ).
 mon_invalidate_dependents(+Head)
A non-monotonic operation was done on Head. Invalidate all dependent tables, preparing for normal incremental reevaluation on the next cycle.
 1854mon_invalidate_dependents(Head) :-
 1855    tdebug(monotonic, 'Invalidate dependents for ~p', [Head]),
 1856    forall(dyn_affected(Head, ATrie),
 1857           '$idg_mono_invalidate'(ATrie)).
 abolish_monotonic_tables
Abolish all monotonic tables and the monotonic dependency relations.
To be done
- : just prepare for incremental reevaluation?
 1865abolish_monotonic_tables :-
 1866    (   '$tbl_variant_table'(VariantTrie),
 1867        trie_gen(VariantTrie, Goal, ATrie),
 1868        '$get_predicate_attribute'(Goal, monotonic, 1),
 1869        '$tbl_destroy_table'(ATrie),
 1870        fail
 1871    ;   true
 1872    ).
 1873
 1874		 /*******************************
 1875		 *      INCREMENTAL TABLING	*
 1876		 *******************************/
 wrap_incremental(:Head) is det
Wrap an incremental dynamic predicate to be added to the IDG.
 1882wrap_incremental(Head) :-
 1883    tdebug(monotonic, 'Wrapping ~p', [Head]),
 1884    abstract_goal(Head, Abstract),
 1885    '$pi_head'(PI, Head),
 1886    (   Head == Abstract
 1887    ->  prolog_listen(PI, dyn_update)
 1888    ;   prolog_listen(PI, dyn_update(Abstract))
 1889    ).
 1890
 1891abstract_goal(M:Head, M:Abstract) :-
 1892    compound(Head),
 1893    '$get_predicate_attribute'(M:Head, abstract, 1),
 1894    !,
 1895    compound_name_arity(Head, Name, Arity),
 1896    functor(Abstract, Name, Arity).
 1897abstract_goal(Head, Head).
 dyn_update(+Action, +Context) is det
Track changes to added or removed clauses. We use '$clause'/4 because it works on erased clauses.
To be done
- Add a '$clause_head'(-Head, +ClauseRef) to only decompile the head.
 1907:- public dyn_update/2, dyn_update/3. 1908
 1909dyn_update(_Action, ClauseRef) :-
 1910    (   atomic(ClauseRef)                       % avoid retractall, start(_)
 1911    ->  '$clause'(Head, _Body, ClauseRef, _Bindings),
 1912        dyn_changed_pattern(Head)
 1913    ;   true
 1914    ).
 1915
 1916dyn_update(Abstract, _, _) :-
 1917    dyn_changed_pattern(Abstract).
 1918
 1919dyn_changed_pattern(Term) :-
 1920    forall(dyn_affected(Term, ATrie),
 1921           '$idg_changed'(ATrie)).
 1922
 1923dyn_affected(Term, ATrie) :-
 1924    '$tbl_variant_table'(VTable),
 1925    trie_gen(VTable, Term, ATrie).
 unwrap_incremental(:Head) is det
Remove dynamic predicate incremenal forwarding, reset the possible abstract property and remove possible tables.
 1932unwrap_incremental(Head) :-
 1933    '$pi_head'(PI, Head),
 1934    abstract_goal(Head, Abstract),
 1935    (   Head == Abstract
 1936    ->  prolog_unlisten(PI, dyn_update)
 1937    ;   '$set_predicate_attribute'(Head, abstract, 0),
 1938        prolog_unlisten(PI, dyn_update(_))
 1939    ),
 1940    (   '$tbl_variant_table'(VariantTrie)
 1941    ->  forall(trie_gen(VariantTrie, Head, ATrie),
 1942               '$tbl_destroy_table'(ATrie))
 1943    ;   true
 1944    ).
 reeval(+ATrie, :Goal, ?Return) is nondet
Called if the table ATrie is out-of-date (has non-zero falsecount). The answers of this predicate are the answers to Goal after re-evaluating the answer trie.

This finds all dependency paths to dynamic predicates and then evaluates the nodes in a breath-first fashion starting at the level just above the dynamic predicates and moving upwards. Bottom up evaluation is used to profit from upward propagation of not-modified events that may cause the evaluation to stop early.

Note that false paths either end in a dynamic node or a complete node. The latter happens if we have and IDG "D -> P -> Q" and we first re-evaluate P for some reason. Now Q can still be invalid after P has been re-evaluated.

Arguments:
ATrie- is the answer trie. When shared tabling, we own this trie.
Goal- is tabled goal (variant). If we run into a deadlock we need to call this.
Return- is the return skeleton. We must run trie_gen_compiled(ATrie, Return) to enumerate the answers
 1970reeval(ATrie, Goal, Return) :-
 1971    catch(try_reeval(ATrie, Goal, Return), deadlock,
 1972          retry_reeval(ATrie, Goal)).
 1973
 1974retry_reeval(ATrie, Goal) :-
 1975    '$tbl_reeval_abandon'(ATrie),
 1976    tdebug(deadlock, 'Deadlock re-evaluating ~p; retrying', [ATrie]),
 1977    sleep(0.000001),
 1978    call(Goal).
 1979
 1980try_reeval(ATrie, Goal, Return) :-
 1981    nb_current('$tbl_reeval', true),
 1982    !,
 1983    tdebug(reeval, 'Nested re-evaluation for ~p', [ATrie]),
 1984    do_reeval(ATrie, Goal, Return).
 1985try_reeval(ATrie, Goal, Return) :-
 1986    tdebug(reeval, 'Planning reeval for ~p', [ATrie]),
 1987    findall(Path, false_path(ATrie, Path), Paths0),
 1988    sort(0, @>, Paths0, Paths1),
 1989    clean_paths(Paths1, Paths),
 1990    tdebug(forall('$member'(Path, Paths),
 1991                  tdebug(reeval, '  Re-eval complete path: ~p', [Path]))),
 1992    reeval_paths(Paths, ATrie),
 1993    do_reeval(ATrie, Goal, Return).
 1994
 1995do_reeval(ATrie, Goal, Return) :-
 1996    '$tbl_reeval_prepare_top'(ATrie, Clause),
 1997    (   Clause == 0                          % complete and answer subsumption
 1998    ->  '$tbl_table_status'(ATrie, _Status, M:Variant, Return),
 1999        M:'$table_mode'(Goal0, Variant, ModeArgs),
 2000        Goal = M:Goal0,
 2001        moded_gen_answer(ATrie, Return, ModeArgs)
 2002    ;   nonvar(Clause)                       % complete
 2003    ->  trie_gen_compiled(Clause, Return)
 2004    ;   call(Goal)                           % actually re-evaluate
 2005    ).
 clean_paths(+PathsIn, -Paths)
Clean the reevaluation paths. Get rid of the head term for ranking and remove duplicate paths. Note that a Path is a list of tries, ground terms.
 2014clean_paths([], []).
 2015clean_paths([[_|Path]|T0], [Path|T]) :-
 2016    clean_paths(T0, Path, T).
 2017
 2018clean_paths([], _, []).
 2019clean_paths([[_|CPath]|T0], CPath, T) :-
 2020    !,
 2021    clean_paths(T0, CPath, T).
 2022clean_paths([[_|Path]|T0], _, [Path|T]) :-
 2023    clean_paths(T0, Path, T).
 reeval_paths(+Paths, +Atrie)
Make Atrie valid again by re-evaluating nodes in Paths. We stop as soon as Atrie is valid again. Note that we may not need to reevaluate all paths because evaluating the head of some path may include other nodes in an SCC, making them valid as well.
 2032reeval_paths([], _) :-
 2033    !.
 2034reeval_paths(BottomUp, ATrie) :-
 2035    is_invalid(ATrie),
 2036    !,
 2037    reeval_heads(BottomUp, ATrie, BottomUp1),
 2038    tdebug(assertion(BottomUp \== BottomUp1)),
 2039    '$list_to_set'(BottomUp1, BottomUp2),
 2040    reeval_paths(BottomUp2, ATrie).
 2041reeval_paths(_, _).
 2042
 2043reeval_heads(_, ATrie, []) :-                % target is valid again
 2044    \+ is_invalid(ATrie),
 2045    !.
 2046reeval_heads([], _, []).
 2047reeval_heads([[H]|B], ATrie, BT) :-          % Last one of a falsepath
 2048    reeval_node(H),
 2049    !,
 2050    reeval_heads(B, ATrie, BT).
 2051reeval_heads([[H|T]|B], ATrie, [T|BT]) :-
 2052    reeval_node(H),
 2053    !,
 2054    reeval_heads(B, ATrie, BT).
 2055reeval_heads([FP|B], ATrie, [FP|BT]) :-
 2056    reeval_heads(B, ATrie, BT).
 false_path(+Atrie, -Path) is nondet
True when Path is a list of invalid tries (bottom up, ending with ATrie). The last element of the list is a term s(Rank,Length,ATrie) that is used for sorting the paths.

If we find a table along the way that is being worked on by some other thread we wait for it.

 2068false_path(ATrie, BottomUp) :-
 2069    false_path(ATrie, Path, []),
 2070    '$reverse'(Path, BottomUp).
 2071
 2072false_path(ATrie, [ATrie|T], Seen) :-
 2073    \+ memberchk(ATrie, Seen),
 2074    '$idg_false_edge'(ATrie, Dep, Status),
 2075    tdebug(reeval, '    ~p has dependent ~p (~w)', [ATrie, Dep, Status]),
 2076    (   Status == invalid
 2077    ->  (   false_path(Dep, T, [ATrie|Seen])
 2078        ->  true
 2079        ;   length(Seen, Len),               % invalid has no dependencies:
 2080            T = [s(2, Len, [])]              % dynamic and tabled or explicitly
 2081        )                                    % invalidated
 2082    ;   status_rank(Status, Rank),
 2083        length(Seen, Len),
 2084        T = [s(Rank,Len,Dep)]
 2085    ).
 2086
 2087status_rank(dynamic,   2) :- !.
 2088status_rank(monotonic, 2) :- !.
 2089status_rank(complete,  1) :- !.
 2090status_rank(Status,    Rank) :-
 2091    var(Rank),
 2092    !,
 2093    format(user_error, 'Re-eval from status ~p~n', [Status]),
 2094    Rank = 0.
 2095status_rank(Rank,   Rank) :-
 2096    format(user_error, 'Re-eval from rank ~p~n', [Rank]).
 2097
 2098is_invalid(ATrie) :-
 2099    '$idg_falsecount'(ATrie, FalseCount),
 2100    FalseCount > 0.
 reeval_node(+ATrie) is semidet
Re-evaluate the invalid answer trie ATrie. Initially this created a nested tabling environment, but this is dropped:

Fails if the node is not ready for evaluation. This is the case if it is valid or it is a lazy table that has invalid dependencies.

 2116reeval_node(ATrie) :-
 2117    '$tbl_reeval_prepare'(ATrie, M:Variant),
 2118    !,
 2119    M:'$table_mode'(Goal0, Variant, _Moded),
 2120    Goal = M:Goal0,
 2121    tdebug(reeval, 'Re-evaluating ~p', [Goal]),
 2122    (   '$idg_reset_current',
 2123        setup_call_cleanup(
 2124            nb_setval('$tbl_reeval', true),
 2125            ignore(Goal),                    % assumes local scheduling
 2126            nb_delete('$tbl_reeval')),
 2127        fail
 2128    ;   tdebug(reeval, 'Re-evaluated ~p', [Goal])
 2129    ).
 2130reeval_node(ATrie) :-
 2131    '$mono_reeval_prepare'(ATrie, Size),
 2132    !,
 2133    reeval_monotonic_node(ATrie, Size).
 2134reeval_node(ATrie) :-
 2135    \+ is_invalid(ATrie).
 2136
 2137reeval_monotonic_node(ATrie, Size) :-
 2138    setup_call_cleanup(
 2139        '$tbl_propagate_start'(Old),
 2140        reeval_monotonic_node(ATrie, Size, Deps),
 2141        '$tbl_propagate_end'(Old)),
 2142    (   Deps == []
 2143    ->  tdebug(reeval, 'Re-evaluation for ~p complete', [ATrie])
 2144    ;   Deps == false
 2145    ->  tdebug(reeval, 'Re-evaluation for ~p queued new answers', [ATrie]),
 2146        reeval_node(ATrie)
 2147    ;   tdebug(reeval, 'Re-evaluation for ~p: new invalid deps: ~p',
 2148               [ATrie, Deps]),
 2149        reeval_nodes(Deps),
 2150        reeval_node(ATrie)
 2151    ).
 reeval_nodes(+Nodes:list(trie)) is det
After pulling in the monotonic answers into some node, this is a list if invalid dependencies. We must revaluate these and then pull in possible queued answers before we are done.
 2159reeval_nodes([]).
 2160reeval_nodes([H|T]) :-
 2161    reeval_node(H),
 2162    reeval_nodes(T).
 2163
 2164reeval_monotonic_node(ATrie, Size, Deps) :-
 2165    tdebug(reeval, 'Re-evaluating lazy monotonic ~p', [ATrie]),
 2166    (   '$idg_mono_affects_lazy'(ATrie, _0SrcTrie, Dep, DepRef, Answers),
 2167        length(Answers, Count),
 2168        '$idg_mono_empty_queue'(DepRef, Count),
 2169        (   Dep = dependency(Head, Cont, Skel)
 2170        ->  (   '$member'(ClauseRef, Answers),
 2171                '$clause'(Head, _Body, ClauseRef, _Bindings),
 2172                tdebug(monotonic, 'Propagating ~p from ~p to ~p',
 2173                       [Head, _0SrcTrie, ATrie]),
 2174                '$idg_set_current'(_, ATrie),
 2175                pdelim(Cont, Skel, ATrie),
 2176                fail
 2177            ;   true
 2178            )
 2179        ;   Dep = dependency(SrcSkel, true, Cont, Skel)
 2180        ->  (   '$member'(Node, Answers),
 2181                '$tbl_node_answer'(Node, SrcSkel),
 2182                tdebug(monotonic, 'Propagating ~p from ~p to ~p',
 2183                       [Skel, _0SrcTrie, ATrie]),
 2184                '$idg_set_current'(_, ATrie),
 2185                pdelim(Cont, Skel, ATrie),
 2186                fail
 2187            ;   true
 2188            )
 2189        ;   tdebug(monotonic, 'Skipped queued ~p, answers ~p',
 2190                   [Dep, Answers])
 2191        ),
 2192        fail
 2193    ;   '$mono_reeval_done'(ATrie, Size, Deps)
 2194    ).
 2195
 2196
 2197		 /*******************************
 2198		 *      EXPAND DIRECTIVES	*
 2199		 *******************************/
 2200
 2201system:term_expansion((:- table(Preds)), Expansion) :-
 2202    \+ current_prolog_flag(xref, true),
 2203    prolog_load_context(module, M),
 2204    phrase(wrappers(Preds, M), Clauses),
 2205    multifile_decls(Clauses, Directives0),
 2206    sort(Directives0, Directives),
 2207    '$append'(Directives, Clauses, Expansion).
 2208
 2209multifile_decls([], []).
 2210multifile_decls([H0|T0], [H|T]) :-
 2211    multifile_decl(H0, H),
 2212    !,
 2213    multifile_decls(T0, T).
 2214multifile_decls([_|T0], T) :-
 2215    multifile_decls(T0, T).
 2216
 2217multifile_decl(M:(Head :- _Body), (:- multifile(M:Name/Arity))) :-
 2218    !,
 2219    functor(Head, Name, Arity).
 2220multifile_decl(M:Head, (:- multifile(M:Name/Arity))) :-
 2221    !,
 2222    functor(Head, Name, Arity).
 2223multifile_decl((Head :- _Body), (:- multifile(Name/Arity))) :-
 2224    !,
 2225    functor(Head, Name, Arity).
 2226multifile_decl(Head, (:- multifile(Name/Arity))) :-
 2227    !,
 2228    Head \= (:-_),
 2229    functor(Head, Name, Arity).
 2230
 2231
 2232		 /*******************************
 2233		 *      ANSWER COMPLETION	*
 2234		 *******************************/
 2235
 2236:- public answer_completion/2.
 answer_completion(+AnswerTrie, +Return) is det
Find positive loops in the residual program and remove the corresponding answers, possibly causing additional simplification. This is called from C if simplify_component() detects there are conditional answers after simplification.

Note that we are called recursively from C. Our caller prepared a clean new tabling environment and restores the old one after this predicate terminates.

author
- This code is by David Warren as part of XSB.
See also
- called from C, pl-tabling.c, answer_completion()
 2252answer_completion(AnswerTrie, Return) :-
 2253    tdebug(trie_goal(AnswerTrie, Goal, _Return)),
 2254    tdebug(ac(start), 'START: Answer completion for ~p', [Goal]),
 2255    call_cleanup(answer_completion_guarded(AnswerTrie, Return, Propagated),
 2256                 abolish_table_subgoals(eval_subgoal_in_residual(_,_))),
 2257    (   Propagated > 0
 2258    ->  answer_completion(AnswerTrie, Return)
 2259    ;   true
 2260    ).
 2261
 2262answer_completion_guarded(AnswerTrie, Return, Propagated) :-
 2263    (   eval_subgoal_in_residual(AnswerTrie, Return),
 2264        fail
 2265    ;   true
 2266    ),
 2267    delete_answers_for_failing_calls(Propagated),
 2268    (   Propagated == 0
 2269    ->  mark_succeeding_calls_as_answer_completed
 2270    ;   true
 2271    ).
 delete_answers_for_failing_calls(-Propagated)
Delete answers whose condition is determined to be false and return the number of additional answers that changed status as a consequence of additional simplification propagation.
 2279delete_answers_for_failing_calls(Propagated) :-
 2280    State = state(0),
 2281    (   subgoal_residual_trie(ASGF, ESGF),
 2282        \+ trie_gen(ESGF, _ETmp),
 2283        tdebug(trie_goal(ASGF, Goal0, _)),
 2284        tdebug(trie_goal(ASGF, Goal, _0Return)),
 2285        '$trie_gen_node'(ASGF, _0Return, ALeaf),
 2286        tdebug(ac(prune), '  Removing answer ~p from ~p', [Goal, Goal0]),
 2287	'$tbl_force_truth_value'(ALeaf, false, Count),
 2288        arg(1, State, Prop0),
 2289        Prop is Prop0+Count-1,
 2290        nb_setarg(1, State, Prop),
 2291	fail
 2292    ;   arg(1, State, Propagated)
 2293    ).
 2294
 2295mark_succeeding_calls_as_answer_completed :-
 2296    (   subgoal_residual_trie(ASGF, _ESGF),
 2297        (   '$tbl_answer_dl'(ASGF, _0Return, _True)
 2298        ->  tdebug(trie_goal(ASGF, Answer, _0Return)),
 2299            tdebug(trie_goal(ASGF, Goal, _0Return)),
 2300            tdebug(ac(prune), '  Completed ~p on ~p', [Goal, Answer]),
 2301            '$tbl_set_answer_completed'(ASGF)
 2302        ),
 2303        fail
 2304    ;   true
 2305    ).
 2306
 2307subgoal_residual_trie(ASGF, ESGF) :-
 2308    '$tbl_variant_table'(VariantTrie),
 2309    context_module(M),
 2310    trie_gen(VariantTrie, M:eval_subgoal_in_residual(ASGF, _), ESGF).
 eval_dl_in_residual(+Condition)
Evaluate a condition by only looking at the residual goals of the involved calls.
 2317eval_dl_in_residual(true) :-
 2318    !.
 2319eval_dl_in_residual((A;B)) :-
 2320    !,
 2321    (   eval_dl_in_residual(A)
 2322    ;   eval_dl_in_residual(B)
 2323    ).
 2324eval_dl_in_residual((A,B)) :-
 2325    !,
 2326    eval_dl_in_residual(A),
 2327    eval_dl_in_residual(B).
 2328eval_dl_in_residual(tnot(G)) :-
 2329    !,
 2330    tdebug(ac, ' ? tnot(~p)', [G]),
 2331    current_table(G, SGF),
 2332    '$tbl_table_status'(SGF, _Status, _Wrapper, Return),
 2333    tnot(eval_subgoal_in_residual(SGF, Return)).
 2334eval_dl_in_residual(G) :-
 2335    tdebug(ac, ' ? ~p', [G]),
 2336    (   current_table(G, SGF)
 2337    ->	true
 2338    ;   more_general_table(G, SGF)
 2339    ->	true
 2340    ;	writeln(user_error, 'MISSING CALL? '(G)),
 2341        fail
 2342    ),
 2343    '$tbl_table_status'(SGF, _Status, _Wrapper, Return),
 2344    eval_subgoal_in_residual(SGF, Return).
 2345
 2346more_general_table(G, Trie) :-
 2347    term_attvars(G, []),
 2348    !,
 2349    term_variables(G, Vars),
 2350    '$tbl_variant_table'(VariantTrie),
 2351    trie_gen(VariantTrie, G, Trie),
 2352    is_most_general_term(Vars).
 2353more_general_table(G, _Trie) :-
 2354    '$type_error'(free_of_attvar, G).
 2355
 2356:- table eval_subgoal_in_residual/2.
 eval_subgoal_in_residual(+AnswerTrie, ?Return)
Derive answers for the variant represented by AnswerTrie based on the residual goals only.
 2363eval_subgoal_in_residual(AnswerTrie, _Return) :-
 2364    '$tbl_is_answer_completed'(AnswerTrie),
 2365    !,
 2366    undefined.
 2367eval_subgoal_in_residual(AnswerTrie, Return) :-
 2368    '$tbl_answer'(AnswerTrie, Return, Condition),
 2369    tdebug(trie_goal(AnswerTrie, Goal, Return)),
 2370    tdebug(ac, 'Condition for ~p is ~p', [Goal, Condition]),
 2371    eval_dl_in_residual(Condition).
 2372
 2373
 2374		 /*******************************
 2375		 *            TRIPWIRES		*
 2376		 *******************************/
 tripwire(+Wire, +Action, +Context)
Called from the tabling engine of some tripwire is exceeded and the situation is not handled internally (such as abstract and bounded_rationality.
 2384:- public tripwire/3. 2385:- multifile prolog:tripwire/2. 2386
 2387tripwire(Wire, _Action, Context) :-
 2388    prolog:tripwire(Wire, Context),
 2389    !.
 2390tripwire(Wire, Action, Context) :-
 2391    Error = error(resource_error(tripwire(Wire, Context)), _),
 2392    tripwire_action(Action, Error).
 2393
 2394tripwire_action(warning, Error) :-
 2395    print_message(warning, Error).
 2396tripwire_action(error, Error) :-
 2397    throw(Error).
 2398tripwire_action(suspend, Error) :-
 2399    print_message(warning, Error),
 2400    break.
 2401
 2402
 2403		 /*******************************
 2404		 *   SYSTEM TABLED PREDICATES	*
 2405		 *******************************/
 2406
 2407:- table
 2408    system:undefined/0,
 2409    system:answer_count_restraint/0,
 2410    system:radial_restraint/0,
 2411    system:tabled_call/1.
 undefined is undefined
Expresses the value bottom from the well founded semantics.
 2417system:(undefined :-
 2418    tnot(undefined)).
 answer_count_restraint is undefined
 radial_restraint is undefined
Similar to undefined/0, providing a specific undefined for restraint violations.
 2426system:(answer_count_restraint :-
 2427    tnot(answer_count_restraint)).
 2428
 2429system:(radial_restraint :-
 2430    tnot(radial_restraint)).
 2431
 2432system:(tabled_call(X) :- call(X))