-
Notifications
You must be signed in to change notification settings - Fork 14
/
parser11.rb
2544 lines (2297 loc) · 93.2 KB
/
parser11.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require 'ebnf'
require 'ebnf/ll1/parser'
require 'sparql/grammar/meta'
module SPARQL::Grammar
##
# A parser for the SPARQL 1.1 grammar.
#
# @see https://www.w3.org/TR/sparql11-query/#grammar
# @see https://en.wikipedia.org/wiki/LR_parser
class Parser
include SPARQL::Grammar::Meta
include SPARQL::Grammar::Terminals
include EBNF::LL1::Parser
# Builtin functions
BUILTINS = %w{
ABS ADJUST BNODE CEIL COALESCE CONCAT
CONTAINS DATATYPE DAY ENCODE_FOR_URI
FLOOR HOURS IF IRI LANGMATCHES LANG LCASE
MD5 MINUTES MONTH NOW RAND ROUND SECONDS
SHA1 SHA224 SHA256 SHA384 SHA512
STRAFTER STRBEFORE STRDT STRENDS STRLANG STRLEN STRSTARTS STRUUID STR
TIMEZONE TZ UCASE URI UUID YEAR
isBLANK isIRI isURI isLITERAL isNUMERIC sameTerm
isTRIPLE TRIPLE SUBJECT PREDICATE OBJECT
}.map {|s| s.downcase.to_sym}.freeze
BUILTIN_RULES = [:aggregate, :regex, :substr, :replace, :exists, :notexists].freeze
AGGREGATE_RULES = [:count, :sum, :min, :max, :avg, :sample, :group_concat]
##
# Any additional options for the parser.
#
# @return [Hash]
attr_reader :options
##
# The current input string being processed.
#
# @return [String]
attr_accessor :input
##
# The current input tokens being processed.
#
# @return [Array<Token>]
attr_reader :tokens
##
# The internal representation of the result using hierarchy of RDF objects and SPARQL::Algebra::Operator
# objects.
# @return [Array]
attr_accessor :result
# Terminals passed to lexer. Order matters!
terminal(:ANON, ANON) do |prod, token, input|
input[:BlankNode] = bnode
end
terminal(:NIL, NIL) do |prod, token, input|
input[:NIL] = RDF['nil']
end
terminal(:BLANK_NODE_LABEL, BLANK_NODE_LABEL) do |prod, token, input|
input[:BlankNode] = bnode(token.value[2..-1])
end
terminal(:IRIREF, IRIREF, unescape: true) do |prod, token, input|
begin
input[:iri] = iri(token.value[1..-2])
rescue ArgumentError => e
raise Error, e.message
end
end
terminal(:DOUBLE_POSITIVE, DOUBLE_POSITIVE) do |prod, token, input|
# Note that a Turtle Double may begin with a '.[eE]', so tack on a leading
# zero if necessary
value = token.value.sub(/\.([eE])/, '.0\1')
input[:literal] = literal(value, datatype: RDF::XSD.double)
end
terminal(:DECIMAL_POSITIVE, DECIMAL_POSITIVE) do |prod, token, input|
# Note that a Turtle Decimal may begin with a '.', so tack on a leading
# zero if necessary
value = token.value
value = "0#{token.value}" if token.value[0,1] == "."
input[:literal] = literal(value, datatype: RDF::XSD.decimal)
end
terminal(:INTEGER_POSITIVE, INTEGER_POSITIVE) do |prod, token, input|
input[:literal] = literal(token.value, datatype: RDF::XSD.integer)
end
terminal(:DOUBLE_NEGATIVE, DOUBLE_NEGATIVE) do |prod, token, input|
# Note that a Turtle Double may begin with a '.[eE]', so tack on a leading
# zero if necessary
value = token.value.sub(/\.([eE])/, '.0\1')
input[:literal] = literal(value, datatype: RDF::XSD.double)
end
terminal(:DECIMAL_NEGATIVE, DECIMAL_NEGATIVE) do |prod, token, input|
# Note that a Turtle Decimal may begin with a '.', so tack on a leading
# zero if necessary
value = token.value
value = "0#{token.value}" if token.value[0,1] == "."
input[:literal] = literal(value, datatype: RDF::XSD.decimal)
end
terminal(:INTEGER_NEGATIVE, INTEGER_NEGATIVE) do |prod, token, input|
input[:literal] = literal(token.value, datatype: RDF::XSD.integer)
end
terminal(:DOUBLE, DOUBLE) do |prod, token, input|
# Note that a Turtle Double may begin with a '.[eE]', so tack on a leading
# zero if necessary
value = token.value.sub(/\.([eE])/, '.0\1')
input[:literal] = literal(value, datatype: RDF::XSD.double)
end
terminal(:DECIMAL, DECIMAL) do |prod, token, input|
# Note that a Turtle Decimal may begin with a '.', so tack on a leading
# zero if necessary
value = token.value
#value = "0#{token.value}" if token.value[0,1] == "."
input[:literal] = literal(value, datatype: RDF::XSD.decimal)
end
terminal(:INTEGER, INTEGER) do |prod, token, input|
input[:literal] = literal(token.value, datatype: RDF::XSD.integer)
end
terminal(:LANGTAG, LANGTAG) do |prod, token, input|
input[:language] = token.value[1..-1]
end
terminal(:PNAME_LN, PNAME_LN, unescape: true) do |prod, token, input|
prefix, suffix = token.value.split(":", 2)
input[:iri] = ns(prefix, suffix)
end
terminal(:PNAME_NS, PNAME_NS) do |prod, token, input|
prefix = token.value[0..-2]
# [68] PrefixedName ::= PNAME_LN | PNAME_NS
input[:iri] = ns(prefix, nil)
input[:prefix] = prefix && prefix.to_sym
end
terminal(:STRING_LITERAL_LONG1, STRING_LITERAL_LONG1, unescape: true) do |prod, token, input|
input[:string] = token.value[3..-4]
end
terminal(:STRING_LITERAL_LONG2, STRING_LITERAL_LONG2, unescape: true) do |prod, token, input|
input[:string] = token.value[3..-4]
end
terminal(:STRING_LITERAL1, STRING_LITERAL1, unescape: true) do |prod, token, input|
input[:string] = token.value[1..-2]
end
terminal(:STRING_LITERAL2, STRING_LITERAL2, unescape: true) do |prod, token, input|
input[:string] = token.value[1..-2]
end
terminal(:VAR1, VAR1) do |prod, token, input|
add_prod_datum(:Var, variable(token.value[1..-1]))
end
terminal(:VAR2, VAR2) do |prod, token, input|
add_prod_datum(:Var, variable(token.value[1..-1]))
end
# Keyword terminals
terminal(nil, STR_EXPR, map: STR_MAP) do |prod, token, input|
case token.value
when '+', '-'
case prod
when :_AdditiveExpression_1, :_AdditiveExpression_4, :_AdditiveExpression_5
add_prod_datum(:AdditiveExpression, token.value)
when :_UnaryExpression_2, :_UnaryExpression_3
add_prod_datum(:UnaryExpression, token.value)
when :PathMod
add_prod_datum(:PathMod, token.value)
else
raise "Unexpected production #{prod} for #{token}"
end
when '?' then add_prod_datum(:PathMod, token.value)
when '^' then input[:reverse] = token.value
when '*', '/' then add_prod_datum(:MultiplicativeExpression, token.value)
when '=', '!=', '<',
'>', '<=', '>=' then add_prod_datum(:RelationalExpression, token.value)
when '&&' then add_prod_datum(:ConditionalAndExpression, token.value)
when '||' then add_prod_datum(:ConditionalOrExpression, token.value)
when '!' then add_prod_datum(:UnaryExpression, token.value)
when 'a' then input[:Verb] = (a = RDF.type.dup; a.lexical = 'a'; a)
when /true|false/ then input[:literal] = RDF::Literal::Boolean.new(token.value.downcase)
when /ASC|DESC/ then input[:OrderDirection] = token.value.downcase.to_sym
when /DISTINCT|REDUCED/ then input[:DISTINCT_REDUCED] = token.value.downcase.to_sym
when %r{
ABS|ADJUST|ALL|AVG|BNODE|BOUND|CEIL|COALESCE|CONCAT
|CONTAINS|COUNT|DATATYPE|DAY|DEFAULT|ENCODE_FOR_URI|EXISTS
|FLOOR|HOURS|IF|GRAPH|GROUP_CONCAT|IRI|LANGMATCHES|LANG|LCASE
|MAX|MD5|MINUTES|MIN|MONTH|NAMED|NOW|RAND|REPLACE|ROUND|SAMPLE|SECONDS|SEPARATOR
|SHA1|SHA224|SHA256|SHA384|SHA512|SILENT
|STRAFTER|STRBEFORE|STRDT|STRENDS|STRLANG|STRLEN|STRSTARTS|STRUUID|SUBSTR|STR|SUM
|TIMEZONE|TZ|UCASE|UNDEF|URI|UUID|YEAR
|isBLANK|isIRI|isURI|isLITERAL|isNUMERIC|sameTerm
|isTRIPLE|TRIPLE|SUBJECT|PREDICATE|OBJECT
}x
add_prod_datum(token.value.downcase.to_sym, token.value.downcase.to_sym)
else
#add_prod_datum(:string, token.value)
end
end
# Productions
# [2] Query ::= Prologue ( SelectQuery | ConstructQuery | DescribeQuery | AskQuery )
#
# Inputs from `data` are `:query` and potentially `:PrefixDecl`.
# Output to prod_data is the Queryable object.
production(:Query) do |input, data, callback|
query = data[:query].first if data[:query]
# Add prefix
if data[:PrefixDecl]
pfx = data[:PrefixDecl].shift
data[:PrefixDecl].each {|p| pfx.merge!(p)}
pfx.operands[1] = query
query = pfx
end
# Add base
query = SPARQL::Algebra::Expression[:base, data[:BaseDecl].first, query] if data[:BaseDecl]
add_prod_datum(:query, query)
end
# [4] Prologue ::= ( BaseDecl | PrefixDecl )*
#
# Inputs from `data` are `:PrefixDecl` and `:BaseDecl`.
# Output to prod_data is the same, if `#resolve_iris?` is `false`.
production(:Prologue) do |input, data, callback|
unless resolve_iris?
# Only output if we're not resolving URIs internally
add_prod_datum(:BaseDecl, data[:BaseDecl])
add_prod_datum(:PrefixDecl, data[:PrefixDecl])
end
end
# [5] BaseDecl ::= 'BASE' IRI_REF
#
# Input from `data` is `:BaseDecl`.
# Output to prod_data is the same, if `#resolve_iris?` is `false`.
production(:BaseDecl) do |input, data, callback|
iri = data[:iri]
debug("BaseDecl") {"Defined base as #{iri}"}
self.base_uri = iri(iri)
add_prod_datum(:BaseDecl, iri) unless resolve_iris?
end
# [6] PrefixDecl ::= 'PREFIX' PNAME_NS IRI_REF
#
# Inputs from `data` are `:iri`, and `:prefix`.
# Output to prod_data is the `:PrefixDecl`, and `Operator::Prefix`, unless there is no `:iri`.
production(:PrefixDecl) do |input, data, callback|
if data[:iri]
pfx = data[:prefix]
self.prefix(pfx, data[:iri])
prefix_op = SPARQL::Algebra::Operator::Prefix.new([["#{pfx}:".to_sym, data[:iri]]], [])
add_prod_datum(:PrefixDecl, prefix_op)
end
end
# [7] SelectQuery ::= SelectClause DatasetClause* WhereClause SolutionModifier
#
# Inputs from `data` are merged into a Queryable object.
# Output to prod_data is `:query`.
production(:SelectQuery) do |input, data, callback|
query = merge_modifiers(data)
add_prod_datum :query, query
end
# [8] SubSelect ::= SelectClause WhereClause SolutionModifier
#
# Inputs from `data` are merged into a Queryable object.
# Output to prod_data is `:query`.
production(:SubSelect) do |input, data, callback|
query = merge_modifiers(data)
add_prod_datum :query, query
end
# [9] SelectClause ::= 'SELECT' ( 'DISTINCT' | 'REDUCED' )? ( ( Var | ( '(' Expression 'AS' Var ')' ) )+ | '*' )
# [9.2] _SelectClause_2 ::= ( ( Var | ( '(' Expression 'AS' Var ')' ) )+ | '*' )
#
# Inputs from `data` are `:Expression` and `:Var`.
# Output to prod_data is `:Var`.
production(:_SelectClause_2) do |input, data, callback|
if data[:MultiplicativeExpression]
add_prod_datum :Var, %i(*)
else
add_prod_datum :extend, data[:extend]
add_prod_datum :Var, data[:Var]
end
end
# [9.8] _SelectClause_8 ::= ( '(' Expression 'AS' Var ')' )
#
# Inputs from `data` are `:Expression` and `:Var`.
# Output to prod_data is `:extend`.
production(:_SelectClause_8) do |input, data, callback|
add_prod_datum :extend, [data[:Expression].unshift(data[:Var].first)]
end
# [10] ConstructQuery ::= 'CONSTRUCT'
# ( ConstructTemplate
# DatasetClause*
# WhereClause
# SolutionModifier | DatasetClause*
# 'WHERE' '{' TriplesTemplate? '}'
# SolutionModifier
# )
#
# Inputs from `data` are `:pattern` and optionally `:ConstructTemplate`.
# If there is no `:query` in data, one is constructed by creating a BGP from all values of `:pattern`.
# Output to prod_data is `:query` made by creating a Operator::Construct using any `:ConstructTemplate` or `:pattern` and the query with merged modifiers.
production(:ConstructQuery) do |input, data, callback|
data[:query] ||= [SPARQL::Algebra::Operator::BGP.new(*data[:pattern])]
query = merge_modifiers(data)
template = data[:ConstructTemplate] || data[:pattern] || []
add_prod_datum :query, SPARQL::Algebra::Expression[:construct, template, query]
end
# [11] DescribeQuery ::= 'DESCRIBE' ( VarOrIri+ | '*' )
# DatasetClause* WhereClause? SolutionModifier
#
# Inputs from `data` are merged into a Queryable object.
# Outputs are created using any `:VarOrIri` in data is used as an argument, along with the Queryable object to create an `Operator::Describe` object, which is added to `:query` in prod datea.
production(:DescribeQuery) do |input, data, callback|
query = merge_modifiers(data)
to_describe = Array(data[:VarOrIri])
add_prod_datum :query, SPARQL::Algebra::Expression[:describe, to_describe, query]
end
# [12] AskQuery ::= 'ASK' DatasetClause* WhereClause
#
# Inputs from `data` are merged into a Queryable object.
# Output to prod_data is `:query` made by creating a Operator::Ask using the query with merged modifiers.
production(:AskQuery) do |input, data, callback|
query = merge_modifiers(data)
add_prod_datum :query, SPARQL::Algebra::Expression[:ask, query]
end
# [14] DefaultGraphClause ::= SourceSelector
#
# Input from `data` is `:iri`.
# Output to prod_data is `:dataset` taken from `:iri`.
production(:DefaultGraphClause) do |input, data, callback|
add_prod_datum :dataset, data[:iri]
end
# [15] NamedGraphClause ::= 'NAMED' SourceSelector
#
# Input from `data` is `:iri`.
# Output to prod_data is `:dataset` taken from `:iri`.
production(:NamedGraphClause) do |input, data, callback|
add_prod_data :dataset, [:named, data[:iri]]
end
# [18] SolutionModifier ::= GroupClause? HavingClause? OrderClause? LimitOffsetClauses?
# [19] GroupClause ::= 'GROUP' 'BY' GroupCondition+
#
# Input from `data` is `:GroupCondition`.
# Output to prod_data is `:group` taken from `:GroupCondition`.
production(:GroupClause) do |input, data, callback|
add_prod_data :group, data[:GroupCondition]
end
# [20] GroupCondition ::= BuiltInCall | FunctionCall
# | '(' Expression ( 'AS' Var )? ')' | Var
#
# Output to prod_data is `:GroupCondition` taken from first value in data.
production(:GroupCondition) do |input, data, callback|
add_prod_datum :GroupCondition, data.values.first
end
# _GroupCondition_1 ::= '(' Expression ( 'AS' Var )? ')'
#
# Input from `data` is `:Expression` and optionally `:Var`.
# Output to prod_data is `:GroupCondition` taken from `:Expression` prepended by any value of `:Var`.
production(:_GroupCondition_1) do |input, data, callback|
cond = if data[:Var]
[data[:Expression].unshift(data[:Var].first)]
else
data[:Expression]
end
add_prod_datum(:GroupCondition, cond)
end
# [21] HavingClause ::= 'HAVING' HavingCondition+
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:HavingClause) do |input, data, callback|
add_prod_datum(:having, data[:Constraint])
end
# [23] OrderClause ::= 'ORDER' 'BY' OrderCondition+
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:OrderClause) do |input, data, callback|
if res = data[:OrderCondition]
res = [res] if [:asc, :desc].include?(res[0]) # Special case when there's only one condition and it's ASC (x) or DESC (x)
add_prod_data :order, res
end
end
# [24] OrderCondition ::= ( ( 'ASC' | 'DESC' )
# BrackettedExpression )
# | ( Constraint | Var )
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:OrderCondition) do |input, data, callback|
if data[:OrderDirection]
add_prod_datum(:OrderCondition, SPARQL::Algebra::Expression(data[:OrderDirection], *data[:Expression]))
else
add_prod_datum(:OrderCondition, data[:Constraint] || data[:Var])
end
end
# [25] LimitOffsetClauses ::= LimitClause OffsetClause?
# | OffsetClause LimitClause?
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:LimitOffsetClauses) do |input, data, callback|
if data[:limit] || data[:offset]
limit = data[:limit] ? data[:limit].last : :_
offset = data[:offset] ? data[:offset].last : :_
add_prod_data :slice, offset, limit
end
end
# [26] LimitClause ::= 'LIMIT' INTEGER
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:LimitClause) do |input, data, callback|
add_prod_datum(:limit, data[:literal])
end
# [27] OffsetClause ::= 'OFFSET' INTEGER
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:OffsetClause) do |input, data, callback|
add_prod_datum(:offset, data[:literal])
end
# [28] ValuesClause ::= ( 'VALUES' DataBlock )?
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:ValuesClause) do |input, data, callback|
debug("ValuesClause") {"vars: #{data[:Var].inspect}, row: #{data[:row].inspect}"}
if data[:row]
add_prod_datum :ValuesClause, SPARQL::Algebra::Expression.for(:table,
Array(data[:Var]).unshift(:vars),
*data[:row]
)
else
add_prod_datum :ValuesClause, SPARQL::Algebra::Expression.for(:table, :empty)
end
end
# [29] Update ::= Prologue (Update1 (";" Update)? )?
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:Update) do |input, data, callback|
update = data[:update] || SPARQL::Algebra::Expression(:update)
# Add prefix
if data[:PrefixDecl]
pfx = data[:PrefixDecl].shift
data[:PrefixDecl].each {|p| pfx.merge!(p)}
pfx.operands[1] = update
update = pfx
end
# Add base
update = SPARQL::Algebra::Expression[:base, data[:BaseDecl].first, update] if data[:BaseDecl]
# Don't use update operator twice, if we can help it
input[:update] = update
end
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:_Update_3) do |input, data, callback|
if data[:update]
if input[:update].is_a?(SPARQL::Algebra::Operator::Update)
# Append operands
input[:update] = SPARQL::Algebra::Expression(:update, *(input[:update].operands + data[:update].operands))
else
add_prod_datum(:update, data[:update])
end
end
end
# [30] Update1 ::= Load | Clear | Drop | Add | Move | Copy
# | Create | InsertData | DeleteData | DeleteWhere | Modify
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:Update1) do |input, data, callback|
input[:update] = SPARQL::Algebra::Expression.for(:update, data[:update_op])
end
# [31] Load ::= "LOAD" "SILENT"? iri ("INTO" GraphRef)?
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:Load) do |input, data, callback|
args = []
args << :silent if data[:silent]
args << data[:iri]
args << data[:into] if data[:into]
input[:update_op] = SPARQL::Algebra::Expression(:load, *args)
end
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:_Load_2) do |input, data, callback|
input[:into] = data[:iri]
end
# [32] Clear ::= "CLEAR" "SILENT"? GraphRefAll
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:Clear) do |input, data, callback|
args = []
%w(silent default named all).map(&:to_sym).each do |s|
args << s if data[s]
end
args += Array(data[:iri])
input[:update_op] = SPARQL::Algebra::Expression(:clear, *args)
end
# [33] Drop ::= "DROP" "SILENT"? GraphRefAll
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:Drop) do |input, data, callback|
args = []
%w(silent default named all).map(&:to_sym).each do |s|
args << s if data[s]
end
args += Array(data[:iri])
input[:update_op] = SPARQL::Algebra::Expression(:drop, *args)
end
# [34] Create ::= "CREATE" "SILENT"? GraphRef
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:Create) do |input, data, callback|
args = []
args << :silent if data[:silent]
args += Array(data[:iri])
input[:update_op] = SPARQL::Algebra::Expression(:create, *args)
end
# [35] Add ::= "ADD" "SILENT"? GraphOrDefault "TO" GraphOrDefault
#
# Input from `data` are `GraphOrDefault` and optionally `:silent`.
# Output to input is `:update_op` with an `Operator::Add` object.
production(:Add) do |input, data, callback|
args = []
args << :silent if data[:silent]
args += data[:GraphOrDefault]
input[:update_op] = SPARQL::Algebra::Expression(:add, *args)
end
# [36] Move ::= "MOVE" "SILENT"? GraphOrDefault "TO" GraphOrDefault
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:Move) do |input, data, callback|
args = []
args << :silent if data[:silent]
args += data[:GraphOrDefault]
input[:update_op] = SPARQL::Algebra::Expression(:move, *args)
end
# [37] Copy ::= "COPY" "SILENT"? GraphOrDefault "TO" GraphOrDefault
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:Copy) do |input, data, callback|
args = []
args << :silent if data[:silent]
args += data[:GraphOrDefault]
input[:update_op] = SPARQL::Algebra::Expression(:copy, *args)
end
# [38] InsertData ::= "INSERT DATA" QuadData
start_production(:InsertData) do |input, data, callback|
# Freeze existing bnodes, so that if an attempt is made to re-use such a node, and error is raised
self.freeze_bnodes
end
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:InsertData) do |input, data, callback|
input[:update_op] = SPARQL::Algebra::Expression(:insertData, data[:pattern])
end
# [39] DeleteData ::= "DELETE DATA" QuadData
start_production(:DeleteData) do |input, data, callback|
# Generate BNodes instead of non-distinguished variables. BNodes are not legal, but this will generate them rather than non-distinguished variables so they can be detected.
self.gen_bnodes
end
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:DeleteData) do |input, data, callback|
raise Error, "DeleteData contains BNode operands: #{data[:pattern].to_sse}" if Array(data[:pattern]).any?(&:node?)
input[:update_op] = SPARQL::Algebra::Expression(:deleteData, Array(data[:pattern]))
end
# [40] DeleteWhere ::= "DELETE WHERE" QuadPattern
start_production(:DeleteWhere) do |input, data, callback|
# Generate BNodes instead of non-distinguished variables. BNodes are not legal, but this will generate them rather than non-distinguished variables so they can be detected.
self.gen_bnodes
end
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:DeleteWhere) do |input, data, callback|
raise Error, "DeleteWhere contains BNode operands: #{data[:pattern].to_sse}" if Array(data[:pattern]).any?(&:node?)
self.gen_bnodes(false)
input[:update_op] = SPARQL::Algebra::Expression(:deleteWhere, Array(data[:pattern]))
end
# [41] Modify ::= ("WITH" iri)? ( DeleteClause InsertClause? | InsertClause) UsingClause* "WHERE" GroupGraphPattern
start_production(:Modify) do |input, data, callback|
self.clear_bnode_cache
end
#
# Input from `data` are:
# * `:query` from `GroupGraphPattern`,
# * optionally `:using` from `UsingClause`,
# * either `:delete` or `:insert` or both from `DeleteClause` and `InsertClause`, and
# * optionally `:iri` from `WITH`
# Output to input is `:update_op`.
production(:Modify) do |input, data, callback|
query = data[:query].first if data[:query]
query = SPARQL::Algebra::Expression.for(:using, data[:using], query) if data[:using]
operands = [query, data[:delete], data[:insert]].compact
operands = [SPARQL::Algebra::Expression.for(:with, data[:iri], *operands)] if data[:iri]
input[:update_op] = SPARQL::Algebra::Expression(:modify, *operands)
end
# [42] DeleteClause ::= "DELETE" QuadPattern
#
# Generate BNodes instead of non-distinguished variables. BNodes are not legal, but this will generate them rather than non-distinguished variables so they can be detected.
start_production(:DeleteClause) do |input, data, callback|
self.gen_bnodes
end
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:DeleteClause) do |input, data, callback|
raise Error, "DeleteClause contains BNode operands: #{Array(data[:pattern]).to_sse}" if Array(data[:pattern]).any?(&:node?)
self.gen_bnodes(false)
input[:delete] = SPARQL::Algebra::Expression(:delete, Array(data[:pattern]))
end
# [43] InsertClause ::= "INSERT" QuadPattern
#
# Generate BNodes instead of non-distinguished variables.
start_production(:InsertClause) do |input, data, callback|
self.gen_bnodes
end
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:InsertClause) do |input, data, callback|
self.gen_bnodes(false)
input[:insert] = SPARQL::Algebra::Expression(:insert, Array(data[:pattern]))
end
# [44] UsingClause ::= "USING" ( iri | "NAMED" iri)
production(:UsingClause) do |input, data, callback|
add_prod_data(:using, data[:iri])
end
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:_UsingClause_2) do |input, data, callback|
input[:iri] = [:named, data[:iri]]
end
# [45] GraphOrDefault ::= "DEFAULT" | "GRAPH"? iri
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:GraphOrDefault) do |input, data, callback|
if data[:default]
add_prod_datum(:GraphOrDefault, :default)
else
add_prod_data(:GraphOrDefault, data[:iri])
end
end
# [46] GraphRef ::= "GRAPH" iri
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:GraphRef) do |input, data, callback|
input[:iri] = data[:iri]
end
# [49] QuadData ::= "{" Quads "}"
# QuadData is like QuadPattern, except without BNodes
start_production(:QuadData) do |input, data, callback|
# Generate BNodes instead of non-distinguished variables
self.gen_bnodes
end
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:QuadData) do |input, data, callback|
# Transform using statements instead of patterns, and verify there are no variables
raise Error, "QuadData contains variable operands: #{Array(data[:pattern]).to_sse}" if Array(data[:pattern]).any?(&:variable?)
self.gen_bnodes(false)
input[:pattern] = Array(data[:pattern])
end
# [51] QuadsNotTriples ::= "GRAPH" VarOrIri "{" TriplesTemplate? "}"
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:QuadsNotTriples) do |input, data, callback|
add_prod_datum(:pattern, [SPARQL::Algebra::Expression.for(:graph, data[:VarOrIri].last, Array(data[:pattern]))])
end
# [52] TriplesTemplate ::= TriplesSameSubject ("." TriplesTemplate? )?
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:TriplesTemplate) do |input, data, callback|
add_prod_datum(:pattern, Array(data[:pattern]))
end
# [54] GroupGraphPatternSub ::= TriplesBlock? (GraphPatternNotTriples "."? TriplesBlock? )*
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:GroupGraphPatternSub) do |input, data, callback|
debug("GroupGraphPatternSub") {"q #{data[:query].inspect}"}
res = case Array(data[:query]).length
when 0 then SPARQL::Algebra::Operator::BGP.new
when 1 then data[:query].first
when 2
SPARQL::Algebra::Operator::Join.new(*data[:query])
else
error(nil, "Expected 0-2 queryies, got #{data[:query].length}", production: :GroupGraphPatternSub)
SPARQL::Algebra::Operator::BGP.new
end
debug("GroupGraphPatternSub(pre-filter)") {"res: #{res.inspect}"}
if data[:filter]
expr, query = flatten_filter(data[:filter])
query = res
# query should be nil
res = SPARQL::Algebra::Operator::Filter.new(expr, query)
end
add_prod_datum(:query, res)
end
# [55] TriplesBlock ::= TriplesSameSubjectPath
# ( '.' TriplesBlock? )?
#
# Input from `data` is `:pattern` and `:query`. Input from input is also `:pattern`
# Patterns are sequenced and segmented into RDF::Query::Pattern and Operator::Path.
# Output to prod_data is `:query` either a BGP, a Join, a Sequence, or a combination of any of these. Any path element results in a Sequence.
production(:TriplesBlock) do |input, data, callback|
raise "TriplesBlock without pattern" if Array(data[:pattern]).empty?
lhs = Array(input.delete(:query)).first
# Sequence is existing patterns, plus new patterns, plus patterns from TriplesBlock?
sequence = []
unless lhs.nil? || lhs.empty?
if lhs.is_a?(SPARQL::Algebra::Operator::Sequence)
sequence += lhs.operands
else
sequence << lhs
end
end
sequence += data[:pattern]
# Append triples from ('.' TriplesBlock? )?
Array(data[:query]).each do |q|
if q.is_a?(SPARQL::Algebra::Operator::Sequence)
q.operands.each do |op|
sequence += op.respond_to?(:patterns) ? op.patterns : [op]
end
elsif q.respond_to?(:patterns)
sequence += q.patterns
else
sequence << q
end
end
# Merge runs of patterns into BGPs
patterns = []
new_seq = []
sequence.each do |element|
case element
when RDF::Query::Pattern
patterns << element
when RDF::Queryable
patterns += element.patterns
else
new_seq << SPARQL::Algebra::Expression.for(:bgp, *patterns) unless patterns.empty?
patterns = []
new_seq << element
end
end
new_seq << SPARQL::Algebra::Expression.for(:bgp, *patterns) unless patterns.empty?
# Optionally create a sequence, if there are enough gathered.
# FIXME: Join?
query = if new_seq.length > 1
if new_seq.any? {|e| e.is_a?(SPARQL::Algebra::Operator::Path)}
SPARQL::Algebra::Expression.for(:sequence, *new_seq)
else
SPARQL::Algebra::Expression.for(:join, *new_seq)
end
else
new_seq.first
end
add_prod_datum(:query, query)
end
# [56] GraphPatternNotTriples ::= GroupOrUnionGraphPattern
# | OptionalGraphPattern
# | MinusGraphPattern
# | GraphGraphPattern
# | ServiceGraphPattern
# | Filter | Bind
start_production(:GraphPatternNotTriples) do |input, data, callback|
# Modifies previous graph
data[:input_query] = input.delete(:query)
end
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:GraphPatternNotTriples) do |input, data, callback|
lhs = Array(data[:input_query]).first || SPARQL::Algebra::Operator::BGP.new
# Filter trickls up to GroupGraphPatternSub
add_prod_datum(:filter, data[:filter])
if data[:extend] && lhs.is_a?(SPARQL::Algebra::Operator::Extend)
# Coalesce extensions
lhs = lhs.dup
lhs.operands.first.concat(data[:extend])
add_prod_datum(:query, lhs)
elsif data[:extend]
# The variable assigned in a BIND clause must not be already in-use within the immediately preceding TriplesBlock within a GroupGraphPattern.
# None of the variables on the lhs of data[:extend] may be used in lhs
data[:extend].each do |(v, _)|
error(nil, "BIND Variable #{v} used in pattern", production: :GraphPatternNotTriples) if lhs.vars.map(&:to_sym).include?(v.to_sym)
end
add_prod_datum(:query, SPARQL::Algebra::Expression.for(:extend, data[:extend], lhs))
elsif data[:leftjoin]
add_prod_datum(:query, SPARQL::Algebra::Expression.for(:leftjoin, lhs, *data[:leftjoin]))
elsif data[:query] && !lhs.empty?
add_prod_datum(:query, SPARQL::Algebra::Expression.for(:join, lhs, *data[:query]))
elsif data[:minus]
add_prod_datum(:query, SPARQL::Algebra::Expression.for(:minus, lhs, *data[:minus]))
elsif data[:query]
add_prod_datum(:query, data[:query])
else
add_prod_datum(:query, lhs)
end
end
# [57] OptionalGraphPattern ::= 'OPTIONAL' GroupGraphPattern
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:OptionalGraphPattern) do |input, data, callback|
expr = nil
query = data[:query] ? data[:query].first : SPARQL::Algebra::Operator::BGP.new
if query.is_a?(SPARQL::Algebra::Operator::Filter)
# Change to expression on left-join with query element
expr, query = query.operands
add_prod_data(:leftjoin, query, expr)
elsif !query.empty?
add_prod_data(:leftjoin, query)
end
end
# [58] GraphGraphPattern ::= 'GRAPH' VarOrIri GroupGraphPattern
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:GraphGraphPattern) do |input, data, callback|
name = (data[:VarOrIri]).last
bgp = data[:query] ? data[:query].first : SPARQL::Algebra::Operator::BGP.new
if name
add_prod_data(:query, SPARQL::Algebra::Expression.for(:graph, name, bgp))
else
add_prod_data(:query, bgp)
end
end
# [59] ServiceGraphPattern ::= 'SERVICE' 'SILENT'? VarOrIri GroupGraphPattern
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:ServiceGraphPattern) do |input, data, callback|
args = []
args << :silent if data[:silent]
args << (data[:VarOrIri]).last
args << data.fetch(:query, [SPARQL::Algebra::Operator::BGP.new]).first
service = SPARQL::Algebra::Expression.for(:service, *args)
add_prod_data(:query, service)
end
# [60] Bind ::= 'BIND' '(' Expression 'AS' Var ')'
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:Bind) do |input, data, callback|
add_prod_datum :extend, [data[:Expression].unshift(data[:Var].first)]
end
# [61] InlineData ::= 'VALUES' DataBlock
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:InlineData) do |input, data, callback|
debug("InlineData") {"vars: #{data[:Var].inspect}, row: #{data[:row].inspect}"}
add_prod_datum :query, SPARQL::Algebra::Expression.for(:table,
Array(data[:Var]).unshift(:vars),
*data[:row]
)
end
# [63] InlineDataOneVar ::= Var '{' DataBlockValue* '}'
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:InlineDataOneVar) do |input, data, callback|
add_prod_datum :Var, data[:Var]
Array(data[:DataBlockValue]).each do |d|
add_prod_datum :row, [[:row, data[:Var].dup << d]]
end
end
# [64] InlineDataFull ::= ( NIL | '(' Var* ')' )
# '{' ( '(' DataBlockValue* ')' | NIL )* '}'
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:InlineDataFull) do |input, data, callback|
vars = data[:Var]
add_prod_datum :Var, vars
if data[:nilrow]
add_prod_data :row, [:row]
else
Array(data[:rowdata]).each do |ds|
if ds.length < data[:Var].length
raise Error, "Too few values in a VALUE clause compared to the number of variables"
elsif ds.length > data[:Var].length
raise Error, "Too many values in a VALUE clause compared to the number of variables"
end
r = [:row]
ds.each_with_index do |d, i|
r << [vars[i], d] if d
end
add_prod_data :row, r unless r.empty?
end
end
end
# _InlineDataFull_6 ::= '(' '(' DataBlockValue* ')' | NIL ')'
#
# Input from `data` is TODO.
# Output to prod_data is TODO.
production(:_InlineDataFull_6) do |input, data, callback|
if data[:DataBlockValue]
add_prod_data :rowdata, data[:DataBlockValue].map {|v| v unless v == :undef}
else
input[:nilrow] = true
end