sophia_api/
quad.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
//! A quad expresses a single fact within a context.
//! Quads are like RDF [`triples`](crate::triple)
//! augmented with an optional graph name.
//!
//! They are the individual statements of an RDF [datasets](crate::dataset).
use crate::term::matcher::{GraphNameMatcher, TermMatcher};
use crate::term::{graph_name_eq, GraphName, Term};

/// Type alias for terms borrowed from a quad.
pub type QBorrowTerm<'a, T> = <<T as Quad>::Term as Term>::BorrowTerm<'a>;
/// The typical structure representing a Quad of terms T
pub type Spog<T> = ([T; 3], GraphName<T>);
/// An alternative structure representing a Quad of terms T
/// (useful when sorting first by graph is required)
pub type Gspo<T> = (GraphName<T>, [T; 3]);

/// This trait represents an abstract RDF quad,
/// and provide convenient methods for working with quads.
pub trait Quad: Sized {
    /// The type of [`Term`] used by this quad when borrowing it
    type Term: Term;

    /// The subject of this quad.
    fn s(&self) -> QBorrowTerm<Self>;

    /// The predicate of this quad.
    fn p(&self) -> QBorrowTerm<Self>;

    /// The object of this quad.
    fn o(&self) -> QBorrowTerm<Self>;

    /// The graph name of this quad.
    ///
    /// `None` means that this quad belongs to the default graph of the dataset.
    fn g(&self) -> GraphName<QBorrowTerm<Self>>;

    /// The four components of this quad, as a quad of borrowed terms.
    ///
    /// See also [`Quad::to_spog`].
    #[inline]
    fn spog(&self) -> Spog<QBorrowTerm<Self>> {
        ([self.s(), self.p(), self.o()], self.g())
    }

    /// Consume this quad, returning its subject.
    fn to_s(self) -> Self::Term {
        let [s, _, _] = self.to_spog().0;
        s
    }

    /// Consume this quad, returning its predicate.
    fn to_p(self) -> Self::Term {
        let [_, p, _] = self.to_spog().0;
        p
    }

    /// Consume this quad, returning its object.
    fn to_o(self) -> Self::Term {
        let [_, _, o] = self.to_spog().0;
        o
    }

    /// Consume this quad, returning its graph name.
    fn to_g(self) -> GraphName<Self::Term> {
        self.to_spog().1
    }

    /// Consume this quad, returning all its components.
    ///
    /// See also [`Quad::spog`].
    fn to_spog(self) -> Spog<Self::Term>;

    /// Checks that the constituents terms of this quad match the respective matchers.
    fn matched_by<S, P, O, G>(&self, sm: S, pm: P, om: O, gm: G) -> bool
    where
        S: TermMatcher,
        P: TermMatcher,
        O: TermMatcher,
        G: GraphNameMatcher,
    {
        sm.matches(&self.s())
            && pm.matches(&self.p())
            && om.matches(&self.o())
            && gm.matches(self.g().as_ref())
    }

    /// Check whether `other` is term-wise equal (using [`Term::eq`]) to `self`.
    ///
    /// See also [`eq_spog`](Quad::eq_spog), [`matched_by`](Quad::matched_by).
    #[inline]
    fn eq<T: Quad>(&self, other: T) -> bool {
        self.eq_spog(other.s(), other.p(), other.o(), other.g())
    }

    /// Check whether the quad (`s`, `p`, `o`) is term-wise equal (using [`Term::eq`]) to `self`.
    ///
    /// See also [`eq`](Quad::eq), [`matched_by`](Quad::matched_by).
    fn eq_spog<S: Term, P: Term, O: Term, G: Term>(
        &self,
        s: S,
        p: P,
        o: O,
        g: GraphName<G>,
    ) -> bool {
        self.s().eq(s) && self.p().eq(p) && self.o().eq(o) && graph_name_eq(self.g(), g)
    }

    /// Convert this quad to a [`Triple`](crate::triple::Triple) (dropping the graph name)
    ///
    /// NB: if you do not wish to consume this quad,
    /// you can combine this method with [`spog`](Quad::spog) as below:
    /// ```
    /// # use sophia_api::quad::Quad;
    /// # use sophia_api::triple::Triple;
    /// # fn test<T: Quad>(q: &T) -> impl Triple + '_ {
    ///     q.spog().into_triple()   
    /// # }
    /// ```
    fn into_triple(self) -> [Self::Term; 3] {
        self.to_spog().0
    }
}

impl<T: Term> Quad for [T; 4] {
    type Term = T;

    fn s(&self) -> QBorrowTerm<Self> {
        self[0].borrow_term()
    }
    fn p(&self) -> QBorrowTerm<Self> {
        self[1].borrow_term()
    }
    fn o(&self) -> QBorrowTerm<Self> {
        self[2].borrow_term()
    }
    fn g(&self) -> GraphName<QBorrowTerm<Self>> {
        Some(self[3].borrow_term())
    }
    fn to_s(self) -> Self::Term {
        let [s, _, _, _] = self;
        s
    }
    fn to_p(self) -> Self::Term {
        let [_, p, _, _] = self;
        p
    }
    fn to_o(self) -> Self::Term {
        let [_, _, o, _] = self;
        o
    }
    fn to_g(self) -> GraphName<Self::Term> {
        let [_, _, _, g] = self;
        Some(g)
    }
    fn to_spog(self) -> Spog<Self::Term> {
        let [s, p, o, g] = self;
        ([s, p, o], Some(g))
    }
}

// Spog<T>
impl<T: Term> Quad for ([T; 3], GraphName<T>) {
    type Term = T;

    fn s(&self) -> QBorrowTerm<Self> {
        self.0[0].borrow_term()
    }
    fn p(&self) -> QBorrowTerm<Self> {
        self.0[1].borrow_term()
    }
    fn o(&self) -> QBorrowTerm<Self> {
        self.0[2].borrow_term()
    }
    fn g(&self) -> GraphName<QBorrowTerm<Self>> {
        self.1.as_ref().map(|gn| gn.borrow_term())
    }
    fn to_s(self) -> Self::Term {
        let [s, _, _] = self.0;
        s
    }
    fn to_p(self) -> Self::Term {
        let [_, p, _] = self.0;
        p
    }
    fn to_o(self) -> Self::Term {
        let [_, _, o] = self.0;
        o
    }
    fn to_g(self) -> GraphName<Self::Term> {
        self.1
    }
    fn to_spog(self) -> Spog<Self::Term> {
        self
    }
}

// Gspo<T>
impl<T: Term> Quad for (GraphName<T>, [T; 3]) {
    type Term = T;

    fn s(&self) -> QBorrowTerm<Self> {
        self.1[0].borrow_term()
    }
    fn p(&self) -> QBorrowTerm<Self> {
        self.1[1].borrow_term()
    }
    fn o(&self) -> QBorrowTerm<Self> {
        self.1[2].borrow_term()
    }
    fn g(&self) -> GraphName<QBorrowTerm<'_, Self>> {
        self.0.as_ref().map(|gn| gn.borrow_term())
    }
    fn to_s(self) -> Self::Term {
        let [s, _, _] = self.1;
        s
    }
    fn to_p(self) -> Self::Term {
        let [_, p, _] = self.1;
        p
    }
    fn to_o(self) -> Self::Term {
        let [_, _, o] = self.1;
        o
    }
    fn to_g(self) -> GraphName<Self::Term> {
        self.0
    }
    fn to_spog(self) -> Spog<Self::Term> {
        let (g, spo) = self;
        (spo, g)
    }
}

/// Iter over all the components of a [`Quad`]
pub fn iter_spog<T: Quad>(q: T) -> impl Iterator<Item = T::Term> {
    let (spo, g) = q.to_spog();
    spo.into_iter().chain(g)
}

#[cfg(test)]
mod check_implementability {
    use super::*;
    use crate::term::*;
    use mownstr::MownStr;

    #[derive(Clone, Copy, Debug)]
    struct MyBnode(usize);

    impl Term for MyBnode {
        type BorrowTerm<'x> = Self;

        fn kind(&self) -> TermKind {
            TermKind::BlankNode
        }
        fn bnode_id(&self) -> Option<BnodeId<MownStr>> {
            Some(BnodeId::new_unchecked(MownStr::from(format!(
                "b{}",
                self.0
            ))))
        }
        fn borrow_term(&self) -> Self::BorrowTerm<'_> {
            *self
        }
    }

    #[derive(Clone, Copy, Debug)]
    struct MyQuad([usize; 4]);

    impl Quad for MyQuad {
        type Term = MyBnode;

        fn s(&self) -> QBorrowTerm<Self> {
            MyBnode(self.0[0])
        }
        fn p(&self) -> QBorrowTerm<Self> {
            MyBnode(self.0[1])
        }
        fn o(&self) -> QBorrowTerm<Self> {
            MyBnode(self.0[2])
        }
        fn g(&self) -> GraphName<QBorrowTerm<Self>> {
            match self.0[3] {
                0 => None,
                n => Some(MyBnode(n)),
            }
        }
        fn to_s(self) -> Self::Term {
            self.s()
        }
        fn to_p(self) -> Self::Term {
            self.p()
        }
        fn to_o(self) -> Self::Term {
            self.o()
        }
        fn to_g(self) -> GraphName<Self::Term> {
            self.g()
        }
        fn to_spog(self) -> Spog<Self::Term> {
            ([self.s(), self.p(), self.o()], self.g())
        }
    }

    #[allow(dead_code)] // only checks that this compiles
    fn check_quad_impl(t: [SimpleTerm; 4]) {
        fn foo<T: Quad>(t: T) {
            println!("{:?}", t.s().kind());
        }
        let rt = t.spog();
        foo(rt);
        {
            let rt2 = t.spog();
            foo(rt2);
        }
        foo(rt);
        foo(rt.spog());
        foo(t);

        let mt = MyQuad([1, 2, 3, 0]);
        let rmt = mt.spog();
        foo(rmt);
        {
            let rmt2 = mt.spog();
            foo(rmt2);
        }
        foo(rmt);
        foo(rmt.spog());
        foo(mt);
    }
}

#[cfg(test)]
mod test_quad {
    use super::*;
    use crate::term::SimpleTerm;
    use sophia_iri::IriRef;

    const S: IriRef<&str> = IriRef::new_unchecked_const("tag:s");
    const P: IriRef<&str> = IriRef::new_unchecked_const("tag:o");
    const O: IriRef<&str> = IriRef::new_unchecked_const("tag:p");
    const G: GraphName<IriRef<&str>> = Some(IriRef::new_unchecked_const("tag:g"));

    #[test]
    fn quad_matched_by() {
        use crate::term::matcher::Any;
        let q = ([S, P, O], G);

        assert!(q.matched_by(Any, Any, Any, Any));
        assert!(q.matched_by([S], [P], [O], [G]));
        assert!(q.matched_by([O, S], [S, P], [P, O], [None, G]));
        let istag = |t: SimpleTerm| t.iri().map(|iri| iri.starts_with("tag:")).unwrap_or(false);
        assert!(q.matched_by(istag, istag, istag, istag.gn()));

        let none: Option<IriRef<&str>> = None;
        assert!(!q.matched_by(none, Any, Any, Any));
        assert!(!q.matched_by(Any, none, Any, Any));
        assert!(!q.matched_by(Any, Any, none, Any));
        assert!(!q.matched_by(Any, Any, Any, none.gn()));
        assert!(!q.matched_by([P, O], Any, Any, Any));
        assert!(!q.matched_by(Any, [S, O], Any, Any));
        assert!(!q.matched_by(Any, Any, [S, P], Any));
        assert!(!q.matched_by(Any, Any, Any, [S, P, O].gn()));
        let notag = |t: SimpleTerm| t.iri().map(|iri| !iri.starts_with("tag:")).unwrap_or(true);
        assert!(!q.matched_by(notag, Any, Any, Any));
        assert!(!q.matched_by(Any, notag, Any, Any));
        assert!(!q.matched_by(Any, Any, notag, Any));
        assert!(!q.matched_by(Any, Any, Any, notag.gn()));

        let ts = vec![
            ([S, P, S], G),
            ([S, P, P], G),
            ([S, P, O], G),
            ([P, P, S], G),
            ([P, P, P], G),
            ([P, P, O], G),
            ([O, P, S], G),
            ([O, P, P], G),
            ([O, P, O], G),
            ([S, P, S], None),
            ([P, P, P], None),
            ([O, P, O], None),
        ];
        let c = ts
            .iter()
            .filter(|t| t.matched_by([S, O], Any, [S, O], Any))
            .count();
        assert_eq!(c, 6);

        let default = G.filter(|_| false);
        let c = ts
            .iter()
            .filter(|t| t.matched_by([S], Any, Any, [default]))
            .count();
        assert_eq!(c, 1);
    }
}