View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2019-2020, VU University Amsterdam
    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(prolog_wrap,
   36          [ wrap_predicate/4,                   % :Head, +Name, -Wrapped, +Body
   37            unwrap_predicate/2,                 % :PI, ?Name
   38            current_predicate_wrapper/4		% :Head, -Name, -Wrapped, -Body
   39          ]).   40:- autoload(library(lists),[member/2]).   41:- autoload(library(pairs),[pairs_keys/2]).   42
   43
   44:- meta_predicate
   45    wrap_predicate(:, +, -, +),
   46%   unwrap_predicate(:, ?),
   47    current_predicate_wrapper(:, -, -, -).   48
   49/** <module> Wrapping predicates
   50
   51This library allows adding  _wrappers_  to   predicates.  The  notion of
   52wrappers is known in various languages  under several names. For example
   53Logtalk knows these as _before methods_   or  _after methods_ and Python
   54has _decorators_. A SWI-Prolog wrapper is   a  _body term_ that normally
   55calls the original wrapped definition somewhere.
   56*/
   57
   58%!  wrap_predicate(:Head, +Name, -Wrapped, +Body) is det.
   59%
   60%   Wrap the predicate referenced by Head   using Body. Subsequent calls
   61%   to Head call the  given  Body  term.   Body  may  call  the original
   62%   definition through Wrapped. Wrapped is a   term  of the shape below,
   63%   where _Closure_ is an opaque _blob_.
   64%
   65%       call(Closure(A1, ...))
   66%
   67%   Name names the wrapper for  inspection using predicate_property/2 or
   68%   deletion using unwrap_predicate/2. If Head has   a wrapper with Name
   69%   the Body of the existing  wrapper   is  updated without changing the
   70%   order of the registered wrappers. The  same predicate may be wrapped
   71%   multiple times. Multiple wrappers  are   executed  starting with the
   72%   last registered (outermost).
   73%
   74%   The predicate referenced by Head does not  need to be defined at the
   75%   moment the wrapper is installed. If Head is undefined, the predicate
   76%   is created instead of _searched for_ using e.g., the auto loader.
   77%
   78%   Registered  wrappers  __are  not  part    of   saved  states__  (see
   79%   qsave_program/2) and thus need  to   be  re-registered,  for example
   80%   using initialization/1.
   81%
   82%   An example of using wrap_predicate/4 for computing GCD:
   83%   ==
   84%       :- wrap_predicate(gcd(A,B,Gcd), gcd_wrap, W, gcd_wrap(W, A, B, Gcd)).
   85%
   86%       gcd(X, Y, Gcd), X < Y => gcd(X, Y-X, Gcd).
   87%       gcd(X, Y, Gcd), X > Y => gcd(Y, X-Y, Gcd).
   88%       gcd(X, _, Gcd) => Gcd = X.
   89%
   90%       gcd_wrap(call(Closure), X, Y, Gcd) :-
   91%           functor(Closure, ClosureBlob, 3),
   92%           X_eval is X,
   93%           Y_eval is Y,
   94%           call(ClosureBlob, X_eval, Y_eval, Gcd).
   95%   ==
   96%   or (less efficient):
   97%   ==
   98%       gcd_wrap(call(Closure), X, Y, Gcd) :-
   99%           functor(Closure, ClosureBlob, 3),
  100%           call(ClosureBlob, X_eval, Y_eval, G),
  101%           Gcd is G.
  102%   ==
  103
  104wrap_predicate(M:Head, WName, Wrapped, Body) :-
  105    '$wrap_predicate'(M:Head, WName, _Closure, Wrapped, Body).
  106
  107%!  unwrap_predicate(:PI, ?Name) is semidet.
  108%
  109%   Remove the outermost wrapper whose name  unifies with Name. Fails if
  110%   no matching wrapper exists.
  111
  112%!  current_predicate_wrapper(:Head, -Name, -Wrapped, -Body) is nondet.
  113%
  114%   True if Head is wrapped with Body. The arguments are compatible with
  115%   wrap_predicate/4 such that the result may   be used to re-create the
  116%   wrapper.
  117%
  118%   Wrappers  are  enumerated  starting  with    the   first  registered
  119%   (innermost) wrapper.
  120
  121current_predicate_wrapper(M:Head, Name, Wrapped, Body) :-
  122    '$wrapped_predicate'(M:Head, Pairs),
  123    Head =.. [_|Args],
  124    member(Name-CRef, Pairs),
  125    clause(M:WHead, Body0, CRef),
  126    WHead =.. [_|Args],
  127    body_closure(Body0, Wrapped, Body).
  128
  129body_closure(call(ClosureTerm), Wrapped, Wrapped) :-
  130    callable(ClosureTerm),
  131    functor(ClosureTerm, Closure, _Arity),
  132    blob(Closure, closure),
  133    !.
  134body_closure(Body0, Wrapped, Body) :-
  135    compound(Body0),
  136    !,
  137    compound_name_arity(Body0, Name, Arity),
  138    compound_name_arity(Body,  Name, Arity),
  139    body_closure_args(0, Arity, Body0, Wrapped, Body).
  140body_closure(Body, _, Body).
  141
  142body_closure_args(I, Arity, Body0, Closure, Body) :-
  143    I < Arity,
  144    !,
  145    I2 is I+1,
  146    arg(I2, Body0, Arg0),
  147    arg(I2, Body, Arg),
  148    body_closure(Arg0, Closure, Arg),
  149    body_closure_args(I2, Arity, Body0, Closure, Body).
  150body_closure_args(_, _, _, _, _).
  151
  152
  153%   Not for public docs!
  154%   '$syspreds':'$predicate_property'(?Property, +Value) is nondet.
  155%
  156%   Extend predicate_property/2 to provide the `wrapped` property
  157
  158:- multifile
  159    '$syspreds':'$predicate_property'/2.  160
  161'$syspreds':'$predicate_property'(wrapped(List), Pred) :-
  162    '$wrapped_predicate'(Pred, Pairs),
  163    pairs_keys(Pairs, List)