1#![allow(clippy::ignored_unit_patterns)]
2use crate::algebra::*;
3use crate::query::*;
4use crate::term::*;
5use crate::update::*;
6use oxilangtag::LanguageTag;
7use oxiri::{Iri, IriParseError};
8use oxrdf::vocab::{rdf, xsd};
9use peg::parser;
10use peg::str::LineCol;
11use rand::random;
12use std::char;
13use std::collections::{HashMap, HashSet};
14use std::mem::take;
15use std::str::FromStr;
16
17pub fn parse_query(query: &str, base_iri: Option<&str>) -> Result<Query, SparqlSyntaxError> {
19 let mut state = ParserState::from_base_iri(base_iri)?;
20 parser::QueryUnit(query, &mut state).map_err(|e| SparqlSyntaxError(ParseErrorKind::Syntax(e)))
21}
22
23pub fn parse_update(update: &str, base_iri: Option<&str>) -> Result<Update, SparqlSyntaxError> {
25 let mut state = ParserState::from_base_iri(base_iri)?;
26 let operations = parser::UpdateInit(update, &mut state)
27 .map_err(|e| SparqlSyntaxError(ParseErrorKind::Syntax(e)))?;
28 Ok(Update {
29 operations,
30 base_iri: state.base_iri,
31 })
32}
33
34#[derive(Debug, thiserror::Error)]
36#[error(transparent)]
37pub struct SparqlSyntaxError(#[from] ParseErrorKind);
38
39#[derive(Debug, thiserror::Error)]
40enum ParseErrorKind {
41 #[error("Invalid SPARQL base IRI provided: {0}")]
42 InvalidBaseIri(#[from] IriParseError),
43 #[error(transparent)]
44 Syntax(#[from] peg::error::ParseError<LineCol>),
45}
46
47struct AnnotatedTerm {
48 term: TermPattern,
49 annotations: Vec<(NamedNodePattern, Vec<AnnotatedTerm>)>,
50}
51
52#[derive(Default)]
53struct FocusedTriplePattern<F> {
54 focus: F,
55 patterns: Vec<TriplePattern>,
56}
57
58impl<F> FocusedTriplePattern<F> {
59 fn new(focus: F) -> Self {
60 Self {
61 focus,
62 patterns: Vec::new(),
63 }
64 }
65}
66
67impl<F> From<FocusedTriplePattern<F>> for FocusedTriplePattern<Vec<F>> {
68 fn from(input: FocusedTriplePattern<F>) -> Self {
69 Self {
70 focus: vec![input.focus],
71 patterns: input.patterns,
72 }
73 }
74}
75
76#[derive(Clone, Debug)]
77enum VariableOrPropertyPath {
78 Variable(Variable),
79 PropertyPath(PropertyPathExpression),
80}
81
82impl From<Variable> for VariableOrPropertyPath {
83 fn from(var: Variable) -> Self {
84 Self::Variable(var)
85 }
86}
87
88impl From<NamedNodePattern> for VariableOrPropertyPath {
89 fn from(pattern: NamedNodePattern) -> Self {
90 match pattern {
91 NamedNodePattern::NamedNode(node) => PropertyPathExpression::from(node).into(),
92 NamedNodePattern::Variable(v) => v.into(),
93 }
94 }
95}
96
97impl From<PropertyPathExpression> for VariableOrPropertyPath {
98 fn from(path: PropertyPathExpression) -> Self {
99 Self::PropertyPath(path)
100 }
101}
102
103fn add_to_triple_patterns(
104 subject: TermPattern,
105 predicate: NamedNodePattern,
106 object: AnnotatedTerm,
107 patterns: &mut Vec<TriplePattern>,
108) -> Result<(), &'static str> {
109 let triple = TriplePattern::new(subject, predicate, object.term);
110 #[cfg(feature = "rdf-star")]
111 for (p, os) in object.annotations {
112 for o in os {
113 add_to_triple_patterns(triple.clone().into(), p.clone(), o, patterns)?
114 }
115 }
116 #[cfg(not(feature = "rdf-star"))]
117 if !object.annotations.is_empty() {
118 return Err("Embedded triples are only available in SPARQL-star");
119 }
120 patterns.push(triple);
121 Ok(())
122}
123
124fn add_to_triple_or_path_patterns(
125 subject: TermPattern,
126 predicate: impl Into<VariableOrPropertyPath>,
127 object: AnnotatedTermPath,
128 patterns: &mut Vec<TripleOrPathPattern>,
129) -> Result<(), &'static str> {
130 match predicate.into() {
131 VariableOrPropertyPath::Variable(p) => {
132 add_triple_to_triple_or_path_patterns(subject, p, object, patterns)?;
133 }
134 VariableOrPropertyPath::PropertyPath(p) => match p {
135 PropertyPathExpression::NamedNode(p) => {
136 add_triple_to_triple_or_path_patterns(subject, p, object, patterns)?;
137 }
138 PropertyPathExpression::Reverse(p) => add_to_triple_or_path_patterns(
139 object.term,
140 *p,
141 AnnotatedTermPath {
142 term: subject,
143 annotations: object.annotations,
144 },
145 patterns,
146 )?,
147 PropertyPathExpression::Sequence(a, b) => {
148 if !object.annotations.is_empty() {
149 return Err("Annotations are not allowed on property paths");
150 }
151 let middle = BlankNode::default();
152 add_to_triple_or_path_patterns(
153 subject,
154 *a,
155 AnnotatedTermPath {
156 term: middle.clone().into(),
157 annotations: Vec::new(),
158 },
159 patterns,
160 )?;
161 add_to_triple_or_path_patterns(
162 middle.into(),
163 *b,
164 AnnotatedTermPath {
165 term: object.term,
166 annotations: Vec::new(),
167 },
168 patterns,
169 )?;
170 }
171 path => {
172 if !object.annotations.is_empty() {
173 return Err("Annotations are not allowed on property paths");
174 }
175 patterns.push(TripleOrPathPattern::Path {
176 subject,
177 path,
178 object: object.term,
179 })
180 }
181 },
182 }
183 Ok(())
184}
185
186fn add_triple_to_triple_or_path_patterns(
187 subject: TermPattern,
188 predicate: impl Into<NamedNodePattern>,
189 object: AnnotatedTermPath,
190 patterns: &mut Vec<TripleOrPathPattern>,
191) -> Result<(), &'static str> {
192 let triple = TriplePattern::new(subject, predicate, object.term);
193 #[cfg(feature = "rdf-star")]
194 for (p, os) in object.annotations {
195 for o in os {
196 add_to_triple_or_path_patterns(triple.clone().into(), p.clone(), o, patterns)?
197 }
198 }
199 #[cfg(not(feature = "rdf-star"))]
200 if !object.annotations.is_empty() {
201 return Err("Embedded triples are only available in SPARQL-star");
202 }
203 patterns.push(triple.into());
204 Ok(())
205}
206
207fn build_bgp(patterns: Vec<TripleOrPathPattern>) -> GraphPattern {
208 let mut bgp = Vec::new();
209 let mut elements = Vec::with_capacity(patterns.len());
210 for pattern in patterns {
211 match pattern {
212 TripleOrPathPattern::Triple(t) => bgp.push(t),
213 TripleOrPathPattern::Path {
214 subject,
215 path,
216 object,
217 } => {
218 if !bgp.is_empty() {
219 elements.push(GraphPattern::Bgp {
220 patterns: take(&mut bgp),
221 });
222 }
223 elements.push(GraphPattern::Path {
224 subject,
225 path,
226 object,
227 })
228 }
229 }
230 }
231 if !bgp.is_empty() {
232 elements.push(GraphPattern::Bgp { patterns: bgp });
233 }
234 elements.into_iter().reduce(new_join).unwrap_or_default()
235}
236
237#[derive(Debug)]
238enum TripleOrPathPattern {
239 Triple(TriplePattern),
240 Path {
241 subject: TermPattern,
242 path: PropertyPathExpression,
243 object: TermPattern,
244 },
245}
246
247impl From<TriplePattern> for TripleOrPathPattern {
248 fn from(tp: TriplePattern) -> Self {
249 Self::Triple(tp)
250 }
251}
252
253#[derive(Debug)]
254struct AnnotatedTermPath {
255 term: TermPattern,
256 annotations: Vec<(VariableOrPropertyPath, Vec<AnnotatedTermPath>)>,
257}
258
259impl From<AnnotatedTerm> for AnnotatedTermPath {
260 fn from(term: AnnotatedTerm) -> Self {
261 Self {
262 term: term.term,
263 annotations: term
264 .annotations
265 .into_iter()
266 .map(|(p, o)| (p.into(), o.into_iter().map(Self::from).collect()))
267 .collect(),
268 }
269 }
270}
271
272#[derive(Debug, Default)]
273struct FocusedTripleOrPathPattern<F> {
274 focus: F,
275 patterns: Vec<TripleOrPathPattern>,
276}
277
278impl<F> FocusedTripleOrPathPattern<F> {
279 fn new(focus: F) -> Self {
280 Self {
281 focus,
282 patterns: Vec::new(),
283 }
284 }
285}
286
287impl<F> From<FocusedTripleOrPathPattern<F>> for FocusedTripleOrPathPattern<Vec<F>> {
288 fn from(input: FocusedTripleOrPathPattern<F>) -> Self {
289 Self {
290 focus: vec![input.focus],
291 patterns: input.patterns,
292 }
293 }
294}
295
296impl<F, T: From<F>> From<FocusedTriplePattern<F>> for FocusedTripleOrPathPattern<T> {
297 fn from(input: FocusedTriplePattern<F>) -> Self {
298 Self {
299 focus: input.focus.into(),
300 patterns: input.patterns.into_iter().map(Into::into).collect(),
301 }
302 }
303}
304
305#[derive(Eq, PartialEq, Debug, Clone, Hash)]
306enum PartialGraphPattern {
307 Optional(GraphPattern, Option<Expression>),
308 #[cfg(feature = "sep-0006")]
309 Lateral(GraphPattern),
310 Minus(GraphPattern),
311 Bind(Expression, Variable),
312 Filter(Expression),
313 Other(GraphPattern),
314}
315
316fn new_join(l: GraphPattern, r: GraphPattern) -> GraphPattern {
317 if let GraphPattern::Bgp { patterns: pl } = &l {
319 if pl.is_empty() {
320 return r;
321 }
322 }
323 if let GraphPattern::Bgp { patterns: pr } = &r {
324 if pr.is_empty() {
325 return l;
326 }
327 }
328
329 match (l, r) {
330 (GraphPattern::Bgp { patterns: mut pl }, GraphPattern::Bgp { patterns: pr }) => {
331 pl.extend(pr);
332 GraphPattern::Bgp { patterns: pl }
333 }
334 (GraphPattern::Bgp { patterns }, other) | (other, GraphPattern::Bgp { patterns })
335 if patterns.is_empty() =>
336 {
337 other
338 }
339 (l, r) => GraphPattern::Join {
340 left: Box::new(l),
341 right: Box::new(r),
342 },
343 }
344}
345
346fn not_empty_fold<T>(
347 iter: impl Iterator<Item = T>,
348 combine: impl Fn(T, T) -> T,
349) -> Result<T, &'static str> {
350 iter.fold(None, |a, b| match a {
351 Some(av) => Some(combine(av, b)),
352 None => Some(b),
353 })
354 .ok_or("The iterator should not be empty")
355}
356
357enum SelectionOption {
358 Distinct,
359 Reduced,
360 Default,
361}
362
363enum SelectionMember {
364 Variable(Variable),
365 Expression(Expression, Variable),
366}
367
368enum SelectionVariables {
369 Explicit(Vec<SelectionMember>),
370 Star,
371 Everything,
372}
373
374struct Selection {
375 pub option: SelectionOption,
376 pub variables: SelectionVariables,
377}
378
379impl Selection {
380 fn no_op() -> Self {
381 Self {
382 option: SelectionOption::Default,
383 variables: SelectionVariables::Everything,
384 }
385 }
386}
387
388fn build_select(
389 select: Selection,
390 r#where: GraphPattern,
391 mut group: Option<(Vec<Variable>, Vec<(Expression, Variable)>)>,
392 having: Option<Expression>,
393 order_by: Option<Vec<OrderExpression>>,
394 offset_limit: Option<(usize, Option<usize>)>,
395 values: Option<GraphPattern>,
396 state: &mut ParserState,
397) -> Result<GraphPattern, &'static str> {
398 let mut p = r#where;
399 let mut with_aggregate = false;
400
401 let aggregates = state.aggregates.pop().unwrap_or_default();
403 if group.is_none() && !aggregates.is_empty() {
404 group = Some((vec![], vec![]));
405 }
406
407 if let Some((clauses, binds)) = group {
408 for (expression, variable) in binds {
409 p = GraphPattern::Extend {
410 inner: Box::new(p),
411 variable,
412 expression,
413 };
414 }
415 p = GraphPattern::Group {
416 inner: Box::new(p),
417 variables: clauses,
418 aggregates,
419 };
420 with_aggregate = true;
421 }
422
423 if let Some(expr) = having {
425 p = GraphPattern::Filter {
426 expr,
427 inner: Box::new(p),
428 };
429 }
430
431 if let Some(data) = values {
433 p = new_join(p, data);
434 }
435
436 let mut pv = Vec::new();
438 let with_project = match select.variables {
439 SelectionVariables::Explicit(sel_items) => {
440 let mut visible = HashSet::new();
441 p.on_in_scope_variable(|v| {
442 visible.insert(v.clone());
443 });
444 for sel_item in sel_items {
445 let v = match sel_item {
446 SelectionMember::Variable(v) => {
447 if with_aggregate && !visible.contains(&v) {
448 return Err("The SELECT contains a variable that is unbound");
450 }
451 v
452 }
453 SelectionMember::Expression(expression, variable) => {
454 if visible.contains(&variable) {
455 return Err(
457 "The SELECT overrides an existing variable using an expression",
458 );
459 }
460 if with_aggregate && !are_variables_bound(&expression, &visible) {
461 return Err(
463 "The SELECT contains an expression with a variable that is unbound",
464 );
465 }
466 p = GraphPattern::Extend {
467 inner: Box::new(p),
468 variable: variable.clone(),
469 expression,
470 };
471 variable
472 }
473 };
474 if pv.contains(&v) {
475 return Err("Duplicated variable name in SELECT");
476 }
477 pv.push(v)
478 }
479 true
480 }
481 SelectionVariables::Star => {
482 if with_aggregate {
483 return Err("SELECT * is not authorized with GROUP BY");
484 }
485 p.on_in_scope_variable(|v| {
487 if !pv.contains(v) {
488 pv.push(v.clone());
489 }
490 });
491 pv.sort();
492 true
493 }
494 SelectionVariables::Everything => false,
495 };
496
497 let mut m = p;
498
499 if let Some(expression) = order_by {
501 m = GraphPattern::OrderBy {
502 inner: Box::new(m),
503 expression,
504 };
505 }
506
507 if with_project {
509 m = GraphPattern::Project {
510 inner: Box::new(m),
511 variables: pv,
512 };
513 }
514 match select.option {
515 SelectionOption::Distinct => m = GraphPattern::Distinct { inner: Box::new(m) },
516 SelectionOption::Reduced => m = GraphPattern::Reduced { inner: Box::new(m) },
517 SelectionOption::Default => (),
518 }
519
520 if let Some((start, length)) = offset_limit {
522 m = GraphPattern::Slice {
523 inner: Box::new(m),
524 start,
525 length,
526 }
527 }
528 Ok(m)
529}
530
531fn are_variables_bound(expression: &Expression, variables: &HashSet<Variable>) -> bool {
532 match expression {
533 Expression::NamedNode(_)
534 | Expression::Literal(_)
535 | Expression::Bound(_)
536 | Expression::Coalesce(_)
537 | Expression::Exists(_) => true,
538 Expression::Variable(var) => variables.contains(var),
539 Expression::UnaryPlus(e) | Expression::UnaryMinus(e) | Expression::Not(e) => {
540 are_variables_bound(e, variables)
541 }
542 Expression::Or(a, b)
543 | Expression::And(a, b)
544 | Expression::Equal(a, b)
545 | Expression::SameTerm(a, b)
546 | Expression::Greater(a, b)
547 | Expression::GreaterOrEqual(a, b)
548 | Expression::Less(a, b)
549 | Expression::LessOrEqual(a, b)
550 | Expression::Add(a, b)
551 | Expression::Subtract(a, b)
552 | Expression::Multiply(a, b)
553 | Expression::Divide(a, b) => {
554 are_variables_bound(a, variables) && are_variables_bound(b, variables)
555 }
556 Expression::In(a, b) => {
557 are_variables_bound(a, variables) && b.iter().all(|b| are_variables_bound(b, variables))
558 }
559 Expression::FunctionCall(_, parameters) => {
560 parameters.iter().all(|p| are_variables_bound(p, variables))
561 }
562 Expression::If(a, b, c) => {
563 are_variables_bound(a, variables)
564 && are_variables_bound(b, variables)
565 && are_variables_bound(c, variables)
566 }
567 }
568}
569
570#[cfg(feature = "sep-0006")]
572fn add_defined_variables<'a>(pattern: &'a GraphPattern, set: &mut HashSet<&'a Variable>) {
573 match pattern {
574 GraphPattern::Bgp { .. } | GraphPattern::Path { .. } => {}
575 GraphPattern::Join { left, right }
576 | GraphPattern::LeftJoin { left, right, .. }
577 | GraphPattern::Lateral { left, right }
578 | GraphPattern::Union { left, right }
579 | GraphPattern::Minus { left, right } => {
580 add_defined_variables(left, set);
581 add_defined_variables(right, set);
582 }
583 GraphPattern::Graph { inner, .. } => {
584 add_defined_variables(inner, set);
585 }
586 GraphPattern::Extend {
587 inner, variable, ..
588 } => {
589 set.insert(variable);
590 add_defined_variables(inner, set);
591 }
592 GraphPattern::Group {
593 variables,
594 aggregates,
595 inner,
596 } => {
597 for (v, _) in aggregates {
598 set.insert(v);
599 }
600 let mut inner_variables = HashSet::new();
601 add_defined_variables(inner, &mut inner_variables);
602 for v in inner_variables {
603 if variables.contains(v) {
604 set.insert(v);
605 }
606 }
607 }
608 GraphPattern::Values { variables, .. } => {
609 for v in variables {
610 set.insert(v);
611 }
612 }
613 GraphPattern::Project { variables, inner } => {
614 let mut inner_variables = HashSet::new();
615 add_defined_variables(inner, &mut inner_variables);
616 for v in inner_variables {
617 if variables.contains(v) {
618 set.insert(v);
619 }
620 }
621 }
622 GraphPattern::Service { inner, .. }
623 | GraphPattern::Filter { inner, .. }
624 | GraphPattern::OrderBy { inner, .. }
625 | GraphPattern::Distinct { inner }
626 | GraphPattern::Reduced { inner }
627 | GraphPattern::Slice { inner, .. } => add_defined_variables(inner, set),
628 }
629}
630
631fn copy_graph(from: impl Into<GraphName>, to: impl Into<GraphNamePattern>) -> GraphUpdateOperation {
632 let bgp = GraphPattern::Bgp {
633 patterns: vec![TriplePattern::new(
634 Variable::new_unchecked("s"),
635 Variable::new_unchecked("p"),
636 Variable::new_unchecked("o"),
637 )],
638 };
639 GraphUpdateOperation::DeleteInsert {
640 delete: Vec::new(),
641 insert: vec![QuadPattern::new(
642 Variable::new_unchecked("s"),
643 Variable::new_unchecked("p"),
644 Variable::new_unchecked("o"),
645 to,
646 )],
647 using: None,
648 pattern: Box::new(match from.into() {
649 GraphName::NamedNode(from) => GraphPattern::Graph {
650 name: from.into(),
651 inner: Box::new(bgp),
652 },
653 GraphName::DefaultGraph => bgp,
654 }),
655 }
656}
657
658enum Either<L, R> {
659 Left(L),
660 Right(R),
661}
662
663pub struct ParserState {
664 base_iri: Option<Iri<String>>,
665 prefixes: HashMap<String, String>,
666 used_bnodes: HashSet<BlankNode>,
667 currently_used_bnodes: HashSet<BlankNode>,
668 aggregates: Vec<Vec<(Variable, AggregateExpression)>>,
669}
670
671impl ParserState {
672 pub(crate) fn from_base_iri(base_iri: Option<&str>) -> Result<Self, SparqlSyntaxError> {
673 Ok(Self {
674 base_iri: if let Some(base_iri) = base_iri {
675 Some(
676 Iri::parse(base_iri.to_owned())
677 .map_err(|e| SparqlSyntaxError(ParseErrorKind::InvalidBaseIri(e)))?,
678 )
679 } else {
680 None
681 },
682 prefixes: HashMap::new(),
683 used_bnodes: HashSet::new(),
684 currently_used_bnodes: HashSet::new(),
685 aggregates: Vec::new(),
686 })
687 }
688
689 fn parse_iri(&self, iri: String) -> Result<Iri<String>, IriParseError> {
690 if let Some(base_iri) = &self.base_iri {
691 base_iri.resolve(&iri)
692 } else {
693 Iri::parse(iri)
694 }
695 }
696
697 fn new_aggregation(&mut self, agg: AggregateExpression) -> Result<Variable, &'static str> {
698 let aggregates = self.aggregates.last_mut().ok_or("Unexpected aggregate")?;
699 Ok(aggregates
700 .iter()
701 .find_map(|(v, a)| (a == &agg).then_some(v))
702 .cloned()
703 .unwrap_or_else(|| {
704 let new_var = variable();
705 aggregates.push((new_var.clone(), agg));
706 new_var
707 }))
708 }
709}
710
711fn unescape_iriref(mut input: &str) -> Result<String, &'static str> {
712 let mut output = String::with_capacity(input.len());
713 while let Some((before, after)) = input.split_once('\\') {
714 output.push_str(before);
715 let mut after = after.chars();
716 let (escape, after) = match after.next() {
717 Some('u') => read_hex_char::<4>(after.as_str())?,
718 Some('U') => read_hex_char::<8>(after.as_str())?,
719 Some(_) => {
720 return Err(
721 "IRIs are only allowed to contain escape sequences \\uXXXX and \\UXXXXXXXX",
722 )
723 }
724 None => return Err("IRIs are not allowed to end with a '\'"),
725 };
726 output.push(escape);
727 input = after;
728 }
729 output.push_str(input);
730 Ok(output)
731}
732
733fn unescape_string(mut input: &str) -> Result<String, &'static str> {
734 let mut output = String::with_capacity(input.len());
735 while let Some((before, after)) = input.split_once('\\') {
736 output.push_str(before);
737 let mut after = after.chars();
738 let (escape, after) = match after.next() {
739 Some('t') => ('\u{0009}', after.as_str()),
740 Some('b') => ('\u{0008}', after.as_str()),
741 Some('n') => ('\u{000A}', after.as_str()),
742 Some('r') => ('\u{000D}', after.as_str()),
743 Some('f') => ('\u{000C}', after.as_str()),
744 Some('"') => ('\u{0022}', after.as_str()),
745 Some('\'') => ('\u{0027}', after.as_str()),
746 Some('\\') => ('\u{005C}', after.as_str()),
747 Some('u') => read_hex_char::<4>(after.as_str())?,
748 Some('U') => read_hex_char::<8>(after.as_str())?,
749 Some(_) => return Err("The character that can be escaped in strings are tbnrf\"'\\"),
750 None => return Err("strings are not allowed to end with a '\'"),
751 };
752 output.push(escape);
753 input = after;
754 }
755 output.push_str(input);
756 Ok(output)
757}
758
759fn read_hex_char<const SIZE: usize>(input: &str) -> Result<(char, &str), &'static str> {
760 if let Some(escape) = input.get(..SIZE) {
761 if let Some(char) = u32::from_str_radix(escape, 16)
762 .ok()
763 .and_then(char::from_u32)
764 {
765 Ok((char, &input[SIZE..]))
766 } else {
767 Err("\\u escape sequence should be followed by hexadecimal digits")
768 }
769 } else {
770 Err("\\u escape sequence should be followed by hexadecimal digits")
771 }
772}
773
774fn variable() -> Variable {
775 Variable::new_unchecked(format!("{:x}", random::<u128>()))
776}
777
778parser! {
779 grammar parser(state: &mut ParserState) for str {
781 pub rule QueryUnit() -> Query = Query()
782
783 rule Query() -> Query = _ Prologue() _ q:(SelectQuery() / ConstructQuery() / DescribeQuery() / AskQuery()) _ {
784 q
785 }
786
787 pub rule UpdateInit() -> Vec<GraphUpdateOperation> = Update()
788
789 rule Prologue() = (BaseDecl() _ / PrefixDecl() _)* {}
790
791 rule BaseDecl() = i("BASE") _ i:IRIREF() {
792 state.base_iri = Some(i)
793 }
794
795 rule PrefixDecl() = i("PREFIX") _ ns:PNAME_NS() _ i:IRIREF() {
796 state.prefixes.insert(ns.into(), i.into_inner());
797 }
798
799 rule SelectQuery() -> Query = s:SelectClause() _ d:DatasetClauses() _ w:WhereClause() _ g:GroupClause()? _ h:HavingClause()? _ o:OrderClause()? _ l:LimitOffsetClauses()? _ v:ValuesClause() {?
800 Ok(Query::Select {
801 dataset: d,
802 pattern: build_select(s, w, g, h, o, l, v, state)?,
803 base_iri: state.base_iri.clone()
804 })
805 }
806
807 rule SubSelect() -> GraphPattern = s:SelectClause() _ w:WhereClause() _ g:GroupClause()? _ h:HavingClause()? _ o:OrderClause()? _ l:LimitOffsetClauses()? _ v:ValuesClause() {?
808 build_select(s, w, g, h, o, l, v, state)
809 }
810
811 rule SelectClause() -> Selection = i("SELECT") _ Selection_init() o:SelectClause_option() _ v:SelectClause_variables() {
812 Selection {
813 option: o,
814 variables: v
815 }
816 }
817 rule Selection_init() = {
818 state.aggregates.push(Vec::new())
819 }
820 rule SelectClause_option() -> SelectionOption =
821 i("DISTINCT") { SelectionOption::Distinct } /
822 i("REDUCED") { SelectionOption::Reduced } /
823 { SelectionOption::Default }
824 rule SelectClause_variables() -> SelectionVariables =
825 "*" { SelectionVariables::Star } /
826 p:SelectClause_member()+ { SelectionVariables::Explicit(p) }
827 rule SelectClause_member() -> SelectionMember =
828 v:Var() _ { SelectionMember::Variable(v) } /
829 "(" _ e:Expression() _ i("AS") _ v:Var() _ ")" _ { SelectionMember::Expression(e, v) }
830
831 rule ConstructQuery() -> Query =
832 i("CONSTRUCT") _ c:ConstructTemplate() _ d:DatasetClauses() _ w:WhereClause() _ g:GroupClause()? _ h:HavingClause()? _ o:OrderClause()? _ l:LimitOffsetClauses()? _ v:ValuesClause() {?
833 Ok(Query::Construct {
834 template: c,
835 dataset: d,
836 pattern: build_select(Selection::no_op(), w, g, h, o, l, v, state)?,
837 base_iri: state.base_iri.clone()
838 })
839 } /
840 i("CONSTRUCT") _ d:DatasetClauses() _ i("WHERE") _ "{" _ c:ConstructQuery_optional_triple_template() _ "}" _ g:GroupClause()? _ h:HavingClause()? _ o:OrderClause()? _ l:LimitOffsetClauses()? _ v:ValuesClause() {?
841 Ok(Query::Construct {
842 template: c.clone(),
843 dataset: d,
844 pattern: build_select(
845 Selection::no_op(),
846 GraphPattern::Bgp { patterns: c },
847 g, h, o, l, v, state
848 )?,
849 base_iri: state.base_iri.clone()
850 })
851 }
852
853 rule ConstructQuery_optional_triple_template() -> Vec<TriplePattern> = TriplesTemplate() / { Vec::new() }
854
855 rule DescribeQuery() -> Query =
856 i("DESCRIBE") _ "*" _ d:DatasetClauses() _ w:WhereClause()? _ g:GroupClause()? _ h:HavingClause()? _ o:OrderClause()? _ l:LimitOffsetClauses()? _ v:ValuesClause() {?
857 Ok(Query::Describe {
858 dataset: d,
859 pattern: build_select(Selection::no_op(), w.unwrap_or_default(), g, h, o, l, v, state)?,
860 base_iri: state.base_iri.clone()
861 })
862 } /
863 i("DESCRIBE") _ p:DescribeQuery_item()+ _ d:DatasetClauses() _ w:WhereClause()? _ g:GroupClause()? _ h:HavingClause()? _ o:OrderClause()? _ l:LimitOffsetClauses()? _ v:ValuesClause() {?
864 Ok(Query::Describe {
865 dataset: d,
866 pattern: build_select(Selection {
867 option: SelectionOption::Default,
868 variables: SelectionVariables::Explicit(p.into_iter().map(|var_or_iri| match var_or_iri {
869 NamedNodePattern::NamedNode(n) => SelectionMember::Expression(n.into(), variable()),
870 NamedNodePattern::Variable(v) => SelectionMember::Variable(v)
871 }).collect())
872 }, w.unwrap_or_default(), g, h, o, l, v, state)?,
873 base_iri: state.base_iri.clone()
874 })
875 }
876 rule DescribeQuery_item() -> NamedNodePattern = i:VarOrIri() _ { i }
877
878 rule AskQuery() -> Query = i("ASK") _ d:DatasetClauses() _ w:WhereClause() _ g:GroupClause()? _ h:HavingClause()? _ o:OrderClause()? _ l:LimitOffsetClauses()? _ v:ValuesClause() {?
879 Ok(Query::Ask {
880 dataset: d,
881 pattern: build_select(Selection::no_op(), w, g, h, o, l, v, state)?,
882 base_iri: state.base_iri.clone()
883 })
884 }
885
886 rule DatasetClause() -> (Option<NamedNode>, Option<NamedNode>) = i("FROM") _ d:(DefaultGraphClause() / NamedGraphClause()) { d }
887 rule DatasetClauses() -> Option<QueryDataset> = d:DatasetClause() ** (_) {
888 if d.is_empty() {
889 return None;
890 }
891 let mut default = Vec::new();
892 let mut named = Vec::new();
893 for (d, n) in d {
894 if let Some(d) = d {
895 default.push(d);
896 }
897 if let Some(n) = n {
898 named.push(n);
899 }
900 }
901 Some(QueryDataset {
902 default, named: Some(named)
903 })
904 }
905
906 rule DefaultGraphClause() -> (Option<NamedNode>, Option<NamedNode>) = s:SourceSelector() {
907 (Some(s), None)
908 }
909
910 rule NamedGraphClause() -> (Option<NamedNode>, Option<NamedNode>) = i("NAMED") _ s:SourceSelector() {
911 (None, Some(s))
912 }
913
914 rule SourceSelector() -> NamedNode = iri()
915
916 rule WhereClause() -> GraphPattern = i("WHERE")? _ p:GroupGraphPattern() {
917 p
918 }
919
920 rule GroupClause() -> (Vec<Variable>, Vec<(Expression,Variable)>) = i("GROUP") _ i("BY") _ c:GroupCondition_item()+ {
921 let mut projections: Vec<(Expression,Variable)> = Vec::new();
922 let clauses = c.into_iter().map(|(e, vo)| {
923 if let Expression::Variable(v) = e {
924 v
925 } else {
926 let v = vo.unwrap_or_else(variable);
927 projections.push((e, v.clone()));
928 v
929 }
930 }).collect();
931 (clauses, projections)
932 }
933 rule GroupCondition_item() -> (Expression, Option<Variable>) = c:GroupCondition() _ { c }
934
935 rule GroupCondition() -> (Expression, Option<Variable>) =
936 e:BuiltInCall() { (e, None) } /
937 e:FunctionCall() { (e, None) } /
938 "(" _ e:Expression() _ v:GroupCondition_as()? ")" { (e, v) } /
939 e:Var() { (e.into(), None) }
940 rule GroupCondition_as() -> Variable = i("AS") _ v:Var() _ { v }
941
942 rule HavingClause() -> Expression = i("HAVING") _ e:HavingCondition()+ {?
943 not_empty_fold(e.into_iter(), |a, b| Expression::And(Box::new(a), Box::new(b)))
944 }
945
946 rule HavingCondition() -> Expression = Constraint()
947
948 rule OrderClause() -> Vec<OrderExpression> = i("ORDER") _ i("BY") _ c:OrderClause_item()+ { c }
949 rule OrderClause_item() -> OrderExpression = c:OrderCondition() _ { c }
950
951 rule OrderCondition() -> OrderExpression =
952 i("ASC") _ e: BrackettedExpression() { OrderExpression::Asc(e) } /
953 i("DESC") _ e: BrackettedExpression() { OrderExpression::Desc(e) } /
954 e: Constraint() { OrderExpression::Asc(e) } /
955 v: Var() { OrderExpression::Asc(Expression::from(v)) }
956
957 rule LimitOffsetClauses() -> (usize, Option<usize>) =
958 l:LimitClause() _ o:OffsetClause()? { (o.unwrap_or(0), Some(l)) } /
959 o:OffsetClause() _ l:LimitClause()? { (o, l) }
960
961 rule LimitClause() -> usize = i("LIMIT") _ l:$(INTEGER()) {?
962 usize::from_str(l).map_err(|_| "The query limit should be a non negative integer")
963 }
964
965 rule OffsetClause() -> usize = i("OFFSET") _ o:$(INTEGER()) {?
966 usize::from_str(o).map_err(|_| "The query offset should be a non negative integer")
967 }
968
969 rule ValuesClause() -> Option<GraphPattern> =
970 i("VALUES") _ p:DataBlock() { Some(p) } /
971 { None }
972
973 rule Update() -> Vec<GraphUpdateOperation> = _ Prologue() _ u:(Update1() ** (_ ";" _)) _ ( ";" _)? { u.into_iter().flatten().collect() }
974
975 rule Update1() -> Vec<GraphUpdateOperation> = Load() / Clear() / Drop() / Add() / Move() / Copy() / Create() / InsertData() / DeleteData() / DeleteWhere() / Modify()
976 rule Update1_silent() -> bool = i("SILENT") { true } / { false }
977
978 rule Load() -> Vec<GraphUpdateOperation> = i("LOAD") _ silent:Update1_silent() _ source:iri() _ destination:Load_to()? {
979 vec![GraphUpdateOperation::Load { silent, source, destination: destination.map_or(GraphName::DefaultGraph, GraphName::NamedNode) }]
980 }
981 rule Load_to() -> NamedNode = i("INTO") _ g: GraphRef() { g }
982
983 rule Clear() -> Vec<GraphUpdateOperation> = i("CLEAR") _ silent:Update1_silent() _ graph:GraphRefAll() {
984 vec![GraphUpdateOperation::Clear { silent, graph }]
985 }
986
987 rule Drop() -> Vec<GraphUpdateOperation> = i("DROP") _ silent:Update1_silent() _ graph:GraphRefAll() {
988 vec![GraphUpdateOperation::Drop { silent, graph }]
989 }
990
991 rule Create() -> Vec<GraphUpdateOperation> = i("CREATE") _ silent:Update1_silent() _ graph:GraphRef() {
992 vec![GraphUpdateOperation::Create { silent, graph }]
993 }
994
995 rule Add() -> Vec<GraphUpdateOperation> = i("ADD") _ silent:Update1_silent() _ from:GraphOrDefault() _ i("TO") _ to:GraphOrDefault() {
996 if from == to {
998 Vec::new() } else {
1000 let bgp = GraphPattern::Bgp { patterns: vec![TriplePattern::new(Variable::new_unchecked("s"), Variable::new_unchecked("p"), Variable::new_unchecked("o"))] };
1001 vec![copy_graph(from, to)]
1002 }
1003 }
1004
1005 rule Move() -> Vec<GraphUpdateOperation> = i("MOVE") _ silent:Update1_silent() _ from:GraphOrDefault() _ i("TO") _ to:GraphOrDefault() {
1006 if from == to {
1008 Vec::new() } else {
1010 let bgp = GraphPattern::Bgp { patterns: vec![TriplePattern::new(Variable::new_unchecked("s"), Variable::new_unchecked("p"), Variable::new_unchecked("o"))] };
1011 vec![GraphUpdateOperation::Drop { silent: true, graph: to.clone().into() }, copy_graph(from.clone(), to), GraphUpdateOperation::Drop { silent, graph: from.into() }]
1012 }
1013 }
1014
1015 rule Copy() -> Vec<GraphUpdateOperation> = i("COPY") _ silent:Update1_silent() _ from:GraphOrDefault() _ i("TO") _ to:GraphOrDefault() {
1016 if from == to {
1018 Vec::new() } else {
1020 let bgp = GraphPattern::Bgp { patterns: vec![TriplePattern::new(Variable::new_unchecked("s"), Variable::new_unchecked("p"), Variable::new_unchecked("o"))] };
1021 vec![GraphUpdateOperation::Drop { silent: true, graph: to.clone().into() }, copy_graph(from, to)]
1022 }
1023 }
1024
1025 rule InsertData() -> Vec<GraphUpdateOperation> = i("INSERT") _ i("DATA") _ data:QuadData() {
1026 vec![GraphUpdateOperation::InsertData { data }]
1027 }
1028
1029 rule DeleteData() -> Vec<GraphUpdateOperation> = i("DELETE") _ i("DATA") _ data:GroundQuadData() {
1030 vec![GraphUpdateOperation::DeleteData { data }]
1031 }
1032
1033 rule DeleteWhere() -> Vec<GraphUpdateOperation> = i("DELETE") _ i("WHERE") _ d:QuadPattern() {?
1034 let pattern = d.iter().map(|q| {
1035 let bgp = GraphPattern::Bgp { patterns: vec![TriplePattern::new(q.subject.clone(), q.predicate.clone(), q.object.clone())] };
1036 match &q.graph_name {
1037 GraphNamePattern::NamedNode(graph_name) => GraphPattern::Graph { name: graph_name.clone().into(), inner: Box::new(bgp) },
1038 GraphNamePattern::DefaultGraph => bgp,
1039 GraphNamePattern::Variable(graph_name) => GraphPattern::Graph { name: graph_name.clone().into(), inner: Box::new(bgp) },
1040 }
1041 }).reduce(new_join).unwrap_or_default();
1042 let delete = d.into_iter().map(GroundQuadPattern::try_from).collect::<Result<Vec<_>,_>>().map_err(|()| "Blank nodes are not allowed in DELETE WHERE")?;
1043 Ok(vec![GraphUpdateOperation::DeleteInsert {
1044 delete,
1045 insert: Vec::new(),
1046 using: None,
1047 pattern: Box::new(pattern)
1048 }])
1049 }
1050
1051 rule Modify() -> Vec<GraphUpdateOperation> = with:Modify_with()? _ Modify_clear() c:Modify_clauses() _ u:(UsingClause() ** (_)) _ i("WHERE") _ pattern:GroupGraphPattern() {
1052 let (delete, insert) = c;
1053 let mut delete = delete.unwrap_or_default();
1054 let mut insert = insert.unwrap_or_default();
1055 #[allow(clippy::shadow_same)]
1056 let mut pattern = pattern;
1057
1058 let mut using = if u.is_empty() {
1059 None
1060 } else {
1061 let mut default = Vec::new();
1062 let mut named = Vec::new();
1063 for (d, n) in u {
1064 if let Some(d) = d {
1065 default.push(d)
1066 }
1067 if let Some(n) = n {
1068 named.push(n)
1069 }
1070 }
1071 Some(QueryDataset { default, named: Some(named) })
1072 };
1073
1074 if let Some(with) = with {
1075 delete = delete.into_iter().map(|q| if q.graph_name == GraphNamePattern::DefaultGraph {
1077 GroundQuadPattern {
1078 subject: q.subject,
1079 predicate: q.predicate,
1080 object: q.object,
1081 graph_name: with.clone().into()
1082 }
1083 } else {
1084 q
1085 }).collect();
1086 insert = insert.into_iter().map(|q| if q.graph_name == GraphNamePattern::DefaultGraph {
1087 QuadPattern {
1088 subject: q.subject,
1089 predicate: q.predicate,
1090 object: q.object,
1091 graph_name: with.clone().into()
1092 }
1093 } else {
1094 q
1095 }).collect();
1096 if using.is_none() {
1097 using = Some(QueryDataset { default: vec![with], named: None });
1098 }
1099 }
1100
1101 vec![GraphUpdateOperation::DeleteInsert {
1102 delete,
1103 insert,
1104 using,
1105 pattern: Box::new(pattern)
1106 }]
1107 }
1108 rule Modify_with() -> NamedNode = i("WITH") _ i:iri() _ { i }
1109 rule Modify_clauses() -> (Option<Vec<GroundQuadPattern>>, Option<Vec<QuadPattern>>) = d:DeleteClause() _ i:InsertClause()? {
1110 (Some(d), i)
1111 } / i:InsertClause() {
1112 (None, Some(i))
1113 }
1114 rule Modify_clear() = {
1115 state.used_bnodes.clear();
1116 state.currently_used_bnodes.clear();
1117 }
1118
1119 rule DeleteClause() -> Vec<GroundQuadPattern> = i("DELETE") _ q:QuadPattern() {?
1120 q.into_iter().map(GroundQuadPattern::try_from).collect::<Result<Vec<_>,_>>().map_err(|()| "Blank nodes are not allowed in DELETE WHERE")
1121 }
1122
1123 rule InsertClause() -> Vec<QuadPattern> = i("INSERT") _ q:QuadPattern() { q }
1124
1125 rule UsingClause() -> (Option<NamedNode>, Option<NamedNode>) = i("USING") _ d:(UsingClause_default() / UsingClause_named()) { d }
1126 rule UsingClause_default() -> (Option<NamedNode>, Option<NamedNode>) = i:iri() {
1127 (Some(i), None)
1128 }
1129 rule UsingClause_named() -> (Option<NamedNode>, Option<NamedNode>) = i("NAMED") _ i:iri() {
1130 (None, Some(i))
1131 }
1132
1133 rule GraphOrDefault() -> GraphName = i("DEFAULT") {
1134 GraphName::DefaultGraph
1135 } / (i("GRAPH") _)? g:iri() {
1136 GraphName::NamedNode(g)
1137 }
1138
1139 rule GraphRef() -> NamedNode = i("GRAPH") _ g:iri() { g }
1140
1141 rule GraphRefAll() -> GraphTarget = i: GraphRef() { i.into() }
1142 / i("DEFAULT") { GraphTarget::DefaultGraph }
1143 / i("NAMED") { GraphTarget::NamedGraphs }
1144 / i("ALL") { GraphTarget::AllGraphs }
1145
1146 rule QuadPattern() -> Vec<QuadPattern> = "{" _ q:Quads() _ "}" { q }
1147
1148 rule QuadData() -> Vec<Quad> = "{" _ q:Quads() _ "}" {?
1149 q.into_iter().map(Quad::try_from).collect::<Result<Vec<_>, ()>>().map_err(|()| "Variables are not allowed in INSERT DATA")
1150 }
1151 rule GroundQuadData() -> Vec<GroundQuad> = "{" _ q:Quads() _ "}" {?
1152 q.into_iter().map(|q| GroundQuad::try_from(Quad::try_from(q)?)).collect::<Result<Vec<_>, ()>>().map_err(|()| "Variables and blank nodes are not allowed in DELETE DATA")
1153 }
1154
1155 rule Quads() -> Vec<QuadPattern> = q:(Quads_TriplesTemplate() / Quads_QuadsNotTriples()) ** (_) {
1156 q.into_iter().flatten().collect()
1157 }
1158 rule Quads_TriplesTemplate() -> Vec<QuadPattern> = t:TriplesTemplate() {
1159 t.into_iter().map(|t| QuadPattern::new(t.subject, t.predicate, t.object, GraphNamePattern::DefaultGraph)).collect()
1160 } rule Quads_QuadsNotTriples() -> Vec<QuadPattern> = q:QuadsNotTriples() _ "."? { q }
1162
1163 rule QuadsNotTriples() -> Vec<QuadPattern> = i("GRAPH") _ g:VarOrIri() _ "{" _ t:TriplesTemplate()? _ "}" {
1164 t.unwrap_or_default().into_iter().map(|t| QuadPattern::new(t.subject, t.predicate, t.object, g.clone())).collect()
1165 }
1166
1167 rule TriplesTemplate() -> Vec<TriplePattern> = ts:TriplesTemplate_inner() ++ (".") ("." _)? {
1168 ts.into_iter().flatten().collect()
1169 }
1170 rule TriplesTemplate_inner() -> Vec<TriplePattern> = _ t:TriplesSameSubject() _ { t }
1171
1172 rule GroupGraphPattern() -> GraphPattern =
1173 "{" _ GroupGraphPattern_clear() p:GroupGraphPatternSub() GroupGraphPattern_clear() _ "}" { p } /
1174 "{" _ GroupGraphPattern_clear() p:SubSelect() GroupGraphPattern_clear() _ "}" { p }
1175 rule GroupGraphPattern_clear() = {
1176 state.used_bnodes.extend(state.currently_used_bnodes.iter().cloned());
1178 state.currently_used_bnodes.clear();
1179 }
1180
1181 rule GroupGraphPatternSub() -> GraphPattern = a:TriplesBlock()? _ b:GroupGraphPatternSub_item()* {?
1182 let mut filter: Option<Expression> = None;
1183 let mut g = a.map_or_else(GraphPattern::default, build_bgp);
1184 for e in b.into_iter().flatten() {
1185 match e {
1186 PartialGraphPattern::Optional(p, f) => {
1187 g = GraphPattern::LeftJoin { left: Box::new(g), right: Box::new(p), expression: f }
1188 }
1189 #[cfg(feature = "sep-0006")]
1190 PartialGraphPattern::Lateral(p) => {
1191 let mut defined_variables = HashSet::new();
1192 add_defined_variables(&p, &mut defined_variables);
1193 let mut contains = false;
1194 g.on_in_scope_variable(|v| {
1195 if defined_variables.contains(v) {
1196 contains = true;
1197 }
1198 });
1199 if contains {
1200 return Err("An existing variable is overridden in the right side of LATERAL");
1201 }
1202 g = GraphPattern::Lateral { left: Box::new(g), right: Box::new(p) }
1203 }
1204 PartialGraphPattern::Minus(p) => {
1205 g = GraphPattern::Minus { left: Box::new(g), right: Box::new(p) }
1206 }
1207 PartialGraphPattern::Bind(expression, variable) => {
1208 let mut contains = false;
1209 g.on_in_scope_variable(|v| {
1210 if *v == variable {
1211 contains = true;
1212 }
1213 });
1214 if contains {
1215 return Err("BIND is overriding an existing variable")
1216 }
1217 g = GraphPattern::Extend { inner: Box::new(g), variable, expression }
1218 }
1219 PartialGraphPattern::Filter(expr) => filter = Some(if let Some(f) = filter {
1220 Expression::And(Box::new(f), Box::new(expr))
1221 } else {
1222 expr
1223 }),
1224 PartialGraphPattern::Other(e) => g = new_join(g, e),
1225 }
1226 }
1227
1228 Ok(if let Some(expr) = filter {
1229 GraphPattern::Filter { expr, inner: Box::new(g) }
1230 } else {
1231 g
1232 })
1233 }
1234 rule GroupGraphPatternSub_item() -> Vec<PartialGraphPattern> = a:GraphPatternNotTriples() _ ("." _)? b:TriplesBlock()? _ {
1235 let mut result = vec![a];
1236 if let Some(v) = b {
1237 result.push(PartialGraphPattern::Other(build_bgp(v)));
1238 }
1239 result
1240 }
1241
1242 rule TriplesBlock() -> Vec<TripleOrPathPattern> = hs:TriplesBlock_inner() ++ (".") ("." _)? {
1243 hs.into_iter().flatten().collect()
1244 }
1245 rule TriplesBlock_inner() -> Vec<TripleOrPathPattern> = _ h:TriplesSameSubjectPath() _ { h }
1246
1247 rule GraphPatternNotTriples() -> PartialGraphPattern = GroupOrUnionGraphPattern() / OptionalGraphPattern() / LateralGraphPattern() / MinusGraphPattern() / GraphGraphPattern() / ServiceGraphPattern() / Filter() / Bind() / InlineData()
1248
1249 rule OptionalGraphPattern() -> PartialGraphPattern = i("OPTIONAL") _ p:GroupGraphPattern() {
1250 if let GraphPattern::Filter { expr, inner } = p {
1251 PartialGraphPattern::Optional(*inner, Some(expr))
1252 } else {
1253 PartialGraphPattern::Optional(p, None)
1254 }
1255 }
1256
1257 rule LateralGraphPattern() -> PartialGraphPattern = i("LATERAL") _ p:GroupGraphPattern() {?
1258 #[cfg(feature = "sep-0006")]{Ok(PartialGraphPattern::Lateral(p))}
1259 #[cfg(not(feature = "sep-0006"))]{Err("The LATERAL modifier is not supported")}
1260 }
1261
1262 rule GraphGraphPattern() -> PartialGraphPattern = i("GRAPH") _ name:VarOrIri() _ p:GroupGraphPattern() {
1263 PartialGraphPattern::Other(GraphPattern::Graph { name, inner: Box::new(p) })
1264 }
1265
1266 rule ServiceGraphPattern() -> PartialGraphPattern =
1267 i("SERVICE") _ i("SILENT") _ name:VarOrIri() _ p:GroupGraphPattern() { PartialGraphPattern::Other(GraphPattern::Service { name, inner: Box::new(p), silent: true }) } /
1268 i("SERVICE") _ name:VarOrIri() _ p:GroupGraphPattern() { PartialGraphPattern::Other(GraphPattern::Service{ name, inner: Box::new(p), silent: false }) }
1269
1270 rule Bind() -> PartialGraphPattern = i("BIND") _ "(" _ e:Expression() _ i("AS") _ v:Var() _ ")" {
1271 PartialGraphPattern::Bind(e, v)
1272 }
1273
1274 rule InlineData() -> PartialGraphPattern = i("VALUES") _ p:DataBlock() { PartialGraphPattern::Other(p) }
1275
1276 rule DataBlock() -> GraphPattern = l:(InlineDataOneVar() / InlineDataFull()) {
1277 GraphPattern::Values { variables: l.0, bindings: l.1 }
1278 }
1279
1280 rule InlineDataOneVar() -> (Vec<Variable>, Vec<Vec<Option<GroundTerm>>>) = var:Var() _ "{" _ d:InlineDataOneVar_value()* "}" {
1281 (vec![var], d)
1282 }
1283 rule InlineDataOneVar_value() -> Vec<Option<GroundTerm>> = t:DataBlockValue() _ { vec![t] }
1284
1285 rule InlineDataFull() -> (Vec<Variable>, Vec<Vec<Option<GroundTerm>>>) = "(" _ vars:InlineDataFull_var()* _ ")" _ "{" _ vals:InlineDataFull_values()* "}" {?
1286 if vals.iter().all(|vs| vs.len() == vars.len()) {
1287 Ok((vars, vals))
1288 } else {
1289 Err("The VALUES clause rows should have exactly the same number of values as there are variables. To set a value to undefined use UNDEF.")
1290 }
1291 }
1292 rule InlineDataFull_var() -> Variable = v:Var() _ { v }
1293 rule InlineDataFull_values() -> Vec<Option<GroundTerm>> = "(" _ v:InlineDataFull_value()* _ ")" _ { v }
1294 rule InlineDataFull_value() -> Option<GroundTerm> = v:DataBlockValue() _ { v }
1295
1296 rule DataBlockValue() -> Option<GroundTerm> =
1297 t:QuotedTripleData() {?
1298 #[cfg(feature = "rdf-star")]{Ok(Some(t.into()))}
1299 #[cfg(not(feature = "rdf-star"))]{Err("Embedded triples are only available in SPARQL-star")}
1300 } /
1301 i:iri() { Some(i.into()) } /
1302 l:RDFLiteral() { Some(l.into()) } /
1303 l:NumericLiteral() { Some(l.into()) } /
1304 l:BooleanLiteral() { Some(l.into()) } /
1305 i("UNDEF") { None }
1306
1307 rule MinusGraphPattern() -> PartialGraphPattern = i("MINUS") _ p: GroupGraphPattern() {
1308 PartialGraphPattern::Minus(p)
1309 }
1310
1311 rule GroupOrUnionGraphPattern() -> PartialGraphPattern = p:GroupOrUnionGraphPattern_item() **<1,> (i("UNION") _) {?
1312 not_empty_fold(p.into_iter(), |a, b| {
1313 GraphPattern::Union { left: Box::new(a), right: Box::new(b) }
1314 }).map(PartialGraphPattern::Other)
1315 }
1316 rule GroupOrUnionGraphPattern_item() -> GraphPattern = p:GroupGraphPattern() _ { p }
1317
1318 rule Filter() -> PartialGraphPattern = i("FILTER") _ c:Constraint() {
1319 PartialGraphPattern::Filter(c)
1320 }
1321
1322 rule Constraint() -> Expression = BrackettedExpression() / FunctionCall() / BuiltInCall()
1323
1324 rule FunctionCall() -> Expression = f: iri() _ a: ArgList() {
1325 Expression::FunctionCall(Function::Custom(f), a)
1326 }
1327
1328 rule ArgList() -> Vec<Expression> =
1329 "(" _ e:ArgList_item() **<1,> ("," _) _ ")" { e } /
1330 NIL() { Vec::new() }
1331 rule ArgList_item() -> Expression = e:Expression() _ { e }
1332
1333 rule ExpressionList() -> Vec<Expression> =
1334 "(" _ e:ExpressionList_item() **<1,> ("," _) ")" { e } /
1335 NIL() { Vec::new() }
1336 rule ExpressionList_item() -> Expression = e:Expression() _ { e }
1337
1338 rule ConstructTemplate() -> Vec<TriplePattern> = "{" _ t:ConstructTriples() _ "}" { t }
1339
1340 rule ConstructTriples() -> Vec<TriplePattern> = p:ConstructTriples_item() ** ("." _) "."? {
1341 p.into_iter().flatten().collect()
1342 }
1343 rule ConstructTriples_item() -> Vec<TriplePattern> = t:TriplesSameSubject() _ { t }
1344
1345 rule TriplesSameSubject() -> Vec<TriplePattern> =
1346 s:VarOrTerm() _ po:PropertyListNotEmpty() {?
1347 let mut patterns = po.patterns;
1348 for (p, os) in po.focus {
1349 for o in os {
1350 add_to_triple_patterns(s.clone(), p.clone(), o, &mut patterns)?
1351 }
1352 }
1353 Ok(patterns)
1354 } /
1355 s:TriplesNode() _ po:PropertyList() {?
1356 let mut patterns = s.patterns;
1357 patterns.extend(po.patterns);
1358 for (p, os) in po.focus {
1359 for o in os {
1360 add_to_triple_patterns(s.focus.clone(), p.clone(), o, &mut patterns)?
1361 }
1362 }
1363 Ok(patterns)
1364 }
1365
1366 rule PropertyList() -> FocusedTriplePattern<Vec<(NamedNodePattern,Vec<AnnotatedTerm>)>> =
1367 PropertyListNotEmpty() /
1368 { FocusedTriplePattern::default() }
1369
1370 rule PropertyListNotEmpty() -> FocusedTriplePattern<Vec<(NamedNodePattern,Vec<AnnotatedTerm>)>> = hp:Verb() _ ho:ObjectList() _ l:PropertyListNotEmpty_item()* {
1371 l.into_iter().flatten().fold(FocusedTriplePattern {
1372 focus: vec![(hp, ho.focus)],
1373 patterns: ho.patterns
1374 }, |mut a, b| {
1375 a.focus.push(b.focus);
1376 a.patterns.extend(b.patterns);
1377 a
1378 })
1379 }
1380 rule PropertyListNotEmpty_item() -> Option<FocusedTriplePattern<(NamedNodePattern,Vec<AnnotatedTerm>)>> = ";" _ c:PropertyListNotEmpty_item_content()? {
1381 c
1382 }
1383 rule PropertyListNotEmpty_item_content() -> FocusedTriplePattern<(NamedNodePattern,Vec<AnnotatedTerm>)> = p:Verb() _ o:ObjectList() _ {
1384 FocusedTriplePattern {
1385 focus: (p, o.focus),
1386 patterns: o.patterns
1387 }
1388 }
1389
1390 rule Verb() -> NamedNodePattern = VarOrIri() / "a" { rdf::TYPE.into_owned().into() }
1391
1392 rule ObjectList() -> FocusedTriplePattern<Vec<AnnotatedTerm>> = o:ObjectList_item() **<1,> ("," _) {
1393 o.into_iter().fold(FocusedTriplePattern::<Vec<AnnotatedTerm>>::default(), |mut a, b| {
1394 a.focus.push(b.focus);
1395 a.patterns.extend_from_slice(&b.patterns);
1396 a
1397 })
1398 }
1399 rule ObjectList_item() -> FocusedTriplePattern<AnnotatedTerm> = o:Object() _ { o }
1400
1401 rule Object() -> FocusedTriplePattern<AnnotatedTerm> = g:GraphNode() _ a:Annotation()? {
1402 if let Some(a) = a {
1403 let mut patterns = g.patterns;
1404 patterns.extend(a.patterns);
1405 FocusedTriplePattern {
1406 focus: AnnotatedTerm {
1407 term: g.focus,
1408 annotations: a.focus
1409 },
1410 patterns
1411 }
1412 } else {
1413 FocusedTriplePattern {
1414 focus: AnnotatedTerm {
1415 term: g.focus,
1416 annotations: Vec::new()
1417 },
1418 patterns: g.patterns
1419 }
1420 }
1421 }
1422
1423 rule TriplesSameSubjectPath() -> Vec<TripleOrPathPattern> =
1424 s:VarOrTerm() _ po:PropertyListPathNotEmpty() {?
1425 let mut patterns = po.patterns;
1426 for (p, os) in po.focus {
1427 for o in os {
1428 add_to_triple_or_path_patterns(s.clone(), p.clone(), o, &mut patterns)?;
1429 }
1430 }
1431 Ok(patterns)
1432 } /
1433 s:TriplesNodePath() _ po:PropertyListPath() {?
1434 let mut patterns = s.patterns;
1435 patterns.extend(po.patterns);
1436 for (p, os) in po.focus {
1437 for o in os {
1438 add_to_triple_or_path_patterns(s.focus.clone(), p.clone(), o, &mut patterns)?;
1439 }
1440 }
1441 Ok(patterns)
1442 }
1443
1444 rule PropertyListPath() -> FocusedTripleOrPathPattern<Vec<(VariableOrPropertyPath,Vec<AnnotatedTermPath>)>> =
1445 PropertyListPathNotEmpty() /
1446 { FocusedTripleOrPathPattern::default() }
1447
1448 rule PropertyListPathNotEmpty() -> FocusedTripleOrPathPattern<Vec<(VariableOrPropertyPath,Vec<AnnotatedTermPath>)>> = hp:(VerbPath() / VerbSimple()) _ ho:ObjectListPath() _ t:PropertyListPathNotEmpty_item()* {
1449 t.into_iter().flatten().fold(FocusedTripleOrPathPattern {
1450 focus: vec![(hp, ho.focus)],
1451 patterns: ho.patterns
1452 }, |mut a, b| {
1453 a.focus.push(b.focus);
1454 a.patterns.extend(b.patterns);
1455 a
1456 })
1457 }
1458 rule PropertyListPathNotEmpty_item() -> Option<FocusedTripleOrPathPattern<(VariableOrPropertyPath,Vec<AnnotatedTermPath>)>> = ";" _ c:PropertyListPathNotEmpty_item_content()? {
1459 c
1460 }
1461 rule PropertyListPathNotEmpty_item_content() -> FocusedTripleOrPathPattern<(VariableOrPropertyPath,Vec<AnnotatedTermPath>)> = p:(VerbPath() / VerbSimple()) _ o:ObjectListPath() _ {
1462 FocusedTripleOrPathPattern {
1463 focus: (p, o.focus),
1464 patterns: o.patterns
1465 }
1466 }
1467
1468 rule VerbPath() -> VariableOrPropertyPath = p:Path() {
1469 p.into()
1470 }
1471
1472 rule VerbSimple() -> VariableOrPropertyPath = v:Var() {
1473 v.into()
1474 }
1475
1476 rule ObjectListPath() -> FocusedTripleOrPathPattern<Vec<AnnotatedTermPath>> = o:ObjectListPath_item() **<1,> ("," _) {
1477 o.into_iter().fold(FocusedTripleOrPathPattern::<Vec<AnnotatedTermPath>>::default(), |mut a, b| {
1478 a.focus.push(b.focus);
1479 a.patterns.extend(b.patterns);
1480 a
1481 })
1482 }
1483 rule ObjectListPath_item() -> FocusedTripleOrPathPattern<AnnotatedTermPath> = o:ObjectPath() _ { o }
1484
1485 rule ObjectPath() -> FocusedTripleOrPathPattern<AnnotatedTermPath> = g:GraphNodePath() _ a:AnnotationPath()? {
1486 if let Some(a) = a {
1487 let mut patterns = g.patterns;
1488 patterns.extend(a.patterns);
1489 FocusedTripleOrPathPattern {
1490 focus: AnnotatedTermPath {
1491 term: g.focus,
1492 annotations: a.focus
1493 },
1494 patterns
1495 }
1496 } else {
1497 FocusedTripleOrPathPattern {
1498 focus: AnnotatedTermPath {
1499 term: g.focus,
1500 annotations: Vec::new()
1501 },
1502 patterns: g.patterns
1503 }
1504 }
1505 }
1506
1507 rule Path() -> PropertyPathExpression = PathAlternative()
1508
1509 rule PathAlternative() -> PropertyPathExpression = p:PathAlternative_item() **<1,> ("|" _) {?
1510 not_empty_fold(p.into_iter(), |a, b| {
1511 PropertyPathExpression::Alternative(Box::new(a), Box::new(b))
1512 })
1513 }
1514 rule PathAlternative_item() -> PropertyPathExpression = p:PathSequence() _ { p }
1515
1516 rule PathSequence() -> PropertyPathExpression = p:PathSequence_item() **<1,> ("/" _) {?
1517 not_empty_fold(p.into_iter(), |a, b| {
1518 PropertyPathExpression::Sequence(Box::new(a), Box::new(b))
1519 })
1520 }
1521 rule PathSequence_item() -> PropertyPathExpression = p:PathEltOrInverse() _ { p }
1522
1523 rule PathElt() -> PropertyPathExpression = p:PathPrimary() _ o:PathElt_op()? {
1524 match o {
1525 Some('?') => PropertyPathExpression::ZeroOrOne(Box::new(p)),
1526 Some('*') => PropertyPathExpression::ZeroOrMore(Box::new(p)),
1527 Some('+') => PropertyPathExpression::OneOrMore(Box::new(p)),
1528 Some(_) => unreachable!(),
1529 None => p
1530 }
1531 }
1532 rule PathElt_op() -> char =
1533 "*" { '*' } /
1534 "+" { '+' } /
1535 "?" !(['0'..='9'] / PN_CHARS_U()) { '?' } rule PathEltOrInverse() -> PropertyPathExpression =
1538 "^" _ p:PathElt() { PropertyPathExpression::Reverse(Box::new(p)) } /
1539 PathElt()
1540
1541 rule PathPrimary() -> PropertyPathExpression =
1542 v:iri() { v.into() } /
1543 "a" { rdf::TYPE.into_owned().into() } /
1544 "!" _ p:PathNegatedPropertySet() { p } /
1545 "(" _ p:Path() _ ")" { p }
1546
1547 rule PathNegatedPropertySet() -> PropertyPathExpression =
1548 "(" _ p:PathNegatedPropertySet_item() **<1,> ("|" _) ")" {
1549 let mut direct = Vec::new();
1550 let mut inverse = Vec::new();
1551 for e in p {
1552 match e {
1553 Either::Left(a) => direct.push(a),
1554 Either::Right(b) => inverse.push(b)
1555 }
1556 }
1557 if inverse.is_empty() {
1558 PropertyPathExpression::NegatedPropertySet(direct)
1559 } else if direct.is_empty() {
1560 PropertyPathExpression::Reverse(Box::new(PropertyPathExpression::NegatedPropertySet(inverse)))
1561 } else {
1562 PropertyPathExpression::Alternative(
1563 Box::new(PropertyPathExpression::NegatedPropertySet(direct)),
1564 Box::new(PropertyPathExpression::Reverse(Box::new(PropertyPathExpression::NegatedPropertySet(inverse))))
1565 )
1566 }
1567 } /
1568 p:PathOneInPropertySet() {
1569 match p {
1570 Either::Left(a) => PropertyPathExpression::NegatedPropertySet(vec![a]),
1571 Either::Right(b) => PropertyPathExpression::Reverse(Box::new(PropertyPathExpression::NegatedPropertySet(vec![b]))),
1572 }
1573 }
1574 rule PathNegatedPropertySet_item() -> Either<NamedNode,NamedNode> = p:PathOneInPropertySet() _ { p }
1575
1576 rule PathOneInPropertySet() -> Either<NamedNode,NamedNode> =
1577 "^" _ v:iri() { Either::Right(v) } /
1578 "^" _ "a" { Either::Right(rdf::TYPE.into()) } /
1579 v:iri() { Either::Left(v) } /
1580 "a" { Either::Left(rdf::TYPE.into()) }
1581
1582 rule TriplesNode() -> FocusedTriplePattern<TermPattern> = Collection() / BlankNodePropertyList()
1583
1584 rule BlankNodePropertyList() -> FocusedTriplePattern<TermPattern> = "[" _ po:PropertyListNotEmpty() _ "]" {?
1585 let mut patterns = po.patterns;
1586 let mut bnode = TermPattern::from(BlankNode::default());
1587 for (p, os) in po.focus {
1588 for o in os {
1589 add_to_triple_patterns(bnode.clone(), p.clone(), o, &mut patterns)?;
1590 }
1591 }
1592 Ok(FocusedTriplePattern {
1593 focus: bnode,
1594 patterns
1595 })
1596 }
1597
1598 rule TriplesNodePath() -> FocusedTripleOrPathPattern<TermPattern> = CollectionPath() / BlankNodePropertyListPath()
1599
1600 rule BlankNodePropertyListPath() -> FocusedTripleOrPathPattern<TermPattern> = "[" _ po:PropertyListPathNotEmpty() _ "]" {?
1601 let mut patterns = po.patterns;
1602 let mut bnode = TermPattern::from(BlankNode::default());
1603 for (p, os) in po.focus {
1604 for o in os {
1605 add_to_triple_or_path_patterns(bnode.clone(), p.clone(), o, &mut patterns)?;
1606 }
1607 }
1608 Ok(FocusedTripleOrPathPattern {
1609 focus: bnode,
1610 patterns
1611 })
1612 }
1613
1614 rule Collection() -> FocusedTriplePattern<TermPattern> = "(" _ o:Collection_item()+ ")" {
1615 let mut patterns: Vec<TriplePattern> = Vec::new();
1616 let mut current_list_node = TermPattern::from(rdf::NIL.into_owned());
1617 for objWithPatterns in o.into_iter().rev() {
1618 let new_blank_node = TermPattern::from(BlankNode::default());
1619 patterns.push(TriplePattern::new(new_blank_node.clone(), rdf::FIRST.into_owned(), objWithPatterns.focus.clone()));
1620 patterns.push(TriplePattern::new(new_blank_node.clone(), rdf::REST.into_owned(), current_list_node));
1621 current_list_node = new_blank_node;
1622 patterns.extend_from_slice(&objWithPatterns.patterns);
1623 }
1624 FocusedTriplePattern {
1625 focus: current_list_node,
1626 patterns
1627 }
1628 }
1629 rule Collection_item() -> FocusedTriplePattern<TermPattern> = o:GraphNode() _ { o }
1630
1631 rule CollectionPath() -> FocusedTripleOrPathPattern<TermPattern> = "(" _ o:CollectionPath_item()+ _ ")" {
1632 let mut patterns: Vec<TripleOrPathPattern> = Vec::new();
1633 let mut current_list_node = TermPattern::from(rdf::NIL.into_owned());
1634 for objWithPatterns in o.into_iter().rev() {
1635 let new_blank_node = TermPattern::from(BlankNode::default());
1636 patterns.push(TriplePattern::new(new_blank_node.clone(), rdf::FIRST.into_owned(), objWithPatterns.focus.clone()).into());
1637 patterns.push(TriplePattern::new(new_blank_node.clone(), rdf::REST.into_owned(), current_list_node).into());
1638 current_list_node = new_blank_node;
1639 patterns.extend(objWithPatterns.patterns);
1640 }
1641 FocusedTripleOrPathPattern {
1642 focus: current_list_node,
1643 patterns
1644 }
1645 }
1646 rule CollectionPath_item() -> FocusedTripleOrPathPattern<TermPattern> = p:GraphNodePath() _ { p }
1647
1648
1649 rule Annotation() -> FocusedTriplePattern<Vec<(NamedNodePattern,Vec<AnnotatedTerm>)>> = "{|" _ a:PropertyListNotEmpty() _ "|}" { a }
1650
1651 rule AnnotationPath() -> FocusedTripleOrPathPattern<Vec<(VariableOrPropertyPath,Vec<AnnotatedTermPath>)>> = "{|" _ a: PropertyListPathNotEmpty() _ "|}" { a }
1652
1653 rule GraphNode() -> FocusedTriplePattern<TermPattern> =
1654 t:VarOrTerm() { FocusedTriplePattern::new(t) } /
1655 TriplesNode()
1656
1657 rule GraphNodePath() -> FocusedTripleOrPathPattern<TermPattern> =
1658 t:VarOrTerm() { FocusedTripleOrPathPattern::new(t) } /
1659 TriplesNodePath()
1660
1661 rule VarOrTerm() -> TermPattern =
1662 v:Var() { v.into() } /
1663 t:QuotedTriple() {?
1664 #[cfg(feature = "rdf-star")]{Ok(t.into())}
1665 #[cfg(not(feature = "rdf-star"))]{Err("Embedded triples are only available in SPARQL-star")}
1666 } /
1667 t:GraphTerm() { t.into() }
1668
1669 rule QuotedTriple() -> TriplePattern = "<<" _ s:VarOrTerm() _ p:Verb() _ o:VarOrTerm() _ ">>" {?
1670 Ok(TriplePattern {
1671 subject: s,
1672 predicate: p,
1673 object: o
1674 })
1675 }
1676
1677 rule QuotedTripleData() -> GroundTriple = "<<" _ s:DataValueTerm() _ p:QuotedTripleData_p() _ o:DataValueTerm() _ ">>" {?
1678 Ok(GroundTriple {
1679 subject: s.try_into().map_err(|()| "Literals are not allowed in subject position of nested patterns")?,
1680 predicate: p,
1681 object: o
1682 })
1683 }
1684 rule QuotedTripleData_p() -> NamedNode = i: iri() { i } / "a" { rdf::TYPE.into() }
1685
1686 rule DataValueTerm() -> GroundTerm = i:iri() { i.into() } /
1687 l:RDFLiteral() { l.into() } /
1688 l:NumericLiteral() { l.into() } /
1689 l:BooleanLiteral() { l.into() } /
1690 t:QuotedTripleData() {?
1691 #[cfg(feature = "rdf-star")]{Ok(t.into())}
1692 #[cfg(not(feature = "rdf-star"))]{Err("Embedded triples are only available in SPARQL-star")}
1693 }
1694
1695 rule VarOrIri() -> NamedNodePattern =
1696 v:Var() { v.into() } /
1697 i:iri() { i.into() }
1698
1699 rule Var() -> Variable = name:(VAR1() / VAR2()) { Variable::new_unchecked(name) }
1700
1701 rule GraphTerm() -> Term =
1702 i:iri() { i.into() } /
1703 l:RDFLiteral() { l.into() } /
1704 l:NumericLiteral() { l.into() } /
1705 l:BooleanLiteral() { l.into() } /
1706 b:BlankNode() { b.into() } /
1707 NIL() { rdf::NIL.into_owned().into() }
1708
1709 rule Expression() -> Expression = e:ConditionalOrExpression() {e}
1710
1711 rule ConditionalOrExpression() -> Expression = e:ConditionalOrExpression_item() **<1,> ("||" _) {?
1712 not_empty_fold(e.into_iter(), |a, b| Expression::Or(Box::new(a), Box::new(b)))
1713 }
1714 rule ConditionalOrExpression_item() -> Expression = e:ConditionalAndExpression() _ { e }
1715
1716 rule ConditionalAndExpression() -> Expression = e:ConditionalAndExpression_item() **<1,> ("&&" _) {?
1717 not_empty_fold(e.into_iter(), |a, b| Expression::And(Box::new(a), Box::new(b)))
1718 }
1719 rule ConditionalAndExpression_item() -> Expression = e:ValueLogical() _ { e }
1720
1721 rule ValueLogical() -> Expression = RelationalExpression()
1722
1723 rule RelationalExpression() -> Expression = a:NumericExpression() _ o: RelationalExpression_inner()? { match o {
1724 Some(("=", Some(b), None)) => Expression::Equal(Box::new(a), Box::new(b)),
1725 Some(("!=", Some(b), None)) => Expression::Not(Box::new(Expression::Equal(Box::new(a), Box::new(b)))),
1726 Some((">", Some(b), None)) => Expression::Greater(Box::new(a), Box::new(b)),
1727 Some((">=", Some(b), None)) => Expression::GreaterOrEqual(Box::new(a), Box::new(b)),
1728 Some(("<", Some(b), None)) => Expression::Less(Box::new(a), Box::new(b)),
1729 Some(("<=", Some(b), None)) => Expression::LessOrEqual(Box::new(a), Box::new(b)),
1730 Some(("IN", None, Some(l))) => Expression::In(Box::new(a), l),
1731 Some(("NOT IN", None, Some(l))) => Expression::Not(Box::new(Expression::In(Box::new(a), l))),
1732 Some(_) => unreachable!(),
1733 None => a
1734 } }
1735 rule RelationalExpression_inner() -> (&'input str, Option<Expression>, Option<Vec<Expression>>) =
1736 s: $("=" / "!=" / ">=" / ">" / "<=" / "<") _ e:NumericExpression() { (s, Some(e), None) } /
1737 i("IN") _ l:ExpressionList() { ("IN", None, Some(l)) } /
1738 i("NOT") _ i("IN") _ l:ExpressionList() { ("NOT IN", None, Some(l)) }
1739
1740 rule NumericExpression() -> Expression = AdditiveExpression()
1741
1742 rule AdditiveExpression() -> Expression = a:MultiplicativeExpression() _ o:AdditiveExpression_inner()? { match o {
1743 Some(("+", b)) => Expression::Add(Box::new(a), Box::new(b)),
1744 Some(("-", b)) => Expression::Subtract(Box::new(a), Box::new(b)),
1745 Some(_) => unreachable!(),
1746 None => a,
1747 } }
1748 rule AdditiveExpression_inner() -> (&'input str, Expression) = s: $("+" / "-") _ e:AdditiveExpression() {
1749 (s, e)
1750 }
1751
1752 rule MultiplicativeExpression() -> Expression = a:UnaryExpression() _ o: MultiplicativeExpression_inner()? { match o {
1753 Some(("*", b)) => Expression::Multiply(Box::new(a), Box::new(b)),
1754 Some(("/", b)) => Expression::Divide(Box::new(a), Box::new(b)),
1755 Some(_) => unreachable!(),
1756 None => a
1757 } }
1758 rule MultiplicativeExpression_inner() -> (&'input str, Expression) = s: $("*" / "/") _ e:MultiplicativeExpression() {
1759 (s, e)
1760 }
1761
1762 rule UnaryExpression() -> Expression = s: $("!" / "+" / "-")? _ e:PrimaryExpression() { match s {
1763 Some("!") => Expression::Not(Box::new(e)),
1764 Some("+") => Expression::UnaryPlus(Box::new(e)),
1765 Some("-") => Expression::UnaryMinus(Box::new(e)),
1766 Some(_) => unreachable!(),
1767 None => e,
1768 } }
1769
1770 rule PrimaryExpression() -> Expression =
1771 BrackettedExpression() /
1772 ExprQuotedTriple() /
1773 iriOrFunction() /
1774 v:Var() { v.into() } /
1775 l:RDFLiteral() { l.into() } /
1776 l:NumericLiteral() { l.into() } /
1777 l:BooleanLiteral() { l.into() } /
1778 BuiltInCall()
1779
1780 rule ExprVarOrTerm() -> Expression =
1781 ExprQuotedTriple() /
1782 i:iri() { i.into() } /
1783 l:RDFLiteral() { l.into() } /
1784 l:NumericLiteral() { l.into() } /
1785 l:BooleanLiteral() { l.into() } /
1786 v:Var() { v.into() }
1787
1788 rule ExprQuotedTriple() -> Expression = "<<" _ s:ExprVarOrTerm() _ p:Verb() _ o:ExprVarOrTerm() _ ">>" {?
1789 #[cfg(feature = "rdf-star")]{Ok(Expression::FunctionCall(Function::Triple, vec![s, p.into(), o]))}
1790 #[cfg(not(feature = "rdf-star"))]{Err("Embedded triples are only available in SPARQL-star")}
1791 }
1792
1793 rule BrackettedExpression() -> Expression = "(" _ e:Expression() _ ")" { e }
1794
1795 rule BuiltInCall() -> Expression =
1796 a:Aggregate() {? state.new_aggregation(a).map(Into::into) } /
1797 i("STR") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Str, vec![e]) } /
1798 i("LANG") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Lang, vec![e]) } /
1799 i("LANGMATCHES") _ "(" _ a:Expression() _ "," _ b:Expression() _ ")" { Expression::FunctionCall(Function::LangMatches, vec![a, b]) } /
1800 i("DATATYPE") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Datatype, vec![e]) } /
1801 i("BOUND") _ "(" _ v:Var() _ ")" { Expression::Bound(v) } /
1802 (i("IRI") / i("URI")) _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Iri, vec![e]) } /
1803 i("BNODE") "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::BNode, vec![e]) } /
1804 i("BNODE") NIL() { Expression::FunctionCall(Function::BNode, vec![]) } /
1805 i("RAND") _ NIL() { Expression::FunctionCall(Function::Rand, vec![]) } /
1806 i("ABS") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Abs, vec![e]) } /
1807 i("CEIL") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Ceil, vec![e]) } /
1808 i("FLOOR") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Floor, vec![e]) } /
1809 i("ROUND") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Round, vec![e]) } /
1810 i("CONCAT") e:ExpressionList() { Expression::FunctionCall(Function::Concat, e) } /
1811 SubstringExpression() /
1812 i("STRLEN") _ "(" _ e: Expression() _ ")" { Expression::FunctionCall(Function::StrLen, vec![e]) } /
1813 StrReplaceExpression() /
1814 i("UCASE") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::UCase, vec![e]) } /
1815 i("LCASE") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::LCase, vec![e]) } /
1816 i("ENCODE_FOR_URI") "(" _ e: Expression() _ ")" { Expression::FunctionCall(Function::EncodeForUri, vec![e]) } /
1817 i("CONTAINS") _ "(" _ a:Expression() _ "," _ b:Expression() _ ")" { Expression::FunctionCall(Function::Contains, vec![a, b]) } /
1818 i("STRSTARTS") _ "(" _ a:Expression() _ "," _ b:Expression() _ ")" { Expression::FunctionCall(Function::StrStarts, vec![a, b]) } /
1819 i("STRENDS") _ "(" _ a:Expression() _ "," _ b:Expression() _ ")" { Expression::FunctionCall(Function::StrEnds, vec![a, b]) } /
1820 i("STRBEFORE") _ "(" _ a:Expression() _ "," _ b:Expression() _ ")" { Expression::FunctionCall(Function::StrBefore, vec![a, b]) } /
1821 i("STRAFTER") _ "(" _ a:Expression() _ "," _ b:Expression() _ ")" { Expression::FunctionCall(Function::StrAfter, vec![a, b]) } /
1822 i("YEAR") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Year, vec![e]) } /
1823 i("MONTH") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Month, vec![e]) } /
1824 i("DAY") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Day, vec![e]) } /
1825 i("HOURS") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Hours, vec![e]) } /
1826 i("MINUTES") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Minutes, vec![e]) } /
1827 i("SECONDS") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Seconds, vec![e]) } /
1828 i("TIMEZONE") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Timezone, vec![e]) } /
1829 i("TZ") _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Tz, vec![e]) } /
1830 i("NOW") _ NIL() { Expression::FunctionCall(Function::Now, vec![]) } /
1831 i("UUID") _ NIL() { Expression::FunctionCall(Function::Uuid, vec![]) }/
1832 i("STRUUID") _ NIL() { Expression::FunctionCall(Function::StrUuid, vec![]) } /
1833 i("MD5") "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Md5, vec![e]) } /
1834 i("SHA1") "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Sha1, vec![e]) } /
1835 i("SHA256") "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Sha256, vec![e]) } /
1836 i("SHA384") "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Sha384, vec![e]) } /
1837 i("SHA512") "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::Sha512, vec![e]) } /
1838 i("COALESCE") e:ExpressionList() { Expression::Coalesce(e) } /
1839 i("IF") _ "(" _ a:Expression() _ "," _ b:Expression() _ "," _ c:Expression() _ ")" { Expression::If(Box::new(a), Box::new(b), Box::new(c)) } /
1840 i("STRLANG") _ "(" _ a:Expression() _ "," _ b:Expression() _ ")" { Expression::FunctionCall(Function::StrLang, vec![a, b]) } /
1841 i("STRDT") _ "(" _ a:Expression() _ "," _ b:Expression() _ ")" { Expression::FunctionCall(Function::StrDt, vec![a, b]) } /
1842 i("sameTerm") "(" _ a:Expression() _ "," _ b:Expression() _ ")" { Expression::SameTerm(Box::new(a), Box::new(b)) } /
1843 (i("isIRI") / i("isURI")) _ "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::IsIri, vec![e]) } /
1844 i("isBLANK") "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::IsBlank, vec![e]) } /
1845 i("isLITERAL") "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::IsLiteral, vec![e]) } /
1846 i("isNUMERIC") "(" _ e:Expression() _ ")" { Expression::FunctionCall(Function::IsNumeric, vec![e]) } /
1847 RegexExpression() /
1848 ExistsFunc() /
1849 NotExistsFunc() /
1850 i("TRIPLE") "(" _ s:Expression() _ "," _ p:Expression() "," _ o:Expression() ")" {?
1851 #[cfg(feature = "rdf-star")]{Ok(Expression::FunctionCall(Function::Triple, vec![s, p, o]))}
1852 #[cfg(not(feature = "rdf-star"))]{Err("The TRIPLE function is only available in SPARQL-star")}
1853 } /
1854 i("SUBJECT") "(" _ e:Expression() _ ")" {?
1855 #[cfg(feature = "rdf-star")]{Ok(Expression::FunctionCall(Function::Subject, vec![e]))}
1856 #[cfg(not(feature = "rdf-star"))]{Err("The SUBJECT function is only available in SPARQL-star")}
1857 } /
1858 i("PREDICATE") "(" _ e:Expression() _ ")" {?
1859 #[cfg(feature = "rdf-star")]{Ok(Expression::FunctionCall(Function::Predicate, vec![e]))}
1860 #[cfg(not(feature = "rdf-star"))]{Err("The PREDICATE function is only available in SPARQL-star")}
1861 } /
1862 i("OBJECT") "(" _ e:Expression() _ ")" {?
1863 #[cfg(feature = "rdf-star")]{Ok(Expression::FunctionCall(Function::Object, vec![e]))}
1864 #[cfg(not(feature = "rdf-star"))]{Err("The OBJECT function is only available in SPARQL-star")}
1865 } /
1866 i("isTriple") "(" _ e:Expression() _ ")" {?
1867 #[cfg(feature = "rdf-star")]{Ok(Expression::FunctionCall(Function::IsTriple, vec![e]))}
1868 #[cfg(not(feature = "rdf-star"))]{Err("The isTriple function is only available in SPARQL-star")}
1869 } /
1870 i("ADJUST") "(" _ a:Expression() _ "," _ b:Expression() _ ")" {?
1871 #[cfg(feature = "sep-0002")]{Ok(Expression::FunctionCall(Function::Adjust, vec![a, b]))}
1872 #[cfg(not(feature = "sep-0002"))]{Err("The ADJUST function is only available in SPARQL 1.2 SEP 0002")}
1873 }
1874
1875 rule RegexExpression() -> Expression =
1876 i("REGEX") _ "(" _ a:Expression() _ "," _ b:Expression() _ "," _ c:Expression() _ ")" { Expression::FunctionCall(Function::Regex, vec![a, b, c]) } /
1877 i("REGEX") _ "(" _ a:Expression() _ "," _ b:Expression() _ ")" { Expression::FunctionCall(Function::Regex, vec![a, b]) }
1878
1879
1880 rule SubstringExpression() -> Expression =
1881 i("SUBSTR") _ "(" _ a:Expression() _ "," _ b:Expression() _ "," _ c:Expression() _ ")" { Expression::FunctionCall(Function::SubStr, vec![a, b, c]) } /
1882 i("SUBSTR") _ "(" _ a:Expression() _ "," _ b:Expression() _ ")" { Expression::FunctionCall(Function::SubStr, vec![a, b]) }
1883
1884
1885 rule StrReplaceExpression() -> Expression =
1886 i("REPLACE") _ "(" _ a:Expression() _ "," _ b:Expression() _ "," _ c:Expression() _ "," _ d:Expression() _ ")" { Expression::FunctionCall(Function::Replace, vec![a, b, c, d]) } /
1887 i("REPLACE") _ "(" _ a:Expression() _ "," _ b:Expression() _ "," _ c:Expression() _ ")" { Expression::FunctionCall(Function::Replace, vec![a, b, c]) }
1888
1889 rule ExistsFunc() -> Expression = i("EXISTS") _ p:GroupGraphPattern() { Expression::Exists(Box::new(p)) }
1890
1891 rule NotExistsFunc() -> Expression = i("NOT") _ i("EXISTS") _ p:GroupGraphPattern() { Expression::Not(Box::new(Expression::Exists(Box::new(p)))) }
1892
1893 rule Aggregate() -> AggregateExpression =
1894 i("COUNT") _ "(" _ i("DISTINCT") _ "*" _ ")" { AggregateExpression::CountSolutions { distinct: true } } /
1895 i("COUNT") _ "(" _ i("DISTINCT") _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::Count, expr, distinct: true } } /
1896 i("COUNT") _ "(" _ "*" _ ")" { AggregateExpression::CountSolutions { distinct: false } } /
1897 i("COUNT") _ "(" _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::Count, expr, distinct: false } } /
1898 i("SUM") _ "(" _ i("DISTINCT") _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::Sum, expr, distinct: true } } /
1899 i("SUM") _ "(" _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::Sum, expr, distinct: false } } /
1900 i("MIN") _ "(" _ i("DISTINCT") _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::Min, expr, distinct: true } } /
1901 i("MIN") _ "(" _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::Min, expr, distinct: false } } /
1902 i("MAX") _ "(" _ i("DISTINCT") _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::Max, expr, distinct: true } } /
1903 i("MAX") _ "(" _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::Max, expr, distinct: false } } /
1904 i("AVG") _ "(" _ i("DISTINCT") _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::Avg, expr, distinct: true } } /
1905 i("AVG") _ "(" _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::Avg, expr, distinct: false } } /
1906 i("SAMPLE") _ "(" _ i("DISTINCT") _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::Sample, expr, distinct: true } } /
1907 i("SAMPLE") _ "(" _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::Sample, expr, distinct: false } } /
1908 i("GROUP_CONCAT") _ "(" _ i("DISTINCT") _ expr:Expression() _ ";" _ i("SEPARATOR") _ "=" _ s:String() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::GroupConcat { separator: Some(s) }, expr, distinct: true } } /
1909 i("GROUP_CONCAT") _ "(" _ i("DISTINCT") _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::GroupConcat { separator: None }, expr, distinct: true } } /
1910 i("GROUP_CONCAT") _ "(" _ expr:Expression() _ ";" _ i("SEPARATOR") _ "=" _ s:String() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::GroupConcat { separator: Some(s) }, expr, distinct: false } } /
1911 i("GROUP_CONCAT") _ "(" _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::GroupConcat { separator: None }, expr, distinct: false } } /
1912 name:iri() _ "(" _ i("DISTINCT") _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::Custom(name), expr, distinct: true } } /
1913 name:iri() _ "(" _ expr:Expression() _ ")" { AggregateExpression::FunctionCall { name: AggregateFunction::Custom(name), expr, distinct: false } }
1914
1915 rule iriOrFunction() -> Expression = i: iri() _ a: ArgList()? {
1916 match a {
1917 Some(a) => Expression::FunctionCall(Function::Custom(i), a),
1918 None => i.into()
1919 }
1920 }
1921
1922 rule RDFLiteral() -> Literal =
1923 value:String() _ "^^" _ datatype:iri() { Literal::new_typed_literal(value, datatype) } /
1924 value:String() _ language:LANGTAG() { Literal::new_language_tagged_literal_unchecked(value, language.into_inner()) } /
1925 value:String() { Literal::new_simple_literal(value) }
1926
1927 rule NumericLiteral() -> Literal = NumericLiteralUnsigned() / NumericLiteralPositive() / NumericLiteralNegative()
1928
1929 rule NumericLiteralUnsigned() -> Literal =
1930 d:$(DOUBLE()) { Literal::new_typed_literal(d, xsd::DOUBLE) } /
1931 d:$(DECIMAL()) { Literal::new_typed_literal(d, xsd::DECIMAL) } /
1932 i:$(INTEGER()) { Literal::new_typed_literal(i, xsd::INTEGER) }
1933
1934 rule NumericLiteralPositive() -> Literal =
1935 d:$(DOUBLE_POSITIVE()) { Literal::new_typed_literal(d, xsd::DOUBLE) } /
1936 d:$(DECIMAL_POSITIVE()) { Literal::new_typed_literal(d, xsd::DECIMAL) } /
1937 i:$(INTEGER_POSITIVE()) { Literal::new_typed_literal(i, xsd::INTEGER) }
1938
1939
1940 rule NumericLiteralNegative() -> Literal =
1941 d:$(DOUBLE_NEGATIVE()) { Literal::new_typed_literal(d, xsd::DOUBLE) } /
1942 d:$(DECIMAL_NEGATIVE()) { Literal::new_typed_literal(d, xsd::DECIMAL) } /
1943 i:$(INTEGER_NEGATIVE()) { Literal::new_typed_literal(i, xsd::INTEGER) }
1944
1945 rule BooleanLiteral() -> Literal =
1946 "true" { Literal::new_typed_literal("true", xsd::BOOLEAN) } /
1947 "false" { Literal::new_typed_literal("false", xsd::BOOLEAN) }
1948
1949 rule String() -> String = STRING_LITERAL_LONG1() / STRING_LITERAL_LONG2() / STRING_LITERAL1() / STRING_LITERAL2()
1950
1951 rule iri() -> NamedNode = i:(IRIREF() / PrefixedName()) {
1952 NamedNode::from(i)
1953 }
1954
1955 rule PrefixedName() -> Iri<String> = PNAME_LN() /
1956 ns:PNAME_NS() {? if let Some(iri) = state.prefixes.get(ns).cloned() {
1957 Iri::parse(iri).map_err(|_| "IRI parsing failed")
1958 } else {
1959 Err("Prefix not found")
1960 } }
1961
1962 rule BlankNode() -> BlankNode = id:BLANK_NODE_LABEL() {?
1963 let node = BlankNode::new_unchecked(id);
1964 if state.used_bnodes.contains(&node) {
1965 Err("Already used blank node id")
1966 } else {
1967 state.currently_used_bnodes.insert(node.clone());
1968 Ok(node)
1969 }
1970 } / ANON() { BlankNode::default() }
1971
1972 rule IRIREF() -> Iri<String> = "<" i:$((!['>'] [_])*) ">" {?
1973 state.parse_iri(unescape_iriref(i)?).map_err(|_| "IRI parsing failed")
1974 }
1975
1976 rule PNAME_NS() -> &'input str = ns:$(PN_PREFIX()?) ":" {
1977 ns
1978 }
1979
1980 rule PNAME_LN() -> Iri<String> = ns:PNAME_NS() local:$(PN_LOCAL()) {?
1981 if let Some(base) = state.prefixes.get(ns) {
1982 let mut iri = String::with_capacity(base.len() + local.len());
1983 iri.push_str(base);
1984 for chunk in local.split('\\') { iri.push_str(chunk);
1986 }
1987 Iri::parse(iri).map_err(|_| "IRI parsing failed")
1988 } else {
1989 Err("Prefix not found")
1990 }
1991 }
1992
1993 rule BLANK_NODE_LABEL() -> &'input str = "_:" b:$((['0'..='9'] / PN_CHARS_U()) PN_CHARS()* ("."+ PN_CHARS()+)*) {
1994 b
1995 }
1996
1997 rule VAR1() -> &'input str = "?" v:$(VARNAME()) { v }
1998
1999 rule VAR2() -> &'input str = "$" v:$(VARNAME()) { v }
2000
2001 rule LANGTAG() -> LanguageTag<String> = "@" l:$(['a' ..= 'z' | 'A' ..= 'Z']+ ("-" ['a' ..= 'z' | 'A' ..= 'Z' | '0' ..= '9']+)*) {?
2002 LanguageTag::parse(l.to_ascii_lowercase()).map_err(|_| "language tag parsing failed")
2003 }
2004
2005 rule INTEGER() = ['0'..='9']+
2006
2007 rule DECIMAL() = ['0'..='9']* "." ['0'..='9']+
2008
2009 rule DOUBLE() = (['0'..='9']+ "." ['0'..='9']* / "." ['0'..='9']+ / ['0'..='9']+) EXPONENT()
2010
2011 rule INTEGER_POSITIVE() = "+" _ INTEGER()
2012
2013 rule DECIMAL_POSITIVE() = "+" _ DECIMAL()
2014
2015 rule DOUBLE_POSITIVE() = "+" _ DOUBLE()
2016
2017 rule INTEGER_NEGATIVE() = "-" _ INTEGER()
2018
2019 rule DECIMAL_NEGATIVE() = "-" _ DECIMAL()
2020
2021 rule DOUBLE_NEGATIVE() = "-" _ DOUBLE()
2022
2023 rule EXPONENT() = ['e' | 'E'] ['+' | '-']? ['0'..='9']+
2024
2025 rule STRING_LITERAL1() -> String = "'" l:$((STRING_LITERAL1_simple_char() / ECHAR() / UCHAR())*) "'" {?
2026 unescape_string(l)
2027 }
2028 rule STRING_LITERAL1_simple_char() = !['\u{27}' | '\u{5C}' | '\u{0A}' | '\u{0D}'] [_]
2029
2030
2031 rule STRING_LITERAL2() -> String = "\"" l:$((STRING_LITERAL2_simple_char() / ECHAR() / UCHAR())*) "\"" {?
2032 unescape_string(l)
2033 }
2034 rule STRING_LITERAL2_simple_char() = !['\u{22}' | '\u{5C}' | '\u{0A}' | '\u{0D}'] [_]
2035
2036 rule STRING_LITERAL_LONG1() -> String = "'''" l:$(STRING_LITERAL_LONG1_inner()*) "'''" {?
2037 unescape_string(l)
2038 }
2039 rule STRING_LITERAL_LONG1_inner() = ("''" / "'")? (STRING_LITERAL_LONG1_simple_char() / ECHAR() / UCHAR())
2040 rule STRING_LITERAL_LONG1_simple_char() = !['\'' | '\\'] [_]
2041
2042 rule STRING_LITERAL_LONG2() -> String = "\"\"\"" l:$(STRING_LITERAL_LONG2_inner()*) "\"\"\"" {?
2043 unescape_string(l)
2044 }
2045 rule STRING_LITERAL_LONG2_inner() = ("\"\"" / "\"")? (STRING_LITERAL_LONG2_simple_char() / ECHAR() / UCHAR())
2046 rule STRING_LITERAL_LONG2_simple_char() = !['"' | '\\'] [_]
2047
2048 rule UCHAR() = "\\u" HEX() HEX() HEX() HEX() / "\\U" HEX() HEX() HEX() HEX() HEX() HEX() HEX() HEX()
2049
2050 rule ECHAR() = "\\" ['t' | 'b' | 'n' | 'r' | 'f' | '"' |'\'' | '\\']
2051
2052 rule NIL() = "(" WS()* ")"
2053
2054 rule WS() = quiet! { ['\u{20}' | '\u{09}' | '\u{0D}' | '\u{0A}'] }
2055
2056 rule ANON() = "[" WS()* "]"
2057
2058 rule PN_CHARS_BASE() = ['A' ..= 'Z' | 'a' ..= 'z' | '\u{00C0}'..='\u{00D6}' | '\u{00D8}'..='\u{00F6}' | '\u{00F8}'..='\u{02FF}' | '\u{0370}'..='\u{037D}' | '\u{037F}'..='\u{1FFF}' | '\u{200C}'..='\u{200D}' | '\u{2070}'..='\u{218F}' | '\u{2C00}'..='\u{2FEF}' | '\u{3001}'..='\u{D7FF}' | '\u{F900}'..='\u{FDCF}' | '\u{FDF0}'..='\u{FFFD}']
2059
2060 rule PN_CHARS_U() = ['_'] / PN_CHARS_BASE()
2061
2062 rule VARNAME() = (['0'..='9'] / PN_CHARS_U()) (['0' ..= '9' | '\u{00B7}' | '\u{0300}'..='\u{036F}' | '\u{203F}'..='\u{2040}'] / PN_CHARS_U())*
2063
2064 rule PN_CHARS() = ['-' | '0' ..= '9' | '\u{00B7}' | '\u{0300}'..='\u{036F}' | '\u{203F}'..='\u{2040}'] / PN_CHARS_U()
2065
2066 rule PN_PREFIX() = PN_CHARS_BASE() PN_CHARS()* ("."+ PN_CHARS()+)*
2067
2068 rule PN_LOCAL() = (PN_CHARS_U() / [':' | '0'..='9'] / PLX()) (PN_CHARS() / [':'] / PLX())* (['.']+ (PN_CHARS() / [':'] / PLX())+)?
2069
2070 rule PLX() = PERCENT() / PN_LOCAL_ESC()
2071
2072 rule PERCENT() = ['%'] HEX() HEX()
2073
2074 rule HEX() = ['0' ..= '9' | 'A' ..= 'F' | 'a' ..= 'f']
2075
2076 rule PN_LOCAL_ESC() = ['\\'] ['_' | '~' | '.' | '-' | '!' | '$' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | ';' | '=' | '/' | '?' | '#' | '@' | '%'] rule _() = quiet! { ([' ' | '\t' | '\n' | '\r'] / comment())* }
2080
2081 rule comment() = quiet! { ['#'] (!['\r' | '\n'] [_])* }
2083
2084 rule i(literal: &'static str) = input: $([_]*<{literal.len()}>) {?
2085 if input.eq_ignore_ascii_case(literal) {
2086 Ok(())
2087 } else {
2088 Err(literal)
2089 }
2090 }
2091 }
2092}