Module: SPARQL::Grammar

Defined in:
vendor/bundler/ruby/3.3.0/bundler/gems/sparql-796d3be4aa08/lib/sparql/grammar.rb,
vendor/bundler/ruby/3.3.0/bundler/gems/sparql-796d3be4aa08/lib/sparql/grammar/parser.rb,
vendor/bundler/ruby/3.3.0/bundler/gems/sparql-796d3be4aa08/lib/sparql/grammar/parser11.rb,
vendor/bundler/ruby/3.3.0/bundler/gems/sparql-796d3be4aa08/lib/sparql/grammar/terminals.rb

Overview

A SPARQL grammar for RDF.rb.

Representation

The parser natively generates native SPARQL S-Expressions (SSE), a hierarch of SPARQL::Algebra::Operator instances which can be executed against a queryable object, such as a Repository identically to RDF::Query.

Other elements within the hierarchy are generated using RDF objects, such as RDF::URI, RDF::Node, RDF::Literal, and RDF::Query.

See Parser for a full listing of algebra operations and RDF objects generated by the parser.

The native SSE representation may be serialized to a textual representation of SSE as serialized general S-Expressions (SXP). The SXP generated closely follows that of OpenJena ARQ, which is intended principally for running the SPARQL rules. Additionally, SSE is generated for CONSTRUCT, ASK, DESCRIBE and FROM operators.

SXP is generated by serializing the parser result as follows:

sse = SPARQL::Grammar.parse("SELECT * WHERE { ?s ?p ?o }")
sxp = sse.to_sxp

The following examples illustrate SPARQL transformations:

SPARQL:

SELECT * WHERE { ?a ?b ?c }

SXP:

(bgp (triple ?a ?b ?c))

SPARQL:

SELECT * FROM <a> WHERE { ?a ?b ?c }

SXP:

(dataset (<a>) (bgp (triple ?a ?b ?c)))

SPARQL:

SELECT * FROM NAMED <a> WHERE { ?a ?b ?c }

SXP:

(dataset ((named <a>)) (bgp (triple ?a ?b ?c)))

SPARQL:

SELECT DISTINCT * WHERE {?a ?b ?c}

SXP:

(distinct (bgp (triple ?a ?b ?c)))

SPARQL:

SELECT ?a ?b WHERE {?a ?b ?c}

SXP:

(project (?a ?b) (bgp (triple ?a ?b ?c)))

SPARQL:

CONSTRUCT {?a ?b ?c} WHERE {?a ?b ?c FILTER (?a)}

SXP:

(construct ((triple ?a ?b ?c)) (filter ?a (bgp (triple ?a ?b ?c))))

SPARQL:

SELECT * WHERE {<a> <b> <c> OPTIONAL {<d> <e> <f>}}

SXP:

(leftjoin (bgp (triple <a> <b> <c>)) (bgp (triple <d> <e> <f>)))

SPARQL:

SELECT * WHERE {<a> <b> <c> {<d> <e> <f>}}

SXP:

(join (bgp (triple <a> <b> <c>)) (bgp (triple <d> <e> <f>)))

SPARQL:

PREFIX : <http://example/> 

SELECT * 
{ 
   { ?s ?p ?o }
  UNION
   { GRAPH ?g { ?s ?p ?o } }
}

SXP:

(prefix ((: <http://example/>))
  (union
    (bgp (triple ?s ?p ?o))
    (graph ?g
      (bgp (triple ?s ?p ?o)))))

SPARQL:

LOAD <etc/doap.ttl>

SXP:

(update (load <etc/doap.ttl>))

SPARQL:

PREFIX     : <http://example.org/> 

INSERT {
        ?s ?p "q"
}
USING :g1
USING :g2
WHERE {
        ?s ?p ?o
}

SXP:

(prefix ((: <http://example.org/>))
  (update
    (modify
      (using (:g1 :g2)
        (bgp (triple ?s ?p ?o)))
      (insert ((triple ?s ?p "q"))))))

SPARQL:

PREFIX : <http://example.org/> 

SELECT * WHERE
{
  ?s :p ?v .
  BIND (2*?v AS ?v2) .
  ?s :p1 ?v2 .
}

SXP:

(prefix ((: <http://example.org/>))
  (join
    (extend ((?v2 (* 2 ?v)))
      (bgp (triple ?s :p ?v)))
    (bgp (triple ?s :p1 ?v2))))

SPARQL:

PREFIX : <http://bigdata.com>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX dct:  <http://purl.org/dc/elements/1.1/>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>

SELECT ?age ?src WHERE {
   ?bob foaf:name "Bob" .
   <<?bob foaf:age ?age>> dct:source ?src .
}

SXP:

(prefix
  ((: <http://bigdata.com>)
   (foaf: <http://xmlns.com/foaf/0.1/>)
   (dct: <http://purl.org/dc/elements/1.1/>)
   (rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>))
  (project (?age ?src)
    (bgp
      (triple ?bob foaf:name "Bob")
      (triple ??1 rdf:reifies (qtriple ?bob foaf:age ?age))
      (triple ??1 dct:source ?src))))

SPARQL:

PREFIX : <http://bigdata.com>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>
PREFIX dct:  <http://purl.org/dc/elements/1.1/>

CONSTRUCT {
  ?bob foaf:name "Bob" .
  <<?bob foaf:age ?age>> dct:creator <http://example.com/crawlers#c1>;
                         dct:source ?src .
}
WHERE {
  ?bob foaf:name "Bob" .
  <<?bob foaf:age ?age>> dct:source ?src .
}

SXP:

(prefix
  ((: <http://bigdata.com>)
   (foaf: <http://xmlns.com/foaf/0.1/>)
   (dct: <http://purl.org/dc/elements/1.1/>))
  (construct
    ((triple ?bob foaf:name "Bob")
    (triple _:b1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies> (qtriple ?bob foaf:age ?age))
    (triple _:b1 dct:creator <http://example.com/crawlers#c1>)
    (triple _:b1 dct:source ?src))
  (bgp
    (triple ?bob foaf:name "Bob")
    (triple ??1 <http://www.w3.org/1999/02/22-rdf-syntax-ns#reifies> (qtriple ?bob foaf:age ?age))
    (triple ??1 dct:source ?src))))

Implementation Notes

The parser is driven through a rules table contained in lib/sparql/grammar/meta.rb. This includes branch rules to indicate productions to be taken based on a current production.

The meta.rb file is generated from etc/sparql11.bnf using the ebnf gem.

ebnf --peg --format rb \
  --mod-name SPARQL::Grammar::Meta \
  --output lib/sparql/grammar/meta.rb \
  etc/sparql11.bnf

Defined Under Namespace

Modules: Meta, Meta11, Terminals Classes: Parser, Parser11

Class Method Summary collapse

Class Method Details

.open(filename, **options) {|reader| ... } ⇒ Object

Parses input from the given file name or URL.

Parameters:

  • filename (String, #to_s)
  • options (Hash{Symbol => Object})

    any additional options (see RDF::Reader#initialize and RDF::Format.for)

Options Hash (**options):

  • :format (Symbol) — default: :ntriples
  • :use11 (Boolean)

    SPARQL 1.1 version parser

  • :use11 (Boolean)

    SPARQL 1.1 version parser

  • :all_vars (Boolean) — default: false

    If true, emits on empty project operator when parsing SELECT *, which will emit all in-scope variables, rather than just those used in solutions. In the next minor release, the default for this option will change to true.

  • :anon_base (#to_s) — default: "b0"

    Basis for generating anonymous Nodes

  • :base_uri (#to_s) — default: nil

    the base URI to use when resolving relative URIs (for acessing intermediate parser productions)

  • :logger (Logger, #write, #<<)

    Record error/info/debug output

  • :prefixes (Hash) — default: Hash.new

    the prefix mappings to use (for acessing intermediate parser productions)

  • :resolve_iris (Boolean) — default: false

    Resolve prefix and relative IRIs, otherwise, when serializing the parsed SSE as S-Expressions, use the original prefixed and relative URIs along with base and prefix definitions.

  • :validate (Boolean) — default: false

    whether to validate the parsed statements and values

Yields:

  • (reader)

Yield Parameters:

Yield Returns:

  • (void)

    ignored

Raises:



277
278
279
280
281
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/sparql-796d3be4aa08/lib/sparql/grammar.rb', line 277

def self.open(filename, **options, &block)
  RDF::Util::File.open_file(filename, **options) do |file|
    self.parse(file, **options, &block)
  end
end

.parse(query, **options, &block) ⇒ Parser

Parse the given SPARQL query string.

Examples:

result = SPARQL::Grammar.parse("SELECT * WHERE { ?s ?p ?o }")

Parameters:

  • query (IO, StringIO, Lexer, Array, String, #to_s)

    Query may be an array of lexed tokens, a lexer, or a string or open file.

  • options (Hash{Symbol => Object})

Options Hash (**options):

  • :use11 (Boolean)

    SPARQL 1.1 version parser

  • :all_vars (Boolean) — default: false

    If true, emits on empty project operator when parsing SELECT *, which will emit all in-scope variables, rather than just those used in solutions. In the next minor release, the default for this option will change to true.

  • :anon_base (#to_s) — default: "b0"

    Basis for generating anonymous Nodes

  • :base_uri (#to_s) — default: nil

    the base URI to use when resolving relative URIs (for acessing intermediate parser productions)

  • :logger (Logger, #write, #<<)

    Record error/info/debug output

  • :prefixes (Hash) — default: Hash.new

    the prefix mappings to use (for acessing intermediate parser productions)

  • :resolve_iris (Boolean) — default: false

    Resolve prefix and relative IRIs, otherwise, when serializing the parsed SSE as S-Expressions, use the original prefixed and relative URIs along with base and prefix definitions.

  • :validate (Boolean) — default: false

    whether to validate the parsed statements and values

Returns:

Raises:



256
257
258
259
260
261
262
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/sparql-796d3be4aa08/lib/sparql/grammar.rb', line 256

def self.parse(query, **options, &block)
  if options[:use11]
    Parser11.new(query, **options).parse(options[:update] ? :UpdateUnit : :QueryUnit)
  else
    Parser.new(query, **options).parse(options[:update] ? :UpdateUnit : :QueryUnit)
  end
end

.tokenize(query, **options) {|lexer| ... } ⇒ Lexer

Tokenizes the given SPARQL query string.

Examples:

lexer = SPARQL::Grammar.tokenize("SELECT * WHERE { ?s ?p ?o }")
lexer.each_token do |token|
  puts token.inspect
end

Parameters:

Yields:

  • (lexer)

Yield Parameters:

  • lexer (Lexer)

Returns:

  • (Lexer)

Raises:

  • (Lexer::Error)

    on invalid input



312
313
314
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/sparql-796d3be4aa08/lib/sparql/grammar.rb', line 312

def self.tokenize(query, **options, &block)
  Lexer.tokenize(query, **options, &block)
end

.valid?(query, **options) ⇒ Boolean

Returns true if the given SPARQL query string is valid.

Examples:

SPARQL::Grammar.valid?("SELECT ?s WHERE { ?s ?p ?o }")  #=> true
SPARQL::Grammar.valid?("SELECT s WHERE { ?s ?p ?o }")   #=> false

Parameters:

Returns:

  • (Boolean)


293
294
295
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/sparql-796d3be4aa08/lib/sparql/grammar.rb', line 293

def self.valid?(query, **options)
  Parser.new(query, **options).valid?
end