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)  2018, VU University Amsterdam
    7                         CWI, Amsterdam
    8    All rights reserved.
    9
   10    Redistribution and use in source and binary forms, with or without
   11    modification, are permitted provided that the following conditions
   12    are met:
   13
   14    1. Redistributions of source code must retain the above copyright
   15       notice, this list of conditions and the following disclaimer.
   16
   17    2. Redistributions in binary form must reproduce the above copyright
   18       notice, this list of conditions and the following disclaimer in
   19       the documentation and/or other materials provided with the
   20       distribution.
   21
   22    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   23    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   24    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   25    FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
   26    COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   27    INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   28    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   29    LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   30    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   31    LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   32    ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   33    POSSIBILITY OF SUCH DAMAGE.
   34*/
   35
   36:- module(dcg_high_order,
   37          [ sequence//2,                % :Element, ?List
   38            sequence//3,                % :Element, :Sep, ?List
   39            sequence//5,                % :Start, :Element, :Sep, :End, ?List
   40            optional//2,                % :Match, :Otherwise
   41            foreach//2,                 % :Generator, :Element
   42            foreach//3                  % :Generator, :Element, :Sep
   43          ]).   44:- use_module(library(ordsets)).   45
   46:- meta_predicate
   47    sequence(3,?,?,?),
   48    sequence(3,//,?,?,?),
   49    sequence(//,3,//,//,?,?,?),
   50    optional(//, //, ?, ?),
   51    foreach(0,//,?,?),
   52    foreach(0,//,//,?,?).   53
   54/** <module> High order grammar operations
   55
   56This library provides facilities  comparable   maplist/3,  ignore/1  and
   57foreach/2 for DCGs.
   58
   59__STATUS__:  This  library   is   experimental.    The   interface   and
   60implementation may change based on feedback. Please send feedback to the
   61mailinglist or the issue page of the `swipl-devel.git` repository.
   62*/
   63
   64%!  sequence(:Element, ?List)// is nondet.
   65%
   66%   Match  or  generate  a  sequence  of   Element.  This  predicate  is
   67%   deterministic  if  List  is  fully    instantiated  and  Element  is
   68%   deterministic. When parsing, this predicate is _gready_ and does not
   69%   prune choice points. For example:
   70%
   71%       ?- phrase(sequence(digit, Digits), `123a`, L).
   72%       Digits = "123",
   73%       L = [97] ;
   74%       Digits = [49, 50],
   75%       L = [51, 97] ;
   76%       ...
   77
   78sequence(OnElem, List) -->
   79    sequence_(List, OnElem).
   80
   81sequence_([H|T], P) -->
   82    call(P, H),
   83    sequence_(T, P).
   84sequence_([], _) -->
   85    [].
   86
   87%!  sequence(:Element, :Sep, ?List)// is nondet.
   88%
   89%   Match or generate a sequence of Element  where each pair of elements
   90%   is separated by Sep. When _parsing_,   a  matched Sep _commits_. The
   91%   final element is _not_ committed. See also sequence//5.
   92
   93sequence(OnElem, OnSep, List) -->
   94    sequence_(List, OnElem, OnSep).
   95
   96%!  sequence(:Start, :Element, :Sep, :End, ?List)// is semidet.
   97%
   98%   Match or generate a sequence of Element   enclosed by Start end End,
   99%   where each pair of elements is separated   by Sep. More formally, it
  100%   matches the following sequence:
  101%
  102%       Start (Element,Sep)*, End
  103%
  104%   The example below matches a Prolog list of integers:
  105%
  106%       ?- phrase(sequence(("[",blanks),
  107%                          number, (",",blanks),
  108%			   (blanks,"]"), L),
  109%			   `[1, 2, 3 ] a`, Tail).
  110%       L = [1, 2, 3],
  111%	Tail = [32, 97].
  112
  113sequence(Start, OnElem, OnSep, End, List) -->
  114    Start,
  115    sequence_(List, OnElem, OnSep),
  116    End, !.
  117
  118sequence_([H|T], P, Sep) -->
  119    call(P, H),
  120    (   {T == []}
  121    ->  []
  122    ;   Sep
  123    ->  !, sequence_(T, P, Sep)
  124    ;   {T = []}
  125    ).
  126sequence_([], _, _) -->
  127    [].
  128
  129
  130%!  optional(:Match, :Default)// is det.
  131%
  132%   Perform an optional  match,  executing  Default   if  Match  is  not
  133%   matched. This is comparable to ignore/1.  Both Match and Default are
  134%   DCG body terms. Default is typically  used to instantiate the output
  135%   variables of Match, but  may  also  be   used  to  match  a  default
  136%   representation.  Using  `[]`  for  Default    succeeds  without  any
  137%   additional actions if Match fails. For example:
  138%
  139%       ?- phrase(optional(number(X), {X=0}), `23`, Tail).
  140%       X = 23,
  141%       Tail = [].
  142%       ?- phrase(optional(number(X), {X=0}), `aap`, Tail).
  143%       X = 0,
  144%       Tail = `aap`.
  145
  146optional(Match, _Default) -->
  147    Match, !.
  148optional(_, Default) -->
  149    Default, !.
  150
  151%!  foreach(:Generator, :Element)// is det.
  152%!  foreach(:Generator, :Element, :Sep)// is det.
  153%
  154%   Generate a list from the  solutions   of  Generator.  This predicate
  155%   collects all solutions  of  Generator,   applies  Element  for  each
  156%   solution and Sep _between_ each pair of solutions.  For example:
  157%
  158%       ?- phrase(foreach(between(1,5,X), number(X), ", "), L).
  159%       L = "1, 2, 3, 4, 5, 6, 7, 8, 9, 10".
  160
  161foreach(Generator, Rule) -->
  162    foreach(Generator, Rule, []).
  163
  164foreach(Generator, Rule, Sep) -->
  165    { term_variables(Generator, GenVars0),   sort(GenVars0, GenVars),
  166      term_variables((Rule,Sep), GoalVars0), sort(GoalVars0, GoalVars),
  167      ord_subtract(GoalVars, GenVars, SharedGoalVars),
  168      ord_intersection(GenVars, GoalVars, SharedVars),
  169      Templ =.. [v|SharedVars],
  170      SharedTempl =.. [v|SharedGoalVars],
  171      findall(Templ, Generator, List)
  172    },
  173    emit_list(List, Templ, SharedTempl, Rule, Sep).
  174
  175emit_list([], _, _, _, _) -->
  176    [].
  177emit_list([H|T], Templ, SharedTempl, OnElem, OnSep) -->
  178    { copy_term(t(Templ,SharedTempl,OnElem,OnSep),
  179                t(H,SharedTempl,OnElemCopy,OnSepCopy))
  180    },
  181    OnElemCopy,
  182    (   { T == [] }
  183    ->  []
  184    ;   OnSepCopy,
  185        emit_list(T, Templ, SharedTempl, OnElem, OnSep)
  186    ).
  187
  188
  189                /*******************************
  190                *            SANDBOX           *
  191                *******************************/
  192
  193:- multifile sandbox:safe_meta_predicate/1.  194
  195sandbox:safe_meta_predicate(dcg_high_order:sequence/4).
  196sandbox:safe_meta_predicate(dcg_high_order:sequence/5).
  197sandbox:safe_meta_predicate(dcg_high_order:sequence/7).
  198sandbox:safe_meta_predicate(dcg_high_order:optional/4).
  199sandbox:safe_meta_predicate(dcg_high_order:foreach/4).
  200sandbox:safe_meta_predicate(dcg_high_order:foreach/5)