1/*  pl2detlog.pl -- Prolog to Detlog and Detlog MNN, in SWI-Prolog
    2
    3    ?- use_module(library(pl2detlog)).
    4    ?- pl2detlog_convert('prog.pl', []).                 % writes prog_detlog/ and prog_mnn/
    5    ?- pl2detlog_compile('prog.pl', [main(main)]).       % builds ./prog, in the fastest form
    6
    7    Command line (see README.md):
    8       swipl pl2detlog convert prog.pl [-g main | -q "Query"] [--form mnn] [--out Dir]
    9       swipl pl2detlog compile prog.pl [-g main | -q "Query"] [-o exe]
   10
   11    The three forms
   12      prolog  the program as written;
   13      detlog  Detlog: no cut, ;, ->, \+, findall/3 or call/N in the program.  A predicate whose
   14              clauses are told apart by a bound argument stays a plain predicate (it leaves no
   15              choicepoint); a nondeterministic one becomes p__all/N+2, which returns its
   16              answers as a list; a necessary cut becomes if_commit/3; an unnecessary cut is
   17              dropped;
   18      mnn     Detlog MNN: Detlog plus the MNN rewrites -- clauses told apart by guard tests,
   19              first-answer versions p__first/N, tabling of pure tree recursion (MEMO), the
   20              accumulator rewrite of append-recursion, facts as data.
   21
   22    Proofs are kept out of the code: each rewrite's side conditions are checked here and
   23    listed in PROOFS.txt in the output folder, and the compile step checks that every form
   24    gives Prolog's output on the query before it times them.
   25*/
   26
   27:- module(pl2detlog,
   28          [ pl2detlog_convert/2,      % +File, +Options
   29            pl2detlog_convert/3,      % +File, +Form, +Options
   30            pl2detlog_compile/2,      % +File, +Options
   31            pl2detlog_check/3,        % +File, +Options, -Results
   32            pl2detlog_cli/1           % +Argv
   33          ]).   34
   35:- use_module(library(lists)).   36:- use_module(library(apply)).   37:- use_module(library(option)).   38:- use_module(library(readutil)).   39:- use_module(library(dcg/basics), []).   40
   41:- dynamic
   42    src_file/2,          % Seq, Path
   43    dbv/5,               % Kind, Key, Term, Vars, Hints
   44    pred_key/2,          % Key, Seq
   45    dyn_key/1,
   46    export_key/1,
   47    aux_of/2,            % Aux, Parent
   48    aux_root/2,          % Aux, RootKey
   49    kept/2,              % Key, Reason
   50    m_pat/2,
   51    m_succ/2,
   52    det_key/1,
   53    eff_key/1,
   54    inf_key/1,
   55    callable_key/1,
   56    has_caller/1,
   57    need/2,
   58    done/2,
   59    table_key/1,
   60    inlined/1,
   61    note/2,
   62    form/1,
   63    counter/2,
   64    entry/2,             % Name, Goal       (the query/main entry)
   65    root_dir/1.   66
   67:- meta_predicate safe_test(0).   68
   69%  Variable names travel with the terms as attributes.
   70attr_unify_hook(_, _).
   71attribute_goals(_) --> [].
   72
   73:- create_prolog_flag(pl2detlog_verbose, false, [keep(true)]).   74
   75                 /*******************************
   76                 *          PUBLIC API          *
   77                 *******************************/
 pl2detlog_convert(+File, +Options)
Write the Detlog and the Detlog MNN form of File (and every file it loads with a relative path) into two folders next to its folder. Options: form(detlog|mnn|both), out(Dir) (the folder for a single form), main(Name) or query(Goal) (the entry: its modes make more of the program deterministic).
   85pl2detlog_convert(File, Options) :-
   86    option(form(F), Options, both),
   87    (   F == both
   88    ->  pl2detlog_convert(File, detlog, Options),
   89        pl2detlog_convert(File, mnn, Options)
   90    ;   pl2detlog_convert(File, F, Options)
   91    ).
   92
   93pl2detlog_convert(File, Form, Options) :-
   94    must_be(oneof([detlog, mnn]), Form),
   95    load_program(File),
   96    ( entry_from_options(Options, _) -> true ; true ),
   97    convert_form(Form),
   98    out_root(Form, Options, OutRoot),
   99    write_program(Form, OutRoot),
  100    root_out_file(OutRoot, Main),
  101    (   option(quiet(true), Options) -> true ; format(user_error, "% ~w: ~w~n", [Form, Main]) ).
 pl2detlog_compile(+File, +Options)
Convert File, run the query in each form (Prolog, Detlog, Detlog MNN), check each gives Prolog's output, and build an executable of the fastest. Options: main(Name) or query(Goal) (needed when the program has no main/0 or initialization(main, main)), exe(Path), forms(List), budget(Seconds).
  109pl2detlog_compile(File, Options) :-
  110    pl2detlog_check(File, Options, Results),
  111    report_results(Results, Best),
  112    absolute_file_name(File, Abs, [file_type(prolog), access(read)]),
  113    (   option(exe(Exe0), Options) -> true ; file_name_extension(Exe0, _, Abs) ),
  114    absolute_file_name(Exe0, Exe),
  115    Best = r(BForm, BDir, BMain, _, _),
  116    build_exe(BForm, BDir, BMain, Exe),
  117    format(user_error, "% built ~w (~w form)~n", [Exe, BForm]).
 pl2detlog_check(+File, +Options, -Results)
Convert File to each form and run the query in each, in a fresh process. Results are r(Form, Folder, MainFile, Answer-Output, SecondsPerRun).
  123pl2detlog_check(File, Options, Results) :-
  124    absolute_file_name(File, Abs, [file_type(prolog), access(read)]),
  125    load_program(Abs),
  126    (   entry_from_options([purpose(compile)|Options], Goal)
  127    ->  true
  128    ;   throw(error(pl2detlog(no_main), _))
  129    ),
  130    option(forms(Forms), Options, [prolog, detlog, mnn]),
  131    option(budget(Budget), Options, 0.5),
  132    (   option(quiet(true), Options) -> true ; format(user_error, "% query: ~q~n", [Goal]) ),
  133    Opts2 = [query(Goal)|Options],
  134    findall(Form-Dir-Main, form_files(Form, Forms, Abs, Opts2, Dir, Main), FDs),
  135    maplist(bench_form(Goal, Budget), FDs, Results).
  136
  137form_files(prolog, Forms, Abs, _, Dir, Abs) :-
  138    memberchk(prolog, Forms),
  139    file_directory_name(Abs, Dir).
  140form_files(Form, Forms, Abs, Options, Dir, Main) :-
  141    member(Form, [detlog, mnn]),
  142    memberchk(Form, Forms),
  143    load_program(Abs),
  144    entry_from_options(Options, _),
  145    convert_form(Form),
  146    out_root(Form, Options, Dir),
  147    write_program(Form, Dir),
  148    root_out_file(Dir, Main).
  149
  150                 /*******************************
  151                 *            LOADING           *
  152                 *******************************/
  153
  154reset_all :-
  155    forall(member(P, [src_file/2, dbv/5, pred_key/2, dyn_key/1, export_key/1, entry/2,
  156                      root_dir/1]),
  157           ( P = N/A, functor(H, N, A), retractall(H) )),
  158    reset_form,
  159    (   current_module(pl2detlog_read) -> true ; true ).
  160
  161reset_form :-
  162    forall(member(P, [aux_of/2, aux_root/2, kept/2, m_pat/2, m_succ/2, det_key/1, eff_key/1,
  163                      inf_key/1,
  164                      callable_key/1, has_caller/1, need/2, done/2, table_key/1, inlined/1,
  165                      note/2, form/1, counter/2]),
  166           ( P = N/A, functor(H, N, A), retractall(H) )),
  167    forall(member(K, [ncl, out, inl]), retractall(dbv(K, _, _, _, _))),
  168    forall(( pred_key(K, _), aux_name(K) ), retractall(pred_key(K, _))).
  169
  170aux_name(N/_) :- sub_atom(N, _, _, _, '__').
  171
  172load_program(File) :-
  173    reset_all,
  174    absolute_file_name(File, Abs, [file_type(prolog), access(read)]),
  175    load_file(Abs),
  176    findall(D, ( src_file(_, P), file_directory_name(P, D) ), Ds),
  177    common_dir(Ds, Root),
  178    assertz(root_dir(Root)).
  179
  180load_file(Path) :- src_file(_, Path), !.
  181load_file(Path) :-
  182    aggregate_all(count, src_file(_, _), N),
  183    assertz(src_file(N, Path)),
  184    file_directory_name(Path, Dir),
  185    setup_call_cleanup(open(Path, read, S),
  186                       read_items(S, Path, Dir, 0),
  187                       close(S)).
  188
  189read_items(S, Path, Dir, Seq) :-
  190    read_term(S, T, [ module(pl2detlog_read), variable_names(Vs), comments(Cs) ]),
  191    comment_texts(Cs, Txt),
  192    (   T == end_of_file
  193    ->  db_put(item, Path, it(Seq, eof, Txt))
  194    ;   names_attach(Vs),
  195        term_item(T, Dir, Item),
  196        db_put(item, Path, it(Seq, Item, Txt)),
  197        Seq1 is Seq + 1,
  198        read_items(S, Path, Dir, Seq1)
  199    ).
  200
  201comment_texts(Cs, Txt) :-
  202    (   is_list(Cs) -> findall(C, member(_-C, Cs), Txt) ; Txt = [] ).
  203
  204term_item((:- D), Dir, dir(D, Loads)) :- !,
  205    catch(dir_effects(D, Dir, Loads), _, Loads = []).
  206term_item((H --> B), _, Item) :- !,
  207    dcg_translate_rule((H --> B), Cl),
  208    cl_item(Cl, Item).
  209term_item(T, _, Item) :-
  210    cl_item(T, Item).
  211
  212cl_item((H :- B), cl(H, B)) :- !, reg_head(H).
  213cl_item(H, cl(H, true)) :- reg_head(H).
  214
  215reg_head(H) :-
  216    callable(H), H \= _:_, !,
  217    functor(H, N, A),
  218    (   pred_key(N/A, _) -> true
  219    ;   aggregate_all(count, pred_key(_, _), I), assertz(pred_key(N/A, I))
  220    ).
  221reg_head(_).
  222
  223dir_effects(op(P, T, N), _, []) :- !, op(P, T, pl2detlog_read:N).
  224dir_effects(module(_, Ex), _, []) :- !,
  225    forall(member(op(P, T, N), Ex), op(P, T, pl2detlog_read:N)),
  226    forall(( member(K, Ex), K = _/_ ), assertz(export_key(K))).
  227dir_effects(dynamic(Spec), _, []) :- !,
  228    forall(spec_key(Spec, K), assertz(dyn_key(K))).
  229dir_effects(D, Dir, Loads) :-
  230    load_directive(D, Spec), !,
  231    local_loads(Spec, Dir, Loads).
  232dir_effects([H|T], Dir, Loads) :- !,
  233    local_loads([H|T], Dir, Loads).
  234dir_effects(_, _, []).
  235
  236load_directive(include(F), F).
  237load_directive(consult(F), F).
  238load_directive(ensure_loaded(F), F).
  239load_directive(use_module(F), F).
  240load_directive(use_module(F, _), F).
  241load_directive(reexport(F), F).
  242load_directive(reexport(F, _), F).
  243load_directive(load_files(F, _), F).
  244
  245spec_key(V, _) :- var(V), !, fail.
  246spec_key((A, B), K) :- !, ( spec_key(A, K) ; spec_key(B, K) ).
  247spec_key([H|T], K) :- !, member(S, [H|T]), spec_key(S, K).
  248spec_key(_:S, K) :- !, spec_key(S, K).
  249spec_key(N/A, N/A).
  250spec_key(as(S, _), K) :- spec_key(S, K).
  251
  252local_loads(Fs, Dir, Loads) :- is_list(Fs), !,
  253    foldl(local_load(Dir), Fs, Loads, []).
  254local_loads(F, Dir, Loads) :-
  255    local_load(Dir, F, Loads, []).
  256
  257local_load(Dir, F, [F-Abs|T], T) :-
  258    local_spec(F),
  259    absolute_file_name(F, Abs, [ file_type(prolog), access(read), relative_to(Dir),
  260                                 file_errors(fail) ]), !,
  261    load_file(Abs).
  262local_load(_, library(L), T, T) :- !,
  263    catch(pl2detlog_read:use_module(library(L)), _, true).
  264local_load(_, _, T, T).
  265
  266local_spec(F) :- atom(F), !.
  267local_spec(F) :- string(F), !.
  268local_spec(A/B) :- local_spec(A), atomic(B).
  269
  270common_dir([D], D) :- !.
  271common_dir([D|Ds], C) :-
  272    common_dir(Ds, C0),
  273    atomic_list_concat(P1, '/', D),
  274    atomic_list_concat(P2, '/', C0),
  275    common_prefix(P1, P2, P),
  276    atomic_list_concat(P, '/', C1),
  277    ( C1 == '' -> C = '/' ; C = C1 ).
  278
  279common_prefix([X|Xs], [X|Ys], [X|Zs]) :- !, common_prefix(Xs, Ys, Zs).
  280common_prefix(_, _, []).
  281
  282                 /*******************************
  283                 *   TERMS WITH VARIABLE NAMES  *
  284                 *******************************/
  285
  286names_attach(Vs) :- maplist(name_pair, Vs).
  287name_pair(N=V) :- name_var(V, N).
  288
  289name_var(V, N) :- var(V), \+ get_attr(V, pl2detlog, _), !, put_attr(V, pl2detlog, N).
  290name_var(_, _).
  291
  292fresh(Hint, V) :- put_attr(V, pl2detlog, Hint).
  293
  294var_hint(V, H) :- ( get_attr(V, pl2detlog, H0) -> H = H0 ; H = '' ).
  295set_hint(V, H) :- ( H \== '', var(V) -> put_attr(V, pl2detlog, H) ; true ).
  296
  297db_put(Kind, Key, T) :-
  298    term_variables(T, Vs),
  299    maplist(var_hint, Vs, Hs),
  300    copy_term_nat(T-Vs, T2-Vs2),
  301    assertz(dbv(Kind, Key, T2, Vs2, Hs)).
  302
  303db_get(Kind, Key, T) :-
  304    dbv(Kind, Key, T, Vs, Hs),
  305    maplist(set_hint, Vs, Hs).
  306
  307db_all(Kind, Key, Ts) :-
  308    findall(T-Vs-Hs, dbv(Kind, Key, T, Vs, Hs), Raw),
  309    maplist(reattach, Raw, Ts).
  310
  311reattach(T-Vs-Hs, T) :- maplist(set_hint, Vs, Hs).
  312
  313                 /*******************************
  314                 *     THE PROGRAM, AS DATA     *
  315                 *******************************/
  316
  317key(G, N/A) :- callable(G), functor(G, N, A).
  318
  319src_clauses(K, Cls) :-
  320    findall((H :- B)-Vs-Hs,
  321            ( src_file(_, P),
  322              dbv(item, P, it(_, cl(H, B), _), Vs, Hs),
  323              key(H, K) ),
  324            Raw),
  325    maplist(reattach, Raw, Cls).
  326
  327ncls(K, Cls) :- db_all(ncl, K, Cls).
  328
  329user_goal(G) :-
  330    callable(G), G \= _:_,
  331    functor(G, N, A),
  332    ( pred_key(N/A, _) ; dyn_key(N/A) ), !.
  333
  334conv_key(K) :- pred_key(K, _), \+ kept(K, _).
  335
  336                 /*******************************
  337                 *         NORMALISATION        *
  338                 *******************************/
  339
  340%   A normalised clause is cl(Head, plain(Goals)) or cl(Head, commit(Guard, Body)): the
  341%   clause had a cut; Guard is what came before it.  Goals are b(G) (builtin), u(G) (user
  342%   predicate), not(S), once(S), ignore(S), findall(T, S, L), findall4(T, S, L, T0) and
  343%   aggr(F, E, S, R), with S a b/1 or u/1 goal.  Inner control constructs become auxiliary
  344%   predicates (named Parent__ite1, Parent__or1, ...); maplist/foldl/include/exclude/
  345%   partition with a known closure become recursive predicates (Parent__map1, ...).
  346
  347normalise :-
  348    forall(( pred_key(K, _), \+ aux_of(K, _) ), normalise_pred(K)).
  349
  350normalise_pred(K) :-
  351    (   dyn_key(K)
  352    ->  assertz(kept(K, 'dynamic'))
  353    ;   src_clauses(K, Cls),
  354        catch(maplist(norm_clause(K), Cls),
  355              unsupported(Why),
  356              ( drop_aux(K), retractall(dbv(ncl, K, _, _, _)), assertz(kept(K, Why)) ))
  357    ).
  358
  359drop_aux(K) :-
  360    forall(aux_of(A, K),
  361           ( drop_aux(A), retractall(aux_of(A, K)), retractall(aux_root(A, _)),
  362             retractall(pred_key(A, _)), retractall(dbv(ncl, A, _, _, _)) )).
  363
  364norm_clause(K, (H :- B)) :-
  365    conj_list(B, Gs0),
  366    norm_goals(Gs0, [], K, H, Gs1),
  367    cut_kind(Gs1, K, H, Kind),
  368    db_put(ncl, K, cl(H, Kind)).
  369
  370conj_list(V, [V]) :- var(V), !.
  371conj_list((A, B), L) :- !, conj_list(A, LA), conj_list(B, LB), append(LA, LB, L).
  372conj_list(true, []) :- !.
  373conj_list(G, [G]).
  374
  375norm_goals([], _, _, _, []).
  376norm_goals([G|Gs], Before, K, H, Out) :-
  377    term_variables(H-Before-Gs, Outside),
  378    norm_goal(G, K, Outside, N),
  379    append(N, Rest, Out),
  380    norm_goals(Gs, [G|Before], K, H, Rest).
  381
  382norm_goal(G, _, _, [b(call(G))]) :- var(G), !.
  383norm_goal(!, _, _, ['$cut']) :- !.
  384norm_goal(true, _, _, []) :- !.
  385norm_goal((A, B), K, O, N) :- !,
  386    conj_list((A, B), Gs),
  387    norm_goals(Gs, [], K, O, N).
  388norm_goal((C *-> _ ; _), _, _, _) :- nonvar(C), !, throw(unsupported('*->')).
  389norm_goal(D, K, O, [u(Aux)]) :- D = (_;_), !,
  390    disj_bodies(D, Bs),
  391    lift(K, or, O, D, Bs, Aux).
  392norm_goal((C -> T), K, O, [u(Aux)]) :- !,
  393    disj_bodies((C -> T), Bs),
  394    lift(K, ite, O, (C -> T), Bs, Aux).
  395norm_goal(\+ G, K, O, [not(S)]) :- !, simple(G, K, O, [], S).
  396norm_goal(not(G), K, O, [not(S)]) :- !, simple(G, K, O, [], S).
  397norm_goal(once(G), K, O, [once(S)]) :- !, simple(G, K, O, [], S).
  398norm_goal(ignore(G), K, O, [ignore(S)]) :- !, simple(G, K, O, [], S).
  399norm_goal(forall(C, A), K, O, N) :- !, norm_goal(\+ (C, \+ A), K, O, N).
  400norm_goal(findall(T, G, L), K, O, [findall(T, S, L)]) :- !, simple(G, K, O, T, S).
  401norm_goal(findall(T, G, L, T0), K, O, [findall4(T, S, L, T0)]) :- !, simple(G, K, O, T, S).
  402norm_goal(aggregate_all(Spec, G, R), K, O, [aggr(F, E, S, R)]) :-
  403    nonvar(Spec), aggr_spec(Spec, F, E), !,
  404    simple(G, K, O, E, S).
  405norm_goal(bagof(T, G0, L), K, O, [findall(T, S, L1), b(L1 \== []), b(L = L1)]) :-
  406    strip_hats(G0, G, QV), no_free(G, T, QV), !,
  407    fresh('L0', L1),
  408    simple(G, K, O, T, S).
  409norm_goal(setof(T, G0, L), K, O, [findall(T, S, L1), b(L1 \== []), b(sort(L1, L))]) :-
  410    strip_hats(G0, G, QV), no_free(G, T, QV), !,
  411    fresh('L0', L1),
  412    simple(G, K, O, T, S).
  413norm_goal(call(G), K, O, N) :- nonvar(G), !,
  414    (   contains_cut(G)
  415    ->  lift(K, call, O, G, [G], Aux), N = [u(Aux)]
  416    ;   norm_goal(G, K, O, N)
  417    ).
  418norm_goal(G, K, O, N) :-
  419    compound(G), G =.. [call, C|Extra], nonvar(C), !,
  420    closure_goal(C, Extra, K, O, G1),
  421    norm_goal(G1, K, O, N).
  422norm_goal(phrase(G, L), K, O, N) :- nonvar(G), !,
  423    norm_goal(phrase(G, L, []), K, O, N).
  424norm_goal(phrase(G, L, R), K, O, N) :- nonvar(G), !,
  425    dcg_translate_rule((pl2detlog_phrase --> G), (H :- B)),
  426    H =.. [_, L, R],
  427    conj_list(B, Gs),
  428    norm_goals(Gs, [], K, O, N).
  429norm_goal(G, K, O, [u(Aux)]) :-
  430    spec_meta(G, Kind, C, Lists, Extra), nonvar(C), closure_ok(C), !,
  431    spec_pred(K, O, Kind, C, Lists, Extra, Aux).
  432norm_goal(M:G, K, O, N) :- atom(M), callable(G), !,
  433    (   user_goal(G) -> norm_goal(G, K, O, N) ; N = [b(M:G)] ).
  434norm_goal(G, _, _, [u(G)]) :- user_goal(G), !.
  435norm_goal(G, _, _, [b(G)]).
  436
  437disj_bodies((C -> T ; E), [(C1, !, T)|Bs]) :- !,
  438    local_cond(C, C1), no_tcut(T), disj_bodies(E, Bs).
  439disj_bodies((C -> T), [(C1, !, T)]) :- !, local_cond(C, C1), no_tcut(T).
  440disj_bodies((A ; B), [A|Bs]) :- !, no_tcut(A), disj_bodies(B, Bs).
  441disj_bodies(A, [A]) :- no_tcut(A).
  442
  443local_cond(C, C1) :- ( contains_cut(C) -> C1 = call(C) ; C1 = C ).
  444
  445no_tcut(G) :- ( contains_cut(G) -> throw(unsupported('cut inside ; or ->')) ; true ).
  446
  447contains_cut(G) :- var(G), !, fail.
  448contains_cut(!).
  449contains_cut((A, B)) :- ( contains_cut(A) -> true ; contains_cut(B) ).
  450contains_cut((A ; B)) :- ( contains_cut(A) -> true ; contains_cut(B) ).
  451contains_cut((A -> B)) :- ( contains_cut(A) -> true ; contains_cut(B) ).
  452contains_cut((A *-> B)) :- ( contains_cut(A) -> true ; contains_cut(B) ).
  453
  454strip_hats(G, G, []) :- var(G), !.
  455strip_hats(V^G0, G, [V|Vs]) :- !, strip_hats(G0, G, Vs).
  456strip_hats(G, G, []).
  457
  458no_free(G, T, QV) :-
  459    term_variables(G, GV), term_variables(T-QV, TV),
  460    forall(member(V, GV), ( member(W, TV), W == V )).
  461
  462aggr_spec(count, count, x).
  463aggr_spec(sum(E), sum, E).
  464aggr_spec(max(E), max, E).
  465aggr_spec(min(E), min, E).
  466aggr_spec(bag(E), bag, E).
  467aggr_spec(set(E), set, E).
  468
  469%   simple(+G, +K, +Outside, +Template, -S): G as one b/u goal, lifting it when needed.
  470simple(G, K, O, T, S) :-
  471    term_variables(O-T, O2),
  472    (   simple_goal(G), norm_goal(G, K, O2, [S0]), ( S0 = b(_) ; S0 = u(_) )
  473    ->  S = S0
  474    ;   lift(K, sub, O2, G, [G], Aux),
  475        S = u(Aux)
  476    ).
  477
  478simple_goal(G) :-
  479    callable(G), G \= _:_,
  480    functor(G, N, A),
  481    \+ memberchk(N/A, [ (',')/2, (;)/2, (->)/2, (*->)/2, (\+)/1, not/1, once/1, ignore/1,
  482                        forall/2, findall/3, findall/4, aggregate_all/3, bagof/3, setof/3,
  483                        phrase/2, phrase/3, call/1, (!)/0 ]).
  484
  485%   lift(+Parent, +Kind, +Outside, +Construct, +Bodies, -AuxHead)
  486lift(K, Kind, O, Construct, Bodies, AuxHead) :-
  487    term_variables(Construct, CV),
  488    shared_vars(CV, O, Args),
  489    new_aux(K, Kind, Args, AuxHead),
  490    AuxHead =.. [_|_],
  491    key(AuxHead, AK),
  492    forall(member(B, Bodies),
  493           ( copy_term(AuxHead-B, H1-B1), norm_clause(AK, (H1 :- B1)) )).
  494
  495shared_vars([], _, []).
  496shared_vars([V|Vs], O, S) :-
  497    (   member(W, O), W == V -> S = [V|S1] ; S = S1 ),
  498    shared_vars(Vs, O, S1).
  499
  500new_aux(K, Kind, Args, Head) :-
  501    root_of(K, R),
  502    R = RN/_,
  503    next_count(R-Kind, N),
  504    format(atom(Name), '~w__~w~w', [RN, Kind, N]),
  505    length(Args, Ar),
  506    Head =.. [Name|Args],
  507    AK = Name/Ar,
  508    aggregate_all(count, pred_key(_, _), I),
  509    assertz(pred_key(AK, I)),
  510    assertz(aux_of(AK, K)),
  511    assertz(aux_root(AK, R)).
  512
  513root_of(K, R) :- ( aux_root(K, R0) -> R = R0 ; R = K ).
  514
  515next_count(Key, N) :-
  516    (   retract(counter(Key, N0)) -> N is N0 + 1 ; N = 1 ),
  517    assertz(counter(Key, N)).
  518
  519%   once-cuts: G1, !, G2, !, G3  is  G1, !, once((G2, !)), G3
  520cut_kind(Gs, _, _, plain(Gs)) :- \+ memberchk('$cut', Gs), !.
  521cut_kind(Gs, K, H, commit(Guard, Body)) :-
  522    append(Guard, ['$cut'|Rest], Gs), \+ memberchk('$cut', Guard), !,
  523    (   memberchk('$cut', Rest)
  524    ->  last_cut(Rest, Pre, Post),
  525        term_variables(H-Guard-Post, O),
  526        term_variables(Pre, PV),
  527        shared_vars(PV, O, Args),
  528        new_aux(K, once, Args, Aux),
  529        key(Aux, AK),
  530        copy_term(Aux-Pre, A1-P1),
  531        cut_kind(P1, AK, A1, AKind),
  532        db_put(ncl, AK, cl(A1, AKind)),
  533        Body = [once(u(Aux))|Post]
  534    ;   Body = Rest
  535    ).
  536
  537last_cut(Gs, Pre, Post) :-
  538    append(Pre0, ['$cut'|Post], Gs), \+ memberchk('$cut', Post), !,
  539    append(Pre0, ['$cut'], Pre).
  540
  541%   closures
  542closure_ok(C) :- callable(C).
  543
  544closure_goal(Ps>>B, Extra, K, O, G) :- !,
  545    lambda_closure(Ps>>B, Extra, K, O, C),
  546    add_args(C, Extra, G).
  547closure_goal(C, Extra, _, _, G) :- add_args(C, Extra, G).
  548
  549add_args(M:C, Extra, M:G) :- !, add_args(C, Extra, G).
  550add_args(C, Extra, G) :- C =.. L0, append(L0, Extra, L), G =.. L.
  551
  552lambda_closure(Lam, Extra, K, O, Closure) :-
  553    (   Lam = Free/(Ps>>B) -> true ; Lam = (Ps>>B), Free = [] ),
  554    is_list(Ps),
  555    length(Extra, NE), length(Ps, NP),
  556    (   NP =< NE -> true ; throw(unsupported('lambda with more parameters than arguments')) ),
  557    term_variables(B, BV), term_variables(Ps, PV), term_variables(Free-O, FO),
  558    exclude(var_in(PV), BV, NonParam),
  559    shared_vars(NonParam, FO, Shared),
  560    new_aux(K, lam, Shared, Closure),
  561    key(Closure, _),
  562    NR is NE - NP, length(Rest, NR),
  563    copy_term(Shared-Ps-B, Sh1-Ps1-B1),
  564    append(Ps1, Rest, Args),
  565    Closure =.. [Name|_],
  566    append(Sh1, Args, HA),
  567    H =.. [Name|HA],
  568    length(HA, Ar),
  569    retract(pred_key(Name/_, I)), assertz(pred_key(Name/Ar, I)),
  570    retract(aux_of(Name/AO, P)), assertz(aux_of(Name/Ar, P)), AO = AO,
  571    retract(aux_root(Name/_, R)), assertz(aux_root(Name/Ar, R)),
  572    (   Rest == [] -> B2 = B1 ; add_args(B1, Rest, B2) ),
  573    norm_clause(Name/Ar, (H :- B2)).
  574
  575var_in(Vs, V) :- member(W, Vs), W == V, !.
  576
  577spec_meta(maplist(C, A), map, C, [A], []).
  578spec_meta(maplist(C, A, B), map, C, [A, B], []).
  579spec_meta(maplist(C, A, B, D), map, C, [A, B, D], []).
  580spec_meta(maplist(C, A, B, D, E), map, C, [A, B, D, E], []).
  581spec_meta(foldl(C, A, V0, V), fold, C, [A], [V0, V]).
  582spec_meta(foldl(C, A, B, V0, V), fold, C, [A, B], [V0, V]).
  583spec_meta(foldl(C, A, B, D, V0, V), fold, C, [A, B, D], [V0, V]).
  584spec_meta(include(C, L, I), include, C, [L], [I]).
  585spec_meta(exclude(C, L, I), exclude, C, [L], [I]).
  586spec_meta(partition(C, L, I, E), partition, C, [L], [I, E]).
  587
  588%   spec_pred(+Parent, +Outside, +Kind, +Closure, +Lists, +Extra, -Call)
  589spec_pred(K, O, Kind, C0, Lists, Extra, Call) :-
  590    length(Lists, NL),
  591    (   Kind == map -> NA = NL
  592    ;   Kind == fold -> NA is NL + 2
  593    ;   NA = 1
  594    ),
  595    length(CA, NA),
  596    (   ( C0 = _>>_ ; C0 = _/(_>>_) )
  597    ->  lambda_closure(C0, CA, K, O, C)
  598    ;   C = C0
  599    ),
  600    term_variables(C, CV),
  601    append(Lists, Extra, LE),
  602    append(LE, CV, Args),
  603    new_aux(K, Kind, Args, Call),
  604    key(Call, AK),
  605    Call =.. [Name|_],
  606    spec_clauses(Kind, Name, C, CV, NL, Cls),
  607    forall(member(Cl, Cls), ( Cl = (_ :- _) -> norm_clause(AK, Cl) ; norm_clause(AK, (Cl :- true)) )).
  608
  609spec_clauses(map, Name, C, CV, NL, [H0, (H1 :- G, R)]) :-
  610    copy_term(C-CV, C1-CV1),
  611    length(Nils, NL), maplist(=([]), Nils),
  612    append(Nils, CV, A0), H0 =.. [Name|A0],
  613    length(Xs, NL), length(Ts, NL),
  614    maplist(hint('X'), Xs), maplist(hint('Xs'), Ts),
  615    maplist(cons, Xs, Ts, Cs),
  616    append(Cs, CV1, A1), H1 =.. [Name|A1],
  617    add_args(C1, Xs, G),
  618    append(Ts, CV1, AR), R =.. [Name|AR].
  619spec_clauses(fold, Name, C, CV, NL, [H0, (H1 :- G, R)]) :-
  620    copy_term(C-CV, C1-CV1),
  621    length(Nils, NL), maplist(=([]), Nils),
  622    fresh('V', V), append(Nils, [V, V|CV], A0), H0 =.. [Name|A0],
  623    length(Xs, NL), length(Ts, NL),
  624    maplist(hint('X'), Xs), maplist(hint('Xs'), Ts),
  625    maplist(cons, Xs, Ts, Cs),
  626    fresh('V0', V0), fresh('V1', V1), fresh('V', VV),
  627    append(Cs, [V0, VV|CV1], A1), H1 =.. [Name|A1],
  628    append(Xs, [V0, V1], GA), add_args(C1, GA, G),
  629    append(Ts, [V1, VV|CV1], AR), R =.. [Name|AR].
  630spec_clauses(Kind, Name, C, CV, 1, [H0, (H1 :- (G -> Yes ; No), R)]) :-
  631    memberchk(Kind, [include, exclude, partition]),
  632    copy_term(C-CV, C1-CV1),
  633    fresh('X', X), fresh('Xs', Xs),
  634    (   Kind == partition
  635    ->  A0 = [[], [], []|CV],
  636        fresh('I', I), fresh('I1', I1), fresh('E', E), fresh('E1', E1),
  637        A1 = [[X|Xs], I, E|CV1], RA = [Xs, I1, E1|CV1],
  638        Yes = (I = [X|I1], E = E1), No = (I = I1, E = [X|E1])
  639    ;   A0 = [[], []|CV],
  640        fresh('I', I), fresh('I1', I1),
  641        A1 = [[X|Xs], I|CV1], RA = [Xs, I1|CV1],
  642        (   Kind == include
  643        ->  Yes = (I = [X|I1]), No = (I = I1)
  644        ;   Yes = (I = I1), No = (I = [X|I1])
  645        )
  646    ),
  647    H0 =.. [Name|A0], H1 =.. [Name|A1], R =.. [Name|RA],
  648    add_args(C1, [X], G).
  649
  650hint(H, V) :- fresh(H, V).
  651cons(X, T, [X|T]).
  652
  653                 /*******************************
  654                 *     BUILTINS: WHAT THEY DO   *
  655                 *******************************/
  656
  657%   Abstract values: a variable bound to '$g' stands for a ground term.
  658
  659bind_g(T) :- term_variables(T, Vs), maplist(=('$g'), Vs).
  660
  661g(X) :- ground(X).
  662
  663%   bi_bind(+AbstractGoal): bind the outputs the builtin makes ground.
  664bi_bind(G) :- var(G), !.
  665bi_bind(_:G) :- !, bi_bind(G).
  666bi_bind(X is _) :- !, bind_g(X).
  667bi_bind(A = B) :- !, aunify(A, B).
  668bi_bind(functor(T, N, A)) :- !, ( g(T) -> bind_g(N-A) ; true ).
  669bi_bind(arg(N, T, A)) :- !, ( g(T) -> bind_g(N-A) ; true ).
  670bi_bind(T =.. L) :- !, ( g(T) -> bind_g(L) ; g(L) -> bind_g(T) ; true ).
  671bi_bind(copy_term(A, B)) :- !, ( g(A) -> bind_g(B) ; true ).
  672bi_bind(length(L, N)) :- !, bind_g(N), ( g(L) -> true ; true ).
  673bi_bind(G) :- functor(G, N, 2), text2(N), !, arg(1, G, A), arg(2, G, B),
  674    ( g(A) -> bind_g(B) ; g(B) -> bind_g(A) ; true ).
  675bi_bind(G) :- functor(G, N, 3), concat3(N), !, arg(1, G, A), arg(2, G, B), arg(3, G, C),
  676    ( g(A-B) -> bind_g(C) ; g(C) -> bind_g(A-B) ; true ).
  677bi_bind(atomic_list_concat(L, S)) :- !, ( g(L) -> bind_g(S) ; true ).
  678bi_bind(atomic_list_concat(L, Sep, S)) :- !, ( g(L-Sep) -> bind_g(S) ; g(Sep-S) -> bind_g(L) ; true ).
  679bi_bind(split_string(S, A, B, L)) :- !, ( g(S-A-B) -> bind_g(L) ; true ).
  680bi_bind(sub_atom(S, B, L, A, Sub)) :- !, ( g(S) -> bind_g(B-L-A-Sub) ; true ).
  681bi_bind(sub_string(S, B, L, A, Sub)) :- !, ( g(S) -> bind_g(B-L-A-Sub) ; true ).
  682bi_bind(format(Sink, _, _)) :- !, ( compound(Sink), arg(1, Sink, X) -> bind_g(X) ; true ).
  683bi_bind(with_output_to(Sink, _)) :- !, ( compound(Sink), arg(1, Sink, X) -> bind_g(X) ; true ).
  684bi_bind(member(X, L)) :- !, ( g(L) -> bind_g(X) ; true ).
  685bi_bind(memberchk(X, L)) :- !, ( g(L) -> bind_g(X) ; true ).
  686bi_bind(append(A, B, C)) :- !, ( g(A-B) -> bind_g(C) ; g(C) -> bind_g(A-B) ; true ).
  687bi_bind(append(L, C)) :- !, ( g(L) -> bind_g(C) ; true ).
  688bi_bind(select(X, L, R)) :- !, ( g(L) -> bind_g(X-R) ; true ).
  689bi_bind(selectchk(X, L, R)) :- !, ( g(L) -> bind_g(X-R) ; true ).
  690bi_bind(select(X, L, Y, R)) :- !, ( g(L-Y) -> bind_g(X-R) ; true ).
  691bi_bind(permutation(A, B)) :- !, ( g(A) -> bind_g(B) ; g(B) -> bind_g(A) ; true ).
  692bi_bind(nth0(I, L, E)) :- !, ( g(L) -> bind_g(I-E) ; true ).
  693bi_bind(nth1(I, L, E)) :- !, ( g(L) -> bind_g(I-E) ; true ).
  694bi_bind(nth0(I, L, E, R)) :- !, ( g(L) -> bind_g(I-E-R) ; true ).
  695bi_bind(nth1(I, L, E, R)) :- !, ( g(L) -> bind_g(I-E-R) ; true ).
  696bi_bind(last(L, E)) :- !, ( g(L) -> bind_g(E) ; true ).
  697bi_bind(between(_, _, X)) :- !, bind_g(X).
  698bi_bind(numlist(_, _, L)) :- !, bind_g(L).
  699bi_bind(succ(A, B)) :- !, bind_g(A-B).
  700bi_bind(plus(A, B, C)) :- !, bind_g(A-B-C).
  701bi_bind(term_to_atom(T, A)) :- !, ( g(T) -> bind_g(A) ; true ).
  702bi_bind(term_string(T, A)) :- !, ( g(T) -> bind_g(A) ; true ).
  703bi_bind(nb_getval(_, _)) :- !.
  704bi_bind(b_getval(_, _)) :- !.
  705bi_bind(G) :- functor(G, N, 2), list_fn(N), !, arg(1, G, A), arg(2, G, B),
  706    ( g(A) -> bind_g(B) ; true ).
  707bi_bind(G) :- functor(G, N, 3), list_fn3(N), !, arg(1, G, A), arg(2, G, B), arg(3, G, C),
  708    ( g(A-B) -> bind_g(C) ; true ).
  709bi_bind(sort(_, _, L, S)) :- !, ( g(L) -> bind_g(S) ; true ).
  710bi_bind(predsort(_, L, S)) :- !, ( g(L) -> bind_g(S) ; true ).
  711bi_bind(_).
  712
  713text2(N) :- memberchk(N, [atom_codes, atom_chars, char_code, atom_number, number_codes,
  714                          number_chars, atom_string, string_chars, string_codes,
  715                          string_to_atom, number_string, upcase_atom, downcase_atom,
  716                          string_upper, string_lower, atom_length, string_length,
  717                          term_to_atom, string_code, text_to_string]).
  718concat3(N) :- memberchk(N, [atom_concat, string_concat]).
  719list_fn(N) :- memberchk(N, [msort, sort, keysort, reverse, list_to_set, sum_list, sumlist,
  720                            max_list, min_list, max_member, min_member, flatten,
  721                            exclude_dups, pairs_keys, pairs_values, length, last,
  722                            sum_list, list_to_ord_set, term_variables, copy_term,
  723                            transpose, max_list, min_list]).
  724list_fn3(N) :- memberchk(N, [subtract, intersection, union, delete, exclude, include,
  725                             pairs_keys_values, ord_union, ord_subtract, ord_intersection,
  726                             sumlist, max_member, min_member, nth0, nth1]).
  727
  728aunify(A, B) :- var(A), !, ( var(B) -> A = B ; A = B -> true ; true ).
  729aunify(A, B) :- var(B), !, ( B = A -> true ; true ).
  730aunify('$g', B) :- !, bind_g(B).
  731aunify(A, '$g') :- !, bind_g(A).
  732aunify(A, B) :- compound(A), compound(B), functor(A, N, Ar), functor(B, N, Ar), !,
  733    A =.. [_|As], B =.. [_|Bs], maplist(aunify, As, Bs).
  734aunify(_, _).
  735
  736%   bi_nondet(+AbstractGoal): the builtin can have several answers.
  737bi_nondet(G) :- var(G), !.
  738bi_nondet(_:G) :- !, bi_nondet(G).
  739bi_nondet(member(_, _)).
  740bi_nondet(between(_, _, X)) :- \+ g(X).
  741bi_nondet(append(A, _, C)) :- \+ g(A), \+ (g(C), fail).
  742bi_nondet(append(L, _)) :- \+ g(L).
  743bi_nondet(select(_, _, _)).
  744bi_nondet(select(_, _, _, _)).
  745bi_nondet(permutation(_, _)).
  746bi_nondet(nth0(I, _, _)) :- \+ g(I).
  747bi_nondet(nth1(I, _, _)) :- \+ g(I).
  748bi_nondet(nth0(I, _, _, _)) :- \+ g(I).
  749bi_nondet(nth1(I, _, _, _)) :- \+ g(I).
  750bi_nondet(length(L, N)) :- \+ g(L), \+ g(N).
  751bi_nondet(last(L, _)) :- \+ g(L).
  752bi_nondet(sub_atom(_, _, _, _, _)).
  753bi_nondet(sub_string(_, _, _, _, _)).
  754bi_nondet(atom_concat(A, B, _)) :- \+ g(A-B).
  755bi_nondet(string_concat(A, B, _)) :- \+ g(A-B).
  756bi_nondet(arg(N, _, _)) :- \+ g(N).
  757bi_nondet(clause(_, _)).
  758bi_nondet(retract(_)).
  759bi_nondet(current_op(_, _, _)).
  760bi_nondet(repeat).
  761bi_nondet(char_type(C, T)) :- \+ g(C-T).
  762bi_nondet(code_type(C, T)) :- \+ g(C-T).
  763bi_nondet(G) :- \+ bi_known(G).
  764
  765bi_known(G) :- functor(G, N, A), ( det_bi(N/A) -> true ; nondet_bi(N/A) ).
  766
  767nondet_bi(N/A) :- memberchk(N/A, [member/2, between/3, append/3, append/2, select/3, select/4,
  768    permutation/2, nth0/3, nth1/3, nth0/4, nth1/4, length/2, last/2, sub_atom/5,
  769    sub_string/5, atom_concat/3, string_concat/3, arg/3, clause/2, retract/1,
  770    current_op/3, repeat/0, char_type/2, code_type/2]).
  771
  772det_bi(N/A) :- memberchk(N/A, [
  773    (is)/2, (=)/2, (\=)/2, (==)/2, (\==)/2, (@<)/2, (@>)/2, (@=<)/2, (@>=)/2, (<)/2,
  774    (>)/2, (=<)/2, (>=)/2, (=:=)/2, (=\=)/2, (=@=)/2, (\=@=)/2, var/1, nonvar/1, atom/1,
  775    number/1, integer/1, float/1, atomic/1, compound/1, callable/1, is_list/1, ground/1,
  776    string/1, is_dict/1, is_assoc/1, functor/3, (=..)/2, copy_term/2, atom_codes/2,
  777    atom_chars/2, char_code/2, atom_length/2, atom_number/2, number_codes/2,
  778    number_chars/2, atom_string/2, string_chars/2, string_codes/2, string_to_atom/2,
  779    string_length/2, number_string/2, term_to_atom/2, term_string/2, upcase_atom/2,
  780    downcase_atom/2, string_upper/2, string_lower/2, split_string/4,
  781    atomic_list_concat/2, atomic_list_concat/3, msort/2, sort/2, sort/4, predsort/3,
  782    keysort/2, reverse/2, list_to_set/2, sum_list/2, sumlist/2, max_list/2, min_list/2,
  783    max_member/2, min_member/2, numlist/3, memberchk/2, subtract/3, intersection/3,
  784    union/3, delete/3, exclude/3, include/3, partition/4, maplist/2, maplist/3,
  785    maplist/4, maplist/5, foldl/4, foldl/5, foldl/6, nb_getval/2, b_getval/2,
  786    nb_setval/2, b_setval/2, succ/2, plus/3, tab/1, tab/2, nl/0, nl/1, write/1, write/2,
  787    writeln/1, writeln/2, print/1, print/2, write_canonical/1, writeq/1, writeq/2,
  788    write_term/2, write_term/3, format/1, format/2, format/3, print_message/2,
  789    put_char/1, halt/0, halt/1, assert/1, asserta/1, assertz/1, retractall/1,
  790    flush_output/0, read_term/2, read_term/3, read/1, true/0, fail/0, false/0,
  791    term_variables/2, setarg/3, nb_setarg/3, string_code/3, selectchk/3, flatten/2,
  792    sum_list/2, list_to_ord_set/2, ord_union/3, ord_subtract/3, ord_intersection/3,
  793    ord_memberchk/2, pairs_keys_values/3, pairs_keys/2, pairs_values/2, transpose/2,
  794    with_output_to/2, findall/3, findall/4, aggregate_all/3, forall/2, (\+)/1, once/1,
  795    ignore/1, throw/1, tab/2, char_code/2, number_vars/3, numbervars/3, text_concat/3,
  796    get_time/1, statistics/2, random/1, random_between/3, garbage_collect/0,
  797    abolish_all_tables/0, succ_or_zero/1, text_to_string/2, sleep/1, shell/1, shell/2,
  798    getenv/2, setenv/2, atom_to_term/3, read_term_from_atom/3, sformat/3, format_atom/3,
  799    string/1, sub_atom_icasechk/3, nb_current/2, tab/1, last/2, length/2, sort/0,
  800    exclude/3, max_list/2, atomics_to_string/2, term_string/3, list_to_assoc/2,
  801    put_assoc/4, get_assoc/3, empty_assoc/1, assoc_to_list/2, assoc_to_keys/2,
  802    assoc_to_values/2, string_number/2, plus/3, abs/1, char_type/2, code_type/2,
  803    tabling/0, set_prolog_flag/2, op/3, garbage_collect/0, prompt/2, nb_setval/2]).
  804
  805%   Builtins that cannot fail (once their arguments are as given): write and friends.
  806bi_total(G, _) :- functor(G, N, A), memberchk(N/A, [nl/0, nl/1, write/1, write/2, writeln/1,
  807    writeln/2, print/1, print/2, writeq/1, writeq/2, write_canonical/1, write_term/2,
  808    write_term/3, format/1, format/2, format/3, tab/1, tab/2, true/0, flush_output/0,
  809    print_message/2, nb_setval/2, assertz/1, asserta/1, assert/1, retractall/1]), !.
  810bi_total(X is _, Seen) :- var(X), \+ var_in(Seen, X), !.
  811bi_total(X = _, Seen) :- var(X), \+ var_in(Seen, X), !.
  812bi_total(_ = X, Seen) :- var(X), \+ var_in(Seen, X), !.
  813
  814%   Side effects: anything that is observable outside the answer.
  815bi_effect(G) :- var(G), !.
  816bi_effect(_:G) :- !, bi_effect(G).
  817bi_effect(format(Sink, _, _)) :- !, \+ ( nonvar(Sink), Sink =.. [K, _], memberchk(K, [atom, string, codes, chars]) ).
  818bi_effect(with_output_to(_, G)) :- !, goal_effect_src(G).
  819bi_effect(G) :- functor(G, N, A), memberchk(N/A, [write/1, write/2, writeln/1, writeln/2,
  820    print/1, print/2, writeq/1, writeq/2, write_canonical/1, write_term/2, write_term/3,
  821    format/1, format/2, nl/0, nl/1, tab/1, tab/2, put_char/1, print_message/2, assert/1,
  822    asserta/1, assertz/1, retract/1, retractall/1, nb_setval/2, b_setval/2, nb_getval/2,
  823    b_getval/2, halt/0, halt/1, read/1, read_term/2, read_term/3, get_char/1,
  824    flush_output/0, set_prolog_flag/2, op/3, random/1, random_between/3, get_time/1,
  825    statistics/2, shell/1, shell/2, sleep/1, gensym/2, flag/3, setenv/2, nb_setarg/3,
  826    garbage_collect/0, abolish_all_tables/0, consult/1, prompt/2, nb_current/2,
  827    setarg/3]), !.
  828bi_effect(G) :- \+ bi_known(G), !.
  829bi_effect(G) :- meta_user_goals(G, Us), member(U-_, Us), ( var(U) -> true ; goal_effect_src(U) ), !.
  830
  831%   user goals inside the meta-arguments of a builtin: Goal-ExtraArgs
  832meta_user_goals(G, Us) :-
  833    findall(U-N, meta_arg(G, U, N), Us).
  834
  835meta_arg(G, U, N) :-
  836    callable(G), \+ G = b(_), \+ G = u(_),
  837    functor(G, F, A),
  838    meta_spec(F/A, Spec),
  839    arg(I, Spec, S), ( integer(S) -> N = S ; S == (^) -> N = 0 ; fail ),
  840    arg(I, G, Arg),
  841    strip_hats(Arg, U0, _),
  842    leaf_goal(U0, U).
  843
  844meta_spec(F/A, Spec) :-
  845    functor(H, F, A),
  846    (   catch(predicate_property(system:H, meta_predicate(Spec)), _, fail) -> true
  847    ;   member(M, [lists, apply, aggregate, yall]),
  848        catch(predicate_property(M:H, meta_predicate(Spec)), _, fail) -> true
  849    ;   memberchk(F/A-Spec, [ aggregate_all/3-aggregate_all(?, 0, -),
  850                              aggregate_all/4-aggregate_all(?, ?, 0, -) ])
  851    ).
  852
  853leaf_goal(V, V) :- var(V), !.
  854leaf_goal((A, B), L) :- !, ( leaf_goal(A, L) ; leaf_goal(B, L) ).
  855leaf_goal((A ; B), L) :- !, ( leaf_goal(A, L) ; leaf_goal(B, L) ).
  856leaf_goal((A -> B), L) :- !, ( leaf_goal(A, L) ; leaf_goal(B, L) ).
  857leaf_goal((A *-> B), L) :- !, ( leaf_goal(A, L) ; leaf_goal(B, L) ).
  858leaf_goal(\+ A, L) :- !, leaf_goal(A, L).
  859leaf_goal(_:A, L) :- !, leaf_goal(A, L).
  860leaf_goal(G, L) :- has_meta(G), !, meta_arg(G, L, _).
  861leaf_goal(G, G).
  862
  863has_meta(G) :- meta_arg(G, _, _), !.
  864
  865goal_effect_src(G) :- var(G), !.
  866goal_effect_src(G) :- leaf_goal(G, L), ( var(L) -> true ; user_goal(L) -> key(L, K), eff_key(K)
  867                                          ; L \== G, bi_effect(L) ; L == G, bi_effect_leaf(L) ), !.
  868
  869bi_effect_leaf(G) :- \+ user_goal(G), bi_effect(G).
  870
  871test_bi(T) :- callable(T), functor(T, N, A), memberchk(N/A, [(<)/2, (>)/2, (=<)/2, (>=)/2,
  872    (=:=)/2, (=\=)/2, (==)/2, (\==)/2, (@<)/2, (@>)/2, (@=<)/2, (@>=)/2, (\=)/2,
  873    integer/1, atom/1, number/1, atomic/1, is_list/1, compound/1, string/1, float/1,
  874    callable/1]).
  875
  876complementary(X, Y) :- ( compl(X, Y) -> true ; compl(Y, X) ).
  877
  878compl(A < B, C >= D) :- A == C, B == D.
  879compl(A > B, C =< D) :- A == C, B == D.
  880compl(A < B, C =< D) :- A == D, B == C.
  881compl(A > B, C >= D) :- A == D, B == C.
  882compl(A =:= B, C =\= D) :- A == C, B == D.
  883compl(A == B, C \== D) :- A == C, B == D.
  884
  885safe_test(G) :- catch(G, _, true).
  886
  887                 /*******************************
  888                 *        MODE ANALYSIS         *
  889                 *******************************/
  890
  891%   One call pattern per predicate (g: ground, f: a fresh variable, a: anything) and one
  892%   success pattern (g or a per argument), by abstract interpretation to a fixpoint.
  893
  894modes :-
  895    retractall(m_pat(_, _)), retractall(m_succ(_, _)), retractall(callable_key(_)),
  896    forall(conv_key(K), ( assertz(m_pat(K, none)), assertz(m_succ(K, none)) )),
  897    forall(kept(K, _), ( K = _/A, length(P, A), maplist(=(a), P),
  898                         assertz(m_pat(K, P)), assertz(m_succ(K, P)),
  899                         assertz(callable_key(K)) )),
  900    forall(kept(K, _), kept_sites(K)),
  901    entries,
  902    mode_loop,
  903    (   conv_key(K), m_pat(K, none)
  904    ->  K = _/A, length(P, A), maplist(=(a), P),
  905        pat_lub(K, P), mode_loop2
  906    ;   true
  907    ).
  908
  909mode_loop2 :-
  910    mode_loop,
  911    (   conv_key(K), m_pat(K, none)
  912    ->  K = _/A, length(P, A), maplist(=(a), P), pat_lub(K, P), mode_loop2
  913    ;   true
  914    ).
  915
  916kept_sites(K) :-
  917    src_clauses(K, Cls),
  918    forall(( member((_ :- B), Cls), leaf_goal(B, L), nonvar(L), user_goal(L) ),
  919           ( key(L, LK), all_a(LK, P), pat_lub(LK, P), assertz(callable_key(LK)) )).
  920
  921all_a(_/A, P) :- length(P, A), maplist(=(a), P).
  922
  923entries :-
  924    retractall(has_caller(_)),
  925    forall(( conv_key(K), ncls(K, Cls), member(cl(_, Kind), Cls), kind_goals(Kind, Gs),
  926             member(G, Gs), called_key(G, CK), CK \== K ),
  927           assertz(has_caller(CK))),
  928    forall(( kept(K, _), src_clauses(K, Cls), member((_ :- B), Cls),
  929             leaf_goal(B, L), nonvar(L), user_goal(L), key(L, CK), CK \== K ),
  930           assertz(has_caller(CK))),
  931    forall(entry(N, _), ( conv_key(N/0) -> pat_lub(N/0, []) ; true )),
  932    forall(directive_goal(G), entry_goal(G)),
  933    forall(( export_key(K), conv_key(K), \+ entry(_, _) ),
  934           ( all_a(K, P), pat_lub(K, P), assertz(callable_key(K)) )),
  935    forall(( conv_key(K), \+ aux_of(K, _), \+ has_caller(K), \+ entry(_, _) ),
  936           ( all_a(K, P), pat_lub(K, P), assertz(callable_key(K)) )).
  937
  938called_key(u(G), K) :- key(G, K).
  939called_key(not(S), K) :- called_key(S, K).
  940called_key(once(S), K) :- called_key(S, K).
  941called_key(ignore(S), K) :- called_key(S, K).
  942called_key(findall(_, S, _), K) :- called_key(S, K).
  943called_key(findall4(_, S, _, _), K) :- called_key(S, K).
  944called_key(aggr(_, _, S, _), K) :- called_key(S, K).
  945called_key(b(G), K) :- meta_user_goals(G, Us), member(U-N, Us), nonvar(U),
  946    callable(U), functor(U, F, A0), A is A0 + N, pred_key(F/A, _), K = F/A.
  947
  948directive_goal(G) :-
  949    src_file(_, P), db_get(item, P, it(_, dir(D, _), _)),
  950    init_goal(D, G).
  951
  952init_goal(initialization(G), G).
  953init_goal(initialization(G, _), G).
  954
  955%   a directive's goal: ordinary Prolog calls the predicates in it by name
  956entry_goal(G) :-
  957    forall(( leaf_goal(G, L), nonvar(L), user_goal(L) ),
  958           ( key(L, K), site_pat(L, [], P), pat_lub(K, P), assertz(callable_key(K)) )).
  959
  960mode_loop :-
  961    nb_setval(pl2detlog_changed, false),
  962    forall(( m_pat(K, P), P \== none, conv_key(K) ), analyse_pred(K, P)),
  963    (   nb_getval(pl2detlog_changed, true) -> mode_loop ; true ).
  964
  965analyse_pred(K, P) :-
  966    ncls(K, Cls),
  967    forall(member(Cl, Cls),
  968           ( abstract_clause(Cl, P, S) -> succ_lub(K, S) ; true )).
  969
  970abstract_clause(cl(H, Kind), P, Succ) :-
  971    copy_term(H-Kind, H1-Kind1),
  972    kind_goals(Kind1, Gs),
  973    H1 =.. [_|As],
  974    maplist(apply_pat, As, P),
  975    seen_init(As, P, S0),
  976    awalk(Gs, S0, reg, _),
  977    maplist(arg_succ, As, Succ).
  978
  979kind_goals(plain(Gs), Gs).
  980kind_goals(commit(G, B), Gs) :- append(G, B, Gs).
  981
  982apply_pat(A, g) :- !, bind_g(A).
  983apply_pat(_, _).
  984
  985arg_succ(A, g) :- ground(A), !.
  986arg_succ(_, a).
  987
  988%   Variables that may already be bound: every head variable but a fresh one at an f position.
  989seen_init(As, P, Seen) :-
  990    term_variables(As, Vs),
  991    exclude(fresh_head_var_(As, P), Vs, Seen).
  992
  993fresh_head_var_(As, P, V) :- fresh_head_var(V, As, P).
  994
  995fresh_head_var(V, As, P) :-
  996    nth1(I, As, A), A == V, nth1(I, P, f),
  997    occurrences(V, As, 1).
  998
  999occurrences(V, T, N) :- term_variables_list(T, L), include(==(V), L, Os), length(Os, N).
 1000
 1001term_variables_list(T, L) :- phrase(tvl(T), L).
 1002tvl(V) --> { var(V) }, !, [V].
 1003tvl(T) --> { compound(T) }, !, { T =.. [_|As] }, tvls(As).
 1004tvl(_) --> [].
 1005tvls([]) --> [].
 1006tvls([A|As]) --> tvl(A), tvls(As).
 1007
 1008seen_add(G, S0, S) :- term_variables(G-S0, S).
 1009
 1010%   awalk(+Goals, +Seen0, +Reg, -Seen): fails when a goal can have no answer.
 1011awalk([], S, _, S).
 1012awalk([G|Gs], S0, R, S) :- agoal(G, S0, R, S1), awalk(Gs, S1, R, S).
 1013
 1014agoal('$cut', S, _, S) :- !.
 1015agoal(b(G), S0, R, S) :- !,
 1016    ( R == reg -> meta_sites(G) ; true ),
 1017    bi_bind(G), seen_add(G, S0, S).
 1018agoal(u(G), S0, R, S) :- !,
 1019    key(G, K),
 1020    ( R == reg -> site_pat(G, S0, P), pat_lub(K, P) ; true ),
 1021    succ_of(K, Succ), Succ \== none,
 1022    G =.. [_|As], maplist(apply_succ, As, Succ),
 1023    seen_add(G, S0, S).
 1024agoal(not(Sg), S0, R, S0) :- !, asite(Sg, S0, R).
 1025agoal(once(Sg), S0, R, S) :- !, agoal(Sg, S0, R, S).
 1026agoal(ignore(Sg), S0, R, S) :- !, asite(Sg, S0, R), seen_add(Sg, S0, S).
 1027agoal(findall(T, Sg, L), S0, R, S) :- !, afind(T, Sg, L, S0, R), seen_add(L, S0, S).
 1028agoal(findall4(T, Sg, L, T0), S0, R, S) :- !,
 1029    afind(T, Sg, L0, S0, R), ( g(L0-T0) -> bind_g(L) ; true ), seen_add(L-L0, S0, S).
 1030agoal(aggr(F, E, Sg, Res), S0, R, S) :- !,
 1031    (   memberchk(F, [count, sum, max, min]) -> asite(Sg, S0, R), bind_g(Res)
 1032    ;   afind(E, Sg, Res, S0, R)
 1033    ),
 1034    seen_add(Res, S0, S).
 1035
 1036afind(T, Sg, L, S0, R) :-
 1037    asite(Sg, S0, R),
 1038    copy_term(T-Sg, T2-Sg2),
 1039    (   agoal(Sg2, S0, noreg, _) -> ( g(T2) -> bind_g(L) ; true ) ; bind_g(L) ).
 1040
 1041asite(b(G), _, R) :- !, ( R == reg -> meta_sites(G) ; true ).
 1042asite(u(G), S0, R) :- !, ( R == reg -> key(G, K), site_pat(G, S0, P), pat_lub(K, P) ; true ).
 1043asite(_, _, _).
 1044
 1045meta_sites(G) :-
 1046    forall(( meta_user_goals(G, Us), member(U-N, Us), nonvar(U), callable(U),
 1047             functor(U, F, A0), A is A0 + N, pred_key(F/A, _) ),
 1048           ( all_a(F/A, P), pat_lub(F/A, P), assertz(callable_key(F/A)) )).
 1049
 1050apply_succ(A, g) :- !, bind_g(A).
 1051apply_succ(_, _).
 1052
 1053succ_of(K, S) :- ( m_succ(K, S0) -> S = S0 ; K = _/A, length(S, A), maplist(=(a), S) ).
 1054
 1055site_pat(G, Seen, P) :-
 1056    G =.. [_|As],
 1057    maplist(site_arg(As, Seen), As, P).
 1058
 1059site_arg(_, _, A, g) :- ground(A), !.
 1060site_arg(As, Seen, A, f) :- var(A), \+ var_in(Seen, A), occurrences(A, As, 1), !.
 1061site_arg(_, _, _, a).
 1062
 1063pat_lub(K, P) :-
 1064    (   m_pat(K, Old) -> true ; Old = none ),
 1065    lub(Old, P, New),
 1066    (   New == Old -> true
 1067    ;   retractall(m_pat(K, _)), assertz(m_pat(K, New)), nb_setval(pl2detlog_changed, true)
 1068    ).
 1069
 1070succ_lub(K, S) :-
 1071    (   m_succ(K, Old) -> true ; Old = none ),
 1072    lub(Old, S, New),
 1073    (   New == Old -> true
 1074    ;   retractall(m_succ(K, _)), assertz(m_succ(K, New)), nb_setval(pl2detlog_changed, true)
 1075    ).
 1076
 1077lub(none, P, P) :- !.
 1078lub(P, none, P) :- !.
 1079lub(P, Q, R) :- maplist(lub1, P, Q, R).
 1080lub1(X, X, X) :- !.
 1081lub1(_, _, a).
 1082
 1083                 /*******************************
 1084                 *    EFFECTS AND DETERMINISM   *
 1085                 *******************************/
 1086
 1087effects :-
 1088    retractall(eff_key(_)),
 1089    forall(kept(K, _), assertz(eff_key(K))),
 1090    eff_loop.
 1091
 1092eff_loop :-
 1093    nb_setval(pl2detlog_changed, false),
 1094    forall(( conv_key(K), \+ eff_key(K), ncls(K, Cls), member(cl(_, Kind), Cls),
 1095             kind_goals(Kind, Gs), member(G, Gs), goal_eff(G) ),
 1096           ( eff_key(K) -> true ; assertz(eff_key(K)), nb_setval(pl2detlog_changed, true) )),
 1097    (   nb_getval(pl2detlog_changed, true) -> eff_loop ; true ).
 1098
 1099%   predicates that can have infinitely many answers (a builtin generator without end)
 1100infinite :-
 1101    retractall(inf_key(_)),
 1102    inf_loop.
 1103
 1104inf_loop :-
 1105    nb_setval(pl2detlog_changed, false),
 1106    forall(( conv_key(K), \+ inf_key(K), ncls(K, Cls), member(cl(_, Kind), Cls),
 1107             kind_goals(Kind, Gs), member(G, Gs), goal_inf(G) ),
 1108           ( inf_key(K) -> true ; assertz(inf_key(K)), nb_setval(pl2detlog_changed, true) )),
 1109    (   nb_getval(pl2detlog_changed, true) -> inf_loop ; true ).
 1110
 1111goal_inf(b(G)) :- infinite_gen(G).
 1112goal_inf(u(G)) :- key(G, K), inf_key(K).
 1113
 1114infinite_gen(between(_, H, _)) :- ( H == inf ; H == infinite ).
 1115infinite_gen(repeat).
 1116
 1117goal_eff(b(G)) :- bi_effect(G).
 1118goal_eff(u(G)) :- key(G, K), eff_key(K).
 1119goal_eff(not(S)) :- goal_eff(S).
 1120goal_eff(once(S)) :- goal_eff(S).
 1121goal_eff(ignore(S)) :- goal_eff(S).
 1122goal_eff(findall(_, S, _)) :- goal_eff(S).
 1123goal_eff(findall4(_, S, _, _)) :- goal_eff(S).
 1124goal_eff(aggr(_, _, S, _)) :- goal_eff(S).
 1125
 1126%   Greatest fixpoint: assume every predicate is deterministic, drop those that are not.
 1127dets :-
 1128    retractall(det_key(_)),
 1129    forall(( conv_key(K), m_pat(K, P), P \== none ), assertz(det_key(K))),
 1130    det_loop.
 1131
 1132det_loop :-
 1133    nb_setval(pl2detlog_changed, false),
 1134    forall(det_key(K),
 1135           (   det_check(K) -> true
 1136           ;   retract(det_key(K)), nb_setval(pl2detlog_changed, true)
 1137           )),
 1138    (   nb_getval(pl2detlog_changed, true) -> det_loop ; true ).
 1139
 1140det_check(K) :-
 1141    m_pat(K, P),
 1142    resolved(K, Rs),
 1143    det_pairs(Rs, P),
 1144    forall(member(r(H, Kind), Rs), det_body(H, Kind, P)).
 1145
 1146det_pairs([], _).
 1147det_pairs([R|Rs], P) :-
 1148    forall(member(R2, Rs), ( R = r(_, commit(_, _)) -> true ; exclusive(R, R2, P, _) )),
 1149    det_pairs(Rs, P).
 1150
 1151det_body(H, plain(Gs), P) :- annotate(H, Gs, P, As), forall(member(A, As), arg(2, A, true)).
 1152det_body(H, commit(G, B), P) :-
 1153    append(G, B, Gs), annotate(H, Gs, P, As),
 1154    length(G, NG), length(Pre, NG), append(Pre, Post, As),
 1155    forall(member(A, Post), arg(2, A, true)).
 1156
 1157%   resolved(+K, -Rs): the clauses, with each unnecessary cut removed.
 1158resolved(K, Rs) :-
 1159    m_pat(K, P),
 1160    ncls(K, Cls),
 1161    resolve_cuts(Cls, P, Rs).
 1162
 1163resolve_cuts([], _, []).
 1164resolve_cuts([cl(H, Kind)|Cs], P, [r(H, Kind1)|Rs]) :-
 1165    (   Kind = commit(G, B), cut_unnecessary(H, G, Cs, P)
 1166    ->  append(G, B, Gs), Kind1 = plain(Gs)
 1167    ;   Kind1 = Kind
 1168    ),
 1169    resolve_cuts(Cs, P, Rs).
 1170
 1171cut_unnecessary(H, G, Later, P) :-
 1172    annotate(H, G, P, As),
 1173    forall(member(A, As), arg(2, A, true)),
 1174    forall(member(cl(H2, K2), Later), exclusive(r(H, commit(G, [])), r(H2, K2), P, _)).
 1175
 1176%   exclusive(+R1, +R2, +P, -How): no call with pattern P can enter both clauses.
 1177exclusive(r(H1, K1), r(H2, K2), P, How) :-
 1178    lead_tests(K1, T1), lead_tests(K2, T2),
 1179    copy_term(H1-T1, A1-U1), copy_term(H2-T2, A2-U2),
 1180    A1 =.. [_|As1], A2 =.. [_|As2],
 1181    (   g_clash(As1, As2, P, How)
 1182    ->  true
 1183    ;   form(mnn),
 1184        g_unify(As1, As2, P),
 1185        (   member(b(T), U1), ground(T), \+ safe_test(T)
 1186        ;   member(b(T), U2), ground(T), \+ safe_test(T)
 1187        ;   member(b(X), U1), member(b(Y), U2), complementary(X, Y)
 1188        )
 1189    ->  How = guard
 1190    ).
 1191
 1192g_clash(As1, As2, P, How) :-
 1193    nth1(I, P, g), nth1(I, As1, X), nth1(I, As2, Y),
 1194    \+ X = Y, !,
 1195    ( I == 1 -> How = index ; How = guard ).
 1196
 1197g_unify([], [], []).
 1198g_unify([X|Xs], [Y|Ys], [M|Ms]) :-
 1199    ( M == g -> X = Y ; true ),
 1200    g_unify(Xs, Ys, Ms).
 1201
 1202lead_tests(plain(Gs), Ts) :- lead_tests_(Gs, Ts).
 1203lead_tests(commit(G, _), Ts) :- lead_tests_(G, Ts).
 1204lead_tests_([b(T)|Gs], [b(T)|Ts]) :- test_bi(T), !, lead_tests_(Gs, Ts).
 1205lead_tests_(_, []).
 1206
 1207%   annotate(+Head, +Goals, +Pattern, -Anns): an(Goal, Det, Total, GroundBefore, InnerDet)
 1208annotate(H, Gs, P, Anns) :-
 1209    term_variables(H-Gs, OVs),
 1210    copy_term(H-Gs-OVs, H1-Gs1-CVs),
 1211    H1 =.. [_|As],
 1212    maplist(apply_pat, As, P),
 1213    seen_init(As, P, S0),
 1214    ann_walk(Gs, Gs1, OVs, CVs, S0, Anns0),
 1215    add_shared(Anns0, H, [], Anns).
 1216
 1217%   an(Goal, Det, Total, GroundBefore, InnerDet, Shared): Shared are the goal's variables that
 1218%   occur elsewhere in the clause
 1219add_shared([], _, _, []).
 1220add_shared([an(G, D, T, GB, ID)|As], H, Before, [an(G, D, T, GB, ID, Sh)|Rs]) :-
 1221    rest_goals(As, After),
 1222    term_variables(H-Before-After, O),
 1223    term_variables(G, GV),
 1224    shared_vars(GV, O, Sh),
 1225    add_shared(As, H, [G|Before], Rs).
 1226
 1227ann_walk([], [], _, _, _, []).
 1228ann_walk([G|Gs], [A|As], OVs, CVs, S0, [an(G, Det, Total, GB, ID)|Rest]) :-
 1229    ground_before(OVs, CVs, GB),
 1230    goal_det(A, Det), inner_det(A, ID),
 1231    ( A = b(AG), bi_total(AG, S0) -> Total = true ; Total = false ),
 1232    (   agoal(A, S0, noreg, S1)
 1233    ->  ann_walk(Gs, As, OVs, CVs, S1, Rest)
 1234    ;   maplist(unreached, Gs, Rest)
 1235    ).
 1236
 1237unreached(G, an(G, true, false, [], true)).  % add_shared adds the 6th argument
 1238
 1239ground_before([], [], []).
 1240ground_before([O|Os], [C|Cs], GB) :-
 1241    ( ground(C) -> GB = [O|GB1] ; GB = GB1 ),
 1242    ground_before(Os, Cs, GB1).
 1243
 1244goal_det(b(G), D) :- !, ( bi_nondet(G) -> D = false ; D = true ).
 1245goal_det(u(G), D) :- !, key(G, K), ( det_key(K) -> D = true ; D = false ).
 1246goal_det(_, true).
 1247
 1248inner_det(G, D) :- inner(G, S), !, goal_det(S, D).
 1249inner_det(_, true).
 1250
 1251inner(not(S), S).
 1252inner(once(S), S).
 1253inner(ignore(S), S).
 1254inner(findall(_, S, _), S).
 1255inner(findall4(_, S, _, _), S).
 1256inner(aggr(_, _, S, _), S).
 1257
 1258                 /*******************************
 1259                 *       MNN SOURCE REWRITES    *
 1260                 *******************************/
 1261
 1262%   Accumulate an appended result:  p([], []).  p([H|T], R) :- p(T, RT), append(RT, E, R).
 1263%   With acc(L, A) = p(L) ++ A:  acc([], A) = A  and  acc([H|T], A) = acc(T, E ++ A), by the
 1264%   associativity of ++; so p(L) = acc(L, []) for every proper list L (a ground first argument).
 1265accumulate :-
 1266    forall(( conv_key(K), K = Name/2, m_pat(K, [g, _]), ncls(K, [C1, C2]),
 1267             acc_shape(K, C1, C2, H, T, E) ),
 1268           acc_rewrite(Name, H, T, E)).
 1269
 1270acc_shape(Name/2, cl(B, plain([])), cl(Hd, plain([u(Rec), App])), H, T, E) :-
 1271    B =.. [Name, [], []],
 1272    Hd =.. [Name, [H|T], R],
 1273    Rec =.. [Name, T1, RT], T1 == T,
 1274    app_goal(App, RT1, E, R1), RT1 == RT, R1 == R,
 1275    var(H), var(T), var(R), var(RT),
 1276    term_variables(E, EV),
 1277    forall(member(V, EV), V == H).
 1278
 1279app_goal(b(append(A, B, C)), A, B, C).
 1280app_goal(u(G), A, B, C) :- G =.. [F, A, B, C], is_append(F/3).
 1281
 1282is_append(K) :-
 1283    ncls(K, [cl(H1, plain([])), cl(H2, plain([u(R)]))]),
 1284    K = F/3,
 1285    H1 =.. [F, [], L1, L2], L1 == L2, var(L1),
 1286    H2 =.. [F, [X|Xs], Y, [X1|Zs]], X == X1,
 1287    R =.. [F, Xs1, Y1, Zs1], Xs1 == Xs, Y1 == Y, Zs1 == Zs,
 1288    var(X), var(Xs), var(Y), var(Zs).
 1289
 1290acc_rewrite(Name, _, _, _) :-
 1291    format(atom(AN), '~w__acc', [Name]),
 1292    retractall(dbv(ncl, Name/2, _, _, _)),
 1293    fresh('L', L), fresh('R', R),
 1294    H0 =.. [Name, L, R], C0 =.. [AN, L, [], R],
 1295    db_put(ncl, Name/2, cl(H0, plain([u(C0)]))),
 1296    aggregate_all(count, pred_key(_, _), I),
 1297    assertz(pred_key(AN/3, I)), assertz(aux_of(AN/3, Name/2)), assertz(aux_root(AN/3, Name/2)),
 1298    fresh('A', A), B1 =.. [AN, [], A, A],
 1299    db_put(ncl, AN/3, cl(B1, plain([]))),
 1300    fail.
 1301acc_rewrite(Name, H, T, E) :-
 1302    format(atom(AN), '~w__acc', [Name]),
 1303    fresh('A', A), fresh('R', R),
 1304    (   is_list(E) -> append(E, A, A1), Pre = []
 1305    ;   fresh('A1', A1), Pre = [b(append(E, A, A1))]
 1306    ),
 1307    H2 =.. [AN, [H|T], A, R], Rec =.. [AN, T, A1, R],
 1308    append(Pre, [u(Rec)], Gs),
 1309    db_put(ncl, AN/3, cl(H2, plain(Gs))),
 1310    format(atom(N), 'MNN accumulate: ~w(L) ++ A = ~w(L, A), so ~w(L) = ~w(L, []) (++ is associative; L is a proper list, ground at every call)', [Name, AN, Name, AN]),
 1311    assertz(note(Name/2, N)).
 1312
 1313%   UNFOLD: a call of a predicate with one clause whose body is pure builtins and whose head
 1314%   arguments are distinct variables is that body (the clause, renamed, in its place).
 1315unfold :-
 1316    findall(K, ( conv_key(K), unfoldable(K) ), Us),
 1317    forall(( conv_key(K), \+ memberchk(K, Us), ncls(K, Cls),
 1318             member(cl(_, Kd), Cls), kind_goals(Kd, Gs), member(u(G), Gs),
 1319             key(G, GK), memberchk(GK, Us) ),
 1320           true),
 1321    forall(( conv_key(K), \+ memberchk(K, Us) ), unfold_pred(K, Us)).
 1322
 1323unfoldable(K) :-
 1324    \+ entry(_, _) -> fail ;
 1325    ncls(K, [cl(H, plain(Gs))]), Gs \== [],
 1326    forall(member(G, Gs), ( G = b(B), \+ bi_effect(B), bi_nondet(B) -> true ; G = b(B), \+ bi_effect(B) )),
 1327    member(b(B0), Gs), bi_nondet(B0), !,
 1328    H =.. [_|As], is_set_vars(As).
 1329
 1330unfold_pred(K, Us) :-
 1331    ncls(K, Cls),
 1332    maplist(unfold_clause(Us, K), Cls, Cls1),
 1333    (   Cls1 == Cls -> true
 1334    ;   retractall(dbv(ncl, K, _, _, _)),
 1335        forall(member(C, Cls1), db_put(ncl, K, C))
 1336    ).
 1337
 1338unfold_clause(Us, K, cl(H, plain(Gs)), cl(H, plain(Gs1))) :- !, unfold_goals(Gs, Us, K, Gs1).
 1339unfold_clause(Us, K, cl(H, commit(G, B)), cl(H, commit(G1, B1))) :-
 1340    unfold_goals(G, Us, K, G1), unfold_goals(B, Us, K, B1).
 1341
 1342unfold_goals([], _, _, []).
 1343unfold_goals([u(G)|Gs], Us, K, Out) :-
 1344    key(G, GK), memberchk(GK, Us), !,
 1345    ncls(GK, [cl(H, plain(Body))]),
 1346    H = G,
 1347    (   note(K, N), sub_atom(N, 0, _, _, 'MNN unfold') -> true
 1348    ;   format(atom(N), 'MNN unfold: ~q has one clause of pure builtins, so its body is written in place of the call', [GK]),
 1349        assertz(note(K, N))
 1350    ),
 1351    append(Body, Rest, Out),
 1352    unfold_goals(Gs, Us, K, Rest).
 1353unfold_goals([G|Gs], Us, K, [G|Rest]) :- unfold_goals(Gs, Us, K, Rest).
 1354
 1355%   MEMO: a deterministic, pure, tree-recursive predicate called with ground inputs and
 1356%   fresh outputs is tabled.  Its one answer per call is a function of the call.
 1357memo :-
 1358    forall(( det_key(K), \+ eff_key(K), m_pat(K, P), \+ memberchk(a, P), memberchk(g, P),
 1359             tree_recursive(K) ),
 1360           ( assertz(table_key(K)),
 1361             format(atom(N), 'MNN memo: pure and deterministic with ground inputs (~w), so each call has one answer: tabled', [P]),
 1362             assertz(note(K, N)) )).
 1363
 1364tree_recursive(K) :-
 1365    ncls(K, Cls), member(cl(_, Kind), Cls), kind_goals(Kind, Gs),
 1366    include(self_call(K), Gs, Calls), length(Calls, N), N >= 2, !.
 1367
 1368self_call(K, u(G)) :- key(G, K).
 1369
 1370                 /*******************************
 1371                 *          CONVERSION          *
 1372                 *******************************/
 1373
 1374convert_form(Form) :-
 1375    reset_form,
 1376    assertz(form(Form)),
 1377    normalise,
 1378    (   Form == mnn -> unfold ; true ),
 1379    modes, effects, infinite, dets,
 1380    (   Form == mnn
 1381    ->  accumulate,
 1382        (   note(_, _) -> modes, effects, infinite, dets ; true ),
 1383        memo
 1384    ;   true
 1385    ),
 1386    plan.
 1387
 1388%   Which versions are needed: what ordinary Prolog calls by name, and what that code calls.
 1389plan :-
 1390    forall(callable_key(K), need_key(K, prolog)),
 1391    forall(entry(Name, _), need_key(Name/0, entry)),
 1392    gen_loop,
 1393    (   entry(_, _)
 1394    ->  true
 1395    ;   forall(( pred_key(K, _), \+ aux_of(K, _), conv_key(K),
 1396                 \+ dbv(out, K-det, _, _, _), \+ dbv(out, K-prolog, _, _, _) ),
 1397               ( assertz(note(K, 'as written too, so that it can be called by name')),
 1398                 assertz(done(K, prolog)), gen_kept(K) )),
 1399        gen_loop
 1400    ),
 1401    forall(( pred_key(K, _), \+ aux_of(K, _), \+ dbv(out, K-_, _, _, _) ),
 1402           ( src_clauses(K, Cls), forall(member(C, Cls), out(K, dead, C)) )).
 1403
 1404need_key(K, M) :- ( need(K, M) -> true ; assertz(need(K, M)) ).
 1405
 1406gen_loop :-
 1407    (   need(K, M), \+ done(K, M)
 1408    ->  assertz(done(K, M)),
 1409        catch(gen(K, M), E, gen_failed(K, M, E)),
 1410        gen_loop
 1411    ;   true
 1412    ).
 1413
 1414gen_failed(K, M, E) :-
 1415    retractall(dbv(out, K-M, _, _, _)),
 1416    format(user_error, "% pl2detlog: ~q (~w version) kept as Prolog: ~q~n", [K, M, E]),
 1417    assertz(note(K, 'kept as Prolog: this version could not be converted')),
 1418    (   done(K, prolog) -> true ; assertz(done(K, prolog)), gen_kept(K) ).
 1419
 1420%   gen(+Key, +Mode): write the clauses of one version into dbv(out, Key-Mode, Clause).
 1421gen(K, prolog) :- !,
 1422    (   kept(K, _) -> gen_kept(K)
 1423    ;   pred_key(K, _), \+ m_pat(K, _) -> gen_kept(K)
 1424    ;   det_key(K) -> need_key(K, det)
 1425    ;   eff_key(K) -> gen_kept(K)
 1426    ;   inf_key(K) -> gen_kept(K)
 1427    ;   need_key(K, all), gen_wrapper(K)
 1428    ).
 1429gen(K, entry) :- !, gen_entry(K).
 1430gen(K, det) :- !, gen_det(K).
 1431gen(K, first) :- !, gen_first(K).
 1432gen(K, all) :- !, gen_all(K).
 1433
 1434out(K, M, Cl) :- copy_term(Cl, Cl1), db_put(out, K-M, Cl1).
 1435
 1436gen_kept(K) :-
 1437    prolog_clauses(K, Cls),
 1438    forall(member(C, Cls), out(K, prolog, C)),
 1439    forall(( member((_ :- B), Cls), leaf_goal(B, L), nonvar(L), user_goal(L) ),
 1440           ( key(L, LK), need_key(LK, prolog) )).
 1441
 1442gen_wrapper(K) :-
 1443    K = N/A, length(Ps, A), name_params(K, Ps),
 1444    H =.. [N|Ps], all_name(K, AN),
 1445    fresh('As', As),
 1446    append(Ps, [As, []], AA), C =.. [AN|AA],
 1447    out(K, prolog, (H :- C, dl_member(H, As))).
 1448
 1449all_name(N/_, AN) :- atom_concat(N, '__all', AN).
 1450first_name(N/_, FN) :- atom_concat(N, '__first', FN).
 1451
 1452name_params(K, Ps) :-
 1453    (   ncls(K, [cl(H, _)|_]), H =.. [_|As] -> maplist(param_name, As, Ps) ; true ),
 1454    (   ncls(K, Cls) -> term_variables(Cls, CVs), maplist(var_hint, CVs, Used) ; Used = [] ),
 1455    distinct_names(Ps, Used, [], _).
 1456
 1457%   distinct_names(+Vars, +UsedHints, +Taken0, -Taken): every variable gets its own name;
 1458%   one with no name, or with a name taken by an earlier one, gets a free letter
 1459distinct_names([], _, T, T).
 1460distinct_names([V|Vs], Used, T0, T) :-
 1461    (   get_attr(V, pl2detlog, N), N \== '', \+ memberchk(N, T0), \+ sub_atom(N, 0, 1, _, '_')
 1462    ->  true
 1463    ;   member(N, ['X', 'Y', 'Z', 'W', 'V', 'U', 'S', 'R', 'Q', 'P', 'M', 'K', 'J']),
 1464        \+ memberchk(N, Used), \+ memberchk(N, T0)
 1465    ->  put_attr(V, pl2detlog, N)
 1466    ;   length(T0, I0), I is I0 + 1, format(atom(N), 'A~w', [I]), put_attr(V, pl2detlog, N)
 1467    ),
 1468    distinct_names(Vs, Used, [N|T0], T).
 1469
 1470param_name(A, P) :- ( var(A), get_attr(A, pl2detlog, N) -> fresh(N, P) ; true ).
 1471numbered_params([], _).
 1472numbered_params([P|Ps], I) :-
 1473    ( get_attr(P, pl2detlog, _) -> true ; format(atom(N), 'A~w', [I]), fresh(N, P) ),
 1474    I1 is I + 1, numbered_params(Ps, I1).
 1475
 1476%   the clauses of K as ordinary Prolog: the source, or for an auxiliary predicate its
 1477%   normalised clauses written back
 1478prolog_clauses(K, Cls) :-
 1479    (   aux_of(K, _)
 1480    ->  ncls(K, NCls), maplist(denorm_clause, NCls, Cls)
 1481    ;   src_clauses(K, Cls)
 1482    ).
 1483
 1484denorm_clause(cl(H, plain(Gs)), (H :- B)) :- denorm_goals(Gs, B).
 1485denorm_clause(cl(H, commit(G, Bd)), (H :- B)) :-
 1486    append(G, ['$cut'|Bd], Gs), denorm_goals(Gs, B).
 1487
 1488denorm_goals([], true).
 1489denorm_goals([G], B) :- !, denorm(G, B).
 1490denorm_goals([G|Gs], (B, Bs)) :- denorm(G, B), denorm_goals(Gs, Bs).
 1491
 1492denorm('$cut', !).
 1493denorm(b(G), G).
 1494denorm(u(G), G).
 1495denorm(not(S), \+ G) :- denorm(S, G).
 1496denorm(once(S), once(G)) :- denorm(S, G).
 1497denorm(ignore(S), ignore(G)) :- denorm(S, G).
 1498denorm(findall(T, S, L), findall(T, G, L)) :- denorm(S, G).
 1499denorm(findall4(T, S, L, T0), findall(T, G, L, T0)) :- denorm(S, G).
 1500denorm(aggr(F, E, S, R), aggregate_all(Spec, G, R)) :-
 1501    denorm(S, G), ( F == count -> Spec = count ; Spec =.. [F, E] ).
 1502
 1503%   the entry: Name :- the first answer of the query.
 1504gen_entry(K) :-
 1505    (   kept(K, _) -> need_key(K, prolog)
 1506    ;   det_key(K) -> need_key(K, det)
 1507    ;   K = N/_, gen_first(K, N, entry)
 1508    ).
 1509
 1510ctx(K, M, c(K, M)).
 1511
 1512%   ---- det version: same name, clauses told apart by a bound first argument ----
 1513gen_det(K) :-
 1514    resolved(K, Rs), m_pat(K, P),
 1515    ctx(K, det, Ctx),
 1516    (   table_key(K) -> K = N/A, out(K, det, (:- table(N/A))) ; true ),
 1517    det_groups(Rs, P, Groups),
 1518    forall(member(Gr, Groups), det_group(Gr, K, P, Ctx)).
 1519
 1520%   Clauses told apart by a ground argument: the first argument where the call is ground
 1521%   and every head has a functor, with two functors or more.  SWI-Prolog indexes that
 1522%   argument, so each group is entered without a choicepoint.
 1523det_groups(Rs, P, Groups) :-
 1524    Rs = [_, _|_],
 1525    nth1(I, P, g),
 1526    forall(member(r(H, _), Rs), ( arg(I, H, A), nonvar(A) )),
 1527    findall(F, ( member(r(H, _), Rs), arg(I, H, A), first_functor(A, F) ), Fs0),
 1528    list_to_set(Fs0, Fs), Fs = [_, _|_], !,
 1529    findall(Gr, ( member(F, Fs), include(has_functor(I, F), Rs, Gr) ), Groups).
 1530det_groups(Rs, _, [Rs]).
 1531
 1532first_functor(A, F) :- ( atomic(A) -> F = A ; functor(A, N, Ar), F = N/Ar ).
 1533has_functor(I, F, r(H, _)) :- arg(I, H, A), first_functor(A, F).
 1534
 1535det_group([r(H, Kind)], K, P, Ctx) :- !,
 1536    det_clause_body(H, Kind, P, Ctx, Body),
 1537    out(K, det, (H :- Body)).
 1538det_group(Rs, K, P, Ctx) :-
 1539    group_head(Rs, K, Head),
 1540    det_chain(Rs, Head, P, Ctx, Body),
 1541    out(K, det, (Head :- Body)).
 1542
 1543det_clause_body(H, plain(Gs), P, Ctx, Body) :-
 1544    annotate(H, Gs, P, As), tr_det(As, Ctx, Body).
 1545det_clause_body(H, commit(G, B), P, Ctx, Body) :-
 1546    append(G, B, Gs), annotate(H, Gs, P, As),
 1547    length(G, NG), length(AG, NG), append(AG, AB, As),
 1548    term_variables(H-B, After),
 1549    tr_first(AG, After, Ctx, GC), tr_det(AB, Ctx, BC),
 1550    conj(GC, BC, Body).
 1551
 1552%   a chain of clauses with the same first-argument functor
 1553det_chain([r(H, Kind)], Head, P, Ctx, Code) :- !,
 1554    copy_term(H-Kind, H1-Kind1),
 1555    head_match(Head, H1, U),
 1556    kind_goals(Kind1, _),
 1557    det_clause_body(H1, Kind1, P, Ctx, B),
 1558    unif_goals(U, UC), conj(UC, B, Code).
 1559det_chain([r(H, Kind)|Rs], Head, P, Ctx, if_commit(Cond, Then, Else)) :-
 1560    copy_term(H-Kind, H1-Kind1),
 1561    head_match(Head, H1, U),
 1562    (   Kind1 = commit(G, B)
 1563    ->  append(G, B, Gs), annotate(H1, Gs, P, As),
 1564        length(G, NG), length(AG, NG), append(AG, AB, As),
 1565        term_variables(Head-U-B, After),
 1566        tr_first(AG, After, Ctx, CG), tr_det(AB, Ctx, TB)
 1567    ;   Kind1 = plain(Gs),
 1568        annotate(H1, Gs, P, As),
 1569        lead_tests(plain(Gs), Ts), length(Ts, NT), length(AT, NT), append(AT, AB, As),
 1570        tr_det(AT, Ctx, CG), tr_det(AB, Ctx, TB)
 1571    ),
 1572    split_unifs(U, Head, P, CG, UC, UT),
 1573    unif_goals(UC, UCC), unif_goals(UT, UTC),
 1574    conj(UCC, CG, Cond), conj(UTC, TB, Then),
 1575    det_chain(Rs, Head, P, Ctx, Else).
 1576
 1577%   output unifications at fresh-variable positions move to the Then branch
 1578split_unifs([], _, _, _, [], []).
 1579split_unifs([V=T|Us], Head, P, CG, UC, UT) :-
 1580    Head =.. [_|Ps],
 1581    (   nth1(I, Ps, X), X == V, nth1(I, P, f), \+ occurs_in(V, CG)
 1582    ->  UC = UC1, UT = [V=T|UT1]
 1583    ;   UC = [V=T|UC1], UT = UT1
 1584    ),
 1585    split_unifs(Us, Head, P, CG, UC1, UT1).
 1586
 1587occurs_in(V, T) :- term_variables(T, Vs), var_in(Vs, V).
 1588
 1589unif_goals([], true).
 1590unif_goals([U], U) :- !.
 1591unif_goals([U|Us], (U, C)) :- unif_goals(Us, C).
 1592
 1593%   the most specific head of a group of clauses (anti-unification)
 1594group_head(Rs, K, Head) :-
 1595    findall(H, member(r(H, _), Rs), [H0|Hs0]),
 1596    copy_term([H0|Hs0], [H1|Hs]),
 1597    foldl(lgg_head, Hs, H1, Head0),
 1598    copy_term(Head0, Head),
 1599    Head =.. [_|As], term_variables(As, HVs),
 1600    term_variables([H0|Hs0], CVs), maplist(var_hint, CVs, Used),
 1601    distinct_names(HVs, Used, [], _), K = K.
 1602
 1603lgg_head(H, G0, G) :- lgg(G0, H, G, [], _).
 1604
 1605lgg(A, B, G, S0, S) :- A == B, !, G = A, S = S0.
 1606lgg(A, B, G, S0, S) :-
 1607    compound(A), compound(B), functor(A, N, Ar), functor(B, N, Ar), !,
 1608    A =.. [_|As], B =.. [_|Bs],
 1609    lgg_list(As, Bs, Gs, S0, S), G =.. [N|Gs].
 1610lgg(A, B, G, S0, S) :-
 1611    (   member((A1-B1)-V, S0), A1 == A, B1 == B -> G = V, S = S0
 1612    ;   G = V,
 1613        (   var(A), get_attr(A, pl2detlog, Nm) -> fresh(Nm, V)
 1614        ;   var(B), get_attr(B, pl2detlog, Nm) -> fresh(Nm, V)
 1615        ;   true
 1616        ),
 1617        S = [(A-B)-V|S0]
 1618    ).
 1619
 1620lgg_list([], [], [], S, S).
 1621lgg_list([A|As], [B|Bs], [G|Gs], S0, S) :- lgg(A, B, G, S0, S1), lgg_list(As, Bs, Gs, S1, S).
 1622
 1623name_head_vars(As, _) :- term_variables(As, Vs), numbered_params(Vs, 1).
 1624
 1625%   head_match(+Head, +ClauseHead, -Unifs): unify the clause's head with Head; a clause
 1626%   variable at a variable position becomes that variable, anything else is a goal V = T.
 1627head_match(Head, CH, U) :-
 1628    term_variables(Head, HVs),
 1629    hm(Head, CH, HVs, U, []).
 1630
 1631hm(V, T, HVs, U0, U) :- var(V), !,
 1632    (   var(T), \+ var_in(HVs, T) -> V = T, U0 = U
 1633    ;   U0 = [V = T|U]
 1634    ).
 1635hm(A, B, HVs, U0, U) :-
 1636    A =.. [_|As], B =.. [_|Bs],
 1637    foldl(hm2(HVs), As, Bs, U0, U).
 1638hm2(HVs, A, B, U0, U) :- hm(A, B, HVs, U0, U).
 1639
 1640%   ---- first-answer version (MNN): p__first/N, semideterministic ----
 1641gen_first(K) :-
 1642    first_name(K, FN),
 1643    gen_first(K, FN, first).
 1644
 1645gen_first(K, FN, Mode) :-
 1646    resolved(K, Rs), m_pat(K, P),
 1647    ctx(K, Mode, Ctx),
 1648    K = _/A, length(Ps, A), name_params(K, Ps),
 1649    H =.. [FN|Ps],
 1650    Head =.. [x|Ps],
 1651    first_chain(Rs, Head, P, Ctx, Code),
 1652    out(K, Mode, (H :- Code)).
 1653
 1654first_chain([], _, _, _, fail).
 1655first_chain([r(CH, Kind)|Rs], Head, P, Ctx, Code) :-
 1656    copy_term(CH-Kind, CH1-Kind1),
 1657    CH1 =.. [_|CA], Head =.. [_|HA], CH2 =.. [x|CA],
 1658    head_match(Head, CH2, U), unif_goals(U, UC),
 1659    term_variables(HA-UC, HV),
 1660    (   Kind1 = commit(G, B)
 1661    ->  append(G, B, Gs), annotate(CH2, Gs, P, As),
 1662        length(G, NG), length(AG, NG), append(AG, AB, As),
 1663        term_variables(HV-B, After),
 1664        tr_first(AG, After, Ctx, CG), tr_first(AB, HV, Ctx, TB),
 1665        conj(UC, CG, Cond),
 1666        (   Rs == [] -> conj(Cond, TB, Code)
 1667        ;   first_chain(Rs, Head, P, Ctx, Else), Code = if_commit(Cond, TB, Else)
 1668        )
 1669    ;   Kind1 = plain(Gs),
 1670        annotate(CH2, Gs, P, As),
 1671        tr_first(As, HV, Ctx, BC), conj(UC, BC, Cond),
 1672        (   Rs == [] -> Code = Cond
 1673        ;   first_chain(Rs, Head, P, Ctx, Else), Code = if_commit(Cond, true, Else)
 1674        )
 1675    ).
 1676
 1677%   ---- all-answers version: p__all(Args..., Answers, Tail) ----
 1678gen_all(K) :-
 1679    resolved(K, Rs), m_pat(K, P),
 1680    ctx(K, all, Ctx),
 1681    K = N/A, length(Ps, A), name_params(K, Ps),
 1682    all_name(K, AN), fresh('Out', Out), fresh('T', T),
 1683    append(Ps, [Out, T], HA), H =.. [AN|HA],
 1684    (   form(mnn), all_facts(Rs, Facts)
 1685    ->  G =.. [N|Ps], Code = dl_match(Facts, G, Out, T),
 1686        assertz(note(K, 'MNN facts as data: answers are the facts that unify with the call'))
 1687    ;   all_chain(Rs, N, Ps, P, Out, T, Ctx, Code)
 1688    ),
 1689    out(K, all, (H :- Code)).
 1690
 1691all_facts(Rs, Facts) :-
 1692    maplist(fact_of, Rs, Facts).
 1693fact_of(r(H, plain([])), H).
 1694
 1695all_chain([], _, _, _, Out, T, _, Out = T).
 1696all_chain([r(CH, Kind)|Rs], N, Ps, P, Out, T, Ctx, Code) :-
 1697    copy_term(CH-Kind, CH1-Kind1),
 1698    arg_copies(Ps, P, Ps1, CopyGs),
 1699    Head =.. [x|Ps1], CH1 =.. [_|CA], CH2 =.. [x|CA],
 1700    head_match(Head, CH2, U), unif_goals(U, UC),
 1701    Ans =.. [N|Ps1],
 1702    term_variables(Ps1-UC, PV),
 1703    (   Kind1 = commit(G, B)
 1704    ->  append(G, B, Gs), annotate(CH2, Gs, P, As),
 1705        length(G, NG), length(AG, NG), append(AG, AB, As),
 1706        term_variables(PV-B, After),
 1707        tr_first(AG, After, Ctx, CG), conj(UC, CG, Cond),
 1708        tr_all(AB, Ans, Out, T, PV, Ctx, Then),
 1709        all_chain(Rs, N, Ps, P, Out, T, Ctx, Else),
 1710        conj(CopyGs, if_commit(Cond, Then, Else), Code)
 1711    ;   Kind1 = plain(Gs),
 1712        annotate(CH2, Gs, P, As),
 1713        (   Rs == [] -> T1 = T ; fresh('T1', T1) ),
 1714        tr_all(As, Ans, Out, T1, PV, Ctx, Body),
 1715        (   UC == true -> C1 = Body ; C1 = if_commit(UC, Body, Out = T1) ),
 1716        (   Rs == [] -> Rest = true ; all_chain(Rs, N, Ps, P, T1, T, Ctx, Rest) ),
 1717        conj(CopyGs, C1, C2), conj(C2, Rest, Code)
 1718    ).
 1719
 1720%   each clause works on a copy of the arguments that are not ground
 1721arg_copies(Ps, P, Ps1, Copy) :-
 1722    maplist(arg_copy, Ps, P, Ps1, Pairs),
 1723    exclude(==(none), Pairs, Cs),
 1724    (   Cs == [] -> Copy = true
 1725    ;   pairs_keys_values(Cs, From, To),
 1726        Copy = copy_term(From, To)
 1727    ).
 1728
 1729arg_copy(X, g, X, none) :- !.
 1730arg_copy(X, f, Y, none) :- !, copy_hint(X, Y).
 1731arg_copy(X, a, Y, X-Y) :- copy_hint(X, Y).
 1732
 1733copy_hint(X, Y) :- ( get_attr(X, pl2detlog, N) -> atom_concat(N, '1', N1), fresh(N1, Y) ; true ).
 1734
 1735                 /*******************************
 1736                 *     GOALS IN EACH MODE       *
 1737                 *******************************/
 1738
 1739conj(true, X, X) :- !.
 1740conj(X, true, X) :- !.
 1741conj(X, Y, (X, Y)).
 1742
 1743%   det: every goal has at most one answer
 1744tr_det([], _, true).
 1745tr_det([A|As], Ctx, Code) :-
 1746    tr_det_goal(A, Ctx, C1), tr_det(As, Ctx, C2), conj(C1, C2, Code).
 1747
 1748tr_det_goal(an(b(G), _, _, _, _, _), _, G) :- !.
 1749tr_det_goal(an(u(G), _, _, _, _, _), Ctx, C) :- !, call_det(G, Ctx, C).
 1750tr_det_goal(an(not(S), _, _, _, ID, _), Ctx, if_commit(C, fail, true)) :- !, first_simple(S, ID, Ctx, C).
 1751tr_det_goal(an(once(S), _, _, _, ID, _), Ctx, C) :- !, first_simple(S, ID, Ctx, C).
 1752tr_det_goal(an(ignore(S), _, _, _, ID, _), Ctx, if_commit(C, true, true)) :- !, first_simple(S, ID, Ctx, C).
 1753tr_det_goal(an(findall(T, S, L), _, _, GB, ID, Sh), Ctx, C) :- !, tr_findall(T, S, ID, L, GB-Sh, Ctx, C).
 1754tr_det_goal(an(findall4(T, S, L, T0), _, _, GB, ID, Sh), Ctx, (C, append(L0, T0, L))) :- !,
 1755    fresh('L0', L0), tr_findall(T, S, ID, L0, GB-Sh, Ctx, C).
 1756tr_det_goal(an(aggr(F, E, S, R), _, _, GB, ID, Sh), Ctx, C) :- !, tr_aggr(F, E, S, ID, R, GB-Sh, Ctx, C).
 1757tr_det_goal(an('$cut', _, _, _, _, _), _, true).
 1758
 1759%   a deterministic user call: in place, or inlined when it is a one-clause auxiliary
 1760%   predicate whose head arguments are distinct variables
 1761call_det(G, _, C) :-
 1762    key(G, K), aux_of(K, _), \+ table_key(K),
 1763    inline_clause(K, (H :- B)), !,
 1764    copy_term(H-B, H1-B1), H1 = G, C = B1.
 1765call_det(G, _, G) :- key(G, K), need_key(K, det).
 1766
 1767inline_clause(K, Cl) :- db_get(inl, K, Cl0), !, Cl = Cl0.
 1768inline_clause(K, Cl) :-
 1769    \+ done(K, det),
 1770    assertz(done(K, det)),
 1771    gen(K, det),
 1772    db_all(out, K-det, Cls),
 1773    partition(main_clause(K), Cls, [(H :- B)], Others),
 1774    H =.. [_|As], is_set_vars(As),
 1775    \+ calls_self(B, H), !,
 1776    retractall(dbv(out, K-det, _, _, _)),
 1777    forall(member(O, Others), db_put(out, K-det, O)),
 1778    Cl = (H :- B),
 1779    db_put(inl, K, Cl),
 1780    assertz(inlined(K)).
 1781inline_clause(K, _) :- need_key(K, det), fail.
 1782
 1783main_clause(N/A, (H :- _)) :- functor(H, N, A).
 1784
 1785is_set_vars(As) :- maplist(var, As), sort(As, S), length(S, N), length(As, N).
 1786
 1787calls_self(B, H) :- functor(H, N, A), sub_term(T, B), callable(T), functor(T, N, A), !.
 1788
 1789%   the first answer of one simple goal, bindings kept
 1790first_simple(b(G), true, _, G) :- !.
 1791first_simple(b(G), false, _, dl_once(G)) :- !.
 1792first_simple(u(G), true, Ctx, C) :- !, call_det(G, Ctx, C).
 1793first_simple(u(G), false, _, C) :-
 1794    key(G, K),
 1795    (   kept(K, _)
 1796    ->  C = dl_once(G), need_key(K, prolog)
 1797    ;   first_call(G, C), need_key(K, first)
 1798    ).
 1799
 1800kept_or_effect_all(K) :- ( kept(K, _) ; eff_key(K) ), !.
 1801
 1802first_call(G, C) :- key(G, K), first_name(K, FN), G =.. [_|As], C =.. [FN|As].
 1803all_call(G, Ans, C) :-
 1804    key(G, K), all_name(K, AN), G =.. [_|As],
 1805    fresh('As', Ans), append(As, [Ans, []], AA), C =.. [AN|AA].
 1806
 1807%   findall over a simple goal
 1808tr_findall(T, S, true, L, GB-Sh, Ctx, Code) :- !,
 1809    det_inner(S, Ctx, G),
 1810    term_variables(G-T, GTV), include(var_in(Sh), GTV, Sh1), exclude(var_in(GB), Sh1, NG),
 1811    copy_nonground(NG, G-T, G1-T1, CopyG),
 1812    conj(CopyG, if_commit(G1, L = [T1], L = []), Code).
 1813tr_findall(T, b(G), false, L, _, _, Code) :- !,
 1814    (   bi_effect(G) -> Code = findall(T, G, L)
 1815    ;   fresh('As', As), Code = (dl_all(G, As, []), dl_project(As, G, T, L))
 1816    ).
 1817tr_findall(T, u(G), false, L, _, _, Code) :-
 1818    key(G, K),
 1819    (   kept_or_effect_all(K)
 1820    ->  Code = findall(T, G, L), need_key(K, prolog)
 1821    ;   need_key(K, all), all_call(G, As, AC),
 1822        Code = (AC, dl_project(As, G, T, L))
 1823    ).
 1824
 1825det_inner(b(G), _, G).
 1826det_inner(u(G), Ctx, C) :- call_det(G, Ctx, C).
 1827
 1828tr_aggr(count, _, S, ID, N, GB-Sh, Ctx, Code) :-
 1829    (   ID == true
 1830    ->  det_inner(S, Ctx, G), term_variables(G, GV), include(var_in(Sh), GV, Sh1),
 1831        exclude(var_in(GB), Sh1, NG),
 1832        copy_nonground(NG, G, G1, CopyG), conj(CopyG, if_commit(G1, N = 1, N = 0), Code)
 1833    ;   S = u(G), key(G, K), \+ kept_or_effect_all(K)
 1834    ->  need_key(K, all), all_call(G, As, AC), Code = (AC, length(As, N))
 1835    ;   S = b(G), \+ bi_effect(G)
 1836    ->  fresh('As', As), Code = (dl_all(G, As, []), length(As, N))
 1837    ;   S = u(G) -> key(G, K), need_key(K, prolog), Code = aggregate_all(count, G, N)
 1838    ;   S = b(G), Code = aggregate_all(count, G, N)
 1839    ).
 1840tr_aggr(F, E, S, ID, R, GS, Ctx, Code) :-
 1841    F \== count,
 1842    fresh('Vs', Vs),
 1843    tr_findall(E, S, ID, Vs, GS, Ctx, C1),
 1844    Code = (C1, dl_aggregate(F, Vs, R)).
 1845
 1846%   first: the first answer of a conjunction (semideterministic); Ctx0 are the variables
 1847%   used outside the conjunction
 1848tr_first(As, Ctx0, Ctx, Code) :- tr_first_(As, Ctx0, Ctx, Code).
 1849
 1850tr_first_([], _, _, true).
 1851tr_first_([A|As], Out, Ctx, Code) :-
 1852    A = an(G, Det, _, _, _, _),
 1853    term_variables(G, GV), append(GV, Out, Out1),
 1854    (   Det == true
 1855    ->  tr_det_goal(A, Ctx, C1), tr_first_(As, Out1, Ctx, C2), conj(C1, C2, Code)
 1856    ;   As == []
 1857    ->  first_simple(G, false, Ctx, Code)
 1858    ;   form(mnn), all_total(As)
 1859    ->  first_simple(G, false, Ctx, C1), tr_det(As, Ctx, C2), conj(C1, C2, Code)
 1860    ;   form(mnn), G = b(BG), \+ bi_effect(BG), fusable(As, first)
 1861    ->  tr_fused(As, Ctx, Test), Code = dl_fused_first(BG, Test),
 1862        fuse_note(Ctx)
 1863    ;   scan(A, As, Out, Ctx, Code)
 1864    ).
 1865
 1866all_det(As) :- forall(member(an(_, D, _, _, _, _), As), D == true).
 1867
 1868%   the rest of a conjunction that the runtime can run as one lazy loop: builtins (more
 1869%   generators among them) and deterministic goals; in the all mode they are pure
 1870fusable(As, Mode) :- forall(member(A, As), fusable_goal(A, Mode)).
 1871
 1872fusable_goal(an(b(G), _, _, _, _, _), Mode) :- !, ( Mode == all -> \+ bi_effect(G) ; true ).
 1873fusable_goal(an(_, true, _, _, _, _), _).
 1874
 1875tr_fused([], _, true).
 1876tr_fused([A|As], Ctx, Code) :-
 1877    (   A = an(b(G), false, _, _, _, _) -> C1 = G ; tr_det_goal(A, Ctx, C1) ),
 1878    tr_fused(As, Ctx, C2), conj(C1, C2, Code).
 1879
 1880fuse_note(c(K, _)) :-
 1881    root_of(K, R),
 1882    (   note(R, N), sub_atom(N, 0, _, _, 'MNN fuse') -> true
 1883    ;   assertz(note(R, 'MNN fuse: a builtin generator followed by deterministic goals is enumerated lazily by the runtime (dl_fused_first/2, dl_fused_all/5): the same answers in the same order, and no answer list is built'))
 1884    ).
 1885
 1886all_total(As) :- forall(member(an(_, _, T, _, _, _), As), T == true).
 1887
 1888%   scan the answers of a nondeterministic goal for the first that the rest accepts
 1889scan(an(G, _, _, _, _, _), As, Out, Ctx, Code) :-
 1890    (   generator(G, Gen, Answers, Pat)
 1891    ->  rest_goals(As, RG),
 1892        term_variables(G-RG, LV),
 1893        shared_vars(LV, Out, Env),
 1894        loop_name(Ctx, s, SN),
 1895        fresh('A', A1), fresh('As', As1),
 1896        H =.. [SN, [A1|As1]|Env], R =.. [SN, As1|Env],
 1897        term_variables(Pat-Env, Out2),
 1898        tr_first_(As, Out2, Ctx, RC),
 1899        conj((A1 = Pat), RC, Cond),
 1900        Ctx = c(K, M),
 1901        out(K, M, (H :- if_commit(Cond, true, R))),
 1902        Call =.. [SN, Answers|Env],
 1903        Code = (Gen, Call)
 1904    ;   tr_island(G, As, Ctx, Code)
 1905    ).
 1906
 1907rest_goals(As, Gs) :- maplist(arg(1), As, Gs).
 1908
 1909%   a goal with side effects whose answers are needed one by one: an ordinary Prolog
 1910%   conjunction, run by Prolog's own backtracking
 1911tr_island(G, As, Ctx, dl_once((G1, RC))) :-
 1912    island_goal(G, G1),
 1913    tr_first_(As, [], Ctx, RC).
 1914
 1915island_goal(b(G), G).
 1916island_goal(u(G), G) :- key(G, K), need_key(K, prolog).
 1917
 1918generator(u(G), Gen, Ans, G) :-
 1919    key(G, K), \+ kept_or_effect_all(K), !,
 1920    need_key(K, all), all_call(G, Ans, Gen).
 1921generator(b(G), dl_all(G, Ans, []), Ans, G) :-
 1922    \+ bi_effect(G), fresh('As', Ans).
 1923
 1924loop_name(c(K, _), Kind, Name) :-
 1925    root_of(K, R), R = N/_,
 1926    next_count(loop(R), I),
 1927    format(atom(Name), '~w__~w~w', [N, Kind, I]).
 1928
 1929%   all: Out-T are the answers Ans of the conjunction, for every way it succeeds
 1930tr_all([], Ans, Out, T, _, _, Out = [Ans|T]).
 1931tr_all([A|As], Ans, Out, T, Seen, Ctx, Code) :-
 1932    A = an(_, true, _, _, _, _), !,
 1933    det_prefix([A|As], Ds, Rest),
 1934    tr_det(Ds, Ctx, DC),
 1935    rest_goals(Ds, DG), term_variables(DG, DV), append(DV, Seen, Seen1),
 1936    tr_all(Rest, Ans, Out, T, Seen1, Ctx, RC),
 1937    (   all_total(Ds) -> conj(DC, RC, Code)
 1938    ;   Code = if_commit(DC, RC, Out = T)
 1939    ).
 1940tr_all([A|As], Ans, Out, T, _, Ctx, Code) :-
 1941    form(mnn), A = an(b(BG), false, _, _, _, _), \+ bi_effect(BG), fusable(As, all), !,
 1942    tr_fused(As, Ctx, Test),
 1943    Code = dl_fused_all(BG, Test, Ans, Out, T),
 1944    fuse_note(Ctx).
 1945tr_all([A|As], Ans, Out, T, Seen, Ctx, Code) :-
 1946    A = an(G, false, _, GB, _, _),
 1947    generator(G, Gen, Answers, Pat), !,
 1948    rest_goals(As, RG),
 1949    term_variables(Pat-RG-Ans, LV),
 1950    shared_vars(LV, Seen, Env0),
 1951    exclude(var_in(GB), Env0, NG),
 1952    loop_name(Ctx, l, LN),
 1953    fresh('A', A1), fresh('As', As1), fresh('Out', LO), fresh('T', LT), fresh('T1', LT1),
 1954    copy_nonground(NG, Pat-As-Ans-Env0, Pat1-As2-Ans1-Env1, CopyG),
 1955    term_variables(Pat1-Env1, Seen2),
 1956    tr_all(As2, Ans1, LO, LT1, Seen2, Ctx, RC),
 1957    append([[A1|As1]|Env0], [LO, LT], HA), LH =.. [LN|HA],
 1958    append([As1|Env0], [LT1, LT], RA), LR =.. [LN|RA],
 1959    append([[]|Env0], [LT, LT], BA), LB =.. [LN|BA],
 1960    conj(CopyG, if_commit(A1 = Pat1, RC, LO = LT1), LBody),
 1961    Ctx = c(K, M),
 1962    out(K, M, LB),
 1963    out(K, M, (LH :- LBody, LR)),
 1964    append([Answers|Env0], [Out, T], CA), Call =.. [LN|CA],
 1965    Code = (Gen, Call).
 1966tr_all([A|_], _, _, _, _, _, _) :-
 1967    A = an(G, _, _, _, _, _),
 1968    throw(unsupported(all_mode_effect(G))).
 1969
 1970det_prefix([A|As], [A|Ds], Rest) :- A = an(_, true, _, _, _, _), !, det_prefix(As, Ds, Rest).
 1971det_prefix(As, [], As).
 1972
 1973%   rename the variables NG in T (a fresh copy per answer), keeping the others
 1974copy_nonground([], T, T, true) :- !.
 1975copy_nonground(NG, T, T1, copy_term(NG, NG1)) :-
 1976    term_variables(T, TV),
 1977    exclude(var_in(NG), TV, Keep),
 1978    copy_term(Keep-NG-T, Keep1-NG1-T1),
 1979    Keep1 = Keep,
 1980    maplist(rehint, NG, NG1).
 1981
 1982rehint(V, V1) :- ( get_attr(V, pl2detlog, N) -> atom_concat(N, '1', N1), put_attr(V1, pl2detlog, N1) ; true ).
 1983
 1984                 /*******************************
 1985                 *        ENTRY AND FOLDERS     *
 1986                 *******************************/
 1987
 1988%   entry_from_options(+Options, -Goal): the query that the program is run with.
 1989entry_from_options(Options, Goal) :-
 1990    (   option(query(Q), Options) -> parse_goal(Q, Goal)
 1991    ;   option(main(M), Options) -> main_goal(M, Goal)
 1992    ;   init_main(Goal)
 1993    ;   option(purpose(compile), Options), pred_key(main/0, _) -> Goal = main
 1994    ), !,
 1995    add_entry(Goal).
 1996
 1997parse_goal(Q, G) :-
 1998    (   ( atom(Q) ; string(Q) )
 1999    ->  term_string(G, Q, [module(pl2detlog_read), variable_names(Vs)]), names_attach(Vs)
 2000    ;   G = Q
 2001    ).
 2002
 2003main_goal(M, G) :-
 2004    (   atom(M), pred_key(M/0, _) -> G = M
 2005    ;   atom(M), pred_key(M/1, _) -> G = main_argv(M)
 2006    ;   parse_goal(M, G)
 2007    ).
 2008
 2009init_main(G) :-
 2010    src_file(_, P), db_get(item, P, it(_, dir(initialization(G, main), _), _)), !.
 2011
 2012add_entry(main_argv(M)) :- !,
 2013    G =.. [M, []], add_entry(G).
 2014add_entry(Goal) :-
 2015    retractall(entry(_, _)),
 2016    assertz(entry(pl2detlog_main, Goal)),
 2017    src_file(0, P),
 2018    db_put(item, P, it(1000000, cl(pl2detlog_main, Goal),
 2019                       ["% the query: pl2detlog_main runs its first answer"])),
 2020    reg_head(pl2detlog_main).
 2021
 2022out_root(Form, Options, OutRoot) :-
 2023    (   option(out(D0), Options), option(form(F), Options, both), F \== both
 2024    ->  absolute_file_name(D0, OutRoot)
 2025    ;   option(out(D0), Options)
 2026    ->  absolute_file_name(D0, D), atomic_list_concat([D, Form], '/', OutRoot)
 2027    ;   root_dir(Root), src_file(0, P),
 2028        file_base_name(P, B), file_name_extension(Base, _, B),
 2029        format(atom(OutRoot), '~w/~w_~w', [Root, Base, Form])
 2030    ).
 2031
 2032rel_path(P, Rel) :-
 2033    root_dir(Root),
 2034    ( Root == '/' -> R1 = '' ; R1 = Root ),
 2035    atom_concat(R1, Rest, P), atom_concat('/', Rel, Rest), !.
 2036rel_path(P, Rel) :- file_base_name(P, Rel).
 2037
 2038root_out_file(OutRoot, Main) :-
 2039    src_file(0, P), rel_path(P, Rel),
 2040    atomic_list_concat([OutRoot, Rel], '/', Main).
 2041
 2042                 /*******************************
 2043                 *            WRITING           *
 2044                 *******************************/
 2045
 2046write_program(Form, OutRoot) :-
 2047    make_dirs(OutRoot),
 2048    nb_setval(pl2detlog_out_root, OutRoot),
 2049    retractall(dbv(written, _, _, _, _)),
 2050    module_property(pl2detlog, file(Self)),
 2051    file_directory_name(Self, SelfDir),
 2052    atomic_list_concat([SelfDir, 'detlog_rt.pl'], '/', RtSrc),
 2053    atomic_list_concat([OutRoot, 'detlog_rt.pl'], '/', Rt),
 2054    copy_text_file(RtSrc, Rt),
 2055    forall(src_file(_, P), write_file(Form, P, OutRoot, Rt)),
 2056    write_proofs(Form, OutRoot).
 2057
 2058write_file(Form, P, OutRoot, Rt) :-
 2059    rel_path(P, Rel),
 2060    atomic_list_concat([OutRoot, Rel], '/', OP),
 2061    file_directory_name(OP, OD), make_dirs(OD),
 2062    relative_to(Rt, OP, RtRel0),
 2063    file_name_extension(RtRel, _, RtRel0),
 2064    db_all(item, P, Items0),
 2065    sort(1, @=<, Items0, Items),
 2066    setup_call_cleanup(
 2067        open(OP, write, S),
 2068        ( form_title(Form, Title),
 2069          format(S, "% ~w of ~w, written by pl2detlog.~n", [Title, Rel]),
 2070          (   Items = [it(_, dir(module(_, _), _), _)|_]
 2071          ->  true
 2072          ;   format(S, ":- use_module(~q).~n~n", [RtRel])
 2073          ),
 2074          write_items(Items, S, P, RtRel)
 2075        ),
 2076        close(S)).
 2077
 2078form_title(detlog, 'Detlog').
 2079form_title(mnn, 'Detlog MNN').
 2080
 2081write_items([], _, _, _).
 2082write_items([it(_, Item, Cmts)|Is], S, P, RtRel) :-
 2083    write_comments(S, Cmts),
 2084    write_item(Item, S, P, RtRel),
 2085    write_items(Is, S, P, RtRel).
 2086
 2087write_comments(_, []) :- !.
 2088write_comments(S, Cs) :- forall(member(C, Cs), format(S, "~s~n", [C])).
 2089
 2090write_item(eof, _, _, _).
 2091write_item(dir(D, Loads), S, _, RtRel) :-
 2092    rewrite_directive(D, Loads, D1),
 2093    print_clause(S, (:- D1)),
 2094    (   D = module(_, _) -> format(S, ":- use_module(~q).~n", [RtRel]) ; true ).
 2095write_item(cl(H, _), S, P, _) :-
 2096    key(H, K),
 2097    (   first_clause_here(K, P, H) -> emit_block(S, K) ; true ).
 2098
 2099first_clause_here(K, P, _) :-
 2100    \+ dbv(written, K, _, _, _),
 2101    src_file(_, P1),
 2102    dbv(item, P1, it(_, cl(H1, _), _), _, _), key(H1, K), !,
 2103    P1 == P,
 2104    assertz(dbv(written, K, x, [], [])).
 2105
 2106rewrite_directive(D, Loads, D1) :-
 2107    load_directive(D, _), Loads \== [], !,
 2108    D =.. [F, Spec|R], map_spec(Spec, Loads, Spec1), D1 =.. [F, Spec1|R].
 2109rewrite_directive([H|T], Loads, L1) :- Loads \== [], !,
 2110    maplist(map_one(Loads), [H|T], L1).
 2111rewrite_directive(module(M, Ex), _, module(M, Ex2)) :- !,
 2112    findall(PI, ( member(K, Ex), K = _/_, export_version(K, PI) ), New),
 2113    append(Ex, New, Ex1), list_to_set(Ex1, Ex2).
 2114rewrite_directive(initialization(G, main), _, initialization(N, main)) :-
 2115    entry(N, G0), G0 =@= G, !.
 2116rewrite_directive(initialization(G), _, initialization(N)) :-
 2117    entry(N, G0), G0 =@= G, !.
 2118rewrite_directive(D, _, D).
 2119
 2120%   the converted versions of an exported predicate are exported too
 2121export_version(N/A, FN/A) :- dbv(out, (N/A)-first, _, _, _), first_name(N/A, FN).
 2122export_version(N/A, AN/A2) :- dbv(out, (N/A)-all, _, _, _), all_name(N/A, AN), A2 is A + 2.
 2123
 2124map_spec(L, Loads, L1) :- is_list(L), !, maplist(map_one(Loads), L, L1).
 2125map_spec(S, Loads, S1) :- map_one(Loads, S, S1).
 2126
 2127%   relative paths stay as they are (the folder structure is the same); an absolute path
 2128%   to a program file is moved into the new folder
 2129map_one(Loads, F, F1) :-
 2130    member(F0-Abs, Loads), F0 == F, is_absolute_file_name(F), current_out_root(OR), !,
 2131    rel_path(Abs, Rel), atomic_list_concat([OR, Rel], '/', F1).
 2132map_one(_, F, F).
 2133
 2134current_out_root(OR) :- nb_current(pl2detlog_out_root, OR), OR \== [].
 2135
 2136%   a predicate's block: its versions, then its auxiliary predicates
 2137emit_block(S, K) :-
 2138    block_note(S, K),
 2139    emit_versions(S, K),
 2140    forall(aux_of(A, K), emit_aux(S, A)).
 2141
 2142emit_aux(S, A) :-
 2143    emit_versions(S, A),
 2144    forall(aux_of(A2, A), emit_aux(S, A2)).
 2145
 2146emit_versions(S, K) :-
 2147    forall(member(M, [det, first, all, entry, prolog, dead]),
 2148           (   db_all(out, K-M, Cls), Cls \== []
 2149           ->  partition(is_main(K, M), Cls, Main, Loops),
 2150               forall(member(C, Main), print_clause(S, C)),
 2151               forall(member(C, Loops), print_clause(S, C)),
 2152               nl(S)
 2153           ;   true
 2154           )).
 2155
 2156is_main(K, M, C) :- ( C = (:- _) -> true ; C = (H :- _) -> true ; H = C ), version_head(K, M, H).
 2157
 2158version_head(N/A, M, H) :- callable(H),
 2159    (   memberchk(M, [det, prolog, dead, entry]) -> functor(H, N, A)
 2160    ;   M == first -> first_name(N/A, FN), functor(H, FN, A)
 2161    ;   M == all -> all_name(N/A, AN), A2 is A + 2, functor(H, AN, A2)
 2162    ).
 2163version_head(_, _, (:- _)).
 2164
 2165block_note(S, K) :-
 2166    (   kept(K, Why) -> format(S, "% ~q: kept as Prolog (~w)~n", [K, Why])
 2167    ;   dbv(out, K-dead, _, _, _) -> format(S, "% ~q: not used by the query; as written~n", [K])
 2168    ;   true
 2169    ),
 2170    forall(note(K, N), format(S, "% ~w~n", [N])).
 2171
 2172%   file helpers (core SWI-Prolog only)
 2173make_dirs(D) :- exists_directory(D), !.
 2174make_dirs(D) :-
 2175    file_directory_name(D, P),
 2176    ( P \== D -> make_dirs(P) ; true ),
 2177    ( exists_directory(D) -> true ; make_directory(D) ).
 2178
 2179copy_text_file(From, To) :-
 2180    read_file_to_string(From, S, []),
 2181    setup_call_cleanup(open(To, write, Out), write(Out, S), close(Out)).
 2182
 2183%   relative_to(+Target, +FromFile, -Rel): Target's path relative to FromFile's folder
 2184relative_to(Target, From, Rel) :-
 2185    file_directory_name(From, FD),
 2186    atomic_list_concat(TP, '/', Target), atomic_list_concat(FP, '/', FD),
 2187    common_prefix(TP, FP, C), length(C, N),
 2188    length(TC, N), append(TC, TRest, TP), length(FC, N), append(FC, FRest, FP),
 2189    exclude(==(''), FRest, FR),
 2190    length(FR, Up), length(Ups, Up), maplist(=('..'), Ups),
 2191    append(Ups, TRest, RP),
 2192    (   RP = ['..'|_] -> atomic_list_concat(RP, '/', Rel)
 2193    ;   atomic_list_concat(['.'|RP], '/', Rel)
 2194    ).
 2195
 2196                 /*******************************
 2197                 *           PRINTING           *
 2198                 *******************************/
 2199
 2200print_clause(S, Cl0) :-
 2201    copy_term(Cl0, Cl),
 2202    bind_names(Cl),
 2203    (   Cl = (:- D)
 2204    ->  format(S, ":- ", []), pflat(S, D, 1199), format(S, ".~n", [])
 2205    ;   Cl = (H :- B), B \== true
 2206    ->  pflat(S, H), format(S, " :-~n", []),
 2207        conj_list(B, Gs),
 2208        pgoals(Gs, S, 4),
 2209        format(S, ".~n", [])
 2210    ;   ( Cl = (H :- true) -> true ; H = Cl ),
 2211        pflat(S, H), format(S, ".~n", [])
 2212    ).
 2213
 2214pgoals([G], S, Col) :- !, tab(S, Col), pgoal(S, G, Col).
 2215pgoals([G|Gs], S, Col) :- tab(S, Col), pgoal(S, G, Col), format(S, ",~n", []), pgoals(Gs, S, Col).
 2216
 2217wopts([quoted(true), numbervars(true), spacing(next_argument), portray(false),
 2218       module(pl2detlog_read), priority(999)]).
 2219
 2220pflat(S, T) :- wopts(O), write_term(S, T, O).
 2221pflat(S, T, Pri) :- wopts(O0), select(priority(_), O0, O1), write_term(S, T, [priority(Pri)|O1]).
 2222flat(T, A) :- with_output_to(string(A), pflat(current_output, T)).
 2223flat(T, Pri, A) :- with_output_to(string(A), pflat(current_output, T, Pri)).
 2224
 2225pgoal(S, G, Col) :-
 2226    ( G = (_;_) ; G = (_->_) ; G = (_*->_) ), !,
 2227    disj_alts(G, Alts),
 2228    write(S, '(   '), C4 is Col + 4,
 2229    palts(Alts, S, Col, C4),
 2230    nl(S), tab(S, Col), write(S, ')').
 2231pgoal(S, G, Col) :-
 2232    flat(G, F), string_length(F, L),
 2233    (   Col + L =< 92
 2234    ->  write(S, F)
 2235    ;   G = if_commit(C, T, E)
 2236    ->  C1 is Col + 10,
 2237        write(S, 'if_commit('), parg(S, C, C1), format(S, ",~n", []),
 2238        tab(S, C1), parg(S, T, C1), format(S, ",~n", []),
 2239        tab(S, C1), parg(S, E, C1), write(S, ')')
 2240    ;   G = dl_once(X), X = (_, _)
 2241    ->  C1 is Col + 8, write(S, 'dl_once('), parg(S, X, C1), write(S, ')')
 2242    ;   write(S, F)
 2243    ).
 2244
 2245parg(S, X, Col) :-
 2246    (   X = (_, _), flat(X, F), string_length(F, L), Col + L > 92
 2247    ->  conj_list(X, Gs), C2 is Col + 2,
 2248        write(S, '( '), pconj(Gs, S, C2), format(S, "~n", []), tab(S, Col), write(S, ')')
 2249    ;   X = (_, _)
 2250    ->  flat(X, 1000, F), format(S, "( ~w )", [F])
 2251    ;   pgoal(S, X, Col)
 2252    ).
 2253
 2254disj_alts((A;B), [A|Bs]) :- !, disj_alts(B, Bs).
 2255disj_alts(A, [A]).
 2256
 2257palts([A], S, Col, C4) :- !, palt(A, S, Col, C4).
 2258palts([A|As], S, Col, C4) :-
 2259    palt(A, S, Col, C4), nl(S), tab(S, Col), write(S, ';   '), palts(As, S, Col, C4).
 2260
 2261palt((C->T), S, Col, C4) :- !,
 2262    conj_list(C, Cs), pconj(Cs, S, C4), nl(S), tab(S, Col), write(S, '->  '),
 2263    conj_list(T, Ts), pconj(Ts, S, C4).
 2264palt((C*->T), S, Col, C4) :- !,
 2265    conj_list(C, Cs), pconj(Cs, S, C4), nl(S), tab(S, Col), write(S, '*-> '),
 2266    conj_list(T, Ts), pconj(Ts, S, C4).
 2267palt(G, S, _, C4) :- conj_list(G, Gs), pconj(Gs, S, C4).
 2268
 2269pconj([], S, _) :- !, write(S, true).
 2270pconj([G], S, Col) :- !, pgoal(S, G, Col).
 2271pconj([G|Gs], S, Col) :- pgoal(S, G, Col), format(S, ",~n", []), tab(S, Col), pconj(Gs, S, Col).
 2272
 2273%   give every variable a name: its source name, a hint, or '_' when it occurs once
 2274bind_names(T) :-
 2275    term_variables_list(T, All),
 2276    term_variables(T, Vs),
 2277    foldl(bind_name(All), Vs, [], _).
 2278
 2279bind_name(All, V, Used, [Name|Used]) :-
 2280    include(==(V), All, Os), length(Os, N),
 2281    (   N =:= 1 -> Name = '_'
 2282    ;   ( get_attr(V, pl2detlog, H0) -> var_name(H0, H) ; H = 'V' ),
 2283        unique_name(H, Used, Name)
 2284    ),
 2285    del_attr(V, pl2detlog),
 2286    V = '$VAR'(Name).
 2287
 2288var_name(H0, H) :-
 2289    atom_codes(H0, [C|Cs]),
 2290    (   ( code_type(C, upper) ; C == 0'_ ) -> H = H0
 2291    ;   code_type(C, to_lower(U)), atom_codes(H, [U|Cs])
 2292    ).
 2293var_name('_', 'V') :- !.
 2294
 2295unique_name(H, Used, Name) :-
 2296    (   H \== '_', \+ memberchk(H, Used) -> Name = H
 2297    ;   between(1, inf, I), format(atom(Name), '~w~w', [H, I]), \+ memberchk(Name, Used) -> true
 2298    ).
 2299
 2300                 /*******************************
 2301                 *            PROOFS            *
 2302                 *******************************/
 2303
 2304write_proofs(Form, OutRoot) :-
 2305    atomic_list_concat([OutRoot, 'PROOFS.txt'], '/', F),
 2306    src_file(0, P), rel_path(P, Rel),
 2307    form_title(Form, Title),
 2308    setup_call_cleanup(open(F, write, S), proof_report(S, Title, Rel), close(S)).
 2309
 2310proof_report(S, Title, Rel) :-
 2311    format(S, "~w of ~w: the rewrites and their side conditions~n~n", [Title, Rel]),
 2312    format(S, "Each rule below was checked on the program; the compile step also runs the query~n", []),
 2313    format(S, "in every form and checks the output is Prolog's before timing it.~n~n", []),
 2314    forall(( pred_key(K, _), \+ aux_of(K, _) ), pred_proof(S, K)).
 2315
 2316pred_proof(S, K) :-
 2317    findall(L, proof_line(K, L), Ls),
 2318    (   Ls == [] -> true
 2319    ;   format(S, "~q~n", [K]), forall(member(L, Ls), format(S, "  - ~w~n", [L])), nl(S)
 2320    ).
 2321
 2322proof_line(K, L) :- note(K, L).
 2323proof_line(K, L) :- kept(K, Why), format(atom(L), 'kept as Prolog: ~w', [Why]).
 2324proof_line(K, L) :-
 2325    conv_key(K), m_pat(K, P), P \== none,
 2326    ncls(K, Cls), resolved(K, Rs),
 2327    nth1(I, Cls, cl(_, commit(_, _))), nth1(I, Rs, r(_, Kind)),
 2328    (   Kind = plain(_)
 2329    ->  format(atom(L), 'CUT clause ~w: removed; its guard is deterministic and no later clause matches a call ~w that it matches', [I, P])
 2330    ;   format(atom(L), 'CUT clause ~w: necessary; written as if_commit/3', [I])
 2331    ).
 2332proof_line(K, L) :-
 2333    det_key(K), m_pat(K, P),
 2334    format(atom(L), 'DET: called as ~w, the clauses exclude each other and every goal has at most one answer', [P]).
 2335proof_line(K, L) :-
 2336    conv_key(K), \+ det_key(K), \+ kept(K, _), m_pat(K, P), P \== none,
 2337    all_name(K, AN),
 2338    (   eff_key(K)
 2339    ->  format(atom(L), 'nondeterministic with side effects (called as ~w): first answers in Detlog, answer lists never built', [P])
 2340    ;   format(atom(L), 'ALL: nondeterministic (called as ~w); ~w returns the answers in Prolog order', [P, AN])
 2341    ).
 2342
 2343                 /*******************************
 2344                 *     COMPILE: TIME, PICK, BUILD    *
 2345                 *******************************/
 2346
 2347bench_form(Goal, Budget, Form-Dir-Main, r(Form, Dir, Main, Res, Time)) :-
 2348    (   Form == prolog -> goal_text(Goal, GT) ; GT = "pl2detlog_main" ),
 2349    tmp_file(pl2detlog, Base),
 2350    atom_concat(Base, '_driver.pl', Driver),
 2351    atom_concat(Base, '_result.pl', Result),
 2352    module_property(pl2detlog, file(Self)), file_directory_name(Self, SD),
 2353    atomic_list_concat([SD, 'pl2detlog_bench'], '/', BM),
 2354    setup_call_cleanup(open(Driver, write, S),
 2355                       ( portray_clause(S, (:- use_module(BM))),
 2356                         portray_clause(S, (pl2detlog_bench_run :-
 2357                                               pl2detlog_bench:bench(Main, GT, Result, Budget))) ),
 2358                       close(S)),
 2359    current_prolog_flag(executable, Exe),
 2360    shell_quote(Exe, QE), shell_quote(Driver, QD),
 2361    format(string(Cmd), "~w -q -g pl2detlog_bench_run -t halt ~w < /dev/null > /dev/null 2>&1",
 2362           [QE, QD]),
 2363    shell(Cmd, _),
 2364    (   exists_file(Result),
 2365        catch(setup_call_cleanup(open(Result, read, RS), read_term(RS, T, []), close(RS)),
 2366              _, fail),
 2367        T = result(R, Out, _, Time0)
 2368    ->  Res = R-Out, Time = Time0
 2369    ;   Res = error(no_result)-"", Time = inf
 2370    ),
 2371    ( getenv('PL2DETLOG_KEEP', _) -> format(user_error, "driver ~w~n", [Driver]) ; catch(delete_file(Driver), _, true) ),
 2372    catch(delete_file(Result), _, true).
 2373
 2374goal_text(G, T) :-
 2375    with_output_to(string(T), write_term(G, [quoted(true), module(pl2detlog_read)])).
 2376
 2377shell_quote(A, Q) :-
 2378    atomic_list_concat(Parts, '\'', A),
 2379    atomic_list_concat(Parts, '\'\\\'\'', A1),
 2380    atomic_list_concat(['\'', A1, '\''], Q).
 2381
 2382report_results(Rs, Best) :-
 2383    (   memberchk(r(prolog, _, _, Ref, _), Rs) -> true ; Rs = [r(_, _, _, Ref, _)|_] ),
 2384    format(user_error, "~n% ~w~t~12|~w~t~30|~w~n", [form, 'time per run', 'output']),
 2385    forall(member(r(F, _, _, R, T), Rs),
 2386           ( ( R == Ref -> Same = 'same as Prolog' ; R = error(E)-_ -> format(atom(Same), 'error: ~q', [E]) ; Same = 'DIFFERS: not used' ),
 2387             time_text(T, TT),
 2388             format(user_error, "% ~w~t~12|~w~t~30|~w~n", [F, TT, Same]) )),
 2389    include(same_as(Ref), Rs, Ok),
 2390    (   Ok == [] -> Rs = [Best|_]
 2391    ;   foldl(faster, Ok, none, Best)
 2392    ),
 2393    Best = r(BF, _, _, _, _),
 2394    format(user_error, "% fastest: ~w~n~n", [BF]).
 2395
 2396same_as(Ref, r(_, _, _, R, T)) :- R == Ref, T \== inf.
 2397
 2398faster(R, none, R) :- !.
 2399faster(R, B, Best) :-
 2400    R = r(_, _, _, _, T1), B = r(_, _, _, _, T2),
 2401    ( T1 < T2 -> Best = R ; Best = B ).
 2402
 2403time_text(inf, '-') :- !.
 2404time_text(T, A) :-
 2405    Us is T * 1000000,
 2406    (   Us >= 1000 -> Ms is Us / 1000, format(atom(A), '~3f ms', [Ms])
 2407    ;   format(atom(A), '~2f us', [Us])
 2408    ).
 2409
 2410build_exe(Form, _Dir, Main, Exe) :-
 2411    current_prolog_flag(executable, SW),
 2412    (   init_main(_) -> GoalOpt = ''
 2413    ;   Form == prolog -> entry(_, G), goal_text(G, GT), shell_quote(GT, QG),
 2414        format(atom(GoalOpt), '--goal=~w', [QG])
 2415    ;   GoalOpt = '--goal=pl2detlog_main'
 2416    ),
 2417    file_directory_name(Main, MD),
 2418    maplist(shell_quote, [SW, Exe, Main, MD], [QS, QX, QM, QD]),
 2419    format(string(Cmd), "cd ~w && ~w -o ~w ~w --toplevel=halt --stand_alone=true -c ~w > /dev/null 2>&1",
 2420           [QD, QS, QX, GoalOpt, QM]),
 2421    shell(Cmd, St),
 2422    (   St =:= 0 -> true ; throw(error(pl2detlog(build_failed(Cmd)), _)) ).
 2423
 2424                 /*******************************
 2425                 *         COMMAND LINE         *
 2426                 *******************************/
 2427
 2428pl2detlog_cli([convert, File|Args]) :- !,
 2429    cli_opts(Args, Opts),
 2430    pl2detlog_convert(File, Opts).
 2431pl2detlog_cli([compile, File|Args]) :- !,
 2432    cli_opts(Args, Opts),
 2433    pl2detlog_compile(File, [purpose(compile)|Opts]).
 2434pl2detlog_cli(_) :-
 2435    format(user_error, "~s", [
 2436"usage: swipl pl2detlog convert FILE [-g MAIN | -q QUERY] [--form detlog|mnn|both] [--out DIR]
 2437       swipl pl2detlog compile FILE [-g MAIN | -q QUERY] [-o EXE] [--forms prolog,detlog,mnn]
 2438                                    [--budget SECONDS]
 2439"]).
 2440
 2441cli_opts([], []).
 2442cli_opts([O, V|As], [Opt|Os]) :- cli_opt(O, V, Opt), !, cli_opts(As, Os).
 2443cli_opts([A|_], _) :- throw(error(pl2detlog(unknown_option(A)), _)).
 2444
 2445cli_opt('-g', V, main(V)).
 2446cli_opt('--main', V, main(V)).
 2447cli_opt('-q', V, query(V)).
 2448cli_opt('--query', V, query(V)).
 2449cli_opt('--form', V, form(F)) :- atom_string(F, V).
 2450cli_opt('--out', V, out(V)).
 2451cli_opt('-o', V, exe(V)).
 2452cli_opt('--forms', V, forms(Fs)) :- atomic_list_concat(Fs, ',', V).
 2453cli_opt('--budget', V, budget(B)) :- atom_number(V, B).
 2454
 2455:- multifile prolog:message//1. 2456prolog:message(error(pl2detlog(no_main), _)) -->
 2457    [ 'pl2detlog: name the main predicate (-g main) or give a query (-q "Goal"): the program has no main/0 and no initialization(main, main)' ]