View source with raw 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)  2013-2015, University of Amsterdam
    7                              VU University 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(turtle,
   37          [ rdf_load_turtle/3,                  % +Input, -Triples, +Options
   38            rdf_read_turtle/3,                  % +Input, -Triples, +Options
   39            rdf_process_turtle/3,               % +Input, :OnObject, +Options
   40                                                % re-exports
   41            rdf_save_turtle/2,                  % +File, +Options
   42            rdf_save_canonical_turtle/2,        % +File, +Options
   43            rdf_save_trig/2,                    % +File, +Options
   44            rdf_save_canonical_trig/2,          % +File, +Options
   45            rdf_save_ntriples/2                 % +File, +Options
   46          ]).   47:- use_module(library(option)).   48:- use_module(library(semweb/rdf_db)).   49:- use_module(library(semweb/rdf_turtle_write)). % re-exports
   50:- use_module(library(uri)).   51:- use_module(library(http/http_open)).   52
   53:- meta_predicate
   54    rdf_process_turtle(+,2,+).   55
   56:- predicate_options(rdf_load_turtle/3, 3,
   57                     [pass_to(rdf_read_turtle/3, 3)]).   58:- predicate_options(rdf_process_turtle/3, 3,
   59                     [ anon_prefix(atom),
   60                       base_uri(atom),
   61                       base_used(-atom),
   62                       db(atom),
   63                       error_count(-integer),
   64                       namespaces(-list),
   65                       on_error(oneof([warning,error])),
   66                       prefixes(-list),
   67                       resources(oneof([uri,iri]))
   68                     ]).   69:- predicate_options(rdf_read_turtle/3, 3,
   70                     [ anon_prefix(atom),
   71                       base_uri(atom),
   72                       base_used(-atom),
   73                       db(atom),
   74                       error_count(-integer),
   75                       namespaces(-list),
   76                       on_error(oneof([warning,error])),
   77                       prefixes(-list),
   78                       resources(oneof([uri,iri]))
   79                     ]).   80
   81:- use_foreign_library(foreign(turtle)).   82:- public                               % used by the writer
   83    turtle_pn_local/1,
   84    turtle_write_quoted_string/2,
   85    turtle_write_uri/2.

Turtle: Terse RDF Triple Language

This module implements the Turtle language for representing the RDF triple model as defined by Dave Beckett from the Institute for Learning and Research Technology University of Bristol and later standardized by the W3C RDF working group.

This module acts as a plugin to rdf_load/2, for processing files with one of the extensions .ttl or .n3.

See also
-
http://www.w3.org/TR/turtle/ (used W3C Recommendation 25 February 2014) */
 rdf_read_turtle(+Input, -Triples, +Options)
Read a stream or file into a set of triples or quadruples (if faced with TriG input) of the format
rdf(Subject, Predicate, Object [, Graph])

The representation is consistent with the SWI-Prolog RDF/XML and ntriples parsers. Provided options are:

base_uri(+BaseURI)
Initial base URI. Defaults to file://<file> for loading files.
anon_prefix(+Prefix)
Blank nodes are generated as <Prefix>1, <Prefix>2, etc. If Prefix is not an atom blank nodes are generated as node(1), node(2), ...
format(+Format)
One of auto (default), turtle or trig. The auto mode switches to TriG format of there is a { before the first triple. Finally, of the format is explicitly stated as turtle and the file appears to be a TriG file, a warning is printed and the data is loaded while ignoring the graphs.
resources(URIorIRI)
Officially, Turtle resources are IRIs. Quite a few applications however send URIs. By default we do URI->IRI mapping because this rarely causes errors. To force strictly conforming mode, pass iri.
prefixes(-Pairs)
Return encountered prefix declarations as a list of Alias-URI
namespaces(-Pairs)
Same as prefixes(Pairs). Compatibility to rdf_load/2.
base_used(-Base)
Base URI used for processing the data. Unified to [] if there is no base-uri.
on_error(+ErrorMode)
In warning (default), print the error and continue parsing the remainder of the file. If error, abort with an exception on the first error encountered.
error_count(-Count)
If on_error(warning) is active, this option cane be used to retrieve the number of generated errors.
Arguments:
Input- is one of stream(Stream), atom(Atom), a http, https or file url or a filename specification as accepted by absolute_file_name/3.
  158rdf_read_turtle(In, Triples, Options) :-
  159    base_uri(In, BaseURI, Options),
  160    setup_call_cleanup(
  161        ( open_input(In, Stream, Close),
  162          create_turtle_parser(Parser, Stream,
  163                               [ base_uri(BaseURI)
  164                               | Options
  165                               ])
  166        ),
  167        ( turtle_parse(Parser, Triples,
  168                       [ parse(document)
  169                       | Options
  170                       ]),
  171          post_options(Parser, Options)
  172        ),
  173        ( destroy_turtle_parser(Parser),
  174          call(Close)
  175        )).
 rdf_load_turtle(+Input, -Triples, +Options)
deprecated
- Use rdf_read_turtle/3
  181rdf_load_turtle(Input, Triples, Options) :-
  182    rdf_read_turtle(Input, Triples, Options).
 rdf_process_turtle(+Input, :OnObject, +Options) is det
Streaming Turtle parser. The predicate rdf_process_turtle/3 processes Turtle data from Input, calling OnObject with a list of triples for every Turtle statement found in Input. OnObject is called as below, where ListOfTriples is a list of rdf(S,P,O) terms for a normal Turtle file or rdf(S,P,O,G) terms if the GRAPH keyword is used to associate a set of triples in the document with a particular graph. The Graph argument provides the default graph for storing the triples and Line is the line number where the statement started.
call(OnObject, ListOfTriples, Graph:Line)

This predicate supports the same Options as rdf_load_turtle/3.

Errors encountered are sent to print_message/2, after which the parser tries to recover and parse the remainder of the data.

See also
- This predicate is normally used by load_rdf/2 for processing RDF data.
  209rdf_process_turtle(In, OnObject, Options) :-
  210    base_uri(In, BaseURI, Options),
  211    option(graph(Graph), Options, BaseURI),
  212    setup_call_cleanup(
  213        ( open_input(In, Stream, Close),
  214          create_turtle_parser(Parser, Stream, Options)
  215        ),
  216        ( process_turtle(Parser, Stream, OnObject, Graph,
  217                         [ parse(statement)
  218                         ]),
  219          post_options(Parser, Options)
  220        ),
  221        ( destroy_turtle_parser(Parser),
  222          call(Close)
  223        )).
  224
  225post_options(Parser, Options) :-
  226    prefix_option(Parser, Options),
  227    namespace_option(Parser, Options),
  228    base_option(Parser, Options),
  229    error_option(Parser, Options).
  230
  231prefix_option(Parser, Options) :-
  232    (   option(prefixes(Pairs), Options)
  233    ->  turtle_prefixes(Parser, Pairs)
  234    ;   true
  235    ).
  236namespace_option(Parser, Options) :-
  237    (   option(namespaces(Pairs), Options)
  238    ->  turtle_prefixes(Parser, Pairs)
  239    ;   true
  240    ).
  241base_option(Parser, Options) :-
  242    (   option(base_used(Base), Options)
  243    ->  turtle_base(Parser, Base)
  244    ;   true
  245    ).
  246error_option(Parser, Options) :-
  247    (   option(error_count(Count), Options)
  248    ->  turtle_error_count(Parser, Count)
  249    ;   true
  250    ).
  251
  252
  253process_turtle(_Parser, Stream, _OnObject, _Graph, _Options) :-
  254    at_end_of_stream(Stream),
  255    !.
  256process_turtle(Parser, Stream, OnObject, Graph, Options) :-
  257    stream_pair(Stream, In, _),
  258    line_count(In, LineNo),
  259    turtle_parse(Parser, Triples,
  260                 [ parse(statement)
  261                 | Options
  262                 ]),
  263    call(OnObject, Triples, Graph:LineNo),
  264    process_turtle(Parser, Stream, OnObject, Graph, Options).
 open_input(+Input, -Stream, -Close) is det
Open given input.
Arguments:
Close- goal to undo the open action
Errors
- existence_error, permission_error
To be done
- Synchronize with input handling of rdf_db.pl.
  275open_input(stream(Stream), Stream, Close) :-
  276    !,
  277    stream_property(Stream, encoding(Old)),
  278    (   (   unicode_encoding(Old)
  279        ;   stream_property(Stream, type(text))
  280        )
  281    ->  Close = true
  282    ;   set_stream(Stream, encoding(utf8)),
  283        Close = set_stream(Stream, encoding(Old))
  284    ).
  285open_input(Stream, Stream, Close) :-
  286    is_stream(Stream),
  287    !,
  288    open_input(stream(Stream), Stream, Close).
  289open_input(atom(Atom), Stream, close(Stream)) :-
  290    !,
  291    atom_to_memory_file(Atom, MF),
  292    open_memory_file(MF, read, Stream, [free_on_close(true)]).
  293open_input(URL, Stream, close(Stream)) :-
  294    (   sub_atom(URL, 0, _, _, 'http://')
  295    ;   sub_atom(URL, 0, _, _, 'https://')
  296    ),
  297    !,
  298    http_open(URL, Stream, []),
  299    set_stream(Stream, encoding(utf8)).
  300open_input(URL, Stream, close(Stream)) :-
  301    uri_file_name(URL, Path),
  302    !,
  303    open(Path, read, Stream, [encoding(utf8)]).
  304open_input(File, Stream, close(Stream)) :-
  305    absolute_file_name(File, Path,
  306                       [ access(read),
  307                         extensions([ttl, ''])
  308                       ]),
  309    open(Path, read, Stream, [encoding(utf8)]).
  310
  311unicode_encoding(utf8).
  312unicode_encoding(wchar_t).
  313unicode_encoding(unicode_be).
  314unicode_encoding(unicode_le).
 base_uri(+Input, -BaseURI, +Options)
Determine the base uri to use for processing.
  320base_uri(_Input, BaseURI, Options) :-
  321    option(base_uri(BaseURI), Options),
  322    !.
  323base_uri(_Input, BaseURI, Options) :-
  324    option(graph(BaseURI), Options),
  325    !.
  326base_uri(stream(Input), BaseURI, _Options) :-
  327    stream_property(Input, file_name(Name)),
  328    !,
  329    name_uri(Name, BaseURI).
  330base_uri(Stream, BaseURI, Options) :-
  331    is_stream(Stream),
  332    !,
  333    base_uri(stream(Stream), BaseURI, Options).
  334base_uri(Name, BaseURI, _Options) :-
  335    atom(Name),
  336    !,
  337    name_uri(Name, BaseURI).
  338base_uri(_, 'http://www.example.com/', _).
  339
  340name_uri(Name, BaseURI) :-
  341    uri_is_global(Name),
  342    !,
  343    uri_normalized(Name, BaseURI).
  344name_uri(Name, BaseURI) :-
  345    uri_file_name(BaseURI, Name).
  346
  347
  348                 /*******************************
  349                 *          WRITE SUPPORT       *
  350                 *******************************/
 turtle_pn_local(+Atom:atom) is semidet
True if Atom is a valid Turtle PN_LOCAL name. The PN_LOCAL name is what can follow the : in a resource. In the new Turtle, this can be anything and this function becomes meaningless. In the old turtle, PN_LOCAL is defined similar (but not equal) to an XML name. This predicate is used by rdf_save_turtle/2 to write files such that can be read by old parsers.
See also
- xml_name/2.
 turtle_write_quoted_string(+Out, +Value, ?WriteLong) is det
Write Value (an atom) as a valid Turtle string. WriteLong determines wether the string is written as a short or long string. It takes the following values:
true
Use Turtle's long string syntax. Embeded newlines and single or double quotes are are emitted verbatim.
false
Use Turtle's short string syntax.
Var
If WriteLong is unbound, this predicate uses long syntax if newlines appear in the string and short otherwise. WriteLong is unified with the decision taken.
 turtle_write_quoted_string(+Out, +Value) is det
Same as turtle_write_quoted_string(Out, Value, false), writing a string with only a single ". Embedded newlines are escapes as \n.
  385turtle_write_quoted_string(Out, Text) :-
  386    turtle_write_quoted_string(Out, Text, false).
 turtle_write_uri(+Out, +Value) is det
Write a URI as <...>
  393                 /*******************************
  394                 *          RDF-DB HOOK         *
  395                 *******************************/
  396
  397:- multifile
  398    rdf_db:rdf_load_stream/3,
  399    rdf_db:rdf_file_type/2.
 rdf_db:rdf_load_stream(+Format, +Stream, :Options)
(Turtle clauses)
  405rdf_db:rdf_load_stream(turtle, Stream, Options) :-
  406    load_turtle_stream(Stream, Options).
  407rdf_db:rdf_load_stream(trig, Stream, Options) :-
  408    load_turtle_stream(Stream, Options).
  409
  410load_turtle_stream(Stream, _Module:Options) :-
  411    rdf_db:graph(Options, Graph),
  412    atom_concat('_:', Graph, BNodePrefix),
  413    rdf_transaction((  rdf_process_turtle(Stream, assert_triples,
  414                                          [ anon_prefix(BNodePrefix)
  415                                          | Options
  416                                          ]),
  417                       rdf_set_graph(Graph, modified(false))
  418                    ),
  419                    parse(Graph)).
  420
  421assert_triples([], _).
  422assert_triples([H|T], Location) :-
  423    assert_triple(H, Location),
  424    assert_triples(T, Location).
  425
  426assert_triple(rdf(S,P,O), Location) :-
  427    rdf_assert(S,P,O,Location).
  428assert_triple(rdf(S,P,O,G), _) :-
  429    rdf_assert(S,P,O,G).
  430
  431
  432rdf_db:rdf_file_type(ttl,  turtle).
  433rdf_db:rdf_file_type(n3,   turtle).     % not really, but good enough
  434rdf_db:rdf_file_type(trig, trig).
  435
  436
  437                 /*******************************
  438                 *             MESSAGES         *
  439                 *******************************/
  440
  441:- multifile prolog:error_message//1.  442
  443prolog:error_message(existence_error(turtle_prefix, '')) -->
  444    [ 'Turtle empty prefix (:) is not defined' ]