Skip to main content

ng_oxigraph/sparopt/
algebra.rs

1//! [SPARQL 1.1 Query Algebra](https://www.w3.org/TR/sparql11-query/#sparqlQuery) representation.
2
3use crate::oxrdf::vocab::xsd;
4use crate::spargebra::algebra::{
5    AggregateExpression as AlAggregateExpression, AggregateFunction, Expression as AlExpression,
6    GraphPattern as AlGraphPattern, OrderExpression as AlOrderExpression,
7};
8pub use crate::spargebra::algebra::{Function, PropertyPathExpression};
9use crate::spargebra::term::{BlankNode, GroundSubject, TermPattern, TriplePattern};
10pub use crate::spargebra::term::{
11    GroundTerm, GroundTermPattern, Literal, NamedNode, NamedNodePattern, Variable,
12};
13#[cfg(feature = "rdf-star")]
14use crate::spargebra::term::{GroundTriple, GroundTriplePattern};
15use rand::random;
16use std::collections::hash_map::DefaultHasher;
17use std::collections::{HashMap, HashSet};
18use std::hash::{Hash, Hasher};
19use std::ops::{Add, BitAnd, BitOr, Div, Mul, Neg, Not, Sub};
20
21/// An [expression](https://www.w3.org/TR/sparql11-query/#expressions).
22#[derive(Eq, PartialEq, Debug, Clone, Hash)]
23pub enum Expression {
24    NamedNode(NamedNode),
25    Literal(Literal),
26    Variable(Variable),
27    /// [Logical-or](https://www.w3.org/TR/sparql11-query/#func-logical-or).
28    Or(Vec<Self>),
29    /// [Logical-and](https://www.w3.org/TR/sparql11-query/#func-logical-and).
30    And(Vec<Self>),
31    /// [RDFterm-equal](https://www.w3.org/TR/sparql11-query/#func-RDFterm-equal) and all the XSD equalities.
32    Equal(Box<Self>, Box<Self>),
33    /// [sameTerm](https://www.w3.org/TR/sparql11-query/#func-sameTerm).
34    SameTerm(Box<Self>, Box<Self>),
35    /// [op:numeric-greater-than](https://www.w3.org/TR/xpath-functions-31/#func-numeric-greater-than) and other XSD greater than operators.
36    Greater(Box<Self>, Box<Self>),
37    GreaterOrEqual(Box<Self>, Box<Self>),
38    /// [op:numeric-less-than](https://www.w3.org/TR/xpath-functions-31/#func-numeric-less-than) and other XSD greater than operators.
39    Less(Box<Self>, Box<Self>),
40    LessOrEqual(Box<Self>, Box<Self>),
41    /// [op:numeric-add](https://www.w3.org/TR/xpath-functions-31/#func-numeric-add) and other XSD additions.
42    Add(Box<Self>, Box<Self>),
43    /// [op:numeric-subtract](https://www.w3.org/TR/xpath-functions-31/#func-numeric-subtract) and other XSD subtractions.
44    Subtract(Box<Self>, Box<Self>),
45    /// [op:numeric-multiply](https://www.w3.org/TR/xpath-functions-31/#func-numeric-multiply) and other XSD multiplications.
46    Multiply(Box<Self>, Box<Self>),
47    /// [op:numeric-divide](https://www.w3.org/TR/xpath-functions-31/#func-numeric-divide) and other XSD divides.
48    Divide(Box<Self>, Box<Self>),
49    /// [op:numeric-unary-plus](https://www.w3.org/TR/xpath-functions-31/#func-numeric-unary-plus) and other XSD unary plus.
50    UnaryPlus(Box<Self>),
51    /// [op:numeric-unary-minus](https://www.w3.org/TR/xpath-functions-31/#func-numeric-unary-minus) and other XSD unary minus.
52    UnaryMinus(Box<Self>),
53    /// [fn:not](https://www.w3.org/TR/xpath-functions-31/#func-not).
54    Not(Box<Self>),
55    /// [EXISTS](https://www.w3.org/TR/sparql11-query/#func-filter-exists).
56    Exists(Box<GraphPattern>),
57    /// [BOUND](https://www.w3.org/TR/sparql11-query/#func-bound).
58    Bound(Variable),
59    /// [IF](https://www.w3.org/TR/sparql11-query/#func-if).
60    If(Box<Self>, Box<Self>, Box<Self>),
61    /// [COALESCE](https://www.w3.org/TR/sparql11-query/#func-coalesce).
62    Coalesce(Vec<Self>),
63    /// A regular function call.
64    FunctionCall(Function, Vec<Self>),
65}
66
67impl Expression {
68    pub fn or_all(args: impl IntoIterator<Item = Self>) -> Self {
69        let args = args.into_iter();
70        let mut all = Vec::with_capacity(args.size_hint().0);
71        for arg in args {
72            if let Some(ebv) = arg.effective_boolean_value() {
73                if ebv {
74                    return true.into();
75                }
76                // We ignore false values
77            } else if let Self::Or(args) = arg {
78                all.extend(args);
79            } else {
80                all.push(arg);
81            }
82        }
83        match all.len() {
84            0 => false.into(),
85            1 => {
86                let result = all.pop().unwrap();
87                if result.returns_boolean() {
88                    result // It's already casted to boolean
89                } else {
90                    Self::And(vec![result])
91                }
92            }
93            _ => Self::Or(order_vec(all)),
94        }
95    }
96
97    pub fn and_all(args: impl IntoIterator<Item = Self>) -> Self {
98        let args = args.into_iter();
99        let mut all = Vec::with_capacity(args.size_hint().0);
100        for arg in args {
101            if let Some(ebv) = arg.effective_boolean_value() {
102                if !ebv {
103                    return false.into();
104                }
105                // We ignore true values
106            } else if let Self::And(args) = arg {
107                all.extend(args);
108            } else {
109                all.push(arg);
110            }
111        }
112        match all.len() {
113            0 => true.into(),
114            1 => {
115                let result = all.pop().unwrap();
116                if result.returns_boolean() {
117                    result
118                } else {
119                    Self::And(vec![result])
120                }
121            }
122            _ => Self::And(order_vec(all)),
123        }
124    }
125
126    pub fn equal(left: Self, right: Self) -> Self {
127        match (left, right) {
128            (Self::NamedNode(left), Self::NamedNode(right)) => (left == right).into(),
129            (Self::Literal(left), Self::Literal(right)) if left == right => true.into(),
130            (left, right) => {
131                let (left, right) = order_pair(left, right);
132                Self::Equal(Box::new(left), Box::new(right))
133            }
134        }
135    }
136
137    pub fn same_term(left: Self, right: Self) -> Self {
138        match (left, right) {
139            (Self::NamedNode(left), Self::NamedNode(right)) => (left == right).into(),
140            (Self::Literal(left), Self::Literal(right)) if left == right => true.into(),
141            (left, right) => {
142                let (left, right) = order_pair(left, right);
143                Self::SameTerm(Box::new(left), Box::new(right))
144            }
145        }
146    }
147
148    pub fn greater(left: Self, right: Self) -> Self {
149        Self::Greater(Box::new(left), Box::new(right))
150    }
151
152    pub fn greater_or_equal(left: Self, right: Self) -> Self {
153        Self::GreaterOrEqual(Box::new(left), Box::new(right))
154    }
155
156    pub fn less(left: Self, right: Self) -> Self {
157        Self::Less(Box::new(left), Box::new(right))
158    }
159
160    pub fn less_or_equal(left: Self, right: Self) -> Self {
161        Self::LessOrEqual(Box::new(left), Box::new(right))
162    }
163
164    pub fn unary_plus(inner: Self) -> Self {
165        Self::UnaryPlus(Box::new(inner))
166    }
167
168    pub fn exists(inner: GraphPattern) -> Self {
169        if inner.is_empty() {
170            return false.into();
171        }
172        if inner.is_empty_singleton() {
173            return true.into();
174        }
175        Self::Exists(Box::new(inner))
176    }
177
178    pub fn if_cond(cond: Self, then: Self, els: Self) -> Self {
179        match cond.effective_boolean_value() {
180            Some(true) => then,
181            Some(false) => els,
182            None => Self::If(Box::new(cond), Box::new(then), Box::new(els)),
183        }
184    }
185
186    pub fn coalesce(args: Vec<Self>) -> Self {
187        Self::Coalesce(args)
188    }
189
190    pub fn call(name: Function, args: Vec<Self>) -> Self {
191        Self::FunctionCall(name, args)
192    }
193
194    pub fn effective_boolean_value(&self) -> Option<bool> {
195        if let Self::Literal(literal) = self {
196            match literal.datatype() {
197                xsd::BOOLEAN => match literal.value() {
198                    "true" | "1" => Some(true),
199                    "false" | "0" => Some(false),
200                    _ => None, // TODO
201                },
202                xsd::STRING => Some(!literal.value().is_empty()),
203                _ => None, // TODO
204            }
205        } else {
206            None
207        }
208    }
209
210    pub fn used_variables(&self) -> HashSet<&Variable> {
211        let mut variables = HashSet::new();
212        self.lookup_used_variables(&mut |v| {
213            variables.insert(v);
214        });
215        variables
216    }
217
218    pub fn lookup_used_variables<'a>(&'a self, callback: &mut impl FnMut(&'a Variable)) {
219        match self {
220            Self::NamedNode(_) | Self::Literal(_) => {}
221            Self::Variable(v) | Self::Bound(v) => callback(v),
222            Self::Or(inner)
223            | Self::And(inner)
224            | Self::Coalesce(inner)
225            | Self::FunctionCall(_, inner) => {
226                for i in inner {
227                    i.lookup_used_variables(callback);
228                }
229            }
230            Self::Equal(a, b)
231            | Self::SameTerm(a, b)
232            | Self::Greater(a, b)
233            | Self::GreaterOrEqual(a, b)
234            | Self::Less(a, b)
235            | Self::LessOrEqual(a, b)
236            | Self::Add(a, b)
237            | Self::Subtract(a, b)
238            | Self::Multiply(a, b)
239            | Self::Divide(a, b) => {
240                a.lookup_used_variables(callback);
241                b.lookup_used_variables(callback);
242            }
243            Self::UnaryPlus(i) | Self::UnaryMinus(i) | Self::Not(i) => {
244                i.lookup_used_variables(callback)
245            }
246            Self::Exists(e) => e.lookup_used_variables(callback),
247            Self::If(a, b, c) => {
248                a.lookup_used_variables(callback);
249                b.lookup_used_variables(callback);
250                c.lookup_used_variables(callback);
251            }
252        }
253    }
254
255    fn from_sparql_algebra(
256        expression: &AlExpression,
257        graph_name: Option<&NamedNodePattern>,
258    ) -> Self {
259        match expression {
260            AlExpression::NamedNode(node) => Self::NamedNode(node.clone()),
261            AlExpression::Literal(literal) => Self::Literal(literal.clone()),
262            AlExpression::Variable(variable) => Self::Variable(variable.clone()),
263            AlExpression::Or(left, right) => Self::Or(vec![
264                Self::from_sparql_algebra(left, graph_name),
265                Self::from_sparql_algebra(right, graph_name),
266            ]),
267            AlExpression::And(left, right) => Self::And(vec![
268                Self::from_sparql_algebra(left, graph_name),
269                Self::from_sparql_algebra(right, graph_name),
270            ]),
271            AlExpression::Equal(left, right) => Self::Equal(
272                Box::new(Self::from_sparql_algebra(left, graph_name)),
273                Box::new(Self::from_sparql_algebra(right, graph_name)),
274            ),
275            AlExpression::SameTerm(left, right) => Self::SameTerm(
276                Box::new(Self::from_sparql_algebra(left, graph_name)),
277                Box::new(Self::from_sparql_algebra(right, graph_name)),
278            ),
279            AlExpression::Greater(left, right) => Self::Greater(
280                Box::new(Self::from_sparql_algebra(left, graph_name)),
281                Box::new(Self::from_sparql_algebra(right, graph_name)),
282            ),
283            AlExpression::GreaterOrEqual(left, right) => Self::GreaterOrEqual(
284                Box::new(Self::from_sparql_algebra(left, graph_name)),
285                Box::new(Self::from_sparql_algebra(right, graph_name)),
286            ),
287            AlExpression::Less(left, right) => Self::Less(
288                Box::new(Self::from_sparql_algebra(left, graph_name)),
289                Box::new(Self::from_sparql_algebra(right, graph_name)),
290            ),
291            AlExpression::LessOrEqual(left, right) => Self::LessOrEqual(
292                Box::new(Self::from_sparql_algebra(left, graph_name)),
293                Box::new(Self::from_sparql_algebra(right, graph_name)),
294            ),
295            AlExpression::In(left, right) => {
296                let left = Self::from_sparql_algebra(left, graph_name);
297                match right.len() {
298                    0 => Self::if_cond(left, false.into(), false.into()),
299                    1 => Self::Equal(
300                        Box::new(left),
301                        Box::new(Self::from_sparql_algebra(&right[0], graph_name)),
302                    ),
303                    _ => Self::Or(
304                        right
305                            .iter()
306                            .map(|e| {
307                                Self::Equal(
308                                    Box::new(left.clone()),
309                                    Box::new(Self::from_sparql_algebra(e, graph_name)),
310                                )
311                            })
312                            .collect(),
313                    ),
314                }
315            }
316            AlExpression::Add(left, right) => Self::Add(
317                Box::new(Self::from_sparql_algebra(left, graph_name)),
318                Box::new(Self::from_sparql_algebra(right, graph_name)),
319            ),
320            AlExpression::Subtract(left, right) => Self::Subtract(
321                Box::new(Self::from_sparql_algebra(left, graph_name)),
322                Box::new(Self::from_sparql_algebra(right, graph_name)),
323            ),
324            AlExpression::Multiply(left, right) => Self::Multiply(
325                Box::new(Self::from_sparql_algebra(left, graph_name)),
326                Box::new(Self::from_sparql_algebra(right, graph_name)),
327            ),
328            AlExpression::Divide(left, right) => Self::Divide(
329                Box::new(Self::from_sparql_algebra(left, graph_name)),
330                Box::new(Self::from_sparql_algebra(right, graph_name)),
331            ),
332            AlExpression::UnaryPlus(inner) => {
333                Self::UnaryPlus(Box::new(Self::from_sparql_algebra(inner, graph_name)))
334            }
335            AlExpression::UnaryMinus(inner) => {
336                Self::UnaryMinus(Box::new(Self::from_sparql_algebra(inner, graph_name)))
337            }
338            AlExpression::Not(inner) => {
339                Self::Not(Box::new(Self::from_sparql_algebra(inner, graph_name)))
340            }
341            AlExpression::Exists(inner) => Self::Exists(Box::new(
342                GraphPattern::from_sparql_algebra(inner, graph_name, &mut HashMap::new()),
343            )),
344            AlExpression::Bound(variable) => Self::Bound(variable.clone()),
345            AlExpression::If(cond, yes, no) => Self::If(
346                Box::new(Self::from_sparql_algebra(cond, graph_name)),
347                Box::new(Self::from_sparql_algebra(yes, graph_name)),
348                Box::new(Self::from_sparql_algebra(no, graph_name)),
349            ),
350            AlExpression::Coalesce(inner) => Self::Coalesce(
351                inner
352                    .iter()
353                    .map(|e| Self::from_sparql_algebra(e, graph_name))
354                    .collect(),
355            ),
356            AlExpression::FunctionCall(name, args) => Self::FunctionCall(
357                name.clone(),
358                args.iter()
359                    .map(|e| Self::from_sparql_algebra(e, graph_name))
360                    .collect(),
361            ),
362        }
363    }
364
365    fn returns_boolean(&self) -> bool {
366        match self {
367            Self::Or(_)
368            | Self::And(_)
369            | Self::Equal(_, _)
370            | Self::SameTerm(_, _)
371            | Self::Greater(_, _)
372            | Self::GreaterOrEqual(_, _)
373            | Self::Less(_, _)
374            | Self::LessOrEqual(_, _)
375            | Self::Not(_)
376            | Self::Exists(_)
377            | Self::Bound(_)
378            | Self::FunctionCall(
379                Function::IsBlank | Function::IsIri | Function::IsLiteral | Function::IsNumeric,
380                _,
381            ) => true,
382            #[cfg(feature = "rdf-star")]
383            Self::FunctionCall(Function::IsTriple, _) => true,
384            Self::Literal(literal) => literal.datatype() == xsd::BOOLEAN,
385            Self::If(_, a, b) => a.returns_boolean() && b.returns_boolean(),
386            _ => false,
387        }
388    }
389}
390
391impl From<NamedNode> for Expression {
392    fn from(value: NamedNode) -> Self {
393        Self::NamedNode(value)
394    }
395}
396
397impl From<Literal> for Expression {
398    fn from(value: Literal) -> Self {
399        Self::Literal(value)
400    }
401}
402
403impl From<GroundSubject> for Expression {
404    fn from(value: GroundSubject) -> Self {
405        match value {
406            GroundSubject::NamedNode(value) => value.into(),
407            #[cfg(feature = "rdf-star")]
408            GroundSubject::Triple(value) => (*value).into(),
409        }
410    }
411}
412
413impl From<GroundTerm> for Expression {
414    fn from(value: GroundTerm) -> Self {
415        match value {
416            GroundTerm::NamedNode(value) => value.into(),
417            GroundTerm::Literal(value) => value.into(),
418            #[cfg(feature = "rdf-star")]
419            GroundTerm::Triple(value) => (*value).into(),
420        }
421    }
422}
423
424impl From<NamedNodePattern> for Expression {
425    fn from(value: NamedNodePattern) -> Self {
426        match value {
427            NamedNodePattern::NamedNode(value) => value.into(),
428            NamedNodePattern::Variable(variable) => variable.into(),
429        }
430    }
431}
432
433impl From<GroundTermPattern> for Expression {
434    fn from(value: GroundTermPattern) -> Self {
435        match value {
436            GroundTermPattern::NamedNode(value) => value.into(),
437            GroundTermPattern::Literal(value) => value.into(),
438            #[cfg(feature = "rdf-star")]
439            GroundTermPattern::Triple(value) => (*value).into(),
440            GroundTermPattern::Variable(variable) => variable.into(),
441        }
442    }
443}
444
445#[cfg(feature = "rdf-star")]
446impl From<GroundTriple> for Expression {
447    fn from(value: GroundTriple) -> Self {
448        Self::FunctionCall(
449            Function::Triple,
450            vec![
451                value.subject.into(),
452                value.predicate.into(),
453                value.object.into(),
454            ],
455        )
456    }
457}
458
459#[cfg(feature = "rdf-star")]
460impl From<GroundTriplePattern> for Expression {
461    fn from(value: GroundTriplePattern) -> Self {
462        Self::FunctionCall(
463            Function::Triple,
464            vec![
465                value.subject.into(),
466                value.predicate.into(),
467                value.object.into(),
468            ],
469        )
470    }
471}
472
473impl From<Variable> for Expression {
474    fn from(value: Variable) -> Self {
475        Self::Variable(value)
476    }
477}
478
479impl From<bool> for Expression {
480    fn from(value: bool) -> Self {
481        Literal::from(value).into()
482    }
483}
484
485impl From<&Expression> for AlExpression {
486    fn from(expression: &Expression) -> Self {
487        match expression {
488            Expression::NamedNode(node) => Self::NamedNode(node.clone()),
489            Expression::Literal(literal) => Self::Literal(literal.clone()),
490            Expression::Variable(variable) => Self::Variable(variable.clone()),
491            Expression::Or(inner) => inner
492                .iter()
493                .map(Into::into)
494                .reduce(|a, b| Self::Or(Box::new(a), Box::new(b)))
495                .unwrap_or_else(|| Literal::from(false).into()),
496            Expression::And(inner) => inner
497                .iter()
498                .map(Into::into)
499                .reduce(|a, b| Self::And(Box::new(a), Box::new(b)))
500                .unwrap_or_else(|| Literal::from(true).into()),
501            Expression::Equal(left, right) => Self::Equal(
502                Box::new(left.as_ref().into()),
503                Box::new(right.as_ref().into()),
504            ),
505            Expression::SameTerm(left, right) => Self::SameTerm(
506                Box::new(left.as_ref().into()),
507                Box::new(right.as_ref().into()),
508            ),
509            Expression::Greater(left, right) => Self::Greater(
510                Box::new(left.as_ref().into()),
511                Box::new(right.as_ref().into()),
512            ),
513            Expression::GreaterOrEqual(left, right) => Self::GreaterOrEqual(
514                Box::new(left.as_ref().into()),
515                Box::new(right.as_ref().into()),
516            ),
517            Expression::Less(left, right) => Self::Less(
518                Box::new(left.as_ref().into()),
519                Box::new(right.as_ref().into()),
520            ),
521            Expression::LessOrEqual(left, right) => Self::LessOrEqual(
522                Box::new(left.as_ref().into()),
523                Box::new(right.as_ref().into()),
524            ),
525            Expression::Add(left, right) => Self::Add(
526                Box::new(left.as_ref().into()),
527                Box::new(right.as_ref().into()),
528            ),
529            Expression::Subtract(left, right) => Self::Subtract(
530                Box::new(left.as_ref().into()),
531                Box::new(right.as_ref().into()),
532            ),
533            Expression::Multiply(left, right) => Self::Multiply(
534                Box::new(left.as_ref().into()),
535                Box::new(right.as_ref().into()),
536            ),
537            Expression::Divide(left, right) => Self::Divide(
538                Box::new(left.as_ref().into()),
539                Box::new(right.as_ref().into()),
540            ),
541            Expression::UnaryPlus(inner) => Self::UnaryPlus(Box::new(inner.as_ref().into())),
542            Expression::UnaryMinus(inner) => Self::UnaryMinus(Box::new(inner.as_ref().into())),
543            Expression::Not(inner) => Self::Not(Box::new(inner.as_ref().into())),
544            Expression::Exists(inner) => Self::Exists(Box::new(inner.as_ref().into())),
545            Expression::Bound(variable) => Self::Bound(variable.clone()),
546            Expression::If(cond, yes, no) => Self::If(
547                Box::new(cond.as_ref().into()),
548                Box::new(yes.as_ref().into()),
549                Box::new(no.as_ref().into()),
550            ),
551            Expression::Coalesce(inner) => Self::Coalesce(inner.iter().map(Into::into).collect()),
552            Expression::FunctionCall(name, args) => {
553                Self::FunctionCall(name.clone(), args.iter().map(Into::into).collect())
554            }
555        }
556    }
557}
558
559impl BitAnd for Expression {
560    type Output = Self;
561
562    fn bitand(self, rhs: Self) -> Self::Output {
563        Self::and_all([self, rhs])
564    }
565}
566
567impl BitOr for Expression {
568    type Output = Self;
569
570    fn bitor(self, rhs: Self) -> Self {
571        Self::or_all([self, rhs])
572    }
573}
574
575impl Not for Expression {
576    type Output = Self;
577
578    fn not(self) -> Self {
579        if let Some(v) = self.effective_boolean_value() {
580            (!v).into()
581        } else if let Self::Not(v) = self {
582            if v.returns_boolean() {
583                *v
584            } else {
585                Self::And(vec![*v])
586            }
587        } else {
588            Self::Not(Box::new(self))
589        }
590    }
591}
592
593impl Add for Expression {
594    type Output = Self;
595
596    fn add(self, rhs: Self) -> Self {
597        let (left, right) = order_pair(self, rhs);
598        Self::Add(Box::new(left), Box::new(right))
599    }
600}
601
602impl Sub for Expression {
603    type Output = Self;
604
605    fn sub(self, rhs: Self) -> Self {
606        Self::Subtract(Box::new(self), Box::new(rhs))
607    }
608}
609
610impl Mul for Expression {
611    type Output = Self;
612
613    fn mul(self, rhs: Self) -> Self {
614        let (left, right) = order_pair(self, rhs);
615        Self::Multiply(Box::new(left), Box::new(right))
616    }
617}
618
619impl Div for Expression {
620    type Output = Self;
621
622    fn div(self, rhs: Self) -> Self {
623        Self::Divide(Box::new(self), Box::new(rhs))
624    }
625}
626
627impl Neg for Expression {
628    type Output = Self;
629
630    fn neg(self) -> Self {
631        Self::UnaryMinus(Box::new(self))
632    }
633}
634
635/// A SPARQL query [graph pattern](https://www.w3.org/TR/sparql11-query/#sparqlQuery).
636#[derive(Eq, PartialEq, Debug, Clone, Hash)]
637pub enum GraphPattern {
638    /// A [basic graph pattern](https://www.w3.org/TR/sparql11-query/#defn_BasicGraphPattern).
639    QuadPattern {
640        subject: GroundTermPattern,
641        predicate: NamedNodePattern,
642        object: GroundTermPattern,
643        graph_name: Option<NamedNodePattern>,
644    },
645    /// A [property path pattern](https://www.w3.org/TR/sparql11-query/#defn_evalPP_predicate).
646    Path {
647        subject: GroundTermPattern,
648        path: PropertyPathExpression,
649        object: GroundTermPattern,
650        graph_name: Option<NamedNodePattern>,
651    },
652    /// [Join](https://www.w3.org/TR/sparql11-query/#defn_algJoin).
653    Join {
654        left: Box<Self>,
655        right: Box<Self>,
656        algorithm: JoinAlgorithm,
657    },
658    /// [LeftJoin](https://www.w3.org/TR/sparql11-query/#defn_algLeftJoin).
659    LeftJoin {
660        left: Box<Self>,
661        right: Box<Self>,
662        expression: Expression,
663        algorithm: LeftJoinAlgorithm,
664    },
665    /// Lateral join i.e. evaluate right for all result row of left
666    #[cfg(feature = "sep-0006")]
667    Lateral { left: Box<Self>, right: Box<Self> },
668    /// [Filter](https://www.w3.org/TR/sparql11-query/#defn_algFilter).
669    Filter {
670        expression: Expression,
671        inner: Box<Self>,
672    },
673    /// [Union](https://www.w3.org/TR/sparql11-query/#defn_algUnion).
674    Union { inner: Vec<Self> },
675    /// [Extend](https://www.w3.org/TR/sparql11-query/#defn_extend).
676    Extend {
677        inner: Box<Self>,
678        variable: Variable,
679        expression: Expression,
680    },
681    /// [Minus](https://www.w3.org/TR/sparql11-query/#defn_algMinus).
682    Minus {
683        left: Box<Self>,
684        right: Box<Self>,
685        algorithm: MinusAlgorithm,
686    },
687    /// A table used to provide inline values
688    Values {
689        variables: Vec<Variable>,
690        bindings: Vec<Vec<Option<GroundTerm>>>,
691    },
692    /// [OrderBy](https://www.w3.org/TR/sparql11-query/#defn_algOrdered).
693    OrderBy {
694        inner: Box<Self>,
695        expression: Vec<OrderExpression>,
696    },
697    /// [Project](https://www.w3.org/TR/sparql11-query/#defn_algProjection).
698    Project {
699        inner: Box<Self>,
700        variables: Vec<Variable>,
701    },
702    /// [Distinct](https://www.w3.org/TR/sparql11-query/#defn_algDistinct).
703    Distinct { inner: Box<Self> },
704    /// [Reduced](https://www.w3.org/TR/sparql11-query/#defn_algReduced).
705    Reduced { inner: Box<Self> },
706    /// [Slice](https://www.w3.org/TR/sparql11-query/#defn_algSlice).
707    Slice {
708        inner: Box<Self>,
709        start: usize,
710        length: Option<usize>,
711    },
712    /// [Group](https://www.w3.org/TR/sparql11-query/#aggregateAlgebra).
713    Group {
714        inner: Box<Self>,
715        variables: Vec<Variable>,
716        aggregates: Vec<(Variable, AggregateExpression)>,
717    },
718    /// [Service](https://www.w3.org/TR/sparql11-federated-query/#defn_evalService).
719    Service {
720        name: NamedNodePattern,
721        inner: Box<Self>,
722        silent: bool,
723    },
724}
725
726impl GraphPattern {
727    pub fn empty() -> Self {
728        Self::Values {
729            variables: Vec::new(),
730            bindings: Vec::new(),
731        }
732    }
733
734    /// Check if the pattern is the empty table
735    fn is_empty(&self) -> bool {
736        if let Self::Values { bindings, .. } = self {
737            bindings.is_empty()
738        } else {
739            false
740        }
741    }
742
743    pub fn empty_singleton() -> Self {
744        Self::Values {
745            variables: Vec::new(),
746            bindings: vec![Vec::new()],
747        }
748    }
749
750    pub fn is_empty_singleton(&self) -> bool {
751        if let Self::Values { bindings, .. } = self {
752            bindings.len() == 1 && bindings.iter().all(|b| b.iter().all(Option::is_none))
753        } else {
754            false
755        }
756    }
757
758    pub fn join(left: Self, right: Self, algorithm: JoinAlgorithm) -> Self {
759        if left.is_empty() || right.is_empty() {
760            return Self::empty();
761        }
762        if left.is_empty_singleton() {
763            return right;
764        }
765        if right.is_empty_singleton() {
766            return left;
767        }
768        Self::Join {
769            left: Box::new(left),
770            right: Box::new(right),
771            algorithm,
772        }
773    }
774
775    #[cfg(feature = "sep-0006")]
776    pub fn lateral(left: Self, right: Self) -> Self {
777        if left.is_empty() || right.is_empty() {
778            return Self::empty();
779        }
780        if left.is_empty_singleton() {
781            return right;
782        }
783        if right.is_empty_singleton() {
784            return left;
785        }
786        Self::Lateral {
787            left: Box::new(left),
788            right: Box::new(right),
789        }
790    }
791
792    pub fn left_join(
793        left: Self,
794        right: Self,
795        expression: Expression,
796        algorithm: LeftJoinAlgorithm,
797    ) -> Self {
798        let expression_ebv = expression.effective_boolean_value();
799        if left.is_empty()
800            || right.is_empty()
801            || right.is_empty_singleton()
802            || expression_ebv == Some(false)
803        {
804            return left;
805        }
806        Self::LeftJoin {
807            left: Box::new(left),
808            right: Box::new(right),
809            expression: if expression_ebv == Some(true) {
810                true.into()
811            } else {
812                expression
813            },
814            algorithm,
815        }
816    }
817
818    pub fn minus(left: Self, right: Self, algorithm: MinusAlgorithm) -> Self {
819        if left.is_empty() {
820            return Self::empty();
821        }
822        if right.is_empty() {
823            return left;
824        }
825        Self::Minus {
826            left: Box::new(left),
827            right: Box::new(right),
828            algorithm,
829        }
830    }
831
832    pub fn union(left: Self, right: Self) -> Self {
833        Self::union_all([left, right])
834    }
835
836    pub fn union_all(args: impl IntoIterator<Item = Self>) -> Self {
837        let args = args.into_iter();
838        let mut all = Vec::with_capacity(args.size_hint().0);
839        for arg in args {
840            if arg.is_empty() {
841                continue;
842            }
843            if let Self::Union { inner } = arg {
844                all.extend(inner);
845            } else {
846                all.push(arg);
847            }
848        }
849        if all.is_empty() {
850            Self::empty()
851        } else {
852            Self::Union {
853                inner: order_vec(all),
854            }
855        }
856    }
857
858    pub fn filter(inner: Self, expression: Expression) -> Self {
859        if inner.is_empty() {
860            return Self::empty();
861        }
862        // We unwrap singleton And
863        let expression = match expression {
864            Expression::And(mut l) if l.len() == 1 => l.pop().unwrap(),
865            e => e,
866        };
867        match expression.effective_boolean_value() {
868            Some(true) => inner,
869            Some(false) => Self::empty(),
870            None => match inner {
871                Self::Filter {
872                    inner,
873                    expression: e2,
874                } => Self::Filter {
875                    inner,
876                    expression: expression & e2,
877                },
878                _ => Self::Filter {
879                    inner: Box::new(inner),
880                    expression,
881                },
882            },
883        }
884    }
885
886    pub fn extend(inner: Self, variable: Variable, expression: Expression) -> Self {
887        if inner.is_empty() {
888            return Self::empty();
889        }
890        Self::Extend {
891            inner: Box::new(inner),
892            variable,
893            expression,
894        }
895    }
896
897    pub fn values(
898        mut variables: Vec<Variable>,
899        mut bindings: Vec<Vec<Option<GroundTerm>>>,
900    ) -> Self {
901        let empty_rows = (0..variables.len())
902            .filter(|row| !bindings.iter().any(|binding| binding.get(*row).is_some()))
903            .collect::<Vec<_>>();
904        if !empty_rows.is_empty() {
905            // We remove empty rows
906            variables = variables
907                .into_iter()
908                .enumerate()
909                .filter_map(|(i, v)| {
910                    if empty_rows.contains(&i) {
911                        None
912                    } else {
913                        Some(v)
914                    }
915                })
916                .collect();
917            bindings = bindings
918                .into_iter()
919                .map(|binding| {
920                    binding
921                        .into_iter()
922                        .enumerate()
923                        .filter_map(|(i, v)| {
924                            if empty_rows.contains(&i) {
925                                None
926                            } else {
927                                Some(v)
928                            }
929                        })
930                        .collect()
931                })
932                .collect();
933        }
934        Self::Values {
935            variables,
936            bindings,
937        }
938    }
939
940    pub fn order_by(inner: Self, expression: Vec<OrderExpression>) -> Self {
941        if inner.is_empty() {
942            return Self::empty();
943        }
944        if expression.is_empty() {
945            return inner;
946        }
947        Self::OrderBy {
948            inner: Box::new(inner),
949            expression,
950        }
951    }
952
953    pub fn project(inner: Self, variables: Vec<Variable>) -> Self {
954        Self::Project {
955            inner: Box::new(inner),
956            variables,
957        }
958    }
959
960    pub fn distinct(inner: Self) -> Self {
961        if inner.is_empty() {
962            return Self::empty();
963        }
964        Self::Distinct {
965            inner: Box::new(inner),
966        }
967    }
968
969    pub fn reduced(inner: Self) -> Self {
970        if inner.is_empty() {
971            return Self::empty();
972        }
973        Self::Reduced {
974            inner: Box::new(inner),
975        }
976    }
977
978    pub fn slice(inner: Self, start: usize, length: Option<usize>) -> Self {
979        if inner.is_empty() {
980            return Self::empty();
981        }
982        if start == 0 && length.is_none() {
983            return inner;
984        }
985        Self::Slice {
986            inner: Box::new(inner),
987            start,
988            length,
989        }
990    }
991
992    pub fn group(
993        inner: Self,
994        variables: Vec<Variable>,
995        aggregates: Vec<(Variable, AggregateExpression)>,
996    ) -> Self {
997        if inner.is_empty() {
998            return Self::empty();
999        }
1000        Self::Group {
1001            inner: Box::new(inner),
1002            variables,
1003            aggregates,
1004        }
1005    }
1006
1007    pub fn service(inner: Self, name: NamedNodePattern, silent: bool) -> Self {
1008        if inner.is_empty() {
1009            return Self::empty();
1010        }
1011        Self::Service {
1012            inner: Box::new(inner),
1013            name,
1014            silent,
1015        }
1016    }
1017
1018    pub fn lookup_used_variables<'a>(&'a self, callback: &mut impl FnMut(&'a Variable)) {
1019        match self {
1020            Self::Values { variables, .. } | Self::Project { variables, .. } => {
1021                for v in variables {
1022                    callback(v);
1023                }
1024            }
1025            Self::QuadPattern {
1026                subject,
1027                predicate,
1028                object,
1029                graph_name,
1030            } => {
1031                lookup_term_pattern_variables(subject, callback);
1032                if let NamedNodePattern::Variable(v) = predicate {
1033                    callback(v);
1034                }
1035                lookup_term_pattern_variables(object, callback);
1036                if let Some(NamedNodePattern::Variable(v)) = graph_name {
1037                    callback(v);
1038                }
1039            }
1040            Self::Path {
1041                subject,
1042                object,
1043                graph_name,
1044                ..
1045            } => {
1046                lookup_term_pattern_variables(subject, callback);
1047                lookup_term_pattern_variables(object, callback);
1048                if let Some(NamedNodePattern::Variable(v)) = graph_name {
1049                    callback(v);
1050                }
1051            }
1052            Self::Filter { inner, expression } => {
1053                expression.lookup_used_variables(callback);
1054                inner.lookup_used_variables(callback);
1055            }
1056            Self::Union { inner } => {
1057                for child in inner {
1058                    child.lookup_used_variables(callback);
1059                }
1060            }
1061            Self::Join { left, right, .. } | Self::Minus { left, right, .. } => {
1062                left.lookup_used_variables(callback);
1063                right.lookup_used_variables(callback);
1064            }
1065            #[cfg(feature = "sep-0006")]
1066            Self::Lateral { left, right } => {
1067                left.lookup_used_variables(callback);
1068                right.lookup_used_variables(callback);
1069            }
1070            Self::LeftJoin {
1071                left,
1072                right,
1073                expression,
1074                ..
1075            } => {
1076                expression.lookup_used_variables(callback);
1077                left.lookup_used_variables(callback);
1078                right.lookup_used_variables(callback);
1079            }
1080            Self::Extend {
1081                inner,
1082                variable,
1083                expression,
1084            } => {
1085                callback(variable);
1086                expression.lookup_used_variables(callback);
1087                inner.lookup_used_variables(callback);
1088            }
1089            Self::OrderBy { inner, .. }
1090            | Self::Distinct { inner }
1091            | Self::Reduced { inner }
1092            | Self::Slice { inner, .. } => inner.lookup_used_variables(callback),
1093            Self::Service { inner, name, .. } => {
1094                if let NamedNodePattern::Variable(v) = name {
1095                    callback(v);
1096                }
1097                inner.lookup_used_variables(callback);
1098            }
1099            Self::Group {
1100                variables,
1101                aggregates,
1102                ..
1103            } => {
1104                for v in variables {
1105                    callback(v);
1106                }
1107                for (v, _) in aggregates {
1108                    callback(v);
1109                }
1110            }
1111        }
1112    }
1113
1114    fn from_sparql_algebra(
1115        pattern: &AlGraphPattern,
1116        graph_name: Option<&NamedNodePattern>,
1117        blank_nodes: &mut HashMap<BlankNode, Variable>,
1118    ) -> Self {
1119        match pattern {
1120            AlGraphPattern::Bgp { patterns } => patterns
1121                .iter()
1122                .map(|p| {
1123                    let (subject, predicate, object) =
1124                        Self::triple_pattern_from_algebra(p, blank_nodes);
1125                    Self::QuadPattern {
1126                        subject,
1127                        predicate,
1128                        object,
1129                        graph_name: graph_name.cloned(),
1130                    }
1131                })
1132                .reduce(|a, b| Self::Join {
1133                    left: Box::new(a),
1134                    right: Box::new(b),
1135                    algorithm: JoinAlgorithm::default(),
1136                })
1137                .unwrap_or_else(Self::empty_singleton),
1138            AlGraphPattern::Path {
1139                subject,
1140                path,
1141                object,
1142            } => Self::Path {
1143                subject: Self::term_pattern_from_algebra(subject, blank_nodes),
1144                path: path.clone(),
1145                object: Self::term_pattern_from_algebra(object, blank_nodes),
1146                graph_name: graph_name.cloned(),
1147            },
1148            AlGraphPattern::Join { left, right } => Self::Join {
1149                left: Box::new(Self::from_sparql_algebra(left, graph_name, blank_nodes)),
1150                right: Box::new(Self::from_sparql_algebra(right, graph_name, blank_nodes)),
1151                algorithm: JoinAlgorithm::default(),
1152            },
1153            AlGraphPattern::LeftJoin {
1154                left,
1155                right,
1156                expression,
1157            } => Self::LeftJoin {
1158                left: Box::new(Self::from_sparql_algebra(left, graph_name, blank_nodes)),
1159                right: Box::new(Self::from_sparql_algebra(right, graph_name, blank_nodes)),
1160                expression: expression.as_ref().map_or_else(
1161                    || true.into(),
1162                    |e| Expression::from_sparql_algebra(e, graph_name),
1163                ),
1164                algorithm: LeftJoinAlgorithm::default(),
1165            },
1166            #[cfg(feature = "sep-0006")]
1167            AlGraphPattern::Lateral { left, right } => Self::Lateral {
1168                left: Box::new(Self::from_sparql_algebra(left, graph_name, blank_nodes)),
1169                right: Box::new(Self::from_sparql_algebra(right, graph_name, blank_nodes)),
1170            },
1171            AlGraphPattern::Filter { inner, expr } => Self::Filter {
1172                inner: Box::new(Self::from_sparql_algebra(inner, graph_name, blank_nodes)),
1173                expression: Expression::from_sparql_algebra(expr, graph_name),
1174            },
1175            AlGraphPattern::Union { left, right } => Self::Union {
1176                inner: vec![
1177                    Self::from_sparql_algebra(left, graph_name, blank_nodes),
1178                    Self::from_sparql_algebra(right, graph_name, blank_nodes),
1179                ],
1180            },
1181            AlGraphPattern::Graph { inner, name } => {
1182                Self::from_sparql_algebra(inner, Some(name), blank_nodes)
1183            }
1184            AlGraphPattern::Extend {
1185                inner,
1186                expression,
1187                variable,
1188            } => Self::Extend {
1189                inner: Box::new(Self::from_sparql_algebra(inner, graph_name, blank_nodes)),
1190                expression: Expression::from_sparql_algebra(expression, graph_name),
1191                variable: variable.clone(),
1192            },
1193            AlGraphPattern::Minus { left, right } => Self::Minus {
1194                left: Box::new(Self::from_sparql_algebra(left, graph_name, blank_nodes)),
1195                right: Box::new(Self::from_sparql_algebra(right, graph_name, blank_nodes)),
1196                algorithm: MinusAlgorithm::default(),
1197            },
1198            AlGraphPattern::Values {
1199                variables,
1200                bindings,
1201            } => Self::Values {
1202                variables: variables.clone(),
1203                bindings: bindings.clone(),
1204            },
1205            AlGraphPattern::OrderBy { inner, expression } => Self::OrderBy {
1206                inner: Box::new(Self::from_sparql_algebra(inner, graph_name, blank_nodes)),
1207                expression: expression
1208                    .iter()
1209                    .map(|e| OrderExpression::from_sparql_algebra(e, graph_name))
1210                    .collect(),
1211            },
1212            AlGraphPattern::Project { inner, variables } => {
1213                let graph_name = if let Some(NamedNodePattern::Variable(graph_name)) = graph_name {
1214                    Some(NamedNodePattern::Variable(
1215                        if variables.contains(graph_name) {
1216                            graph_name.clone()
1217                        } else {
1218                            new_var()
1219                        },
1220                    ))
1221                } else {
1222                    graph_name.cloned()
1223                };
1224                Self::Project {
1225                    inner: Box::new(Self::from_sparql_algebra(
1226                        inner,
1227                        graph_name.as_ref(),
1228                        &mut HashMap::new(),
1229                    )),
1230                    variables: variables.clone(),
1231                }
1232            }
1233            AlGraphPattern::Distinct { inner } => Self::Distinct {
1234                inner: Box::new(Self::from_sparql_algebra(inner, graph_name, blank_nodes)),
1235            },
1236            AlGraphPattern::Reduced { inner } => Self::Distinct {
1237                inner: Box::new(Self::from_sparql_algebra(inner, graph_name, blank_nodes)),
1238            },
1239            AlGraphPattern::Slice {
1240                inner,
1241                start,
1242                length,
1243            } => Self::Slice {
1244                inner: Box::new(Self::from_sparql_algebra(inner, graph_name, blank_nodes)),
1245                start: *start,
1246                length: *length,
1247            },
1248            AlGraphPattern::Group {
1249                inner,
1250                variables,
1251                aggregates,
1252            } => Self::Group {
1253                inner: Box::new(Self::from_sparql_algebra(inner, graph_name, blank_nodes)),
1254                variables: variables.clone(),
1255                aggregates: aggregates
1256                    .iter()
1257                    .map(|(var, expr)| {
1258                        (
1259                            var.clone(),
1260                            AggregateExpression::from_sparql_algebra(expr, graph_name),
1261                        )
1262                    })
1263                    .collect(),
1264            },
1265            AlGraphPattern::Service {
1266                inner,
1267                name,
1268                silent,
1269            } => Self::Service {
1270                inner: Box::new(Self::from_sparql_algebra(inner, graph_name, blank_nodes)),
1271                name: name.clone(),
1272                silent: *silent,
1273            },
1274        }
1275    }
1276
1277    fn triple_pattern_from_algebra(
1278        pattern: &TriplePattern,
1279        blank_nodes: &mut HashMap<BlankNode, Variable>,
1280    ) -> (GroundTermPattern, NamedNodePattern, GroundTermPattern) {
1281        (
1282            Self::term_pattern_from_algebra(&pattern.subject, blank_nodes),
1283            pattern.predicate.clone(),
1284            Self::term_pattern_from_algebra(&pattern.object, blank_nodes),
1285        )
1286    }
1287
1288    fn term_pattern_from_algebra(
1289        pattern: &TermPattern,
1290        blank_nodes: &mut HashMap<BlankNode, Variable>,
1291    ) -> GroundTermPattern {
1292        match pattern {
1293            TermPattern::NamedNode(node) => node.clone().into(),
1294            TermPattern::BlankNode(node) => blank_nodes
1295                .entry(node.clone())
1296                .or_insert_with(new_var)
1297                .clone()
1298                .into(),
1299            TermPattern::Literal(literal) => literal.clone().into(),
1300            #[cfg(feature = "rdf-star")]
1301            TermPattern::Triple(pattern) => {
1302                let (subject, predicate, object) =
1303                    Self::triple_pattern_from_algebra(pattern, blank_nodes);
1304                GroundTriplePattern {
1305                    subject,
1306                    predicate,
1307                    object,
1308                }
1309                .into()
1310            }
1311            TermPattern::Variable(variable) => variable.clone().into(),
1312        }
1313    }
1314}
1315
1316impl From<&AlGraphPattern> for GraphPattern {
1317    fn from(pattern: &AlGraphPattern) -> Self {
1318        Self::from_sparql_algebra(pattern, None, &mut HashMap::new())
1319    }
1320}
1321
1322impl From<&GraphPattern> for AlGraphPattern {
1323    fn from(pattern: &GraphPattern) -> Self {
1324        match pattern {
1325            GraphPattern::QuadPattern {
1326                subject,
1327                predicate,
1328                object,
1329                graph_name,
1330            } => {
1331                let pattern = Self::Bgp {
1332                    patterns: vec![TriplePattern {
1333                        subject: subject.clone().into(),
1334                        predicate: predicate.clone(),
1335                        object: object.clone().into(),
1336                    }],
1337                };
1338                if let Some(graph_name) = graph_name {
1339                    Self::Graph {
1340                        inner: Box::new(pattern),
1341                        name: graph_name.clone(),
1342                    }
1343                } else {
1344                    pattern
1345                }
1346            }
1347            GraphPattern::Path {
1348                subject,
1349                path,
1350                object,
1351                graph_name,
1352            } => {
1353                let pattern = Self::Path {
1354                    subject: subject.clone().into(),
1355                    path: path.clone(),
1356                    object: object.clone().into(),
1357                };
1358                if let Some(graph_name) = graph_name {
1359                    Self::Graph {
1360                        inner: Box::new(pattern),
1361                        name: graph_name.clone(),
1362                    }
1363                } else {
1364                    pattern
1365                }
1366            }
1367            GraphPattern::Join { left, right, .. } => {
1368                match (left.as_ref().into(), right.as_ref().into()) {
1369                    (Self::Bgp { patterns: mut left }, Self::Bgp { patterns: right }) => {
1370                        left.extend(right);
1371                        Self::Bgp { patterns: left }
1372                    }
1373                    (left, right) => Self::Join {
1374                        left: Box::new(left),
1375                        right: Box::new(right),
1376                    },
1377                }
1378            }
1379            GraphPattern::LeftJoin {
1380                left,
1381                right,
1382                expression,
1383                ..
1384            } => {
1385                let empty_expr = if let Expression::Literal(l) = expression {
1386                    l.datatype() == xsd::BOOLEAN && l.value() == "true"
1387                } else {
1388                    false
1389                };
1390                Self::LeftJoin {
1391                    left: Box::new(left.as_ref().into()),
1392                    right: Box::new(right.as_ref().into()),
1393                    expression: if empty_expr {
1394                        None
1395                    } else {
1396                        Some(expression.into())
1397                    },
1398                }
1399            }
1400            #[cfg(feature = "sep-0006")]
1401            GraphPattern::Lateral { left, right } => {
1402                match (left.as_ref().into(), right.as_ref().into()) {
1403                    (Self::Bgp { patterns: mut left }, Self::Bgp { patterns: right }) => {
1404                        left.extend(right);
1405                        Self::Bgp { patterns: left }
1406                    }
1407                    (left, right) => Self::Lateral {
1408                        left: Box::new(left),
1409                        right: Box::new(right),
1410                    },
1411                }
1412            }
1413            GraphPattern::Filter { inner, expression } => Self::Filter {
1414                inner: Box::new(inner.as_ref().into()),
1415                expr: expression.into(),
1416            },
1417            GraphPattern::Union { inner } => inner
1418                .iter()
1419                .map(Into::into)
1420                .reduce(|a, b| Self::Union {
1421                    left: Box::new(a),
1422                    right: Box::new(b),
1423                })
1424                .unwrap_or_else(|| Self::Values {
1425                    variables: Vec::new(),
1426                    bindings: Vec::new(),
1427                }),
1428            GraphPattern::Extend {
1429                inner,
1430                expression,
1431                variable,
1432            } => Self::Extend {
1433                inner: Box::new(inner.as_ref().into()),
1434                expression: expression.into(),
1435                variable: variable.clone(),
1436            },
1437            GraphPattern::Minus { left, right, .. } => Self::Minus {
1438                left: Box::new(left.as_ref().into()),
1439                right: Box::new(right.as_ref().into()),
1440            },
1441            GraphPattern::Values {
1442                variables,
1443                bindings,
1444            } => Self::Values {
1445                variables: variables.clone(),
1446                bindings: bindings.clone(),
1447            },
1448            GraphPattern::OrderBy { inner, expression } => Self::OrderBy {
1449                inner: Box::new(inner.as_ref().into()),
1450                expression: expression.iter().map(Into::into).collect(),
1451            },
1452            GraphPattern::Project { inner, variables } => Self::Project {
1453                inner: Box::new(inner.as_ref().into()),
1454                variables: variables.clone(),
1455            },
1456            GraphPattern::Distinct { inner } => Self::Distinct {
1457                inner: Box::new(inner.as_ref().into()),
1458            },
1459            GraphPattern::Reduced { inner } => Self::Distinct {
1460                inner: Box::new(inner.as_ref().into()),
1461            },
1462            GraphPattern::Slice {
1463                inner,
1464                start,
1465                length,
1466            } => Self::Slice {
1467                inner: Box::new(inner.as_ref().into()),
1468                start: *start,
1469                length: *length,
1470            },
1471            GraphPattern::Group {
1472                inner,
1473                variables,
1474                aggregates,
1475            } => Self::Group {
1476                inner: Box::new(inner.as_ref().into()),
1477                variables: variables.clone(),
1478                aggregates: aggregates
1479                    .iter()
1480                    .map(|(var, expr)| (var.clone(), expr.into()))
1481                    .collect(),
1482            },
1483            GraphPattern::Service {
1484                inner,
1485                name,
1486                silent,
1487            } => Self::Service {
1488                inner: Box::new(inner.as_ref().into()),
1489                name: name.clone(),
1490                silent: *silent,
1491            },
1492        }
1493    }
1494}
1495
1496/// The join algorithm used (c.f. [`GraphPattern::Join`]).
1497#[derive(Eq, PartialEq, Debug, Clone, Hash)]
1498pub enum JoinAlgorithm {
1499    HashBuildLeftProbeRight { keys: Vec<Variable> },
1500}
1501
1502impl Default for JoinAlgorithm {
1503    fn default() -> Self {
1504        Self::HashBuildLeftProbeRight {
1505            keys: Vec::default(),
1506        }
1507    }
1508}
1509
1510/// The left join algorithm used (c.f. [`GraphPattern::LeftJoin`]).
1511#[derive(Eq, PartialEq, Debug, Clone, Hash)]
1512pub enum LeftJoinAlgorithm {
1513    HashBuildRightProbeLeft { keys: Vec<Variable> },
1514}
1515
1516impl Default for LeftJoinAlgorithm {
1517    fn default() -> Self {
1518        Self::HashBuildRightProbeLeft {
1519            keys: Vec::default(),
1520        }
1521    }
1522}
1523
1524/// The left join algorithm used (c.f. [`GraphPattern::Minus`]).
1525#[derive(Eq, PartialEq, Debug, Clone, Hash)]
1526pub enum MinusAlgorithm {
1527    HashBuildRightProbeLeft { keys: Vec<Variable> },
1528}
1529
1530impl Default for MinusAlgorithm {
1531    fn default() -> Self {
1532        Self::HashBuildRightProbeLeft {
1533            keys: Vec::default(),
1534        }
1535    }
1536}
1537
1538/// A set function used in aggregates (c.f. [`GraphPattern::Group`]).
1539#[derive(Eq, PartialEq, Debug, Clone, Hash)]
1540pub enum AggregateExpression {
1541    CountSolutions {
1542        distinct: bool,
1543    },
1544    FunctionCall {
1545        name: AggregateFunction,
1546        expr: Expression,
1547        distinct: bool,
1548    },
1549}
1550
1551impl AggregateExpression {
1552    fn from_sparql_algebra(
1553        expression: &AlAggregateExpression,
1554        graph_name: Option<&NamedNodePattern>,
1555    ) -> Self {
1556        match expression {
1557            AlAggregateExpression::CountSolutions { distinct } => Self::CountSolutions {
1558                distinct: *distinct,
1559            },
1560            AlAggregateExpression::FunctionCall {
1561                name,
1562                expr,
1563                distinct,
1564            } => Self::FunctionCall {
1565                name: name.clone(),
1566                expr: Expression::from_sparql_algebra(expr, graph_name),
1567                distinct: *distinct,
1568            },
1569        }
1570    }
1571}
1572
1573impl From<&AggregateExpression> for AlAggregateExpression {
1574    fn from(expression: &AggregateExpression) -> Self {
1575        match expression {
1576            AggregateExpression::CountSolutions { distinct } => Self::CountSolutions {
1577                distinct: *distinct,
1578            },
1579            AggregateExpression::FunctionCall {
1580                name,
1581                expr,
1582                distinct,
1583            } => Self::FunctionCall {
1584                name: name.clone(),
1585                expr: expr.into(),
1586                distinct: *distinct,
1587            },
1588        }
1589    }
1590}
1591
1592/// An ordering comparator used by [`GraphPattern::OrderBy`].
1593#[derive(Eq, PartialEq, Debug, Clone, Hash)]
1594pub enum OrderExpression {
1595    /// Ascending order
1596    Asc(Expression),
1597    /// Descending order
1598    Desc(Expression),
1599}
1600
1601impl OrderExpression {
1602    fn from_sparql_algebra(
1603        expression: &AlOrderExpression,
1604        graph_name: Option<&NamedNodePattern>,
1605    ) -> Self {
1606        match expression {
1607            AlOrderExpression::Asc(e) => Self::Asc(Expression::from_sparql_algebra(e, graph_name)),
1608            AlOrderExpression::Desc(e) => {
1609                Self::Desc(Expression::from_sparql_algebra(e, graph_name))
1610            }
1611        }
1612    }
1613}
1614
1615impl From<&OrderExpression> for AlOrderExpression {
1616    fn from(expression: &OrderExpression) -> Self {
1617        match expression {
1618            OrderExpression::Asc(e) => Self::Asc(e.into()),
1619            OrderExpression::Desc(e) => Self::Desc(e.into()),
1620        }
1621    }
1622}
1623
1624fn new_var() -> Variable {
1625    Variable::new_unchecked(format!("{:x}", random::<u128>()))
1626}
1627
1628fn order_pair<T: Hash>(a: T, b: T) -> (T, T) {
1629    if hash(&a) <= hash(&b) {
1630        (a, b)
1631    } else {
1632        (b, a)
1633    }
1634}
1635
1636fn order_vec<T: Hash>(mut vec: Vec<T>) -> Vec<T> {
1637    vec.sort_unstable_by_key(|a| hash(a));
1638    vec
1639}
1640
1641fn hash(v: impl Hash) -> u64 {
1642    let mut hasher = DefaultHasher::new();
1643    v.hash(&mut hasher);
1644    hasher.finish()
1645}
1646
1647fn lookup_term_pattern_variables<'a>(
1648    pattern: &'a GroundTermPattern,
1649    callback: &mut impl FnMut(&'a Variable),
1650) {
1651    if let GroundTermPattern::Variable(v) = pattern {
1652        callback(v);
1653    }
1654    #[cfg(feature = "rdf-star")]
1655    if let GroundTermPattern::Triple(t) = pattern {
1656        lookup_term_pattern_variables(&t.subject, callback);
1657        if let NamedNodePattern::Variable(v) = &t.predicate {
1658            callback(v);
1659        }
1660        lookup_term_pattern_variables(&t.object, callback);
1661    }
1662}