1:- module(scasp_dyncall,
    2          [ scasp/2,                    % :Query, +Options
    3            scasp_query_clauses/2,      % :Query, -Clauses
    4            scasp_model/1,              % -Model
    5            scasp_justification/2,      % -Tree, +Options
    6
    7            scasp_show/2,               % :Query,+What
    8
    9            (scasp_dynamic)/1,          % :Spec
   10            scasp_assert/1,             % :Clause
   11            scasp_assert/2,             % :Clause
   12            scasp_retract/1,            % :Clause
   13            scasp_retractall/1,         % :Head
   14            scasp_abolish/1,            % :PredicateIndicator
   15            (#)/1,                      % :Directive
   16            (#)/2,                      % :Directive, +Pos
   17            (pred)/1,
   18            (show)/1,
   19            (abducible)/1,
   20            (abducible)/2,
   21
   22            (#=)/2,
   23            (#<>)/2,
   24            (#<)/2,
   25            (#>)/2,
   26            (#=<)/2,
   27            (#>=)/2,
   28
   29            op(900, fy, not),
   30            op(950, xfx, ::),           % pred not x :: "...".
   31            op(1200, fx, #),
   32            op(1150, fx, pred),
   33            op(1150, fx, show),
   34            op(1150, fx, abducible),
   35            op(1150, fx, scasp_dynamic),
   36            op(700, xfx, #=),
   37            op(700, xfx, #<>),
   38            op(700, xfx, #<),
   39            op(700, xfx, #>),
   40            op(700, xfx, #=<),
   41            op(700, xfx, #>=)
   42          ]).   43:- use_module(compile).   44:- use_module(embed).   45:- use_module(common).   46:- use_module(modules).   47:- use_module(source_ref).   48:- use_module(listing).   49:- use_module(clp/clpq, [apply_clpq_constraints/1]).   50:- use_module(pr_rules, [process_pr_pred/5]).   51:- use_module(predicates, [prolog_builtin/1, clp_builtin/1]).   52
   53:- use_module(library(apply), [maplist/3, exclude/3, maplist/2]).   54:- use_module(library(assoc), [empty_assoc/1, get_assoc/3, put_assoc/4]).   55:- use_module(library(error),
   56              [ instantiation_error/1,
   57                permission_error/3,
   58                type_error/2,
   59                must_be/2
   60              ]).   61:- use_module(library(lists), [member/2, append/3]).   62:- use_module(library(modules),
   63              [in_temporary_module/3, current_temporary_module/1]).   64:- use_module(library(option), [option/2]).   65:- use_module(library(ordsets), [ord_intersect/2, ord_union/3]).   66:- use_module(library(prolog_code), [pi_head/2]).   67
   68:- meta_predicate
   69    scasp(0, +),
   70    scasp_show(:, +),
   71    scasp_query_clauses(:, -),
   72    scasp_dynamic(:),
   73    scasp_assert(:),
   74    scasp_retract(:),
   75    scasp_retractall(:),
   76    scasp_abolish(:),
   77    pred(:),
   78    show(:),
   79    abducible(:).

This predicate assembles the clauses that are reachable from a given goal.

Issues:

 scasp(:Query) is nondet
 scasp(:Query, +Options) is nondet
Prove query using s(CASP) semantics. This performs the following steps:

Options are passed to scasp_compile/2. Other options processed:

model(-Model)
Unify Model with the s(CASP) model, a list of model terms. See scasp_model/1.
tree(-Tree)
Unify Tree with the s(CASP) justification tree. See scasp_justification/2 for details.
  119scasp(Query, Options) :-
  120    scasp_query_clauses(Query, Clauses),
  121    qualify(Query, SrcModule:QQuery),
  122    expand_program(SrcModule, Clauses, Clauses1, QQuery, QQuery1),
  123    in_temporary_module(
  124        Module,
  125        prepare(Clauses1, Module, Options),
  126        scasp_call_and_results(Module:QQuery1, SrcModule, Options)).
  127
  128prepare(Clauses, Module, Options) :-
  129    scasp_compile(Module:Clauses, Options),
  130    (   option(write_program(_), Options)
  131    ->  scasp_portray_program(Module:Options)
  132    ;   true
  133    ).
  134
  135qualify(M:Q0, M:Q) :-
  136    qualify(Q0, M, Q1),
  137    intern_negation(Q1, Q).
  138
  139expand_program(SrcModule, Clauses, Clauses1, QQuery, QQuery1) :-
  140    current_predicate(SrcModule:scasp_expand_program/4),
  141    SrcModule:scasp_expand_program(Clauses, Clauses1, QQuery, QQuery1),
  142    !.
  143expand_program(_, Clauses, Clauses, QQuery, QQuery).
  144
  145
  146scasp_call_and_results(Query, SrcModule, Options) :-
  147    scasp_embed:scasp_call(Query),
  148    (   option(model(Model), Options)
  149    ->  scasp_model(SrcModule:Model)
  150    ;   true
  151    ),
  152    (   option(tree(Tree), Options)
  153    ->  scasp_justification(SrcModule:Tree, Options)
  154    ;   true
  155    ).
 scasp_show(:Query, +What)
Show some aspect of the translated s(CASP) program. Currently What is one of:
code(Options)
Show the collected program. By default shows the query and user program. To show only the integrity constraints, use:
?- scasp_show(Query, code(user(false), constraints(true))).
  169scasp_show(Query, What) :-
  170    What =.. [Type|Options],
  171    scasp_show(Query, Type, Options).
  172
  173scasp_show(Query, code, Options) =>
  174    Query = M:_,
  175    scasp_query_clauses(Query, Clauses),
  176    in_temporary_module(
  177        Module,
  178        prepare(Clauses, Module, []),
  179        scasp_portray_program(Module:[source_module(M)|Options])).
 scasp_query_clauses(:Query, -Clauses) is det
  183:- det(scasp_query_clauses/2).  184
  185scasp_query_clauses(Query, Clauses) :-
  186    query_callees(Query, Callees0),
  187    include_global_constraint(Callees0, Constraints, Callees),
  188    findall(Clause, scasp_clause(Callees, Clause), Clauses, QConstraints),
  189    maplist(mkconstraint, Constraints, QConstraints).
  190
  191scasp_clause(Callees, source(ClauseRef, Clause)) :-
  192    member(PI, Callees),
  193    pi_head(PI, M:Head),
  194    @(clause(Head, Body, ClauseRef), M),
  195    mkclause(Head, Body, M, Clause).
  196
  197mkclause(Head, true, M, Clause) =>
  198    qualify(Head, M, Clause).
  199mkclause(Head, Body, M, Clause) =>
  200    qualify((Head:-Body), M, Clause).
  201
  202mkconstraint(source(Ref, M:Body), source(Ref, (:- Constraint))) :-
  203    qualify(Body, M, Constraint).
  204
  205qualify(-(Head), M, Q) =>
  206    Q = -QHead,
  207    qualify(Head, M, QHead).
  208qualify(not(Head), M, Q) =>
  209    Q = not(QHead),
  210    qualify(Head, M, QHead).
  211qualify((A,B), M, Q) =>
  212    Q = (QA,QB),
  213    qualify(A, M, QA),
  214    qualify(B, M, QB).
  215qualify((A:-B), M, Q) =>
  216    Q = (QA:-QB),
  217    qualify(A, M, QA),
  218    qualify(B, M, QB).
  219qualify(G, M, Q), callable(G) =>
  220    (   built_in(G)
  221    ->  Q = G
  222    ;   implementation(M:G, Callee),
  223        encoded_module_term(Callee, Q)
  224    ).
 query_callees(:Query, -Callees) is det
True when Callees is a list of predicate indicators for predicates reachable from Query.
Arguments:
Callees- is an ordered set.
  233query_callees(M:Query, Callees) :-
  234    findall(Call, body_calls_pi(Query,M,Call), Calls0),
  235    sort(Calls0, Calls),
  236    callee_graph(Calls, Callees).
  237
  238body_calls_pi(Query, M, PI) :-
  239    body_calls(Query, M, Call),
  240    pi_head(PI, Call).
  241
  242callee_graph(Preds, Nodes) :-
  243    empty_assoc(Expanded),
  244    callee_closure(Preds, Expanded, Preds, Nodes0),
  245    sort(Nodes0, Nodes).
  246
  247callee_closure([], _, Preds, Preds).
  248callee_closure([H|T], Expanded, Preds0, Preds) :-
  249    (   get_assoc(H, Expanded, _)
  250    ->  callee_closure(T, Expanded, Preds0, Preds)
  251    ;   put_assoc(H, Expanded, true, Expanded1),
  252        pi_head(H, Head),
  253        predicate_callees(Head, Called),
  254        exclude(expanded(Expanded1), Called, New),
  255        append(New, T, Agenda),
  256        append(New, Preds0, Preds1),
  257        callee_closure(Agenda, Expanded1, Preds1, Preds)
  258    ).
  259
  260expanded(Assoc, PI) :-
  261    get_assoc(PI, Assoc, _).
 include_global_constraint(+Callees, -Constraints, -AllCallees) is det
  265include_global_constraint(Callees0, Constraints, Callees) :-
  266    include_global_constraint(Callees0, Callees, [], Constraints).
  267
  268include_global_constraint(Callees0, Callees, Constraints0, Constraints) :-
  269    global_constraint(Constraint),
  270    Constraint = source(_, Body),
  271    \+ ( member(source(_, Body0), Constraints0),
  272         Body =@= Body0
  273       ),
  274    query_callees(Body, Called),
  275    ord_intersect(Callees0, Called),
  276    !,
  277    ord_union(Callees0, Called, Callees1),
  278    include_global_constraint(Callees1, Callees,
  279                              [Constraint|Constraints0], Constraints).
  280include_global_constraint(Callees, Callees, Constraints, Constraints).
  281
  282
  283global_constraint(source(Ref, M:Body)) :-
  284    (   current_temporary_module(M)
  285    ;   current_module(M)
  286    ),
  287    current_predicate(M:(-)/0),
  288    \+ predicate_property(M:(-), imported_from(_)),
  289    @(clause(-, Body, Ref), M).
 predicate_callees(:Head, -Callees) is det
True when Callees is the list of direct callees from Head. Each callee is a predicate indicator.
  296:- dynamic predicate_callees_c/4.  297
  298predicate_callees(M:Head, Callees) :-
  299    predicate_callees_c(Head, M, Gen, Callees0),
  300    predicate_generation(M:Head, Gen),
  301    !,
  302    Callees = Callees0.
  303predicate_callees(M:Head, Callees) :-
  304    module_property(M, class(temporary)),
  305    !,
  306    predicate_callees_nc(M:Head, Callees).
  307predicate_callees(M:Head, Callees) :-
  308    retractall(predicate_callees_c(Head, M, _, _)),
  309    predicate_callees_nc(M:Head, Callees0),
  310    predicate_generation(M:Head, Gen),
  311    assertz(predicate_callees_c(Head, M, Gen, Callees0)),
  312    Callees = Callees0.
  313
  314predicate_callees_nc(Head, Callees) :-
  315    findall(Callee, predicate_calls(Head, Callee), Callees0),
  316    sort(Callees0, Callees).
  317
  318predicate_calls(Head0, PI) :-
  319    generalise(Head0, M:Head),
  320    @(clause(Head, Body), M),
  321    body_calls(Body, M, Callee),
  322    pi_head(PI, Callee).
  323
  324body_calls(Goal, _M, _), var(Goal) =>
  325    instantiation_error(Goal).
  326body_calls(true, _M, _) => fail.
  327body_calls((A,B), M, Callee) =>
  328    (   body_calls(A, M, Callee)
  329    ;   body_calls(B, M, Callee)
  330    ).
  331body_calls(not(A), M, Callee) =>
  332    body_calls(A, M, Callee).
  333body_calls(N, M, Callee), rm_classic_negation(N,A) =>
  334    body_calls(A, M, Callee).
  335body_calls(M:A, _, Callee), atom(M) =>
  336    body_calls(A, M, Callee).
  337body_calls(G, _M, _CalleePM), callable(G), built_in(G) =>
  338    fail.
  339body_calls(G, M, CalleePM), callable(G) =>
  340    implementation(M:G, Callee0),
  341    generalise(Callee0, Callee),
  342    (   predicate_property(Callee, interpreted),
  343        \+ predicate_property(Callee, meta_predicate(_))
  344    ->  pm(Callee, CalleePM)
  345    ;   \+ predicate_property(Callee, _)
  346    ->  pm(Callee, CalleePM)            % undefined
  347    ;   pi_head(CalleePI, Callee),
  348        permission_error(scasp, procedure, CalleePI)
  349    ).
  350body_calls(G, _, _) =>
  351    type_error(callable, G).
  352
  353built_in(Head) :-
  354    prolog_builtin(Head).
  355built_in(Head) :-
  356    clp_builtin(Head).
  357built_in(_ is _).
  358
  359rm_classic_negation(-Goal, Goal) :-
  360    !.
  361rm_classic_negation(Goal, PGoal) :-
  362    functor(Goal, Name, _),
  363    atom_concat(-, Plain, Name),
  364    Goal  =.. [Name|Args],
  365    PGoal =.. [Plain|Args].
  366
  367pm(P, P).
  368pm(M:P, M:MP) :-
  369    intern_negation(-P, MP).
  370
  371implementation(M0:Head, M:Head) :-
  372    predicate_property(M0:Head, imported_from(M1)),
  373    !,
  374    M = M1.
  375implementation(Head, Head).
  376
  377generalise(M:Head0, Gen), atom(M) =>
  378    Gen = M:Head,
  379    generalise(Head0, Head).
  380generalise(-Head0, Gen) =>
  381    Gen = -Head,
  382    generalise(Head0, Head).
  383generalise(Head0, Head) =>
  384    functor(Head0, Name, Arity),
  385    functor(Head, Name, Arity).
  386
  387predicate_generation(Head, Gen) :-
  388    predicate_property(Head, last_modified_generation(Gen0)),
  389    !,
  390    Gen = Gen0.
  391predicate_generation(_, 0).
  392
  393
  394		 /*******************************
  395		 *   MANIPULATING THE PROGRAM	*
  396		 *******************************/
 scasp_dynamic(:Spec) is det
Declare a predicates as dynamic or thread_local. Usage patterns:

:- scasp_dynamic p/1. :- scasp_dynamic p/1 as shared.

  405scasp_dynamic(M:Spec) :-
  406    scasp_dynamic(Spec, M, private).
  407scasp_dynamic(M:(Spec as Scoped)) :-
  408    scasp_dynamic(Spec, M, Scoped).
  409
  410scasp_dynamic((A,B), M, Scoped) =>
  411    scasp_dynamic(A, M, Scoped),
  412    scasp_dynamic(B, M, Scoped).
  413scasp_dynamic(Name/Arity, M, Scoped) =>
  414    atom_concat(-, Name, NName),
  415    (   Scoped == shared
  416    ->  dynamic((M:Name/Arity,
  417                 M:NName/Arity))
  418    ;   thread_local((M:Name/Arity,
  419                     M:NName/Arity))
  420    ).
 scasp_assert(:Clause) is det
 scasp_retract(:Clause) is nondet
 scasp_retractall(:Head) is det
Wrappers for assertz/1, retract/1 and retractall/1 that deal with sCASP terms which may have a head or body terms that are wrapped in -(Term), indicating classical negation. Also deals with global constraints written in any of these formats:
  434scasp_assert(Clause) :-
  435    scasp_assert(Clause, false).
  436
  437scasp_assert(M:(-Head :- Body0), Pos) =>
  438    intern_negation(-Head, MHead),
  439    expand_goal(Body0, Body),
  440    scasp_assert_(M:(MHead :- Body), Pos).
  441scasp_assert(M:(-Head), Pos) =>
  442    intern_negation(-Head, MHead),
  443    scasp_assert_(M:(MHead), Pos).
  444scasp_assert(M:(:- Body0), Pos) =>
  445    expand_goal(Body0, Body),
  446    scasp_assert_(M:((-) :- Body), Pos).
  447scasp_assert(M:(false :- Body0), Pos) =>
  448    expand_goal(Body0, Body),
  449    scasp_assert_(M:((-) :- Body), Pos).
  450scasp_assert(M:(Head :- Body0), Pos) =>
  451    expand_goal(Body0, Body),
  452    scasp_assert_(M:(Head :- Body), Pos).
  453scasp_assert(Head, Pos) =>
  454    scasp_assert_(Head, Pos).
  455
  456scasp_assert_(Clause, false) =>
  457    assertz(Clause).
  458scasp_assert_(Clause, Pos) =>
  459    assertz(Clause, Ref),
  460    assertz(scasp_dynamic_clause_position(Ref, Pos)).
  461
  462scasp_assert_into(M, Pos, Rule) :-
  463    scasp_assert(M:Rule, Pos).
  464
  465scasp_retract(M:(-Head :- Body0)) =>
  466    intern_negation(-Head, MHead),
  467    expand_goal(Body0, Body),
  468    retract(M:(MHead :- Body)).
  469scasp_retract(M:(-Head)) =>
  470    intern_negation(-Head, MHead),
  471    retract(M:(MHead)).
  472scasp_retract(M:(:- Body0)) =>
  473    expand_goal(Body0, Body),
  474    retract(M:((-) :- Body)).
  475scasp_retract(M:(false :- Body0)) =>
  476    expand_goal(Body0, Body),
  477    retract(M:((-) :- Body)).
  478scasp_retract(M:(Head :- Body0)) =>
  479    expand_goal(Body0, Body),
  480    retract(M:(Head :- Body)).
  481scasp_retract(Head) =>
  482    retract(Head).
  483
  484scasp_retractall(M:(-Head)) =>
  485    intern_negation(-Head, MHead),
  486    retractall(M:MHead).
  487scasp_retractall(Head) =>
  488    retractall(Head).
 scasp_abolish(:PredicateIndicator) is det
Remove all facts for both PredicateIndicator and its classical negation.
  495scasp_abolish(M:(Name/Arity)) =>
  496    pi_head(Name/Arity, Head),
  497    scasp_retractall(M:Head),
  498    scasp_retractall(M:(-Head)).
  499
  500
  501		 /*******************************
  502		 *          DIRECTIVES		*
  503		 *******************************/
 #(:Directive)
Handle s(CASP) directives. Same as :- Directive.. Provides compatibility with sCASP sources as normally found.
  510#(Directive) :- #(Directive, false).
  511
  512#(M:pred(Spec), _)        => pred(M:Spec).
  513#(M:show(Spec), _)        => show(M:Spec).
  514#(M:abducible(Spec), Pos) => abducible(M:Spec, Pos).
  515
  516pred(M:(Spec :: Template)) =>
  517    process_pr_pred(Spec :: Template, Atom, Children, Cond, Human),
  518    assertz(M:pr_pred_predicate(Atom, Children, Cond, Human)).
  519
  520show(M:PIs) =>
  521    phrase(show(PIs), Clauses),
  522    maplist(assert_show(M), Clauses).
  523
  524assert_show(M, Clause) :-
  525    assertz(M:Clause).
  526
  527show(Var) -->
  528    { var(Var),
  529      instantiation_error(Var)
  530    }.
  531show((A,B)) -->
  532    !,
  533    show(A),
  534    show(B).
  535show(not(PI)) -->
  536    { pi_head(PI, Head) },
  537    [ pr_show_predicate(not(Head)) ].
  538show(PI) -->
  539    { pi_head(PI, Head) },
  540    [ pr_show_predicate(Head) ].
 abducible(:Spec)
Declare Spec, a comma list of heads to be abducible, meaning they can both be in or outside the model.
  547abducible(Spec) :- abducible(Spec, false).
  548
  549abducible(M:(A,B), Pos) =>
  550    abducible(M:A, Pos),
  551    abducible(M:B, Pos).
  552abducible(M:Head, Pos), callable(Head) =>
  553    abducible_rules(Head, Rules),
  554    discontiguous(M:('abducible$'/1, 'abducible$$'/1)),
  555    maplist(scasp_assert_into(M, Pos), Rules).
  556
  557abducible_rules(Head,
  558                [ (Head                   :- not(-(Head)), 'abducible$'(Head)),
  559                  (-(Head)                :- not Head),
  560                  ('abducible$'(Head)   :- not 'abducible$$'(Head)),
  561                  ('abducible$$'(Head)  :- not 'abducible$'(Head))
  562                ]).
  563
  564
  565
  566abducible(Var) -->
  567    { var(Var),
  568      instantiation_error(Var)
  569    }.
  570abducible((A,B)) -->
  571    !,
  572    abducible(A),
  573    abducible(B).
  574abducible(Head) -->
  575    { must_be(callable, Head),
  576      abducible_rules(Head, Clauses)
  577    },
  578    list(Clauses).
  579
  580list([]) --> [].
  581list([H|T]) --> [H], list(T).
  582
  583
  584
  585		 /*******************************
  586		 *            EXPAND		*
  587		 *******************************/
  588
  589user:term_expansion(-Fact, MFact) :-
  590    callable(Fact),
  591    intern_negation(-Fact, MFact).
  592user:term_expansion((-Head :- Body), (MHead :- Body)) :-
  593    callable(Head),
  594    intern_negation(-Head, MHead).
  595user:term_expansion((false :- Body), ((-) :- Body)).
  596user:term_expansion((:- pred(SpecIn)),
  597                    pr_pred_predicate(Atom, Children, Cond, Human)) :-
  598    process_pr_pred(SpecIn, Atom, Children, Cond, Human).
  599user:term_expansion((:- show(SpecIn)), Clauses) :-
  600    phrase(show(SpecIn), Clauses).
  601user:term_expansion((:- abducible(SpecIn)), Clauses) :-
  602    phrase(abducible(SpecIn), Clauses).
  603user:term_expansion((# pred(SpecIn)),
  604                    pr_pred_predicate(Atom, Children, Cond, Human)) :-
  605    process_pr_pred(SpecIn, Atom, Children, Cond, Human).
  606user:term_expansion((# show(SpecIn)), Clauses) :-
  607    phrase(show(SpecIn), Clauses).
  608user:term_expansion((# abducible(SpecIn)), Clauses) :-
  609    phrase(abducible(SpecIn), Clauses).
  610
  611user:goal_expansion(-Goal, MGoal) :-
  612    callable(Goal),
  613    intern_negation(-Goal, MGoal).
  614
  615
  616		 /*******************************
  617		 *              CLP		*
  618		 *******************************/
  619
  620%!  #=(?A, ?B).
  621%!  #<>(?A, ?B).
  622%!  #<(?A, ?B).
  623%!  #>(?A, ?B).
  624%!  #>=(?A, ?B).
  625%!  #=<(?A, ?B).
  626%
  627%   Implementation of the s(CASP) constraints.   This  implementation is
  628%   normally not used and mostly makes the program analysis work.
  629
  630A #=  B :- apply_clpq_constraints(A #=  B).
  631A #<> B :- apply_clpq_constraints(A #<> B).
  632A #<  B :- apply_clpq_constraints(A #<  B).
  633A #>  B :- apply_clpq_constraints(A #>  B).
  634A #=< B :- apply_clpq_constraints(A #=< B).
  635A #>= B :- apply_clpq_constraints(A #>= B).
  636
  637
  638		 /*******************************
  639		 *            SANDBOX		*
  640		 *******************************/
  641
  642:- multifile
  643    sandbox:safe_meta_predicate/1.  644
  645% scasp/1 is safe as it only allows for pure Prolog predicates
  646% and limited arithmetic.  Note that this does allow calling e.g.
  647% member/2. s(CASP) does not allow for calling _qualified goals,
  648% lists:member(...),
  649
  650sandbox:safe_meta(scasp_dyncall:scasp(_, _), [])