View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        jan@swi-prolog.org
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2026, SWI-Prolog Solutions b.v.
    7    All rights reserved.
    8
    9    Redistribution and use in source and binary forms, with or without
   10    modification, are permitted provided that the following conditions
   11    are met:
   12
   13    1. Redistributions of source code must retain the above copyright
   14       notice, this list of conditions and the following disclaimer.
   15
   16    2. Redistributions in binary form must reproduce the above copyright
   17       notice, this list of conditions and the following disclaimer in
   18       the documentation and/or other materials provided with the
   19       distribution.
   20
   21    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   22    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   23    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   24    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   25    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   26    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   27    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   28    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   29    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   30    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   31    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   32    POSSIBILITY OF SUCH DAMAGE.
   33*/
   34
   35:- module(sscasp,
   36          [ scasp/1,                   % :Query
   37            scasp/2,                   % :Query, +Options
   38            scasp_query_clauses/2,     % :Query, -Terms
   39            scasp_query_clauses/3,     % :Query, -Terms, +Options
   40            scasp_directive/1,         % :Directive
   41            scasp_show/2,              % :Query, +What
   42            scasp_json/2,              % :Query, -Dict
   43            scasp_json/3,              % :Query, -Dict, +Options
   44            scasp_human/1,             % :Query
   45            scasp_human/2,             % :Query, +Options
   46            (scasp_dynamic)/1,         % :Spec
   47            scasp_assert/1,            % :Clause
   48            scasp_assert/2,            % :Clause, +Position
   49            scasp_retract/1,           % :Clause
   50            scasp_retractall/1,        % :Head
   51            scasp_abolish/1,           % :PredicateIndicator
   52            (sld)/1,                    % :PredicateIndicator
   53            (describe)/1,               % :Description
   54            (pred)/1,                   % :Signature or :Description
   55            (domain)/1,                 % :Definition
   56            (#=)/2, (#<>)/2,            % ?A, ?B: the comparisons,
   57            (#<)/2, (#>)/2,             % for Prolog's sake
   58            (#=<)/2, (#>=)/2,
   59
   60            (?)/1,                      % :Query
   61            (??)/1,                     % :Query
   62            (?--)/1,                    % :Query
   63            (?+-)/1,                    % :Query
   64            (?-+)/1,                    % :Query
   65            (?++)/1,                    % :Query
   66            (??+-)/1,                   % :Query
   67            (??-+)/1,                   % :Query
   68            (??++)/1,                   % :Query
   69
   70            scasp_readable/2,          % +Term, -Readable
   71            scasp_readable/3,          % +Term, -Readable, +Options
   72            portray_model/1,            % +Model
   73            portray_model/2,            % +Model, +Options
   74            portray_justification/1,    % +Justification
   75            portray_justification/2,    % +Justification, +Options
   76            html_model//2,              % +Model, +Options
   77            html_justification//2,      % +Justification, +Options
   78            html_query//2,              % +Query, +Options
   79            html_atom//2,               % +Literal, +Options
   80
   81            op(900,  fy,  not),
   82            op(700,  xfx, #=),
   83            op(700,  xfx, #<>),
   84            op(700,  xfx, #<),
   85            op(700,  xfx, #>),
   86            op(700,  xfx, #=<),
   87            op(700,  xfx, #>=),
   88            op(700,  xfx, '∉'),
   89            op(700,  xfx, '∈'),
   90            op(700,  xfx, '| '),
   91            op(1150, fx,  domain),
   92            op(1150, fx,  pred),
   93            op(1150, fx,  abducible),   % `#abducible p` and `:- abducible p`
   94            op(1150, fx,  show),        % `#show p`
   95            op(1150, fx,  sld),
   96            op(1150, fx,  describe),
   97            op(1150, fx,  scasp_dynamic),
   98            op(1200, fx,  #),           % the legacy `#pred` spelling
   99            op(950,  xfx, ::),
  100            op(200,  xfx, ..),
  101
  102            op(1150, fx,  ?),           % the query shortcuts
  103            op(1150, fx,  ??),
  104            op(1150, fx,  ?--),
  105            op(1150, fx,  ?+-),
  106            op(1150, fx,  ?-+),
  107            op(1150, fx,  ?++),
  108            op(1150, fx,  ??+-),
  109            op(1150, fx,  ??-+),
  110            op(1150, fx,  ??++)
  111          ]).  112:- use_module(sscasp/ops).  113:- reexport(sscasp/dyncall,
  114            [ scasp/1, scasp/2,
  115              scasp_query_clauses/2, scasp_query_clauses/3,
  116              scasp_directive/1,
  117              scasp_show/2,
  118              scasp_json/2, scasp_json/3,
  119              (scasp_dynamic)/1,
  120              scasp_assert/1, scasp_assert/2,
  121              scasp_retract/1, scasp_retractall/1, scasp_abolish/1,
  122              (sld)/1,
  123              (describe)/1,
  124              (pred)/1,
  125              (domain)/1,
  126              (#=)/2, (#<>)/2, (#<)/2, (#>)/2, (#=<)/2, (#>=)/2
  127            ]).  128:- reexport(sscasp/html,
  129            [ html_model//2, html_justification//2,
  130              html_query//2, html_atom//2
  131            ]).  132:- use_module(sscasp/dyncall, [constraint_clauses/2]).  133:- use_module(sscasp/annotations, [program_annotations/2]).  134:- use_module(library(ansi_term), [ansi_format/3]).  135:- use_module(library(option), [option/2, merge_options/3]).  136:- use_module(library(apply), [exclude/3, maplist/3]).  137:- use_module(library(lists), [member/2, select/3]).  138:- use_module(sscasp/clauses, [body_list/2]).  139:- use_module(sscasp/dualise, [builtin/1]).  140:- reexport(sscasp/render,
  141            [ scasp_readable/2, scasp_readable/3,
  142              portray_model/1, portray_model/2,
  143              portray_justification/1, portray_justification/2
  144            ]).  145
  146%   With the imports and before the first clause, because a
  147%   meta-predicate mode is part of the module's **signature**: a reader —
  148%   or a tool — taking the interface from the head of the file stops at
  149%   the first clause, and a declaration below that point changes how a
  150%   caller must pass an argument without saying so where the interface is
  151%   stated.
  152%
  153%   `:` rather than `0`, for the reason `sscasp/dyncall.pl` gives: a
  154%   query is a term to take apart, and expanding it as a goal where it is
  155%   written turns `-p(X)` into something else.
  156
  157:- meta_predicate
  158    ?(:),
  159    ??(:),
  160    ?--(:),
  161    ?+-(:),
  162    ?-+(:),
  163    ?++(:),
  164    ??+-(:),
  165    ??-+(:),
  166    ??++(:),
  167    scasp_human(:),
  168    scasp_human(:, +),
  169    solve_and_show(:, +).  170
  171/** <module> s(CASP) from Prolog
  172
  173Load this, write the program as ordinary Prolog clauses, and ask:
  174
  175    :- use_module(library(sscasp)).
  176
  177    bird(tweety).
  178    bird(polly).
  179    penguin(polly).
  180    flies(X) :- bird(X), not penguin(X).
  181
  182    ?- ? flies(X).
  183    Model:
  184        bird(tweety)
  185        flies(tweety)
  186        not penguin(tweety)
  187    X = tweety.
  188
  189`scasp/2` is the predicate; the `?`-prefixed operators are the same thing
  190with the printing chosen for you, for use at a toplevel.  `scasp/2` collects
  191the clauses the query reaches — see `sscasp/dyncall.pl` for what that means
  192and for how a program says the things Prolog has no syntax for.
  193
  194## The shortcuts
  195
  196Each asks for what its name says — the `+` and `-` are the **model** and the
  197**justification**, in that order — and the *toplevel* shows it, as part of
  198the answer:
  199
  200| `?-- Q` | bindings only |
  201| `?+- Q`, `? Q` | and the model |
  202| `?-+ Q` | and the justification |
  203| `?++ Q`, `?? Q` | both |
  204| `??+- Q`, `??-+ Q`, `??++ Q` | the same, said in words |
  205
  206They are ordinary nondeterministic goals: `;` at the toplevel asks for the
  207next answer, and shows it the same way.
  208
  209**They show nothing outside a toplevel.**  The model reaches the terminal
  210through `residual_goals//0`, which is the toplevel's hook for adding to an
  211answer, and that is deliberate: the model then comes *after* the bindings,
  212and the toplevel names the variables of the answer and of the model
  213together — `¬ ab(_A)` and `_A` being anything but john or sam are one
  214variable, and a model printed on its own could not say so.  To print from
  215a program, use `scasp_human/1,2`, or `scasp/2` with `portray_model/2` and
  216`portray_justification/2`.
  217*/
  218
  219%!  user:term_expansion(+Term, -Expanded) is semidet.
  220%
  221%   A global constraint is a rule with no head.  `:- Body.` in a Prolog
  222%   file is a directive to run at load time, and `false/0` is a built-in
  223%   that cannot be given clauses, so `false :- Body.` becomes a clause of
  224%   `'scasp$constraint'/1` in the same module instead — see
  225%   `sscasp/dyncall.pl:constraint_clauses/2`.
  226%
  227%   In `user` because that is where SWI looks: an expansion exported from
  228%   a library is not consulted for the module that imported it.  The old
  229%   implementation puts its own there for the same reason
  230%   (`scasp/dyncall.pl`, which maps `false :- Body` onto a clause of
  231%   `-/0`).
  232
  233:- multifile user:term_expansion/2.  234
  235%!  claimed(?Term, ?Module, -Expanded) is nondet.
  236%
  237%   The spellings **both** libraries read, and what *this* one expands
  238%   each to in Module: a directive recording it, or for a global
  239%   constraint the clauses holding it.  Everything else about the spellings
  240%   is the same, which is why they are a table rather than separate
  241%   expansions.
  242%
  243%   | `:- pred Spec` | a signature here, a description in the old tree, whose expansion **raises** on this spelling rather than declining it |
  244%   | `:- scasp_dynamic Spec` | declares `p/N` and `-/1`; the old tree declares the interned `'-p'/N`, which this one never puts a clause in |
  245%   | `#pred Spec` | the spelling s(CASP) programs are written in — 84 in `test/le_programs/` alone |
  246%   | `#abducible Spec`, `:- abducible Spec` | an abducible; the old tree calls its own `abducible/1` |
  247%   | `#show Spec`, `:- show Spec` | what the model shows |
  248%   | `#sld Spec`, `#domain Spec`, `#describe Spec` | the file spelling of `:- sld`, `:- domain`, `:- describe`, so a program reads the same in a module and in a file |
  249%   | `false :- Body` | a global constraint; the old tree makes it a clause of `-/0` |
  250%
  251%   Qualified with `sscasp_dyncall` because what the guard establishes is
  252%   that the file imported `scasp/2`, not that it imported these:
  253%   `use_module(library(sscasp), [scasp/2])` is a file we claim and in
  254%   which a bare `pred/1` would not resolve.
  255
  256claimed((:- pred Spec),          M, (:- sscasp_dyncall:pred(M:Spec))) :-
  257    nonvar(Spec).
  258claimed((:- scasp_dynamic Spec), M, (:- sscasp_dyncall:scasp_dynamic(M:Spec))) :-
  259    nonvar(Spec).
  260claimed(#(pred(Spec)),           M, (:- sscasp_dyncall:Goal)) :-
  261    nonvar(Spec),
  262    template(Spec, M, Goal).
  263claimed(#(abducible(Spec)),      M, (:- sscasp_dyncall:scasp_directive(M:abducible(Spec)))) :-
  264    nonvar(Spec).
  265claimed((:- abducible Spec),     M, (:- sscasp_dyncall:scasp_directive(M:abducible(Spec)))) :-
  266    nonvar(Spec).
  267claimed(#(show(Spec)),           M, (:- sscasp_dyncall:scasp_directive(M:show(Spec)))) :-
  268    nonvar(Spec).
  269claimed((:- show Spec),          M, (:- sscasp_dyncall:scasp_directive(M:show(Spec)))) :-
  270    nonvar(Spec).
  271claimed(#(sld(Spec)),            M, (:- sscasp_dyncall:sld(M:Spec))) :-
  272    nonvar(Spec).
  273claimed(#(domain(Spec)),         M, (:- sscasp_dyncall:domain(M:Spec))) :-
  274    nonvar(Spec).
  275claimed(#(describe(Spec)),       M, (:- sscasp_dyncall:describe(M:Spec))) :-
  276    nonvar(Spec).
  277claimed((false :- Body),         _, Clauses) :-
  278    constraint_clauses(Body, Clauses).
  279
  280%!  template(@Spec, ?Module, -Goal) is det.
  281%
  282%   `#pred p(X) :: 'text'` is a description and `#pred p(dom)` a
  283%   signature.  The description goes to `describe/1` rather than
  284%   `pred/1`, so it does **not** warn:
  285%   `source.pl:partition_terms/7` makes the same choice, because the
  286%   warning is for `:- pred X :: "..."` written where `:- describe` was
  287%   available and `#pred` is what the generator emits.
  288
  289:- det(template/3).  290
  291template(Spec, M, Goal), Spec = (_ :: _) =>
  292    Goal = describe(M:Spec).
  293template(Spec, M, Goal) =>
  294    Goal = pred(M:Spec).
  295
  296%!  ours(+Module) is semidet.
  297%
  298%   Module is being compiled against **this** library rather than the old
  299%   one.  Anything installed in `user` is consulted for every file in the
  300%   process, so it has to ask which library the file it is firing on
  301%   imported — `prolog_load_context(module, M)` for the file, and then
  302%   this.  `scasp/dyncall.pl:ours/0` asks the mirror-image question, so
  303%   the two never both fire and load order decides nothing.
  304%
  305%   `scasp/2` is the marker rather than the directive being claimed,
  306%   because it is what a file imports the library *for*: a file that has
  307%   `pred/1` has it by way of `scasp/2`, and a file that has neither is
  308%   not speaking to either library.  The property survives the re-export
  309%   through `library(sscasp)`, which is why it can be asked of the
  310%   importing module rather than of the library.
  311
  312ours(Module) :-
  313    predicate_property(Module:scasp(_, _), imported_from(sscasp_dyncall)).
  314
  315%!  negated_clause(@Term) is semidet.
  316%
  317%   Term is a clause of `-/1`: a classically negated fact or rule.
  318
  319negated_clause((Head :- _)) =>
  320    nonvar(Head),
  321    Head = -(_).
  322negated_clause(Head) =>
  323    nonvar(Head),
  324    Head = -(_).
  325
  326%   One expansion for all of them, and it is the table plus the guard.
  327%
  328%   Term first, because it discriminates and the other two are asked of
  329%   every term in every file otherwise.  `Module` is unbound while the
  330%   table builds the goal around it and
  331%   `prolog_load_context/2` binds it after.
  332%
  333%   Below both, because a clause of `user:term_expansion/2` is live from
  334%   the moment it is read: every term after it in *this* file goes
  335%   through it, and one placed above would call a predicate that does not
  336%   exist yet.
  337
  338user:term_expansion(Term, Expanded) :-
  339    claimed(Term, Module, Expanded),
  340    prolog_load_context(module, Module),
  341    ours(Module).
  342
  343%   `-p(X) :- Body` is a clause of `-/1`, and so is `-q(X)`: one predicate
  344%   whose clauses a program writes next to those of p and q, never
  345%   together.  Declared discontiguous before the first of them, or every
  346%   program that negates two predicates classically is warned about it.
  347
  348user:term_expansion(Clause, [(:- discontiguous((-)/1)), Clause]) :-
  349    negated_clause(Clause),
  350    prolog_load_context(module, Module),
  351    ours(Module),
  352    \+ predicate_property(Module:(-(_)), discontiguous).
  353
  354%   **A negated literal with a variable of its own** is almost always a
  355%   mistake.  `not obs(temperature, _Value)` is read as Prolog's `\+`,
  356%   "there is no temperature reading", but a variable that occurs nowhere
  357%   else is existentially quantified *outside* the negation: the literal
  358%   holds if obs(temperature, V) is false for **some** V, which it nearly
  359%   always is.  What was meant needs an auxiliary predicate,
  360%   `temperature_known :- obs(temperature, _)`, and
  361%   `not temperature_known`.  Prolog's singleton warning does not help, as the
  362%   variable is usually written `_` or `_Name`.  This only warns: the
  363%   expansion fails.
  364
  365%!  local_negation(@Head, @Body, -Literal, -Local) is nondet.
  366%
  367%   Literal is a `not G` in Body's conjunction, G a user literal, and
  368%   Local the variables of G that occur nowhere else in the clause,
  369%   named as the reader named them, `_` for an anonymous one.
  370
  371local_negation(Head, Body, Literal, Local) :-
  372    body_list(Body, Goals),
  373    select(not(Goal), Goals, Others),
  374    callable(Goal),
  375    \+ builtin(Goal),
  376    \+ memberchk_goal(Goal, [forall(_, _), findall(_, _, _)]),
  377    term_variables(Goal, GoalVars),
  378    term_variables(Head-Others, OtherVars),
  379    exclude(var_member(OtherVars), GoalVars, LocalVars),
  380    LocalVars \== [],
  381    (   prolog_load_context(variable_names, Bindings)
  382    ->  true
  383    ;   Bindings = []
  384    ),
  385    maplist(var_name(Bindings), LocalVars, Local),
  386    named(not(Goal), Bindings, Literal).
  387
  388%   The literal as written: its variables as '$VAR'(Name), `_` for
  389%   an anonymous one.
  390
  391named(Term, Bindings, Named) :-
  392    copy_term(Term+Bindings, Named+Bindings1),
  393    maplist(bind_name, Bindings1),
  394    term_variables(Named, Anonymous),
  395    maplist(=('$VAR'('_')), Anonymous).
  396
  397bind_name(Name=Var) :-
  398    (   var(Var)
  399    ->  Var = '$VAR'(Name)
  400    ;   true
  401    ).
  402
  403memberchk_goal(Goal, Constructs) :-
  404    member(Construct, Constructs),
  405    subsumes_term(Construct, Goal),
  406    !.
  407
  408var_member(Vars, Var) :-
  409    member(V, Vars),
  410    V == Var,
  411    !.
  412
  413var_name(Bindings, Var, Name) :-
  414    (   member(Name0=V, Bindings),
  415        V == Var
  416    ->  Name = Name0
  417    ;   Name = '_'
  418    ).
  419
  420:- multifile prolog:message//1.  421
  422prolog:message(scasp(local_negation_variables(Literal, Names))) -->
  423    { atomic_list_concat(Names, ', ', NameList) },
  424    [ 's(CASP): ~w occur only in ~W'-
  425      [NameList, Literal, [numbervars(true), quoted(true), portray(true)]], nl,
  426      '  This holds if the literal is false for SOME value of them.'-[], nl,
  427      '  For "there is no such ...", negate an auxiliary predicate.'-[]
  428    ].
  429
  430%   Last, as it is live from the moment it is read.
  431
  432user:term_expansion((Head :- Body), _) :-
  433    prolog_load_context(module, Module),
  434    ours(Module),
  435    forall(local_negation(Head, Body, Literal, Local),
  436           print_message(warning,
  437                         scasp(local_negation_variables(Literal, Local)))),
  438    fail.
  439
  440
  441?    Query :- scasp(Query, [show_model(true)]).
  442??   Query :- scasp(Query, [show_model(true), show_justification(true)]).
  443?--  Query :- scasp(Query, []).
  444?+-  Query :- scasp(Query, [show_model(true)]).
  445?-+  Query :- scasp(Query, [show_justification(true)]).
  446?++  Query :- scasp(Query, [show_model(true), show_justification(true)]).
  447??+- Query :- scasp(Query, [show_model(human)]).
  448??-+ Query :- scasp(Query, [show_justification(human)]).
  449??++ Query :- scasp(Query, [show_model(human), show_justification(human)]).
  450
  451		 /*******************************
  452		 *         THE TOPLEVEL		*
  453		 *******************************/
  454
  455%!  scasp_residuals// is det.
  456%
  457%   Add the model and the justification to the toplevel's answer.  They
  458%   are emitted as *goals* the toplevel then portrays, which is how the
  459%   old implementation does it (`scasp/embed.pl`) and why the variables
  460%   come out named: the toplevel names the whole answer — bindings,
  461%   model and the constraints still on the answer's variables — in one
  462%   go, so a variable two of them share is one name.
  463%
  464%   Nothing is emitted unless the query asked, which is what separates
  465%   `? Q` from `scasp(Q)`.
  466
  467:- residual_goals(scasp_residuals).  468
  469scasp_residuals,
  470    nb_current(scasp_answer,
  471               scasp_answer(Model, Justification, Terms, Options)) ==>
  472    shown(show_model(Model), Terms, Options),
  473    shown(show_justification(Justification), Terms, Options).
  474scasp_residuals ==>
  475    [].
  476
  477shown(What, Terms, Options),
  478    compound_name_arguments(What, Name, [Value]),
  479    Spec =.. [Name, How],
  480    option(Spec, Options),
  481    How \== false ==>
  482    { how(How, Terms, ShowOptions),
  483      Goal =.. [Name, Value, ShowOptions]
  484    },
  485    [ Goal ].
  486shown(_, _, _) ==>
  487    [].
  488
  489%   `human` is the one that needs the program: a description is the
  490%   program's own and the table is built from the terms that were run.
  491
  492how(human, Terms, ShowOptions) =>
  493    ShowOptions = [readable(true), human(true), annotations(Annotations)],
  494    program_annotations(Terms, Annotations).
  495how(_, _, ShowOptions) =>
  496    ShowOptions = [readable(true), layout(columns)].
  497
  498user:portray(show_model(Model, Options)) :-
  499    ansi_format(comment, '% s(CASP) model~n', []),
  500    portray_model(Model, Options).
  501user:portray(show_justification(Justification, Options)) :-
  502    ansi_format(comment, '% s(CASP) justification~n', []),
  503    portray_justification(Justification, Options).
  504
  505%!  scasp_human(:Query) is nondet.
  506%!  scasp_human(:Query, +Options) is nondet.
  507%
  508%   The same, said in words: each literal by its `:- describe` template
  509%   where the program wrote one, and by `sscasp/lang.pl`'s vocabulary
  510%   where it did not.  This is the old implementation's `--human`, and
  511%   it goes through the same HTML description — see `sscasp/html.pl`.
  512%
  513%   Unlike the `?`-shortcuts this **prints**, so it is the one to use
  514%   from a program.  Options are `scasp/2`'s, plus `show_model(Boolean)`
  515%   and `show_justification(Boolean)`, both `true` here.
  516
  517scasp_human(Query) :-
  518    scasp_human(Query, []).
  519
  520scasp_human(Query, Options) :-
  521    merge_options(Options, [show_model(true), show_justification(true)], All),
  522    solve_and_show(Query, [human(true)|All]).
  523
  524%!  solve_and_show(:Query, +Options) is nondet.
  525%
  526%   The model and the justification are made readable **together**, and
  527%   with the query: a variable shared between them has to get one name,
  528%   or the three printed terms say different things by the same letter.
  529%
  530%   @arg Options are scasp_human/2's, plus `human(Boolean)` to say the
  531%       answer in words.
  532
  533solve_and_show(Query, Options) :-
  534    exclude(shown_here, Options, SolveOptions),
  535    scasp(Query, [model(Model), tree(Justification), program(Terms)
  536                 |SolveOptions]),
  537    \+ \+ show(Query, Model, Justification, Terms, Options).
  538
  539%   What this prints is not handed on to scasp/2, which would leave it
  540%   for scasp_residuals//0 and the toplevel would print it again.
  541
  542shown_here(show_model(_)).
  543shown_here(show_justification(_)).
  544
  545show(Query, Model, Justification, Terms, Options) :-
  546    scasp_readable(answer(Query, Model, Justification),
  547                    answer(_, Readable, Because)),
  548    said_how(Terms, Options, How),
  549    (   option(show_model(true), Options)
  550    ->  format("Model:~n"),
  551        portray_model(Readable, How),
  552        nl
  553    ;   true
  554    ),
  555    (   option(show_justification(true), Options)
  556    ->  format("Justification:~n"),
  557        portray_justification(Because, How),
  558        nl
  559    ;   true
  560    ).
  561
  562%   The annotation table is built only where something will read it: it
  563%   is the program's descriptions, and the machine form says the literal
  564%   itself whatever the program called it.
  565
  566said_how(Terms, Options, How) :-
  567    (   option(human(true), Options)
  568    ->  program_annotations(Terms, Annotations),
  569        How = [readable(true), human(true), annotations(Annotations)]
  570    ;   How = [readable(true)]
  571    ).
  572
  573
  574		 /*******************************
  575		 *            SANDBOX		*
  576		 *******************************/
  577
  578%   What SWISH may run.  The query shortcuts and `scasp/1,2` are safe
  579%   because the solver runs nothing of the program's but its logic: the
  580%   collected clauses are compiled, not called, and what the compiled
  581%   program calls is `runtime.pl` and limited arithmetic.  A qualified
  582%   goal `lists:append(...)` does reach another module — the collector
  583%   follows it and compiles *that* module's clauses — which reads code
  584%   rather than running it.  The one way out to Prolog is `:- sld`, and
  585%   the directive that declares one is not on this list.
  586%
  587%   The option `module(M)` is refused: it asserts the compiled program
  588%   into M and adds `sscasp_runtime` to M's imports for good, which in
  589%   `module(lists)` is exactly what a sandbox is there to stop.  So an
  590%   option list is accepted only as a proper list without it.
  591%
  592%   Three flags rather than the old library's seven, because the rest do
  593%   not exist here: `scasp_forall` selects among four algorithms and this
  594%   tree has one, dynamic consistency checking is `sscasp_dcc` rather than
  595%   `scasp_dcc`, `scasp_plain_dual` is unimplemented, and
  596%   `scasp_unknown` and `scasp_lang` have no reader yet.  A flag listed
  597%   before something reads it would be a promise about behaviour that is
  598%   not there.
  599
  600:- multifile
  601    sandbox:safe_meta/2,
  602    sandbox:safe_prolog_flag/2,
  603    sandbox:safe_directive/1.  604
  605sandbox:safe_meta(sscasp:(?    _), []).
  606sandbox:safe_meta(sscasp:(??   _), []).
  607sandbox:safe_meta(sscasp:(?--  _), []).
  608sandbox:safe_meta(sscasp:(?+-  _), []).
  609sandbox:safe_meta(sscasp:(?-+  _), []).
  610sandbox:safe_meta(sscasp:(?++  _), []).
  611sandbox:safe_meta(sscasp:(??+- _), []).
  612sandbox:safe_meta(sscasp:(??-+ _), []).
  613sandbox:safe_meta(sscasp:(??++ _), []).
  614sandbox:safe_meta(sscasp:scasp_human(_), []).
  615sandbox:safe_meta(sscasp:scasp_human(_, Options), []) :-
  616    safe_options(Options).
  617
  618sandbox:safe_meta(sscasp_dyncall:scasp(_), []).
  619sandbox:safe_meta(sscasp_dyncall:scasp(_, Options), []) :-
  620    safe_options(Options).
  621sandbox:safe_meta(sscasp_dyncall:scasp_show(_, _), []).
  622sandbox:safe_meta(sscasp_dyncall:scasp_json(_, _), []).
  623sandbox:safe_meta(sscasp_dyncall:scasp_json(_, _, Options), []) :-
  624    safe_options(Options).
  625sandbox:safe_meta(sscasp_dyncall:scasp_query_clauses(_, _), []).
  626sandbox:safe_meta(sscasp_dyncall:scasp_query_clauses(_, _, Options), []) :-
  627    safe_options(Options).
  628
  629sandbox:safe_directive(sscasp_dyncall:Goal) :-
  630    safe_declaration(Goal).
  631sandbox:safe_directive(M:Goal) :-
  632    prolog_load_context(module, M),
  633    callable(Goal),
  634    predicate_property(M:Goal, imported_from(sscasp_dyncall)),
  635    safe_declaration_in(Goal, M).
  636
  637safe_declaration(Goal) :-
  638    callable(Goal),
  639    Goal =.. [Name, Module:Arg],
  640    prolog_load_context(module, Module),
  641    Goal0 =.. [Name, Arg],
  642    safe_declaration_in(Goal0, Module).
  643
  644safe_declaration_in(scasp_directive(Directive), _) :-
  645    nonvar(Directive),
  646    \+ Directive = sld(_).
  647safe_declaration_in(describe(_), _).
  648safe_declaration_in(pred(_), _).
  649safe_declaration_in(domain(_), _).
  650safe_declaration_in(scasp_dynamic(_), _).
  651
  652safe_options(Options) :-
  653    is_list(Options),
  654    \+ ( member(Option, Options),
  655          ( var(Option) ; Option = module(_) )
  656        ).
  657
  658%   Not the program-changing half: `scasp_assert/1` writes clauses into
  659%   the calling module, which is exactly what a sandbox is there to stop.
  660%
  661%   The **directives** are another matter: each writes only into the
  662%   module being loaded — a `'scasp$directive'/1` clause, or `dynamic`
  663%   for `:- scasp_dynamic` — which is what a sandboxed program is allowed
  664%   to do to itself.  They reach the sandbox in two shapes: expanded by
  665%   claimed/3 to `sscasp_dyncall:Goal`, which it takes for a cross-module
  666%   directive, and called as they stand, `M:describe(Spec)`, where the
  667%   work happens in code it would then walk and refuse.  Either is
  668%   allowed when it names the module being loaded — except `:- sld`,
  669%   whose whole point is to run Prolog the sandbox has not checked.
  670
  671
  672sandbox:safe_prolog_flag(scasp_compile_nmr, _).
  673sandbox:safe_prolog_flag(scasp_compile_olon, _).
  674sandbox:safe_prolog_flag(sscasp_dcc, _)