View source with formatted comments or as raw
    1/*  Part of SWI-Prolog
    2
    3    Author:        Jan Wielemaker and Wouter Beek
    4    E-mail:        J.Wielemaker@vu.nl
    5    WWW:           http://www.swi-prolog.org
    6    Copyright (c)  2015-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
   37:- module(rdf11,
   38          [ rdf/3,                      % ?S, ?P, ?O
   39            rdf/4,                      % ?S, ?P, ?O, ?G
   40            rdf_has/3,                  % ?S, ?P, ?O
   41            rdf_has/4,                  % ?S, ?P, ?O, -RealP
   42            rdf_update/4,               % +S, +P, +O, +Action
   43            rdf_update/5,               % +S, +P, +O, +G, +Action
   44            rdf_reachable/3,            % ?S, ?P, ?O
   45            rdf_reachable/5,            % ?S, ?P, ?O, +MaxD, -D
   46
   47            rdf_assert/3,               % +S, +P, +O
   48            rdf_assert/4,               % +S, +P, +O, ?G
   49            rdf_retractall/3,           % ?S, ?P, ?O
   50            rdf_retractall/4,           % ?S, ?P, ?O, ?G
   51
   52            {}/1,                       % +Where
   53            rdf_where/1,                % +Where
   54            rdf_compare/3,              % -Diff, +Left, +Right
   55
   56            rdf_term/1,                 % ?Term
   57            rdf_literal/1,              % ?Term
   58            rdf_bnode/1,                % ?Term
   59            rdf_iri/1,                  % ?Term
   60            rdf_name/1,                 % ?Term
   61
   62            rdf_is_iri/1,               % @Term
   63            rdf_is_bnode/1,             % @Term
   64            rdf_is_literal/1,           % @Term
   65            rdf_is_name/1,              % @Term
   66            rdf_is_object/1,            % @Term
   67            rdf_is_predicate/1,         % @Term
   68            rdf_is_subject/1,           % @Term
   69            rdf_is_term/1,              % @Term
   70
   71            rdf_subject/1,              % ?Term
   72            rdf_predicate/1,            % ?Term
   73            rdf_object/1,               % ?Term
   74            rdf_node/1,                 % ?Term
   75
   76            rdf_create_bnode/1,         % ?Term
   77
   78            rdf_canonical_literal/2,    % +In, -Canonical
   79            rdf_lexical_form/2,         % +Literal, -Lexical
   80
   81            rdf_default_graph/1,        % -Graph
   82            rdf_default_graph/2,        % -Old, +New
   83
   84            rdf_estimate_complexity/4,  % ?S, ?P, ?O, -Estimate
   85            rdf_assert_list/2,          % +PrologList, ?RDFList
   86            rdf_assert_list/3,          % +PrologList, ?RDFList, +G
   87            rdf_last/2,                 % +RDFList, ?Last
   88            rdf_list/1,                 % ?RDFList
   89            rdf_list/2,                 % +RDFList, -PrologList
   90            rdf_length/2,               % ?RDFList, ?Length
   91            rdf_member/2,               % ?Member, +RDFList
   92            rdf_nextto/2,               % ?X, ?Y
   93            rdf_nextto/3,               % ?X, ?Y, ?RdfList
   94            rdf_nth0/3,                 % ?Index, +RDFList, ?X
   95            rdf_nth1/3,                 % ?Index, +RDFList, ?X
   96            rdf_retract_list/1,         % +RDFList
   97
   98            op(110, xfx, @),            % must be above .
   99            op(650, xfx, ^^),           % must be above :
  100            op(1150, fx, rdf_meta)
  101          ]).  102:- use_module(library(semweb/rdf_prefixes),
  103              [ (rdf_meta)/1, op(_,_,rdf_meta)
  104              ]).  105:- use_module(library(semweb/rdf_db),
  106              [ rdf_transaction/2,
  107                rdf_match_label/3,
  108                rdf_equal/2,
  109                rdf_is_bnode/1,
  110                rdf_transaction/1
  111              ]).  112
  113:- autoload(library(apply),[partition/4]).  114:- autoload(library(c14n2),[xml_write_canonical/3]).  115:- autoload(library(debug),[assertion/1,debug/3]).  116:- autoload(library(error),
  117	    [ must_be/2,
  118	      domain_error/2,
  119	      instantiation_error/1,
  120	      existence_error/2,
  121	      type_error/2,
  122	      is_of_type/2,
  123	      uninstantiation_error/1
  124	    ]).  125:- autoload(library(lists),[select/3,append/3]).  126:- autoload(library(memfile),
  127	    [new_memory_file/1,open_memory_file/3,free_memory_file/1]).  128:- autoload(library(sgml),
  129	    [ xsd_number_string/2,
  130	      xsd_time_string/3,
  131	      xml_is_dom/1,
  132	      load_xml/3,
  133	      load_html/3
  134	    ]).  135:- autoload(library(sgml_write),[html_write/3,xml_write/2]).  136:- autoload(library(solution_sequences),[distinct/2]).  137
  138:- reexport(library(semweb/rdf_db),
  139            except([ rdf/3,
  140                     rdf/4,
  141                     rdf_assert/3,
  142                     rdf_assert/4,
  143                     rdf_current_literal/1,
  144                     rdf_current_predicate/1,
  145                     rdf_has/3,
  146                     rdf_has/4,
  147                     rdf_update/4,
  148                     rdf_update/5,
  149                     rdf_reachable/3,
  150                     rdf_reachable/5,
  151                     rdf_retractall/3,
  152                     rdf_retractall/4,
  153                     rdf_node/1,
  154                     rdf_bnode/1,
  155                     rdf_is_literal/1,
  156                     rdf_is_resource/1,
  157                     rdf_literal_value/2,
  158                     rdf_compare/3,
  159                     rdf_estimate_complexity/4
  160                   ])
  161           ).  162/** <module> RDF 1.1 API
  163
  164This library provides a new API   on  top of library(semweb/rdf_db). The
  165new API follows the  RDF  1.1  terminology   and  notation  as  much  as
  166possible. It runs on top of the old API, which implies that applications
  167can use the new API in one file and   the other in another one. Once the
  168new API is considered stable and robust the old API will be deprecated.
  169
  170In a nutshell, the following issues are addressed:
  171
  172  - Literals are now represented by Value^^Type or Text@Lang.  Plain
  173    literals no longer exist. Value is a Prolog representation of
  174    the value for known types.  In particular:
  175      - xsd:double, xsd:float and xsd:decimal are represented by a Prolog
  176        float
  177      - Integer types are represented by a Prolog integer
  178      - The date/time types are presented by Prolog terms
  179  - Literal matching and comparison operations are represented as
  180    Prolog _constraints_.  This replaces the literal(+Search,-Value)
  181    construct used by library(semweb/rdf_db). For example, the following
  182    query returns literals with prefix "ams", exploiting the RDF literal
  183    index.
  184
  185      ==
  186      { prefix(Name, "ams") },
  187      rdf(S,P,Name).
  188      ==
  189  - Graphs are always identified by the graph name only, i.e., the
  190    notation Graph:Line is no longer supported.  If a graph name is an IRI
  191    then RDF prefix notation can now be used.
  192  - The enumeration and type-testing predicates are now more closely based
  193    on the RDF 1.1 specification and use consistent naming.
  194
  195@author Jan Wielemaker
  196@author Wouter Beek
  197@see https://github.com/SWI-Prolog/packages-semweb/wiki/Proposal-for-Semweb-library-redesign
  198@version 2016
  199*/
  200
  201:- multifile
  202    in_ground_type_hook/3,                  % +Type, +Input, -Lexical:atom
  203    out_type_hook/3,                        % +Type, -Output, +Lexical:atom
  204    invalid_lexical_form_hook/3.            % +Type, +Lexical, -Prolog
  205
  206:- meta_predicate
  207    parse_partial_xml(3,+,-).  208
  209:- rdf_meta
  210    rdf(r,r,o),
  211    rdf(r,r,o,r),
  212    rdf_assert(r,r,o),
  213    rdf_assert(r,r,o,r),
  214    rdf_has(r,r,o),
  215    rdf_has(r,r,o,-),
  216    rdf_update(r,r,o,t),
  217    rdf_update(r,r,o,r,t),
  218    rdf_reachable(r,r,o),
  219    rdf_reachable(r,r,o,+,-),
  220    rdf_retractall(r,r,o),
  221    rdf_retractall(r,r,o,r),
  222    {}(t),
  223    rdf_where(t),
  224    rdf_canonical_literal(o,-),
  225    rdf_lexical_form(o,-),
  226    rdf_compare(-,o,o),
  227    rdf_iri(r),
  228    rdf_is_iri(r),
  229    rdf_is_literal(o),
  230    rdf_is_name(o),
  231    rdf_is_object(o),
  232    rdf_is_predicate(r),
  233    rdf_is_subject(r),
  234    rdf_is_term(o),
  235    rdf_term(o),
  236    rdf_literal(o),
  237    rdf_name(o),
  238    rdf_object(o),
  239    rdf_estimate_complexity(r,r,o,-),
  240    rdf_assert_list(t,r),
  241    rdf_assert_list(t,r,r),
  242    rdf_last(r,o),
  243    rdf_list(r),
  244    rdf_list(r,-),
  245    rdf_length(r,-),
  246    rdf_member(o,r),
  247    rdf_nextto(o,o),
  248    rdf_nth0(?,r,o),
  249    rdf_nth1(?,r,o),
  250    rdf_retract_list(r).  251
  252
  253%!  rdf(?S, ?P, ?O) is nondet.
  254%!  rdf(?S, ?P, ?O, ?G) is nondet.
  255%
  256%   True if an RDF triple <S,P,O> exists, optionally in the graph G.
  257%   The object O is either a resource  (atom)   or  one of the terms
  258%   listed below. The described types apply for  the case where O is
  259%   unbound. If O is instantiated it   is converted according to the
  260%   rules described with rdf_assert/3.
  261%
  262%   Triples consist of the following three terms:
  263%
  264%     - Blank nodes are encoded by atoms that start with `_:`.
  265%     - IRIs appear in two notations:
  266%       - Full IRIs are encoded by atoms that do not start with
  267%         `_:`.  Specifically, an IRI term is not required to follow
  268%         the IRI standard grammar.
  269%       - Abbreviated IRI notation that allows IRI prefix aliases
  270%         that are registered by rdf_register_prefix/[2,3] to be
  271%         used.  Their notation is `Alias:Local`, where Alias and
  272%         Local are atoms.  Each abbreviated IRI is expanded by the
  273%         system to a full IRI.
  274%     - Literals appear in two notations:
  275%       - String@Lang
  276%       A language-tagged string, where String is a Prolog string
  277%       and Lang is an atom.
  278%       - Value^^Type
  279%       A type qualified literal.  For unknown types, Value is a
  280%       Prolog string. If type is known, the Prolog representations
  281%       from the table below are used.
  282%
  283%       | **Datatype IRI**      | **Prolog term**                 |
  284%       |:----------------------|:--------------------------------|
  285%       | xsd:float             | float                           |
  286%       | xsd:double            | float                           |
  287%       | xsd:decimal           | float                     (1)   |
  288%       | xsd:integer           | integer                         |
  289%       | XSD integer sub-types | integer                         |
  290%       | xsd:boolean           | `true` or `false`               |
  291%       | xsd:date              | date(Y,M,D)                     |
  292%       | xsd:dateTime          | date_time(Y,M,D,HH,MM,SS) (2,3) |
  293%       | xsd:gDay              | integer                         |
  294%       | xsd:gMonth            | integer                         |
  295%       | xsd:gMonthDay         | month_day(M,D)                  |
  296%       | xsd:gYear             | integer                         |
  297%       | xsd:gYearMonth        | year_month(Y,M)                 |
  298%       | xsd:time              | time(HH,MM,SS)            (2)   |
  299%
  300%   Notes:
  301%
  302%     (1) The current implementation of `xsd:decimal` values
  303%         as floats is formally incorrect.  Future versions
  304%         of SWI-Prolog may introduce decimal as a subtype
  305%         of rational.
  306%
  307%     (2) `SS` fields denote the number of seconds.  This can
  308%         either be an integer or a float.
  309%
  310%     (3) The `date_time` structure can have a 7th field that
  311%         denotes the timezone offset *in seconds* as an
  312%         integer.
  313%
  314%   In addition, a _ground_  object  value   is  translated  into  a
  315%   properly typed RDF literal using rdf_canonical_literal/2.
  316%
  317%   There is a fine distinction  in   how  duplicate  statements are
  318%   handled in rdf/[3,4]: backtracking over  rdf/3 will never return
  319%   duplicate triples that appear  in   multiple  graphs. rdf/4 will
  320%   return such duplicate triples, because their graph term differs.
  321%
  322%   @arg S is the subject term.  It is either a blank node or IRI.
  323%   @arg P is the predicate term.  It is always an IRI.
  324%   @arg O is the object term.  It is either a literal, a blank
  325%        node or IRI (except for `true` and `false` that denote the
  326%        values of datatype XSD boolean).
  327%   @arg G is the graph term.  It is always an IRI.
  328%
  329%   @see [Triple pattern querying](http://www.w3.org/TR/sparql11-query/#sparqlTriplePatterns)
  330%   @see xsd_number_string/2 and xsd_time_string/3 are used to
  331%        convert between lexical representations and Prolog terms.
  332
  333rdf(S,P,O) :-
  334    pre_object(O,O0,S,P),
  335    rdf_db:rdf(S,P,O0),
  336    post_object(O,O0).
  337
  338rdf(S,P,O,G) :-
  339    pre_object(O,O0,S,P),
  340    pre_graph(G,G0),
  341    rdf_db:rdf(S,P,O0,G0),
  342    post_graph(G, G0),
  343    post_object(O,O0).
  344
  345%!  rdf_has(?S, +P, ?O) is nondet.
  346%!  rdf_has(?S, +P, ?O, -RealP) is nondet.
  347%
  348%   Similar to rdf/3 and rdf/4, but   P  matches all predicates that
  349%   are defined as an rdfs:subPropertyOf of   P. This predicate also
  350%   recognises   the   predicate   properties     `inverse_of`   and
  351%   `symmetric`. See rdf_set_predicate/2.
  352
  353rdf_has(S,P,O) :-
  354    pre_object(O,O0,S,P),
  355    rdf_db:rdf_has(S,P,O0),
  356    post_object(O,O0).
  357
  358rdf_has(S,P,O,RealP) :-
  359    pre_object(O,O0,S,P),
  360    rdf_db:rdf_has(S,P,O0,RealP),
  361    post_object(O,O0).
  362
  363
  364%!  rdf_update(+S, +P, +O, ++Action) is det.
  365%!  rdf_update(+S, +P, +O, +G, ++Action) is det.
  366%
  367%   Replaces one of the three  (four)   fields  on  the matching triples
  368%   depending on Action:
  369%
  370%     * subject(Resource)
  371%     Changes the first field of the triple.
  372%     * predicate(Resource)
  373%     Changes the second field of the triple.
  374%     * object(Object)
  375%     Changes the last field of the triple to the given resource or
  376%     literal(Value).
  377%     * graph(Graph)
  378%     Moves the triple from its current named graph to Graph.
  379%     This only works with rdf_update/5 and throws an error when
  380%     used with rdf_update/4.
  381%
  382%   The argument matching Action must  be   ground.  If this argument is
  383%   equivalent to the current value, no  action is performed. Otherwise,
  384%   the requested action is  performed  on   all  matching  triples. For
  385%   example,  all  resources  typed  `rdfs:Class`   can  be  changed  to
  386%   `owl:Class` using
  387%
  388%     ```
  389%     ?- rdf_update(_, rdf:type, rdfs:'Class',
  390%                   object(owl:'Class')).
  391%     ```
  392%
  393%   @error instantiation_error if Action or the matching argument is
  394%          not ground.
  395%   @error domain_error(rdf_update_action, Action) if Action is not
  396%          one of the above terms.
  397
  398rdf_update(S, P, O, Action) :-
  399    rdf_update(S, P, O, _, Action).
  400rdf_update(S, P, O, G, Action) :-
  401    must_be(ground, Action),
  402    (   update_column(Action, S,P,O,G, On)
  403    ->  must_be(ground, On),
  404        arg(1, Action, Old),
  405        (   On == Old
  406        ->  true
  407        ;   rdf_transaction(rdf_update_(S, P, O, G, Action), update)
  408        )
  409    ;   domain_error(rdf_update_action, Action)
  410    ).
  411
  412update_column(subject(_),   S,_,_,_, S).
  413update_column(predicate(_), _,P,_,_, P).
  414update_column(object(_),    _,_,O,_, O).
  415update_column(graph(_),     _,_,_,G, G).
  416
  417rdf_update_(S1, P, O, G, subject(S2)) :-
  418    !,
  419    forall(rdf(S1, P, O, G),
  420           ( rdf_retractall(S1, P, O, G),
  421             rdf_assert(S2, P, O, G)
  422           )).
  423rdf_update_(S, P1, O, G, predicate(P2)) :-
  424    !,
  425    forall(rdf(S, P1, O, G),
  426           ( rdf_retractall(S, P1, O, G),
  427             rdf_assert(S, P2, O, G)
  428           )).
  429rdf_update_(S, P, O1, G, object(O2)) :-
  430    !,
  431    forall(rdf(S, P, O1, G),
  432           ( rdf_retractall(S, P, O1, G),
  433             rdf_assert(S, P, O2, G)
  434           )).
  435rdf_update_(S, P, O, G1, graph(G2)) :-
  436    !,
  437    forall(rdf(S, P, O, G1),
  438           ( rdf_retractall(S, P, O, G1),
  439             rdf_assert(S, P, O, G2)
  440           )).
  441
  442
  443%!  rdf_reachable(?S, +P, ?O) is nondet.
  444%!  rdf_reachable(?S, +P, ?O, +MaxD, -D) is nondet.
  445%
  446%   True when O can be reached from S using the transitive closure
  447%   of P. The predicate uses (the internals of) rdf_has/3 and thus
  448%   matches both rdfs:subPropertyOf and the `inverse_of` and
  449%   `symmetric` predicate properties. The version rdf_reachable/5
  450%   maximizes the steps considered and returns the number of steps
  451%   taken.
  452%
  453%   If both S and O are given,   these predicates are `semidet`. The
  454%   number of steps D is  minimal   because  the implementation uses
  455%   _breadth first_ search.
  456
  457rdf_reachable(S,P,O) :-
  458    pre_object(O,O0,S,P),
  459    rdf_db:rdf_reachable(S,P,O0),
  460    post_object(O,O0).
  461
  462rdf_reachable(S,P,O,MaxD,D) :-
  463    pre_object(O,O0,S,P),
  464    rdf_db:rdf_reachable(S,P,O0,MaxD,D),
  465    post_object(O,O0).
  466
  467
  468%!  rdf_assert(+S, +P, +O) is det.
  469%!  rdf_assert(+S, +P, +O, +G) is det.
  470%
  471%   Assert a new triple. If O is a literal, certain Prolog terms are
  472%   translated  to  typed  RDF  literals.    These  conversions  are
  473%   described with rdf_canonical_literal/2.
  474%
  475%   If a type  is  provided   using  Value^^Type  syntax, additional
  476%   conversions are performed. All types accept   either  an atom or
  477%   Prolog string holding a valid RDF lexical value for the type and
  478%   xsd:float and xsd:double accept a Prolog integer.
  479
  480rdf_assert(S,P,O) :-
  481    rdf_default_graph(G),
  482    rdf_assert(S,P,O,G).
  483
  484rdf_assert(S,P,O,G) :-
  485    must_be(ground, O),
  486    pre_ground_object(O,O0),
  487    rdf_db:rdf_assert(S,P,O0,G).
  488
  489%!  rdf_retractall(?S, ?P, ?O) is nondet.
  490%!  rdf_retractall(?S, ?P, ?O, ?G) is nondet.
  491%
  492%   Remove all matching  triples  from   the  database.  Matching is
  493%   performed using the same  rules  as   rdf/3.  The  call does not
  494%   instantiate any of its arguments.
  495
  496rdf_retractall(S,P,O) :-
  497    pre_object(O,O0,S,P),
  498    rdf_db:rdf_retractall(S,P,O0).
  499
  500rdf_retractall(S,P,O,G) :-
  501    pre_object(O,O0,S,P),
  502    pre_graph(G,G0),
  503    rdf_db:rdf_retractall(S,P,O0,G0).
  504
  505
  506%!  rdf_compare(-Diff, +Left, +Right) is det.
  507%
  508%   True if the RDF terms Left and   Right  are ordered according to
  509%   the comparison operator Diff.  The ordering is defines as:
  510%
  511%     - Literal < BNode < IRI
  512%     - For literals
  513%       - Numeric < non-numeric
  514%       - Numeric literals are ordered by value.  If both are
  515%         equal, floats are ordered before integers.
  516%       - Other data types are ordered lexicographically.
  517%     - BNodes and IRIs are ordered lexicographically.
  518%
  519%   Note that this ordering is a complete ordering of RDF terms that
  520%   is consistent with the partial ordering defined by SPARQL.
  521%
  522%   @arg Diff is one of `<`, `=` or `>`
  523
  524rdf_compare(Diff, Left, Right) :-
  525    pre_ground_object(Left, Left0),
  526    pre_ground_object(Right, Right0),
  527    rdf_db:rdf_compare(Diff, Left0, Right0).
  528
  529
  530%!  {}(+Where) is semidet.
  531%!  rdf_where(+Where) is semidet.
  532%
  533%   Formulate constraints on RDF terms,  notably literals. These are
  534%   intended to be used as illustrated   below.  RDF constraints are
  535%   pure: they may be placed before, after or inside a graph pattern
  536%   and, provided the code contains no  _commit_ operations (!, ->),
  537%   the  semantics  of  the  goal   remains  the  same.  Preferably,
  538%   constraints are placed _before_ the graph  pattern as they often
  539%   help the RDF database to  exploit   its  literal indexes. In the
  540%   example below, the database can choose between using the subject
  541%   and/or predicate hash or the ordered literal table.
  542%
  543%     ==
  544%         { Date >= "2000-01-01"^^xsd:date },
  545%         rdf(S, P, Date)
  546%     ==
  547%
  548%   The following constraints are currently defined:
  549%
  550%     - >, >=, ==, =<, <
  551%       The comparison operators are defined between numbers (of any
  552%       recognised type), typed literals of the same type and
  553%       langStrings of the same language.
  554%     - prefix(String, Pattern)
  555%     - substring(String, Pattern)
  556%     - word(String, Pattern)
  557%     - like(String, Pattern)
  558%     - icase(String, Pattern)
  559%       Text matching operators that act on both typed literals
  560%       and langStrings.
  561%     - lang_matches(Term, Pattern)
  562%       Demands a full RDF term (Text@Lang) or a plain `Lang` term
  563%       to match the language pattern Pattern.
  564%
  565%   The  predicates  rdf_where/1  and  {}/1    are   identical.  The
  566%   rdf_where/1  variant  is  provided   to    avoid   ambiguity  in
  567%   applications where {}/1 is used for other purposes. Note that it
  568%   is also possible to write `rdf11:{...}`.
  569
  570{}(Where) :-
  571    rdf_where(Where).
  572
  573rdf_where(Var) :-
  574    var(Var),
  575    !,
  576    instantiation_error(Var).
  577rdf_where((A,B)) :-
  578    !,
  579    rdf_where(A),
  580    rdf_where(B).
  581rdf_where(Constraint) :-
  582    rdf_constraint(Constraint, Goal),
  583    !,
  584    call(Goal).
  585rdf_where(Constraint) :-
  586    existence_error(rdf_constraint, Constraint).
  587
  588% Comparison operators
  589rdf_constraint(Term >= Value,
  590               add_value_constraint(Term, >=, Value)).
  591rdf_constraint(Term >  Value,
  592               add_value_constraint(Term, >,  Value)).
  593rdf_constraint(Term == Value,
  594               add_value_constraint(Term, ==,  Value)).
  595rdf_constraint(Term <  Value,
  596               add_value_constraint(Term, <,  Value)).
  597rdf_constraint(Term =< Value,
  598               add_value_constraint(Term, =<, Value)).
  599% String selection
  600rdf_constraint(prefix(Term, Pattern),
  601               add_text_constraint(Term, prefix(PatternA))) :-
  602    atom_string(PatternA, Pattern).
  603rdf_constraint(substring(Term, Pattern),
  604               add_text_constraint(Term, substring(PatternA))) :-
  605    atom_string(PatternA, Pattern).
  606rdf_constraint(word(Term, Pattern),
  607               add_text_constraint(Term, word(PatternA))) :-
  608    atom_string(PatternA, Pattern).
  609rdf_constraint(like(Term, Pattern),
  610               add_text_constraint(Term, like(PatternA))) :-
  611    atom_string(PatternA, Pattern).
  612rdf_constraint(icase(Term, Pattern),
  613               add_text_constraint(Term, icase(PatternA))) :-
  614    atom_string(PatternA, Pattern).
  615% Lang selection
  616rdf_constraint(lang_matches(Term, Pattern),
  617               add_lang_constraint(Term, lang_matches(Pattern))).
  618
  619add_text_constraint(Var, Cond) :-
  620    var(Var),
  621    !,
  622    (   get_attr(Var, rdf11, Cond0)
  623    ->  put_attr(Var, rdf11, [Cond|Cond0])
  624    ;   put_attr(Var, rdf11, [Cond])
  625    ).
  626add_text_constraint(Text^^_Type, Cond) :-
  627    !,
  628    add_text_constraint(Text, Cond).
  629add_text_constraint(Text@_Lang, Cond) :-
  630    !,
  631    add_text_constraint(Text, Cond).
  632add_text_constraint(Var, Cond) :-
  633    eval_condition(Cond, Var).
  634
  635%!  add_lang_constraint(?Term, +Constraint)
  636%
  637%   Add a constraint on the language of a literal
  638
  639add_lang_constraint(Var, Constraint) :-
  640    var(Var),
  641    !,
  642    (   get_attr(Var, rdf11, Cond0)
  643    ->  put_attr(Var, rdf11, [Constraint|Cond0])
  644    ;   put_attr(Var, rdf11, [Constraint])
  645    ).
  646add_lang_constraint(_Text@Lang, Constraint) :-
  647    !,
  648    add_lang_constraint(Lang, Constraint).
  649add_lang_constraint(_Text^^_Type, _Constraint) :-
  650    !,
  651    fail.
  652add_lang_constraint(Term, Constraint) :-
  653    eval_condition(Constraint, Term).
  654
  655%!  add_value_constraint(?Term, +Constraint, +Value)
  656%
  657%   Apply a value constraint to the RDF Term.
  658
  659add_value_constraint(Term, Constraint, ValueIn) :-
  660    constraint_literal_value(ValueIn, Value),
  661    add_value_constraint_cann(Value, Constraint, Term).
  662
  663constraint_literal_value(Value, Value^^_Type) :-
  664    number(Value),
  665    !.
  666constraint_literal_value(Value, Literal) :-
  667    rdf_canonical_literal(Value, Literal).
  668
  669add_value_constraint_cann(RefVal^^Type, Constraint, Term) :-
  670    var(Term), var(Type),
  671    !,
  672    add_text_constraint(Term, value(Constraint, RefVal, Type)).
  673add_value_constraint_cann(RefVal^^Type, Constraint, Val^^Type2) :-
  674    !,
  675    Type = Type2,
  676    add_text_constraint(Val, value(Constraint, RefVal, Type)).
  677add_value_constraint_cann(RefVal@Lang, Constraint, Val@Lang) :-
  678    !,
  679    add_text_constraint(Val, value(Constraint, RefVal, lang(Lang))).
  680add_value_constraint_cann(RefVal^^Type, Constraint, Val) :-
  681    !,
  682    ground(Val),
  683    Val \= _@_,
  684    eval_condition(value(Constraint, RefVal, Type), Val).
  685
  686put_cond(Var, []) :-
  687    !,
  688    del_attr(Var, rdf11).
  689put_cond(Var, List) :-
  690    put_attr(Var, rdf11, List).
  691
  692eval_condition(Cond, Literal) :-
  693    text_condition(Cond),
  694    !,
  695    text_of(Literal, Text),
  696    text_condition(Cond, Text).
  697eval_condition(Cond, Literal) :-
  698    lang_condition(Cond),
  699    !,
  700    lang_of(Literal, Lang),
  701    lang_condition(Cond, Lang).
  702eval_condition(value(Comp, Ref, _Type), Value) :-
  703    (   number(Ref)
  704    ->  number(Value),
  705        compare_numeric(Comp, Ref, Value)
  706    ;   compare_std(Comp, Ref, Value)
  707    ).
  708
  709compare_numeric(<,  Ref, Value) :- Value  < Ref.
  710compare_numeric(=<, Ref, Value) :- Value =< Ref.
  711compare_numeric(==, Ref, Value) :- Value =:= Ref.
  712compare_numeric(>=, Ref, Value) :- Value >= Ref.
  713compare_numeric( >, Ref, Value) :- Value >  Ref.
  714
  715compare_std(<,  Ref, Value) :- Value  @< Ref.
  716compare_std(=<, Ref, Value) :- Value @=< Ref.
  717compare_std(==, Ref, Value) :- Value ==  Ref.
  718compare_std(>=, Ref, Value) :- Value @>= Ref.
  719compare_std( >, Ref, Value) :- Value @>  Ref.
  720
  721text_condition(prefix(_)).
  722text_condition(substring(_)).
  723text_condition(word(_)).
  724text_condition(like(_)).
  725text_condition(icase(_)).
  726
  727text_of(Literal, Text) :-
  728    atomic(Literal),
  729    !,
  730    Text = Literal.
  731text_of(Text@_Lang, Text).
  732text_of(Text^^_Type, Text).
  733
  734text_condition(prefix(Pattern), Text) :-
  735    rdf_match_label(prefix, Pattern, Text).
  736text_condition(substring(Pattern), Text) :-
  737    rdf_match_label(substring, Pattern, Text).
  738text_condition(word(Pattern), Text) :-
  739    rdf_match_label(word, Pattern, Text).
  740text_condition(like(Pattern), Text) :-
  741    rdf_match_label(like, Pattern, Text).
  742text_condition(icase(Pattern), Text) :-
  743    rdf_match_label(icase, Pattern, Text).
  744
  745lang_condition(lang_matches(_)).
  746
  747lang_of(_Text@Lang0, Lang) :-
  748    !,
  749    Lang = Lang0.
  750lang_of(Lang, Lang) :-
  751    atom(Lang).
  752
  753lang_condition(lang_matches(Pattern), Lang) :-
  754    rdf_db:lang_matches(Lang, Pattern).
  755
  756%!  literal_condition(+Object, -Cond) is semidet.
  757%
  758%   True when some of the constraints   on  Object can be translated
  759%   into an equivalent query  of   the  form  literal(Cond, _Value).
  760%   Translated constraints are removed from object.
  761
  762literal_condition(Object, Cond) :-
  763    get_attr(Object, rdf11, Cond0),
  764    best_literal_cond(Cond0, Cond, Rest),
  765    put_cond(Object, Rest).
  766
  767%!  best_literal_cond(+Conditions, -Best, -Rest) is semidet.
  768%
  769%   Extract the constraints that can be translated into the _Search_
  770%   of literal(Search, Value).
  771%
  772%   @tbd    Select the best rather than the first.
  773
  774best_literal_cond(Conditions, Best, Rest) :-
  775    sort(Conditions, Unique),
  776    best_literal_cond2(Unique, Best, Rest).
  777
  778best_literal_cond2(Conds, Best, Rest) :-
  779    select(Cond, Conds, Rest0),
  780    rdf10_cond(Cond, Best, Rest0, Rest),
  781    !.
  782
  783rdf10_cond(value(=<, URef, UType), Cond, Rest0, Rest) :-
  784    (   select(value(>=, LRef, LType), Rest0, Rest)
  785    ->  true
  786    ;   memberchk(value(>, LRef, LType), Rest0)
  787    ->  Rest = Rest0
  788    ),
  789    !,
  790    in_constaint_type(LType, SLType, LRef, LRef0),
  791    in_constaint_type(UType, SUType, URef, URef0),
  792    Cond = between(type(SLType, LRef0), type(SUType, URef0)).
  793rdf10_cond(value(<, URef, UType), Cond, Rest0, Rest) :-
  794    (   select(value(>=, LRef, LType), Rest0, Rest1)
  795    ->  true
  796    ;   memberchk(value(>, LRef, LType), Rest0)
  797    ->  Rest1 = Rest0
  798    ),
  799    !,
  800    Rest = [value(<, URef, UType)|Rest1],
  801    in_constaint_type(LType, SLType, LRef, LRef0),
  802    in_constaint_type(UType, SUType, URef, URef0),
  803    Cond = between(type(SLType, LRef0), type(SUType, URef0)).
  804rdf10_cond(value(Cmp, Ref, Type), Pattern, Rest, Rest) :-
  805    !,
  806    rdf10_compare(Cmp, Ref, Type, Pattern).
  807rdf10_cond(lang_matches(_), _, _, _) :- !, fail.
  808rdf10_cond(Cond, Cond, Rest, Rest).
  809
  810rdf10_compare(Cmp, Ref, Type, Pattern) :-
  811    nonvar(Type), Type = lang(Lang),
  812    !,
  813    atom_string(Ref0, Ref),
  814    rdf10_lang_cond(Cmp, Ref0, Lang, Pattern).
  815rdf10_compare(Cmp, Ref, Type, Pattern) :-
  816    in_constaint_type(Type, SType, Ref, Ref0),
  817    rdf10_type_cond(Cmp, Ref0, SType, Pattern).
  818
  819rdf10_lang_cond( <, Ref, Lang, lt(lang(Lang,Ref))).
  820rdf10_lang_cond(=<, Ref, Lang, le(lang(Lang,Ref))).
  821rdf10_lang_cond(==, Ref, Lang, eq(lang(Lang,Ref))).
  822rdf10_lang_cond(>=, Ref, Lang, ge(lang(Lang,Ref))).
  823rdf10_lang_cond(>,  Ref, Lang, gt(lang(Lang,Ref))).
  824
  825rdf10_type_cond( <, Ref, Type, lt(type(Type,Ref))).
  826rdf10_type_cond(=<, Ref, Type, le(type(Type,Ref))).
  827rdf10_type_cond(==, Ref, Type, eq(type(Type,Ref))).
  828rdf10_type_cond(>=, Ref, Type, ge(type(Type,Ref))).
  829rdf10_type_cond( >, Ref, Type, gt(type(Type,Ref))).
  830
  831
  832%!  in_constaint_type(?Type, -SType, ++Val, -Val0)
  833
  834in_constaint_type(Type, SType, Val, Val0) :-
  835    nonvar(Type), ground(Val),
  836    !,
  837    SType = Type,
  838    in_ground_type(Type, Val, Val0).
  839in_constaint_type(Type, SType, Val, Val0) :-
  840    var(Type), number(Val),
  841    !,
  842    (   integer(Val)
  843    ->  rdf_equal(SType, xsd:integer),
  844        in_ground_type(xsd:integer, Val, Val0)
  845    ;   float(Val)
  846    ->  rdf_equal(SType, xsd:double),
  847        in_ground_type(xsd:double, Val, Val0)
  848    ;   assertion(fail)
  849    ).
  850
  851
  852%!  literal_class(+Term, -Class)
  853%
  854%   Classify Term as literal  and  if   possible  as  lang  or typed
  855%   literal on the basis of the constraints that apply to it.
  856
  857literal_class(Term, Class) :-
  858    get_attr(Term, rdf11, Conds),
  859    select(Cond, Conds, Rest),
  860    lang_condition(Cond),
  861    !,
  862    Term = Text@Lang,
  863    put_attr(Lang, rdf11, [Cond]),
  864    put_cond(Text, Rest),
  865    (   var(Text)
  866    ->  true
  867    ;   atom_string(Text2, Text)
  868    ),
  869    Class = lang(Lang, Text2).
  870
  871%!  attr_unify_hook(+AttributeValue, +Value)
  872
  873attr_unify_hook(Cond, Value) :-
  874    get_attr(Value, rdf11, Cond2),
  875    !,
  876    append(Cond, Cond2, CondJ),
  877    sort(CondJ, Unique),
  878    put_cond(Value, Unique).
  879attr_unify_hook(Cond, Text^^_Type) :-
  880    var(Text),
  881    !,
  882    put_cond(Text, Cond).
  883attr_unify_hook(Cond, Text@Lang) :-
  884    var(Text), var(Lang),
  885    !,
  886    partition(lang_condition, Cond, LangCond, TextCond),
  887    put_cond(Text, TextCond),
  888    put_cond(Lang, LangCond).
  889attr_unify_hook(Cond, Value) :-
  890    sort(Cond, Unique),
  891    propagate_conditions(Unique, Value).
  892
  893propagate_conditions([], _).
  894propagate_conditions([H|T], Val) :-
  895    propagate_condition(H, Val),
  896    propagate_conditions(T, Val).
  897
  898propagate_condition(value(Comp, Ref, Type), Value) :-
  899    !,
  900    (   Value = Plain^^VType
  901    ->  VType = Type
  902    ;   Plain = Value
  903    ),
  904    cond_compare(Comp, Ref, Plain).
  905propagate_condition(lang_matches(Pattern), Value) :-
  906    !,
  907    (   Value = _@Lang
  908    ->  true
  909    ;   Lang = Value
  910    ),
  911    rdf_db:lang_matches(Lang, Pattern).
  912propagate_condition(Cond, Value) :-
  913    Cond =.. [Name|Args],
  914    Constraint =.. [Name,Value|Args],
  915    rdf_constraint(Constraint, Continuation),
  916    call(Continuation).
  917
  918cond_compare(>,  Ref, Value) :- Value @>  Ref.
  919cond_compare(>=, Ref, Value) :- Value @>= Ref.
  920cond_compare(==, Ref, Value) :- Value ==  Ref.
  921cond_compare(=<, Ref, Value) :- Value @=< Ref.
  922cond_compare( <, Ref, Value) :- Value  @< Ref.
  923
  924
  925%!  rdf_default_graph(-Graph) is det.
  926%!  rdf_default_graph(-Old, +New) is det.
  927%
  928%   Query/set the notion of the  default   graph.  The notion of the
  929%   default graph is local to a  thread. Threads created inherit the
  930%   default graph from their creator. See set_prolog_flag/2.
  931
  932:- create_prolog_flag(rdf_default_graph, default,
  933                      [ type(atom),
  934                        keep(true)
  935                      ]).  936
  937rdf_default_graph(Graph) :-
  938    current_prolog_flag(rdf_default_graph, Graph).
  939rdf_default_graph(Old, New) :-
  940    current_prolog_flag(rdf_default_graph, Old),
  941    (   New == Old
  942    ->  true
  943    ;   set_prolog_flag(rdf_default_graph, New)
  944    ).
  945
  946
  947pre_graph(G, _G0) :-
  948    var(G),
  949    !.
  950pre_graph(G, G) :-
  951    atom(G),
  952    !.
  953pre_graph(G, _) :-
  954    type_error(rdf_graph, G).
  955
  956post_graph(G, G0:_) :-
  957    !,
  958    G = G0.
  959post_graph(G, G).
  960
  961
  962%   left for code calling this directly
  963
  964pre_object(Atom, URI) :-
  965    pre_object(Atom, URI, _, _).
  966
  967%!  pre_object(+APIObject, -DBObject, +APISubject, +APIPredicate)
  968
  969pre_object(Atom, URI, _, _) :-
  970    atom(Atom),
  971    \+ boolean(Atom),
  972    !,
  973    URI = Atom.
  974pre_object(Var, Var1, Subj, Pred) :-
  975    var(Var),
  976    !,
  977    (   literal_condition(Var, Cond)
  978    ->  Var1 = literal(Cond, _)
  979    ;   literal_class(Var, Value)
  980    ->  Var1 = literal(Value)
  981    ;   (   Var == Subj
  982        ->  Var1 = Subj
  983        ;   true
  984        ),
  985        (   Var == Pred
  986        ->  Var1 = Pred
  987        ;   true
  988        )
  989    ).
  990pre_object(Val@Lang, Var1, _, _) :-
  991    !,
  992    (   literal_condition(Val, Cond)
  993    ->  Var1 = literal(Cond, lang(Lang, _))
  994    ;   literal_class(Val@Lang, Class)
  995    ->  Var1 = literal(Class)
  996    ;   in_lang_string(Val, Val0),
  997        Var1 = literal(lang(Lang, Val0))
  998    ).
  999pre_object(Val^^Type, Var1, _, _) :-
 1000    !,
 1001    (   literal_condition(Val, Cond)
 1002    ->  Var1 = literal(Cond, type(Type, _))
 1003    ;   in_type(Type, Val, Type0, Val0),
 1004        (   var(Type0), var(Val0)
 1005        ->  Var1 = literal(_)
 1006        ;   Var1 = literal(type(Type0, Val0))
 1007        )
 1008    ).
 1009pre_object(Obj, Val0, _, _) :-
 1010    ground(Obj),
 1011    !,
 1012    pre_ground_object(Obj, Val0).
 1013pre_object(Obj, _, _, _) :-
 1014    type_error(rdf_object, Obj).
 1015
 1016
 1017%!  pre_ground_object(+Object, -RDF) is det.
 1018%
 1019%   Convert between a Prolog value and an RDF value for rdf_assert/3
 1020%   and friends.  Auto-conversion:
 1021%
 1022%     - Integer
 1023%     Converted to Integer^^xsd:integer
 1024%     - Float
 1025%     Converted to Float^^xsd:double
 1026%     - String
 1027%     Converted to String^^xsd:string
 1028%     - true
 1029%     Converted to true^^xsd:boolean
 1030%     - false
 1031%     Converted to false^^xsd:boolean
 1032%     - date(Y,M,D)
 1033%     Converted to date(Y,M,D)^^xsd:date
 1034%     - date_time(Y,M,D,HH,MM,SS)
 1035%     Converted to date_time(Y,M,D,HH,MM,SS)^^xsd:dateTime
 1036%     - date_time(Y,M,D,HH,MM,SS,TZ)
 1037%     Converted to date_time(Y,M,D,HH,MM,SS,TZ)^^xsd:dateTime
 1038%     - month_day(M,D)
 1039%     Converted to month_day(M,D)^^xsd:gMonthDay
 1040%     - year_month(Y,M)
 1041%     Converted to year_month(Y,M)^^xsd:gYearMonth
 1042%     - time(HH,MM,SS)
 1043%     Converted to time(HH,MM,SS)^^xsd:time
 1044%     - Text@Lang
 1045%     Converted to Text@Lang.  Uses canonical (lowercase) lang.
 1046%     Text is converted into an atom.
 1047%     - Value^^Type
 1048%     Typed conversion.  The translation of Value depends on
 1049%     Type:
 1050%       - Numeric types
 1051%       - Boolean
 1052%       - Date types
 1053%     - Atom
 1054%     All atoms except for `true` and `false` are considered
 1055%     URIs.
 1056
 1057:- rdf_meta
 1058    pre_ground_object(+, o). 1059
 1060% Interpret Prolog integer as xsd:integer.
 1061pre_ground_object(Int, Object) :-
 1062    integer(Int),
 1063    !,
 1064    rdf_equal(Object, literal(type(xsd:integer, Atom))),
 1065    atom_number(Atom, Int).
 1066% Interpret Prolog floating-point value as xsd:double.
 1067pre_ground_object(Float, Object) :-
 1068    float(Float),
 1069    !,
 1070    rdf_equal(Object, literal(type(xsd:double, Atom))),
 1071    xsd_number_string(Float, String),
 1072    atom_string(Atom, String).
 1073% Interpret SWI string as xsd:string.
 1074pre_ground_object(String, Object) :-
 1075    string(String),
 1076    !,
 1077    rdf_equal(Object, literal(type(xsd:string, Atom))),
 1078    atom_string(Atom, String).
 1079% Interpret `false' and `true' as the Boolean values.
 1080pre_ground_object(false, literal(type(xsd:boolean, false))) :- !.
 1081pre_ground_object(true, literal(type(xsd:boolean, true))) :- !.
 1082% Interpret date(Y,M,D) as xsd:date,
 1083%           date_time(Y,M,D,HH,MM,SS) as xsd:dateTime,
 1084%           date_time(Y,M,D,HH,MM,SS,TZ) as xsd:dateTime,
 1085%           month_day(M,D) as xsd:gMonthDay,
 1086%           year_month(Y,M) as xsd:gYearMonth, and
 1087%           time(HH,MM,SS) as xsd:time.
 1088pre_ground_object(Term, literal(type(Type, Atom))) :-
 1089    xsd_date_time_term(Term),
 1090    !,
 1091    xsd_time_string(Term, Type, String),
 1092    atom_string(Atom, String).
 1093pre_ground_object(Val@Lang,  literal(lang(Lang0, Val0))) :-
 1094    !,
 1095    downcase_atom(Lang, Lang0),
 1096    in_lang_string(Val, Val0).
 1097pre_ground_object(Val^^Type, literal(type(Type0, Val0))) :-
 1098    !,
 1099    in_type(Type, Val, Type0, Val0).
 1100pre_ground_object(Atom, URI) :-
 1101    atom(Atom),
 1102    !,
 1103    URI = Atom.
 1104pre_ground_object(literal(Lit0), literal(Lit)) :-
 1105    old_literal(Lit0, Lit),
 1106    !.
 1107pre_ground_object(Value, _) :-
 1108    type_error(rdf_object, Value).
 1109
 1110xsd_date_time_term(date(_,_,_)).
 1111xsd_date_time_term(date_time(_,_,_,_,_,_)).
 1112xsd_date_time_term(date_time(_,_,_,_,_,_,_)).
 1113xsd_date_time_term(month_day(_,_)).
 1114xsd_date_time_term(year_month(_,_)).
 1115xsd_date_time_term(time(_,_,_)).
 1116
 1117old_literal(Lit0, Lit) :-
 1118    old_literal(Lit0),
 1119    !,
 1120    Lit = Lit0.
 1121old_literal(Atom, Lit) :-
 1122    atom(Atom),
 1123    rdf_equal(xsd:string, XSDString),
 1124    Lit = type(XSDString, Atom).
 1125
 1126old_literal(type(Type, Value)) :-
 1127    atom(Type), atom(Value).
 1128old_literal(lang(Lang, Value)) :-
 1129    atom(Lang), atom(Value).
 1130
 1131in_lang_string(Val, Val0) :-
 1132    atomic(Val),
 1133    !,
 1134    atom_string(Val0, Val).
 1135in_lang_string(_, _).
 1136
 1137in_type(Type, Val, Type, Val0) :-
 1138    nonvar(Type), ground(Val),
 1139    !,
 1140    in_ground_type(Type, Val, Val0).
 1141in_type(VarType, Val, VarType, Val0) :-
 1142    ground(Val),
 1143    \+ catch(xsd_number_string(_, Val), _, fail),
 1144    !,
 1145    atom_string(Val0, Val).
 1146in_type(_, _, _, _).
 1147
 1148:- rdf_meta
 1149    in_ground_type(r,?,?),
 1150    in_date_component(r, +, +, -). 1151
 1152%!  in_ground_type(+Type, +Input, -Lexical:atom) is det.
 1153%
 1154%   Translate the Prolog date Input according   to Type into its RDF
 1155%   lexical form. The lecical form  is   represented  as an atom. In
 1156%   future versions this is likely to become a string.
 1157
 1158in_ground_type(Type, Input, Lex) :-
 1159    \+ string(Input),
 1160    in_ground_type_hook(Type, Input, Lex),
 1161    !.
 1162in_ground_type(IntType, Val, Val0) :-
 1163    xsd_numerical(IntType, Domain, PrologType),
 1164    !,
 1165    in_number(PrologType, Domain, IntType, Val, Val0).
 1166in_ground_type(xsd:boolean, Val, Val0) :-
 1167    !,
 1168    (   in_boolean(Val, Val0)
 1169    ->  true
 1170    ;   type_error(rdf_boolean, Val)
 1171    ).
 1172in_ground_type(rdf:langString, _Val0, _) :-
 1173    !,
 1174    domain_error(rdf_data_type, rdf:langString).
 1175in_ground_type(DateTimeType, Val, Val0) :-
 1176    xsd_date_time_type(DateTimeType),
 1177    !,
 1178    in_date_time(DateTimeType, Val, Val0).
 1179in_ground_type(rdf:'XMLLiteral', Val, Val0) :-
 1180    !,
 1181    in_xml_literal(xml, Val, Val0).
 1182in_ground_type(rdf:'HTML', Val, Val0) :-
 1183    !,
 1184    in_xml_literal(html, Val, Val0).
 1185in_ground_type(_Unknown, Val, Val0) :-
 1186    atom_string(Val0, Val).
 1187
 1188%!  in_date_time(+Type, +Input, -Lexical) is det.
 1189%
 1190%   Accepts either a term as  accepted   by  xsd_time_string/3  or a
 1191%   valid string for the corresponding XSD type.
 1192
 1193:- rdf_meta
 1194    in_date_time(r,+,-). 1195
 1196in_date_time(Type, Text, Text0) :-
 1197    atom(Text),
 1198    !,
 1199    xsd_time_string(_, Type, Text),
 1200    Text0 = Text.
 1201in_date_time(Type, Text, Text0) :-
 1202    string(Text),
 1203    !,
 1204    xsd_time_string(_, Type, Text),
 1205    atom_string(Text0, Text).
 1206in_date_time(xsd:dateTime, Stamp, Text0) :-
 1207    number(Stamp),
 1208    !,
 1209    format_time(atom(Text0), '%FT%T%:z', Stamp).
 1210in_date_time(Type, Term, Text0) :-
 1211    !,
 1212    xsd_time_string(Term, Type, String),
 1213    atom_string(Text0, String).
 1214
 1215
 1216%!  in_boolean(?NonCanonical, ?Canonical)
 1217%
 1218%   True when Canonical is the canonical boolean for NonCanonical.
 1219
 1220in_boolean(true,    true).
 1221in_boolean(false,   false).
 1222in_boolean("true",  true).
 1223in_boolean("false", false).
 1224in_boolean(1,       true).
 1225in_boolean(0,       false).
 1226
 1227boolean(false).
 1228boolean(true).
 1229
 1230%!  in_number(+PrologType, +Domain, +XSDType, +Value, -Lexical)
 1231%
 1232%   Lexical is the lexical representation for Value.
 1233%
 1234%   @error  type_error(PrologType, Value)
 1235%   @error  domain_error(XSDType, Value)
 1236
 1237in_number(integer, Domain, XSDType, Val, Val0) :-
 1238    integer(Val),
 1239    !,
 1240    check_integer_domain(Domain, XSDType, Val),
 1241    atom_number(Val0, Val).
 1242in_number(integer, Domain, XSDType, Val, Val0) :-
 1243    atomic(Val),
 1244    atom_number(Val, Num),
 1245    integer(Num),
 1246    !,
 1247    check_integer_domain(Domain, XSDType, Num),
 1248    atom_number(Val0, Num).
 1249in_number(double, _Domain, _, Val, Val0) :-
 1250    number(Val),
 1251    !,
 1252    ValF is float(Val),
 1253    xsd_number_string(ValF, ValS),
 1254    atom_string(Val0, ValS).
 1255in_number(double, _Domain, _, Val, Val0) :-
 1256    atomic(Val),
 1257    xsd_number_string(Num, Val),
 1258    ValF is float(Num),
 1259    !,
 1260    xsd_number_string(ValF, ValS),
 1261    atom_string(Val0, ValS).
 1262in_number(PrologType, _, _, Val, _) :-
 1263    type_error(PrologType, Val).
 1264
 1265check_integer_domain(PLType, _, Val) :-
 1266    is_of_type(PLType, Val),
 1267    !.
 1268check_integer_domain(_, XSDType, Val) :-
 1269    domain_error(XSDType, Val).
 1270
 1271error:has_type(nonpos, T):-
 1272    integer(T),
 1273    T =< 0.
 1274
 1275%check_integer_domain(between(Low, High), XSDType, Val) :-
 1276%       (   between(Low, High, Val)
 1277%       ->  true
 1278%       ;   domain_error(XSDType, Val)
 1279%       ).
 1280%check_integer_domain(integer, _, _).
 1281
 1282%!  xsd_numerical(?URI, ?TypeCheck, ?PrologType)
 1283
 1284:- rdf_meta
 1285    xsd_numerical(r, ?, ?). 1286
 1287xsd_numerical(xsd:byte,               between(-128,127),               integer).
 1288xsd_numerical(xsd:double,             float,                           double).
 1289xsd_numerical(xsd:decimal,            float,                           double).
 1290xsd_numerical(xsd:float,              float,                           double).
 1291xsd_numerical(xsd:int,                between(-2147483648,2147483647), integer).
 1292xsd_numerical(xsd:integer,            integer,                         integer).
 1293xsd_numerical(xsd:long,               between(-9223372036854775808,
 1294                                               9223372036854775807),   integer).
 1295xsd_numerical(xsd:negativeInteger,    negative_integer,                integer).
 1296xsd_numerical(xsd:nonNegativeInteger, nonneg,                          integer).
 1297xsd_numerical(xsd:nonPositiveInteger, nonpos,                          integer).
 1298xsd_numerical(xsd:positiveInteger,    positive_integer,                integer).
 1299xsd_numerical(xsd:short,              between(-32768,32767),           integer).
 1300xsd_numerical(xsd:unsignedByte,       between(0,255),                  integer).
 1301xsd_numerical(xsd:unsignedInt,        between(0,4294967295),           integer).
 1302xsd_numerical(xsd:unsignedLong,       between(0,18446744073709551615), integer).
 1303xsd_numerical(xsd:unsignedShort,      between(0,65535),                integer).
 1304
 1305%!  xsd_date_time_type(?URI)
 1306%
 1307%   True when URI is an XSD date or time type.
 1308
 1309:- rdf_meta
 1310    xsd_date_time_type(r). 1311
 1312xsd_date_time_type(xsd:date).
 1313xsd_date_time_type(xsd:dateTime).
 1314xsd_date_time_type(xsd:gDay).
 1315xsd_date_time_type(xsd:gMonth).
 1316xsd_date_time_type(xsd:gMonthDay).
 1317xsd_date_time_type(xsd:gYear).
 1318xsd_date_time_type(xsd:gYearMonth).
 1319xsd_date_time_type(xsd:time).
 1320
 1321
 1322%!  in_xml_literal(+Type, +Val, -Val0) is det.
 1323%
 1324%   Translate an XMLLiteral or HTML literal to its canonical textual
 1325%   representation. Input is either text or a Prolog XML DOM.
 1326%
 1327%   @tbd    Deal with partial content?
 1328
 1329in_xml_literal(Type, Val, Val0) :-
 1330    xml_is_dom(Val),
 1331    !,
 1332    write_xml_literal(Type, Val, Val0).
 1333in_xml_literal(xml, Val, Val0) :-
 1334    parse_partial_xml(load_xml, Val, DOM),
 1335    write_xml_literal(xml, DOM, Val0).
 1336in_xml_literal(html, Val, Val0) :-
 1337    parse_partial_xml(load_html, Val, DOM),
 1338    write_xml_literal(html, DOM, Val0).
 1339
 1340parse_partial_xml(Parser, Val, DOM) :-
 1341    setup_call_cleanup(
 1342        new_memory_file(MF),
 1343        (   setup_call_cleanup(
 1344                open_memory_file(MF, write, Out),
 1345                format(Out, "<xml>~w</xml>", [Val]),
 1346                close(Out)),
 1347            setup_call_cleanup(
 1348                open_memory_file(MF, read, In),
 1349                call(Parser, stream(In), [element(xml, _, DOM)], []),
 1350                close(In))
 1351        ),
 1352        free_memory_file(MF)).
 1353
 1354
 1355write_xml_literal(xml, DOM, Text) :-
 1356    with_output_to(atom(Text),
 1357                   xml_write_canonical(current_output, DOM, [])).
 1358write_xml_literal(html, DOM, Text) :-
 1359    with_output_to(atom(Text),
 1360                   html_write(current_output, DOM,
 1361                              [ header(false),
 1362                                layout(false)
 1363                              ])).
 1364
 1365%!  rdf_canonical_literal(++In, -Literal) is det.
 1366%
 1367%   Transform  a  relaxed  literal  specification   as  allowed  for
 1368%   rdf_assert/3 into its canonical form. The following Prolog terms
 1369%   are translated:
 1370%
 1371%   | **Prolog Term**               | **Datatype IRI** |
 1372%   |:------------------------------|:-----------------|
 1373%   | float                         | xsd:double       |
 1374%   | integer                       | xsd:integer      |
 1375%   | string                        | xsd:string       |
 1376%   | `true` or `false`             | xsd:boolean      |
 1377%   | date(Y,M,D)                   | xsd:date         |
 1378%   | date_time(Y,M,D,HH,MM,SS)     | xsd:dateTime     |
 1379%   | date_time(Y,M,D,HH,MM,SS,TZ)  | xsd:dateTime     |
 1380%   | month_day(M,D)                | xsd:gMonthDay    |
 1381%   | year_month(Y,M)               | xsd:gYearMonth   |
 1382%   | time(HH,MM,SS)                | xsd:time         |
 1383%
 1384%   For example:
 1385%
 1386%     ```
 1387%     ?- rdf_canonical_literal(42, X).
 1388%     X = 42^^'http://www.w3.org/2001/XMLSchema#integer'.
 1389%     ```
 1390
 1391rdf_canonical_literal(In, Literal) :-
 1392    ground(In),
 1393    !,
 1394    pre_ground_object(In, DBTerm),
 1395    post_object(Literal, DBTerm).
 1396rdf_canonical_literal(In, _) :-
 1397    must_be(ground, In).
 1398
 1399%!  rdf_lexical_form(++Literal, -Lexical:compound) is det.
 1400%
 1401%   True when Lexical is the lexical   form for the literal Literal.
 1402%   Lexical is of one of the forms below. The ntriples serialization
 1403%   is obtained by transforming String into a proper ntriples string
 1404%   using double quotes and escaping where   needed and turning Type
 1405%   into a proper IRI reference.
 1406%
 1407%     - String^^Type
 1408%     - String@Lang
 1409
 1410%       For example,
 1411%
 1412%       ==
 1413%       ?- rdf_lexical_form(2.3^^xsd:double, L).
 1414%       L = "2.3E0"^^'http://www.w3.org/2001/XMLSchema#double'.
 1415%       ==
 1416
 1417rdf_lexical_form(Literal, Lexical) :-
 1418    pre_ground_object(Literal, literal(Lit0)),
 1419    !,
 1420    text_of0(Lit0, Lexical).
 1421rdf_lexical_form(Literal, _) :-
 1422    type_error(rdf_literal, Literal).
 1423
 1424text_of0(type(TypeA, LexicalA), LexicalS^^TypeA) :-
 1425    atom_string(LexicalA, LexicalS).
 1426text_of0(lang(LangA, LexicalA), LexicalS@LangA) :-
 1427    atom_string(LexicalA, LexicalS).
 1428
 1429
 1430                 /*******************************
 1431                 *       POST PROCESSING        *
 1432                 *******************************/
 1433
 1434:- rdf_meta
 1435    post_object(o,o),
 1436    out_type(r,-,+). 1437
 1438post_object(Val, _) :-
 1439    ground(Val),
 1440    !.                 % already specified and matched
 1441post_object(URI, URI0) :-
 1442    atom(URI0),
 1443    !,
 1444    URI = URI0.
 1445post_object(Val@Lang, literal(lang(Lang, Val0))) :-
 1446    nonvar(Lang),          % lang(Lang,Text) returns var(Lang) if no lang
 1447    !,
 1448    atom_string(Val0, Val).
 1449post_object(Val^^Type, literal(type(Type, Val0))) :-
 1450    !,
 1451    out_type(Type, Val, Val0).
 1452post_object(Val^^xsd:string, literal(Plain)) :-
 1453    !,
 1454    atomic(Plain),
 1455    atom_string(Plain, Val).
 1456post_object(Val@Lang, literal(_, lang(Lang, Val0))) :-
 1457    nonvar(Lang),
 1458    !,
 1459    atom_string(Val0, Val).
 1460post_object(Val^^Type, literal(_, type(Type, Val0))) :-
 1461    !,
 1462    out_type(Type, Val, Val0).
 1463post_object(Val^^xsd:string, literal(_, Plain)) :-
 1464    atomic(Plain),
 1465    atom_string(Plain, Val).
 1466
 1467out_type(xsd:string, Val, Val0) :-     % catches unbound type too
 1468    !,
 1469    atom_string(Val0, Val).
 1470out_type(Type, Val, Val0) :-
 1471    out_type_hook(Type, Val, Val0),
 1472    !.
 1473out_type(IntType, Val, Val0) :-
 1474    xsd_numerical(IntType, _Domain, _BasicType),
 1475    !,
 1476    xsd_number_string(Val, Val0).
 1477out_type(DateTimeType, Val, Val0) :-
 1478    xsd_date_time_type(DateTimeType),
 1479    !,
 1480    out_date_time(DateTimeType, Val, Val0).
 1481out_type(xsd:boolean, Val, Val0) :-
 1482    !,
 1483    Val = Val0.
 1484out_type(rdf:'XMLLiteral', XML, DOM) :-
 1485    xml_is_dom(DOM),
 1486    !,
 1487    with_output_to(string(XML),
 1488                   xml_write(DOM, [header(false)])).
 1489out_type(_Unknown, Val, Val0) :-
 1490    atom_string(Val0, Val).
 1491
 1492
 1493%!  out_date_time(+DateTimeType, -Val, +Val0) is det.
 1494%
 1495%   Translate an XSD lexical form for   a date/time related datatype
 1496%   into the cannical form as defined by xsd_time_string/3.
 1497
 1498out_date_time(Type, Prolog, Lexical) :-
 1499    catch(xsd_time_string(Prolog, Type, Lexical),
 1500          error(_,_),
 1501          invalid_lexical_form_hook(Type, Lexical, Prolog)).
 1502
 1503
 1504%!  invalid_lexical_form_hook(+Type, +Lexical, -Prolog)
 1505%
 1506%   This hook is called if translation of the lexical form to the Prolog
 1507%   representation fails due to a syntax  error.   By  default it is not
 1508%   defined, causing such invalid triples to be silently ignored.
 1509
 1510
 1511                 /*******************************
 1512                 *          ENUMERATION         *
 1513                 *******************************/
 1514
 1515%!  rdf_term(?Term) is nondet.
 1516%
 1517%   True if Term appears in the RDF database. Term is either an IRI,
 1518%   literal or blank node and may  appear   in  any  position of any
 1519%   triple. If Term is ground,  it   is  pre-processed as the object
 1520%   argument of rdf_assert/3 and the predicate is _semidet_.
 1521
 1522rdf_term(N) :-
 1523    ground(N),
 1524    !,
 1525    pre_object(N, N0, _, _),
 1526    visible_term(N0).
 1527rdf_term(N) :-
 1528    gen_term(N).
 1529
 1530gen_term(N) :-
 1531    resource(N),
 1532    visible_term(N).
 1533gen_term(O) :-                          % performs double conversion!
 1534    rdf_literal(O),
 1535    (rdf(_,_,O) -> true).
 1536
 1537%!  rdf_literal(?Term) is nondet.
 1538%
 1539%   True if Term is a  known  literal.   If  Term  is  ground, it is
 1540%   pre-processed as the object  argument   of  rdf_assert/3 and the
 1541%   predicate is _semidet_.
 1542
 1543rdf_literal(Term) :-
 1544    ground(Term),
 1545    !,
 1546    pre_ground_object(Term, Object),
 1547    (rdf_db:rdf(_,_,Object)->true).
 1548rdf_literal(Term) :-
 1549    pre_object(Term,literal(Lit0), _, _),
 1550    rdf_db:rdf_current_literal(Lit0),
 1551    (rdf_db:rdf(_,_,literal(Lit0))->true),
 1552    post_object(Term, literal(Lit0)).
 1553
 1554%!  rdf_bnode(?BNode) is nondet.
 1555%
 1556%   True if BNode is a currently known  blank node. The predicate is
 1557%   _semidet_ if BNode is ground.
 1558
 1559rdf_bnode(BNode) :-
 1560    atom(BNode),
 1561    !,
 1562    current_bnode(BNode).
 1563rdf_bnode(BNode) :-
 1564    rdf_db:rdf_resource(BNode),
 1565    current_bnode(BNode).
 1566
 1567current_bnode(BNode) :-
 1568    rdf_is_bnode(BNode),
 1569    visible_node(BNode).            % Assumes BNodes cannot be predicates
 1570
 1571%!  rdf_iri(?IRI) is nondet.
 1572%
 1573%   True if IRI is a current IRI.  The predicate is _semidet_ if IRI
 1574%   is ground.
 1575
 1576rdf_iri(IRI) :-
 1577    atom(IRI),
 1578    !,
 1579    \+ rdf_is_bnode(IRI),
 1580    visible_term(IRI).
 1581rdf_iri(IRI) :-
 1582    resource(IRI),
 1583    \+ rdf_is_bnode(IRI),
 1584    visible_term(IRI).
 1585
 1586%!  rdf_name(?Name) is nondet.
 1587%
 1588%   True if Name is a  current  IRI   or  literal.  The predicate is
 1589%   _semidet_ if Name is ground.
 1590
 1591rdf_name(Name) :-
 1592    atom(Name), \+ boolean(Name),
 1593    !,
 1594    \+ rdf_is_bnode(Name),
 1595    visible_term(Name).
 1596rdf_name(Name) :-
 1597    ground(Name),
 1598    !,
 1599    pre_ground_object(Name, Name0),
 1600    (rdf_db:rdf(_,_,Name0)->true).
 1601rdf_name(Name) :-
 1602    rdf_iri(Name).
 1603rdf_name(Name) :-
 1604    rdf_literal(Name).
 1605
 1606%!  rdf_subject(?S) is nondet.
 1607%
 1608%   True when S is a currently known   _subject_, i.e. it appears in
 1609%   the subject position of some visible   triple.  The predicate is
 1610%   _semidet_ if S is ground.
 1611
 1612
 1613%!  rdf_predicate(?P) is nondet.
 1614%
 1615%   True when P is a currently known   predicate, i.e. it appears in
 1616%   the predicate position of some visible  triple. The predicate is
 1617%   _semidet_ if P is ground.
 1618
 1619rdf_predicate(P) :-
 1620    atom(P),
 1621    !,
 1622    (rdf(_,P,_) -> true).
 1623rdf_predicate(P) :-
 1624    rdf_db:rdf_current_predicate(P),
 1625    (rdf(_,P,_) -> true).
 1626
 1627%!  rdf_object(?O) is nondet.
 1628%
 1629%   True when O is a currently known  object, i.e. it appears in the
 1630%   object position of some visible triple. If Term is ground, it is
 1631%   pre-processed as the object  argument   of  rdf_assert/3 and the
 1632%   predicate is _semidet_.
 1633
 1634rdf_object(O) :-
 1635    ground(O),
 1636    !,
 1637    (   atom(O), \+ boolean(O)
 1638    ->  (rdf_db:rdf(_,_,O) -> true)
 1639    ;   rdf_literal(O)
 1640    ).
 1641rdf_object(O) :-
 1642    rdf_db:rdf_resource(O),
 1643    (rdf_db:rdf(_,_,O) -> true).
 1644rdf_object(O) :-
 1645    rdf_literal(O).
 1646
 1647%!  rdf_node(?T) is nondet.
 1648%
 1649%   True when T appears in the subject or object position of a known
 1650%   triple, i.e., is a node in the RDF graph.
 1651
 1652rdf_node(N) :-
 1653    var(N),
 1654    !,
 1655    gen_node(N).
 1656rdf_node(N) :-
 1657    pre_ground_object(N, N0),
 1658    visible_node(N0).
 1659
 1660gen_node(N) :-
 1661    rdf_db:rdf_resource(N),
 1662    visible_node(N).
 1663gen_node(O) :-                          % performs double conversion!
 1664    rdf_literal(O),
 1665    (rdf(_,_,O) -> true).
 1666
 1667%!  resource(?R)
 1668%
 1669%   True if R is a node that is not a literal. Note that RDF-DB does
 1670%   not necessarily include predicates in the set of resources. Also
 1671%   note that the resource may not really exist or be visible.
 1672
 1673resource(R) :-
 1674    var(R),
 1675    !,
 1676    gen_resource(R).
 1677resource(R) :-
 1678    rdf_db:rdf_resource(R),
 1679    !.
 1680resource(R) :-
 1681    rdf_db:rdf_current_predicate(R),
 1682    !.
 1683
 1684gen_resource(R) :-
 1685    rdf_db:rdf_resource(R).
 1686gen_resource(R) :-
 1687    rdf_db:rdf_current_predicate(R),
 1688    \+ rdf_db:rdf_resource(R).
 1689
 1690visible_node(Term) :-
 1691    atom(Term),
 1692    !,
 1693    (   rdf_db:rdf(Term,_,_)
 1694    ;   rdf_db:rdf(_,_,Term)
 1695    ),
 1696    !.
 1697visible_node(Term) :-
 1698    rdf_db:rdf(_,_,Term).
 1699
 1700visible_term(Term) :-
 1701    atom(Term),
 1702    !,
 1703    (   rdf_db:rdf(Term,_,_)
 1704    ;   rdf_db:rdf(_,Term,_)
 1705    ;   rdf_db:rdf(_,_,Term)
 1706    ),
 1707    !.
 1708visible_term(Term) :-
 1709    rdf_db:rdf(_,_,Term).
 1710
 1711%!  rdf_create_bnode(--BNode)
 1712%
 1713%   Create a new BNode. A  blank  node   is  an  atom  starting with
 1714%   =|_:|=. Blank nodes generated by this  predicate are of the form
 1715%   =|_:genid|= followed by a unique integer.
 1716
 1717rdf_create_bnode(BNode) :-
 1718    var(BNode),
 1719    !,
 1720    rdf_db:rdf_bnode(BNode).
 1721rdf_create_bnode(BNode) :-
 1722    uninstantiation_error(BNode).
 1723
 1724
 1725                 /*******************************
 1726                 *         TYPE CHECKING        *
 1727                 *******************************/
 1728
 1729%!  rdf_is_iri(@IRI) is semidet.
 1730%
 1731%   True if IRI is an RDF IRI term.
 1732%
 1733%   For performance reasons, this does not check for compliance to
 1734%   the syntax defined in [[RFC
 1735%   3987][http://www.ietf.org/rfc/rfc3987.txt]].  This checks
 1736%   whether the term is (1) an atom and (2) not a blank node
 1737%   identifier.
 1738%
 1739%   Success of this goal does not imply that the IRI is present in
 1740%   the database (see rdf_iri/1 for that).
 1741
 1742rdf_is_iri(IRI) :-
 1743    atom(IRI),
 1744    \+ rdf_is_bnode(IRI).
 1745
 1746%!  rdf_is_bnode(@Term) is semidet.
 1747%
 1748%   True if Term is an RDF blank node identifier.
 1749%
 1750%   A blank node is represented by an atom that starts with
 1751%   =|_:|=.
 1752%
 1753%   Success of this goal does not imply that the blank node is
 1754%   present in the database (see rdf_bnode/1 for that).
 1755%
 1756%   For backwards compatibility, atoms that are represented with
 1757%   an atom that starts with =|__|= are also considered to be a
 1758%   blank node.
 1759
 1760
 1761%!  rdf_is_literal(@Term) is semidet.
 1762%
 1763%   True if Term is an RDF literal term.
 1764%
 1765%   An RDF literal term is of the form `String@LanguageTag` or
 1766%   `Value^^Datatype`.
 1767%
 1768%   Success of this goal does not imply that the literal is
 1769%   well-formed or that it is present in the database (see
 1770%   rdf_literal/1 for that).
 1771
 1772rdf_is_literal(Literal) :-
 1773    literal_form(Literal),
 1774    !,
 1775    ground(Literal).
 1776
 1777literal_form(_@_).
 1778literal_form(_^^_).
 1779
 1780
 1781%!  rdf_is_name(@Term) is semidet.
 1782%
 1783%   True if Term is an RDF Name, i.e., an IRI or literal.
 1784%
 1785%   Success of this goal does not imply that the name is
 1786%   well-formed or that it is present in the database (see
 1787%   rdf_name/1 for that).
 1788
 1789rdf_is_name(T) :- rdf_is_iri(T), !.
 1790rdf_is_name(T) :- rdf_is_literal(T).
 1791
 1792
 1793%!  rdf_is_object(@Term) is semidet.
 1794%
 1795%   True if Term can appear in the object position of a triple.
 1796%
 1797%   Success of this goal does not imply that the object term in
 1798%   well-formed or that it is present in the database (see
 1799%   rdf_object/1 for that).
 1800%
 1801%   Since any RDF term can appear in the object position, this is
 1802%   equaivalent to rdf_is_term/1.
 1803
 1804rdf_is_object(T) :- rdf_is_subject(T), !.
 1805rdf_is_object(T) :- rdf_is_literal(T).
 1806
 1807
 1808%!  rdf_is_predicate(@Term) is semidet.
 1809%
 1810%   True if Term can appear in the   predicate position of a triple.
 1811%
 1812%   Success of this goal does not imply that the predicate term is
 1813%   present in the database (see rdf_predicate/1 for that).
 1814%
 1815%   Since only IRIs can appear in the predicate position, this is
 1816%   equivalent to rdf_is_iri/1.
 1817
 1818rdf_is_predicate(T) :- rdf_is_iri(T).
 1819
 1820
 1821%!  rdf_is_subject(@Term) is semidet.
 1822%
 1823%   True if Term can appear in  the   subject  position of a triple.
 1824%
 1825%   Only blank nodes and IRIs can appear in the subject position.
 1826%
 1827%   Success of this goal does not imply that the subject term is
 1828%   present in the database (see rdf_subject/1 for that).
 1829%
 1830%   Since blank nodes are represented by atoms that start with
 1831%   `_:` and an IRIs are atoms as well, this is equivalent to
 1832%   atom(Term).
 1833
 1834rdf_is_subject(T) :- atom(T).
 1835
 1836%!  rdf_is_term(@Term) is semidet.
 1837%
 1838%   True if Term can be used as an RDF term, i.e., if Term is
 1839%   either an IRI, a blank node or an RDF literal.
 1840%
 1841%   Success of this goal does not imply that the RDF term is
 1842%   present in the database (see rdf_term/1 for that).
 1843
 1844rdf_is_term(N) :- rdf_is_subject(N), !.
 1845rdf_is_term(N) :- rdf_is_literal(N).
 1846
 1847
 1848                 /*******************************
 1849                 *          COLLECTIONS         *
 1850                 *******************************/
 1851
 1852%!  rdf_list(?RDFTerm) is semidet.
 1853%
 1854%   True if RDFTerm is a proper RDF   list.  This implies that every
 1855%   node in the list has an  `rdf:first` and `rdf:rest` property and
 1856%   the list ends in `rdf:nil`.
 1857%
 1858%   If RDFTerm is unbound, RDFTerm is   bound  to each _maximal_ RDF
 1859%   list. An RDF list is _maximal_  if   there  is  no triple rdf(_,
 1860%   rdf:rest, RDFList).
 1861
 1862rdf_list(L) :-
 1863    var(L),
 1864    !,
 1865    rdf_has(L, rdf:first, _),
 1866    \+ rdf_has(_, rdf:rest, L),
 1867    rdf_list_g(L).
 1868rdf_list(L) :-
 1869    rdf_list_g(L),
 1870    !.
 1871
 1872:- rdf_meta
 1873    rdf_list_g(r). 1874
 1875rdf_list_g(rdf:nil) :- !.
 1876rdf_list_g(L) :-
 1877    once(rdf_has(L, rdf:first, _)),
 1878    rdf_has(L, rdf:rest, Rest),
 1879    (   rdf_equal(rdf:nil, Rest)
 1880    ->  true
 1881    ;   rdf_list_g(Rest)
 1882    ).
 1883
 1884
 1885%!  rdf_list(+RDFList, -PrologList) is det.
 1886%
 1887%   True when PrologList represents the   rdf:first  objects for all
 1888%   cells in RDFList. Note that  this   can  be non-deterministic if
 1889%   cells have multiple rdf:first or rdf:rest triples.
 1890
 1891rdf_list(RDFList, Prolog) :-
 1892    rdf_is_subject(RDFList),
 1893    !,
 1894    rdf_list_to_prolog(RDFList, Prolog).
 1895rdf_list(RDFList, _Prolog) :-
 1896    type_error(rdf_subject, RDFList).
 1897
 1898:- rdf_meta
 1899    rdf_list_to_prolog(r,-). 1900
 1901rdf_list_to_prolog(rdf:nil, Prolog) :-
 1902    !,
 1903    Prolog = [].
 1904rdf_list_to_prolog(RDF, [H|T2]) :-
 1905    (   rdf_has(RDF, rdf:first, H0),
 1906        rdf_has(RDF, rdf:rest, T1)
 1907    *-> H = H0,
 1908        rdf_list_to_prolog(T1, T2)
 1909    ;   type_error(rdf_list, RDF)
 1910    ).
 1911
 1912
 1913%!  rdf_length(+RDFList, -Length:nonneg) is nondet.
 1914%
 1915%   True when Length is the number of  cells in RDFList. Note that a
 1916%   list cell may have multiple rdf:rest   triples, which makes this
 1917%   predicate  non-deterministic.  This  predicate  does  not  check
 1918%   whether the list cells have   associated values (rdf:first). The
 1919%   list must end in rdf:nil.
 1920
 1921rdf_length(RDFList, Len) :-
 1922    rdf_is_subject(RDFList),
 1923    !,
 1924    rdf_length(RDFList, 0, Len).
 1925
 1926:- rdf_meta
 1927    rdf_length(r,+,-). 1928
 1929rdf_length(rdf:nil, Len, Len) :- !.
 1930rdf_length(RDF, Len0, Len) :-
 1931    (   rdf_has(RDF, rdf:rest, T)
 1932    *-> Len1 is Len0+1,
 1933        rdf_length(T, Len1, Len)
 1934    ;   type_error(rdf_list, RDF)
 1935    ).
 1936
 1937
 1938%!  rdf_member(?Member, +RDFList) is nondet.
 1939%
 1940%   True when Member is a member of RDFList
 1941
 1942rdf_member(M, L) :-
 1943    ground(M),
 1944    !,
 1945    (   rdf_member2(M, L)
 1946    ->  true
 1947    ).
 1948rdf_member(M, L) :-
 1949    rdf_member2(M, L).
 1950
 1951rdf_member2(M, L) :-
 1952    rdf_has(L, rdf:first, M).
 1953rdf_member2(M, L) :-
 1954    rdf_has(L, rdf:rest, L1),
 1955    rdf_member2(M, L1).
 1956
 1957
 1958%! rdf_nextto(?X, ?Y) is nondet.
 1959%! rdf_nextto(?X, ?Y, ?RdfList) is nondet.
 1960%
 1961%       True if Y directly follows X in RdfList.
 1962
 1963rdf_nextto(X, Y) :-
 1964    distinct(X-Y, rdf_nextto(X, Y, _)).
 1965
 1966
 1967rdf_nextto(X, Y, L) :-
 1968    var(X), ground(Y),
 1969    !,
 1970    rdf_nextto(Y, X, L).
 1971rdf_nextto(X, Y, L) :-
 1972    rdf_has(L, rdf:first, X),
 1973    rdf_has(L, rdf:rest, T),
 1974    rdf_has(T, rdf:first, Y).
 1975
 1976
 1977%!  rdf_nth0(?Index, +RDFList, ?X) is nondet.
 1978%!  rdf_nth1(?Index, +RDFList, ?X) is nondet.
 1979%
 1980%   True when X is the Index-th element (0-based or 1-based) of
 1981%   RDFList.  This predicate is deterministic if Index is given and
 1982%   the list has no multiple rdf:first or rdf:rest values.
 1983
 1984rdf_nth0(I, L, X) :-
 1985    rdf_nth(0, I, L, X).
 1986
 1987rdf_nth1(I, L, X) :-
 1988    rdf_nth(1, I, L, X).
 1989
 1990rdf_nth(Offset, I, L, X) :-
 1991    rdf_is_subject(L),
 1992    !,
 1993    (   var(I)
 1994    ->  true
 1995    ;   must_be(nonneg, I)
 1996    ),
 1997    rdf_nth_(I, Offset, L, X).
 1998rdf_nth(_, _, L, _) :-
 1999    type_error(rdf_subject, L).
 2000
 2001rdf_nth_(I, I0, L, X) :-
 2002    (   I0 == I
 2003    ->  !
 2004    ;   I0 = I
 2005    ),
 2006    rdf_has(L, rdf:first, X).
 2007rdf_nth_(I, I0, L, X) :-
 2008    rdf_has(L, rdf:rest, T),
 2009    I1 is I0+1,
 2010rdf_nth_(I, I1, T, X).
 2011
 2012
 2013%!  rdf_last(+RDFList, -Last) is det.
 2014%
 2015%   True when Last is the last element  of RDFList. Note that if the
 2016%   last cell has multiple rdf:first triples, this predicate becomes
 2017%   nondet.
 2018
 2019rdf_last(L, Last) :-
 2020    rdf_is_subject(L),
 2021    !,
 2022    rdf_has(L, rdf:rest, T),
 2023    (   rdf_equal(T, rdf:nil)
 2024    ->  rdf_has(L, rdf:first, Last)
 2025    ;   rdf_last(T, Last)
 2026    ).
 2027rdf_last(L, _) :-
 2028    type_error(rdf_subject, L).
 2029
 2030
 2031%!  rdf_estimate_complexity(?S, ?P, ?O, -Estimate) is det.
 2032
 2033rdf_estimate_complexity(S, P, O, Estimate) :-
 2034    pre_object(O,O0,S,P),
 2035    rdf_db:rdf_estimate_complexity(S,P,O0,Estimate).
 2036
 2037
 2038%!  rdf_assert_list(+PrologList, ?RDFList) is det.
 2039%!  rdf_assert_list(+PrologList, ?RDFList, +Graph) is det.
 2040%
 2041%   Create an RDF list from the   given Prolog List. PrologList must
 2042%   be a proper Prolog list and  all   members  of  the list must be
 2043%   acceptable as object for rdf_assert/3. If RDFList is unbound and
 2044%   PrologList is not empty, rdf_create_bnode/1   is  used to create
 2045%   RDFList.
 2046
 2047rdf_assert_list(Prolog, RDF) :-
 2048    rdf_default_graph(G),
 2049    rdf_assert_list(Prolog, RDF, G).
 2050
 2051rdf_assert_list(Prolog, RDF, G) :-
 2052    must_be(list, Prolog),
 2053    rdf_transaction(rdf_assert_list_(Prolog, RDF, G)).
 2054
 2055rdf_assert_list_([], Nil, _) :-
 2056    rdf_equal(rdf:nil, Nil).
 2057rdf_assert_list_([H|T], L2, G) :-
 2058    (var(L2) -> rdf_create_bnode(L2) ; true),
 2059    rdf_assert(L2, rdf:type, rdf:'List', G),
 2060    rdf_assert(L2, rdf:first, H, G),
 2061    (   T == []
 2062    ->  rdf_assert(L2, rdf:rest, rdf:nil, G)
 2063    ;   rdf_create_bnode(T2),
 2064        rdf_assert(L2, rdf:rest, T2, G),
 2065        rdf_assert_list_(T, T2, G)
 2066    ).
 2067
 2068
 2069%!  rdf_retract_list(+RDFList) is det.
 2070%
 2071%   Retract the rdf:first, rdf:rest  and rdf:type=rdf:'List' triples
 2072%   from all nodes  reachable  through   rdf:rest.  Note  that other
 2073%   triples that exist on the nodes are left untouched.
 2074
 2075rdf_retract_list(L) :-
 2076    rdf_is_subject(L),
 2077    !,
 2078    rdf_transaction(rdf_retract_list_(L)).
 2079rdf_retract_list(L) :-
 2080    type_error(rdf_subject, L).
 2081
 2082:- rdf_meta
 2083    rdf_retract_list_(r). 2084
 2085rdf_retract_list_(rdf:nil) :- !.
 2086rdf_retract_list_(L) :-
 2087    rdf_retractall(L, rdf:first, _),
 2088    forall(rdf_has(L, rdf:rest, L1),
 2089           rdf_retract_list_(L1)),
 2090    rdf_retractall(L, rdf:rest, _),
 2091    rdf_retractall(L, rdf:type, rdf:'List')