/*  Part of SWI-Prolog

    Author:        Jan Wielemaker
    E-mail:        J.Wielemaker@vu.nl
    WWW:           http://www.swi-prolog.org
    Copyright (c)  2010-2020, University of Amsterdam
                              CWI, Amsterdam
    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions
    are met:

    1. Redistributions of source code must retain the above copyright
       notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright
       notice, this list of conditions and the following disclaimer in
       the documentation and/or other materials provided with the
       distribution.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/

:- module(rewrite_term,
          [ rewrite_term/2,                  % +Rule, +Input
            rew_term_expansion/2,
            rew_goal_expansion/2,

            op(1200, xfx, (::=))
          ]).
:- autoload(library(occurs),[sub_term/2]).

:- meta_predicate
    rewrite_term(1, +).

                 /*******************************
                 *          COMPILATION         *
                 *******************************/

rew_term_expansion((Rule ::= RuleBody), (Head :- Body)) :-
    translate(RuleBody, Term, Body0),
    simplify(Body0, Body),
    Rule =.. [Name|List],
    Head =.. [Name,Term|List].

rew_goal_expansion(rewrite_term(To, From), Goal) :-
    nonvar(To),
    To = \Rule,
    callable(Rule),
    Rule =.. [Name|List],
    Goal =.. [Name,From|List].


                 /*******************************
                 *            TOPLEVEL          *
                 *******************************/

%!  rewrite_term(:To, +From)
%
%   Invoke the term-rewriting system

rewrite_term(M:T, From) :-
    (   var(T)
    ->  From = T
    ;   T = \Rule
    ->  Rule =.. [Name|List],
        Goal =.. [Name,From|List],
        M:Goal
    ;   match(T, M, From)
    ).

match(Rule, M, From) :-
    translate(Rule, From, Code),
    M:Code.

translate(Var, Var, true) :-
    var(Var),
    !.
translate((\Command, !), Var, (Goal, !)) :-
    !,
    (   callable(Command),
        Command =.. [Name|List]
    ->  Goal =.. [Name,Var|List]
    ;   Goal = rewrite(\Command, Var)
    ).
translate(\Command, Var, Goal) :-
    !,
    (   callable(Command),
        Command =.. [Name|List]
    ->  Goal =.. [Name,Var|List]
    ;   Goal = rewrite(\Command, Var)
    ).
translate(Atomic, Atomic, true) :-
    atomic(Atomic),
    !.
translate(C, _, Cmd) :-
    command(C, Cmd),
    !.
translate((A, B), T, Code) :-
    (   command(A, Cmd)
    ->  !, translate(B, T, C),
        Code = (Cmd, C)
    ;   command(B, Cmd)
    ->  !, translate(A, T, C),
        Code = (C, Cmd)
    ).
translate(Term0, Term, Command) :-
    functor(Term0, Name, Arity),
    functor(Term, Name, Arity),
    translate_args(0, Arity, Term0, Term, Command).

translate_args(N, N, _, _, true) :- !.
translate_args(I0, Arity, T0, T1, (C0,C)) :-
    I is I0 + 1,
    arg(I, T0, A0),
    arg(I, T1, A1),
    translate(A0, A1, C0),
    translate_args(I, Arity, T0, T1, C).

command(0, _) :-                       % catch variables
    !,
    fail.
command({A}, A).
command(!, !).

                 /*******************************
                 *            SIMPLIFY          *
                 *******************************/

%!  simplify(+Raw, -Simplified)
%
%   Get rid of redundant `true' goals generated by translate/3.

simplify(V, V) :-
    var(V),
    !.
simplify((A0,B), A) :-
    B == true,
    !,
    simplify(A0, A).
simplify((A,B0), B) :-
    A == true,
    !,
    simplify(B0, B).
simplify((A0, B0), C) :-
    !,
    simplify(A0, A),
    simplify(B0, B),
    (   (   A \== A0
        ;   B \== B0
        )
    ->  simplify((A,B), C)
    ;   C = (A,B)
    ).
simplify(X, X).

                 /*******************************
                 *             XREF             *
                 *******************************/

:- multifile
    prolog:called_by/2.

prolog:called_by(rewrite(Spec, _Term), Called) :-
    findall(G+1, sub_term(\G, Spec), Called).
