srdf/srdf_parser/
rdf_node_parser.rs

1use std::{
2    collections::{HashMap, HashSet},
3    marker::PhantomData,
4};
5
6use iri_s::iri;
7use iri_s::IriS;
8use std::fmt::Debug;
9
10use crate::{
11    literal::Literal, matcher::Any, rdf_parser, FocusRDF, PResult, Query, RDFParseError, Rdf,
12    Triple, RDF_FIRST, RDF_NIL_STR, RDF_REST, RDF_TYPE,
13};
14use crate::{srdf_basic::Literal as _, Iri as _};
15
16/// By implementing the `RDFNodeParse` trait a type says that it can be used to parse RDF data which have a focus node.
17/// RDF data with a focus node have to implement the [`FocusRDF`] trait.
18pub trait RDFNodeParse<RDF: FocusRDF> {
19    /// The type which is returned if the parser is successful.
20    type Output;
21
22    /// Entry point to the parser. It moves the focus node of `rdf` to `node` and runs the parser.
23    ///
24    /// Returns the parsed result if the parser succeeds, or an error otherwise.
25    #[inline(always)]
26    fn parse(&mut self, node: &IriS, mut rdf: RDF) -> PResult<Self::Output> {
27        let iri: RDF::IRI = node.clone().into();
28        let focus = iri.into();
29        rdf.set_focus(&focus);
30        self.parse_impl(&mut rdf)
31    }
32
33    #[inline(always)]
34    fn by_ref(&mut self) -> ByRef<'_, Self>
35    where
36        Self: core::marker::Sized,
37    {
38        ByRef::new(self)
39    }
40
41    /// Parses the current focus node without modifying the state
42    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output>;
43
44    /// Uses `f` to map over the output of `self`. If `f` returns an error the parser fails.
45    ///
46    /// ```
47    /// # use iri_s::{IriS, iri};
48    /// # use srdf::SRDFGraph;
49    /// use srdf::{RDFNodeParse, RDFFormat, RDFParseError, ReaderMode, property_string, PResult};
50    ///     let s = r#"prefix : <http://example.org/>
51    ///     :x :p "1" .
52    ///   "#;
53    ///   let mut graph = SRDFGraph::from_str(s, &RDFFormat::Turtle, None, &ReaderMode::default()).unwrap();
54    ///   let x = iri!("http://example.org/x");
55    ///   let p = iri!("http://example.org/p");
56    ///   fn cnv_int(s: String) -> PResult<isize> {
57    ///      s.parse().map_err(|_| RDFParseError::Custom{ msg: format!("Error converting {s}")})
58    ///   }
59    ///   let mut parser = property_string(&p).flat_map(cnv_int);
60    ///   assert_eq!(parser.parse(&x, graph).unwrap(), 1)
61    /// ```
62    fn flat_map<F, O>(self, f: F) -> FlatMap<Self, F>
63    where
64        Self: Sized,
65        F: FnMut(Self::Output) -> PResult<O>,
66    {
67        flat_map(self, f)
68    }
69
70    /// Parses with `self` and applies `f` on the result if `self` parses successfully.
71    /// `f` may optionally fail with an error which is automatically converted to a `RDFParseError`.
72    ///
73    /// ```
74    /// # use iri_s::{IriS, iri};
75    /// # use srdf::srdf_graph::SRDFGraph;
76    /// use srdf::{RDFNodeParse, RDFFormat, RDFParseError, ReaderMode, property_string};
77    /// let s = r#"prefix : <http://example.org/>
78    ///        :x :p "1" .
79    ///   "#;
80    /// let mut graph = SRDFGraph::from_str(s, &RDFFormat::Turtle, None, &ReaderMode::default()).unwrap();
81    /// let x = iri!("http://example.org/x");
82    /// let p = iri!("http://example.org/p");
83    ///
84    ///
85    /// struct IntConversionError(String);
86    ///
87    /// fn cnv_int(s: String) -> Result<isize, IntConversionError> {
88    ///    s.parse().map_err(|_| IntConversionError(s))
89    /// }
90    ///
91    /// impl Into<RDFParseError> for IntConversionError {
92    ///     fn into(self) -> RDFParseError {
93    ///         RDFParseError::Custom { msg: format!("Int conversion error: {}", self.0)}
94    ///     }
95    /// }
96    ///
97    /// let mut parser = property_string(&p).and_then(cnv_int);
98    /// assert_eq!(parser.parse(&x, graph).unwrap(), 1)
99    /// ```
100    fn and_then<F, O, E>(self, f: F) -> AndThen<Self, F>
101    where
102        Self: Sized,
103        F: FnMut(Self::Output) -> Result<O, E>,
104        E: Into<RDFParseError>,
105    {
106        and_then(self, f)
107    }
108
109    /// Uses `f` to map over the parsed value.
110    ///
111    /// ```
112    /// # use iri_s::{IriS, iri};
113    /// # use srdf::srdf_graph::SRDFGraph;
114    /// use srdf::{RDFNodeParse, RDFFormat, ReaderMode, property_integer};
115    /// let s = r#"prefix : <http://example.org/>
116    ///          :x :p 1 .
117    ///  "#;
118    /// let mut graph = SRDFGraph::from_str(s, &RDFFormat::Turtle, None, &ReaderMode::default()).unwrap();
119    /// let p = iri!("http://example.org/p");
120    /// let mut parser = property_integer(&p).map(|n| n + 1);
121    /// assert_eq!(parser.parse(&iri!("http://example.org/x"), graph).unwrap(), 2)
122    /// ```
123    fn map<F, B>(self, f: F) -> Map<Self, F>
124    where
125        Self: Sized,
126        F: FnMut(Self::Output) -> B,
127    {
128        map(self, f)
129    }
130
131    /// Parses `self` followed by `p`.
132    /// Succeeds if both parsers succeed, otherwise fails.
133    /// Returns a tuple with both values on success.
134    ///
135    /// ```
136    /// # use iri_s::IriS;
137    /// # use srdf::srdf_graph::SRDFGraph;
138    /// # use srdf::{RDFNodeParse, RDFFormat, ReaderMode, property_bool, property_integer};
139    /// let s = r#"prefix : <http://example.org/>
140    ///       :x :p true ;
141    ///          :q 1    .
142    ///     "#;
143    /// let mut graph = SRDFGraph::from_str(s, &RDFFormat::Turtle, None, &ReaderMode::default()).unwrap();
144    /// let x = IriS::new_unchecked("http://example.org/x");
145    /// let p = IriS::new_unchecked("http://example.org/p");
146    /// let q = IriS::new_unchecked("http://example.org/q");
147    /// let mut parser = property_bool(&p).and(property_integer(&q));
148    /// assert_eq!(parser.parse(&x, graph).unwrap(), (true, 1))
149    /// ```
150    fn and<P2>(self, parser: P2) -> (Self, P2)
151    where
152        Self: Sized,
153        P2: RDFNodeParse<RDF>,
154    {
155        (self, parser)
156    }
157
158    /// Parses using `self` and then passes the value to `f` which returns a parser used to parse
159    /// the rest of the input.
160    fn then<N, F>(self, f: F) -> Then<Self, F>
161    where
162        Self: Sized,
163        F: FnMut(Self::Output) -> N,
164        N: RDFNodeParse<RDF>,
165    {
166        then(self, f)
167    }
168
169    /// Parses using `self` and then passes a reference to the value to `f` which returns a parser used to parse
170    /// the rest of the input.
171    fn then_ref<N, F>(self, f: F) -> ThenRef<Self, F>
172    where
173        Self: Sized,
174        F: FnMut(&Self::Output) -> N,
175        N: RDFNodeParse<RDF>,
176    {
177        then_ref(self, f)
178    }
179
180    /// Parses using `self` and then passes a reference to the mutable value to `f` which returns a parser used to parse
181    /// the rest of the input.
182    ///
183    /// ```
184    /// # use iri_s::IriS;
185    /// # use srdf::srdf_graph::SRDFGraph;
186    /// # use oxrdf::Term;
187    /// # use std::collections::HashSet;
188    /// use srdf::{RDFNodeParse, RDFFormat, ReaderMode, ok, property_integers};
189    ///     let s = r#"prefix : <http://example.org/>
190    ///       :x :p 1, 2, 3 .
191    ///     "#;
192    ///     let mut graph = SRDFGraph::from_str(s, &RDFFormat::Turtle, None, &ReaderMode::default()).unwrap();
193    ///     let x = IriS::new_unchecked("http://example.org/x");
194    ///     let p = IriS::new_unchecked("http://example.org/p");
195    ///     let mut parser = property_integers(&p).then_mut(move |ns| {
196    ///         ns.extend(vec![4, 5]);
197    ///         ok(ns)
198    ///      });
199    ///     assert_eq!(parser.parse(&x, graph).unwrap(), HashSet::from([1, 2, 3, 4, 5]))
200    /// ```
201    fn then_mut<N, F>(self, f: F) -> ThenMut<Self, F>
202    where
203        Self: Sized,
204        F: FnMut(&mut Self::Output) -> N,
205        N: RDFNodeParse<RDF>,
206    {
207        then_mut(self, f)
208    }
209
210    /// Returns a parser which attempts to parse using `self`. If `self` fails then it attempts `parser`.
211    ///
212    /// ```
213    /// # use iri_s::IriS;
214    /// # use srdf::srdf_graph::SRDFGraph;
215    /// # use srdf::{RDFNodeParse, RDFFormat, ReaderMode, property_bool};
216    /// # use std::collections::HashSet;
217    ///  let s = r#"prefix : <http://example.org/>
218    ///       :x :p 1, 2 ;
219    ///          :q true .
220    ///     "#;
221    ///  let mut graph = SRDFGraph::from_str(s, &RDFFormat::Turtle, None, &ReaderMode::default()).unwrap();
222    ///  let x = IriS::new_unchecked("http://example.org/x");
223    ///  let p = IriS::new_unchecked("http://example.org/p");
224    ///  let q = IriS::new_unchecked("http://example.org/q");
225    ///  let mut parser = property_bool(&p).or(property_bool(&q));
226    ///  assert_eq!(parser.parse(&x, graph).unwrap(), true)
227    /// ```
228    fn or<P2>(self, parser: P2) -> Or<Self, P2>
229    where
230        Self: Sized,
231        P2: RDFNodeParse<RDF, Output = Self::Output>,
232    {
233        or(self, parser)
234    }
235
236    /// Sets the focus node and returns ()
237    fn focus(self, node: &RDF::Term) -> SetFocus<RDF>
238    where
239        Self: Sized,
240    {
241        set_focus(node)
242    }
243
244    /// Discards the value of the current parser and returns the value of `parser`
245    ///
246    /// ```
247    /// # use iri_s::IriS;
248    /// # use srdf::{rdf_parser, RDFParser, RDF, RDFFormat, FocusRDF, ReaderMode, satisfy, RDFNodeParse, Query, Rdf, property_value, rdf_list, set_focus, parse_property_value_as_list, ok};
249    /// # use srdf::srdf_graph::SRDFGraph;
250    /// let s = r#"prefix : <http://example.org/>
251    ///            :x :p :y .
252    /// "#;
253    /// let mut graph = SRDFGraph::from_str(s, &RDFFormat::Turtle, None, &ReaderMode::default()).unwrap();
254    /// let p = IriS::new_unchecked("http://example.org/p");
255    /// let x = IriS::new_unchecked("http://example.org/x");
256    /// assert_eq!(
257    ///   property_value(&p).with(ok(&1))
258    ///   .parse(&x, graph).unwrap(),
259    ///   1
260    /// )
261    /// ```
262    fn with<P, A>(self, parser: P) -> With<Self, P>
263    where
264        Self: Sized,
265        P: RDFNodeParse<RDF, Output = A>,
266    {
267        with(self, parser)
268    }
269}
270
271impl<RDF, P1, P2, A> RDFNodeParse<RDF> for Result<P1, P2>
272where
273    RDF: FocusRDF,
274    P1: RDFNodeParse<RDF, Output = A>,
275    P2: RDFNodeParse<RDF, Output = A>,
276{
277    type Output = A;
278
279    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
280        match self {
281            Result::Ok(a) => a.parse_impl(rdf),
282            Err(a) => a.parse_impl(rdf),
283        }
284    }
285}
286
287impl<RDF, P1, P2, A, B> RDFNodeParse<RDF> for (P1, P2)
288where
289    RDF: FocusRDF,
290    P1: RDFNodeParse<RDF, Output = A>,
291    P2: RDFNodeParse<RDF, Output = B>,
292{
293    type Output = (A, B);
294
295    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
296        match self.0.parse_impl(rdf) {
297            Ok(a) => match self.1.parse_impl(rdf) {
298                Ok(b) => Ok((a, b)),
299                Err(e) => Err(e),
300            },
301            Err(e) => Err(e),
302        }
303    }
304}
305
306/// Applies a function `f` on the result of a parser
307///
308pub fn map<RDF, P, F, B>(parser: P, f: F) -> Map<P, F>
309where
310    RDF: FocusRDF,
311    P: RDFNodeParse<RDF>,
312    F: FnMut(P::Output) -> B,
313{
314    Map { parser, f }
315}
316
317#[derive(Copy, Clone)]
318pub struct Map<P, F> {
319    parser: P,
320    f: F,
321}
322
323impl<RDF, A, B, P, F> RDFNodeParse<RDF> for Map<P, F>
324where
325    RDF: FocusRDF,
326    P: RDFNodeParse<RDF, Output = A>,
327    F: FnMut(A) -> B,
328{
329    type Output = B;
330
331    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
332        match self.parser.parse_impl(rdf) {
333            Ok(a) => Ok((self.f)(a)),
334            Err(e) => Err(e),
335        }
336    }
337}
338
339pub fn and_then<RDF, P, F, O, E>(parser: P, function: F) -> AndThen<P, F>
340where
341    RDF: FocusRDF,
342    P: RDFNodeParse<RDF>,
343    F: FnMut(P::Output) -> Result<O, E>,
344    E: Into<RDFParseError>,
345{
346    AndThen { parser, function }
347}
348
349#[derive(Copy, Clone)]
350pub struct AndThen<P, F> {
351    parser: P,
352    function: F,
353}
354
355impl<RDF, P, F, O, E> RDFNodeParse<RDF> for AndThen<P, F>
356where
357    RDF: FocusRDF,
358    P: RDFNodeParse<RDF>,
359    F: FnMut(P::Output) -> Result<O, E>,
360    E: Into<RDFParseError>,
361{
362    type Output = O;
363
364    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
365        match self.parser.parse_impl(rdf) {
366            Ok(value) => match (self.function)(value) {
367                Ok(result) => Ok(result),
368                Err(e) => Err(e.into()),
369            },
370            Err(err) => Err(err),
371        }
372    }
373}
374
375pub fn flat_map<RDF, P, F, O>(parser: P, function: F) -> FlatMap<P, F>
376where
377    RDF: FocusRDF,
378    P: RDFNodeParse<RDF>,
379    F: FnMut(P::Output) -> PResult<O>,
380{
381    FlatMap { parser, function }
382}
383
384#[derive(Copy, Clone)]
385pub struct FlatMap<P, F> {
386    parser: P,
387    function: F,
388}
389
390impl<RDF, P, F, O> RDFNodeParse<RDF> for FlatMap<P, F>
391where
392    RDF: FocusRDF,
393    P: RDFNodeParse<RDF>,
394    F: FnMut(P::Output) -> PResult<O>,
395{
396    type Output = O;
397
398    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
399        match self.parser.parse_impl(rdf) {
400            Ok(value) => match (self.function)(value) {
401                Ok(result) => Ok(result),
402                Err(err) => Err(err),
403            },
404            Err(err) => Err(err),
405        }
406    }
407}
408
409pub fn optional<RDF, P>(parser: P) -> Optional<P>
410where
411    RDF: FocusRDF,
412    P: RDFNodeParse<RDF>,
413{
414    Optional { parser }
415}
416
417#[derive(Copy, Clone)]
418pub struct Optional<P> {
419    parser: P,
420}
421
422impl<RDF, P> RDFNodeParse<RDF> for Optional<P>
423where
424    RDF: FocusRDF,
425    P: RDFNodeParse<RDF>,
426{
427    type Output = Option<P::Output>;
428
429    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
430        match self.parser.parse_impl(rdf) {
431            Ok(value) => Ok(Some(value)),
432            Err(_err) => Ok(None),
433        }
434    }
435}
436
437/// Equivalent to [`parser1.or(parser2)`].
438///
439/// /// [`parser1.or(parser2)`]: trait.RDFNodeParse.html#method.or
440pub fn or<RDF, P1, P2>(parser1: P1, parser2: P2) -> Or<P1, P2>
441where
442    RDF: FocusRDF,
443    P1: RDFNodeParse<RDF>,
444    P2: RDFNodeParse<RDF>,
445{
446    Or { parser1, parser2 }
447}
448
449#[derive(Copy, Clone)]
450pub struct Or<P1, P2> {
451    parser1: P1,
452    parser2: P2,
453}
454
455impl<RDF, P1, P2, O> RDFNodeParse<RDF> for Or<P1, P2>
456where
457    RDF: FocusRDF,
458    P1: RDFNodeParse<RDF, Output = O>,
459    P2: RDFNodeParse<RDF, Output = O>,
460{
461    type Output = O;
462
463    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
464        match self.parser1.parse_impl(rdf) {
465            Ok(value) => Ok(value),
466            Err(err1) => match self.parser2.parse_impl(rdf) {
467                Ok(value) => Ok(value),
468                Err(err2) => Err(RDFParseError::FailedOr {
469                    err1: Box::new(err1),
470                    err2: Box::new(err2),
471                }),
472            },
473        }
474    }
475}
476
477/// Equivalent to [`p.then(f)`].
478///
479/// [`p.then(f)`]: trait.RDFNodeParse.html#method.then
480pub fn then<RDF, P, F, N>(parser: P, function: F) -> Then<P, F>
481where
482    RDF: FocusRDF,
483    P: RDFNodeParse<RDF>,
484    F: FnMut(P::Output) -> N,
485    N: RDFNodeParse<RDF>,
486{
487    Then { parser, function }
488}
489
490#[derive(Copy, Clone)]
491pub struct Then<P, F> {
492    parser: P,
493    function: F,
494}
495
496impl<RDF, P, F, N> RDFNodeParse<RDF> for Then<P, F>
497where
498    RDF: FocusRDF,
499    P: RDFNodeParse<RDF>,
500    F: FnMut(P::Output) -> N,
501    N: RDFNodeParse<RDF>,
502{
503    type Output = N::Output;
504
505    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
506        match self.parser.parse_impl(rdf) {
507            Ok(value) => (self.function)(value).parse_impl(rdf),
508            Err(err) => Err(err),
509        }
510    }
511}
512
513/// Equivalent to [`p.then_ref(f)`].
514///
515/// [`p.then_ref(f)`]: trait.RDFNodeParse.html#method.then_ref
516pub fn then_ref<RDF, P, F, N>(parser: P, function: F) -> ThenRef<P, F>
517where
518    RDF: FocusRDF,
519    P: RDFNodeParse<RDF>,
520    F: FnMut(&P::Output) -> N,
521    N: RDFNodeParse<RDF>,
522{
523    ThenRef { parser, function }
524}
525
526#[derive(Copy, Clone)]
527pub struct ThenRef<P, F> {
528    parser: P,
529    function: F,
530}
531
532impl<RDF, P, F, N> RDFNodeParse<RDF> for ThenRef<P, F>
533where
534    RDF: FocusRDF,
535    P: RDFNodeParse<RDF>,
536    F: FnMut(&P::Output) -> N,
537    N: RDFNodeParse<RDF>,
538{
539    type Output = N::Output;
540
541    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
542        match self.parser.parse_impl(rdf) {
543            Ok(value) => (self.function)(&value).parse_impl(rdf),
544            Err(err) => Err(err),
545        }
546    }
547}
548
549/// Equivalent to [`p.then_mut(f)`].
550///
551/// [`p.then_mut(f)`]: trait.RDFNodeParse.html#method.then_mut
552pub fn then_mut<RDF, P, F, N>(parser: P, function: F) -> ThenMut<P, F>
553where
554    RDF: FocusRDF,
555    P: RDFNodeParse<RDF>,
556    F: FnMut(&mut P::Output) -> N,
557    N: RDFNodeParse<RDF>,
558{
559    ThenMut { parser, function }
560}
561
562#[derive(Copy, Clone)]
563pub struct ThenMut<P, F> {
564    parser: P,
565    function: F,
566}
567
568impl<RDF, P, F, N> RDFNodeParse<RDF> for ThenMut<P, F>
569where
570    RDF: FocusRDF,
571    P: RDFNodeParse<RDF>,
572    F: FnMut(&mut P::Output) -> N,
573    N: RDFNodeParse<RDF>,
574{
575    type Output = N::Output;
576
577    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
578        match self.parser.parse_impl(rdf) {
579            Ok(mut value) => (self.function)(&mut value).parse_impl(rdf),
580            Err(err) => Err(err),
581        }
582    }
583}
584
585/// Not parser succeeds if the `parser` fails and viceversa
586/// Example:
587/// ```
588/// use iri_s::{IriS, iri};
589/// use srdf::SRDFGraph;
590/// use srdf::{literal, not, RDFFormat, RDFNodeParse};
591///
592/// let graph = SRDFGraph::new();
593/// let x = iri!("http://example.org/x");
594/// assert_eq!(not(literal()).parse(&x, graph).unwrap(), ())
595/// ```
596pub fn not<RDF, P>(parser: P) -> Not<P>
597where
598    RDF: FocusRDF,
599    P: RDFNodeParse<RDF>,
600{
601    Not { parser }
602}
603
604#[derive(Copy, Clone)]
605pub struct Not<P> {
606    parser: P,
607}
608
609impl<RDF, P, O> RDFNodeParse<RDF> for Not<P>
610where
611    RDF: FocusRDF,
612    P: RDFNodeParse<RDF, Output = O>,
613    O: Debug,
614{
615    type Output = ();
616
617    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
618        match self.parser.parse_impl(rdf) {
619            Err(_err) => Ok(()),
620            Ok(value) => Err(RDFParseError::FailedNot {
621                value: format!("{value:?}"),
622            }),
623        }
624    }
625}
626
627/// Checks if the focus node is an IRI
628/// ```
629/// use iri_s::{IriS, iri};
630/// use srdf::{SRDFGraph, iri, RDFNodeParse};
631///
632/// let graph = SRDFGraph::new();
633/// let x = iri!("http://example.org/x");
634/// assert_eq!(iri().parse(&x, graph).unwrap(), x)
635/// ```
636pub fn iri<R>() -> impl RDFNodeParse<R, Output = IriS>
637where
638    R: FocusRDF,
639{
640    // TODO: this clone can be removed as it is only necessary because of the error
641    //       and the error can be propagated from the try_into
642    term().flat_map(|t: R::Term| {
643        let iri: R::IRI = t
644            .clone()
645            .try_into()
646            .map_err(|_| RDFParseError::ExpectedIRI {
647                term: format!("{t}"),
648            })?;
649        let iri_string = iri.as_str();
650        Ok(iri!(iri_string))
651    })
652}
653
654/// Checks if the focus node is an IRI
655/// ```
656/// use iri_s::{IriS, iri};
657/// use srdf::{SRDFGraph, iri, RDFNodeParse};
658///
659/// let graph = SRDFGraph::new();
660/// let x = iri!("http://example.org/x");
661/// assert_eq!(iri().parse(&x, graph).unwrap(), x)
662/// ```
663pub fn literal<RDF: FocusRDF>() -> impl RDFNodeParse<RDF, Output = Literal> {
664    term().flat_map(|ref t: RDF::Term| {
665        let literal: RDF::Literal =
666            t.clone()
667                .try_into()
668                .map_err(|_| RDFParseError::ExpectedLiteral {
669                    term: t.to_string(),
670                })?;
671        let literal: Literal = literal.as_literal();
672        Ok(literal)
673    })
674}
675
676/// Creates a parser that returns the current focus node as a term
677///
678/// This is equivalent to [`get_focus`]
679pub fn term<RDF>() -> ParseTerm<RDF>
680where
681    RDF: FocusRDF,
682{
683    ParseTerm {
684        _marker_rdf: PhantomData,
685    }
686}
687
688#[derive(Debug, Clone)]
689pub struct ParseTerm<RDF> {
690    _marker_rdf: PhantomData<RDF>,
691}
692
693impl<RDF> RDFNodeParse<RDF> for ParseTerm<RDF>
694where
695    RDF: FocusRDF,
696{
697    type Output = RDF::Term;
698
699    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<RDF::Term> {
700        match rdf.get_focus() {
701            Some(focus) => Ok(focus.clone()),
702            None => Err(RDFParseError::NoFocusNode),
703        }
704    }
705}
706
707/// Parses the RDF list linked from the value of property `prop` at focus node
708///
709pub fn property_list<RDF>(prop: &IriS) -> impl RDFNodeParse<RDF, Output = Vec<RDF::Term>>
710where
711    RDF: FocusRDF,
712{
713    property_value(prop).and(rdf_list()).map(|(_, ls)| ls)
714}
715
716/// Created a parser that returns the boolean associated with the current focus node for `property`
717///
718/// It doesn't move the current focus node
719pub fn property_bool<R>(prop: &IriS) -> impl RDFNodeParse<R, Output = bool>
720where
721    R: FocusRDF,
722{
723    property_value(prop).flat_map(|term: R::Term| {
724        let literal: R::Literal =
725            term.clone()
726                .try_into()
727                .map_err(|_| RDFParseError::ExpectedLiteral {
728                    term: format!("{term}"),
729                })?;
730        literal
731            .as_bool()
732            .ok_or_else(|| RDFParseError::ExpectedBoolean {
733                term: format!("{term}"),
734            })
735    })
736}
737
738pub fn parse_rdf_nil<R>() -> impl RDFNodeParse<R, Output = ()>
739where
740    R: FocusRDF,
741{
742    satisfy(
743        |term: &R::Term| {
744            let tmp: Result<R::IRI, _> = term.clone().try_into();
745            match tmp {
746                Ok(iri) => iri.as_str() == RDF_NIL_STR,
747                Err(_) => false,
748            }
749        },
750        "rdf_nil",
751    )
752}
753
754/// Creates a parser that checks if the current node satisfies a predicate
755///
756/// The `predicate_name` argument is useful in case of failure to know which condition has failed
757pub fn satisfy<RDF, P>(predicate: P, predicate_name: &str) -> Satisfy<RDF, P>
758where
759    RDF: Query,
760    P: FnMut(&RDF::Term) -> bool,
761{
762    Satisfy {
763        predicate,
764        predicate_name: predicate_name.to_string(),
765        _marker_rdf: PhantomData,
766    }
767}
768
769#[derive(Clone)]
770pub struct Satisfy<RDF, P> {
771    predicate: P,
772    predicate_name: String,
773    _marker_rdf: PhantomData<RDF>,
774}
775
776impl<RDF, P> RDFNodeParse<RDF> for Satisfy<RDF, P>
777where
778    RDF: FocusRDF,
779    P: FnMut(&RDF::Term) -> bool,
780{
781    type Output = ();
782
783    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<()> {
784        match rdf.get_focus() {
785            Some(term) => {
786                if (self.predicate)(term) {
787                    Ok(())
788                } else {
789                    Err(RDFParseError::NodeDoesntSatisfyCondition {
790                        condition_name: self.predicate_name.clone(),
791                        node: format!("{term}"),
792                    })
793                }
794            }
795            None => todo!(),
796        }
797    }
798}
799
800/// Return the integer values of `property` for the focus node
801///
802/// If some value is not an integer it fails, if there is no value returns an empty set
803pub fn property_values_int<RDF>(property: &IriS) -> impl RDFNodeParse<RDF, Output = Vec<isize>>
804where
805    RDF: FocusRDF,
806{
807    property_values(property).flat_map(|values| {
808        let ints: Vec<_> = values
809            .iter()
810            .flat_map(|t| {
811                let i = term_to_int::<RDF>(t)?;
812                Ok::<isize, RDFParseError>(i)
813            })
814            .collect();
815        Ok(ints)
816    })
817}
818
819/// Return the IRI values of `property` for the focus node
820///
821/// If some value is not an IRI it fails, if there is no value returns an empty set
822pub fn property_values_iri<RDF>(property: &IriS) -> impl RDFNodeParse<RDF, Output = Vec<IriS>>
823where
824    RDF: FocusRDF,
825{
826    property_values(property).flat_map(|values| {
827        let ints: Vec<_> = values
828            .iter()
829            .flat_map(|t| {
830                let iri = term_to_iri::<RDF>(t)?;
831                Ok::<IriS, RDFParseError>(iri)
832            })
833            .collect();
834        Ok(ints)
835    })
836}
837
838/// Returns the values of `property` for the focus node
839///
840/// If there is no value, it returns an error
841pub fn property_values_non_empty<RDF>(
842    property: &IriS,
843) -> impl RDFNodeParse<RDF, Output = HashSet<RDF::Term>>
844where
845    RDF: FocusRDF,
846{
847    property_values(property).and_then(move |vs| {
848        if vs.is_empty() {
849            Err(RDFParseError::Custom {
850                msg: "Property values are empty".to_string(),
851            })
852        } else {
853            Ok(vs)
854        }
855    })
856}
857
858/// Returns the values of `property` for the focus node
859///
860/// If there is no value, it returns an empty set
861pub fn property_values<RDF>(property: &IriS) -> PropertyValues<RDF>
862where
863    RDF: FocusRDF,
864{
865    PropertyValues {
866        property: property.clone(),
867        _marker_rdf: PhantomData,
868    }
869}
870
871pub struct PropertyValues<RDF: FocusRDF> {
872    property: IriS,
873    _marker_rdf: PhantomData<RDF>,
874}
875
876impl<RDF> RDFNodeParse<RDF> for PropertyValues<RDF>
877where
878    RDF: FocusRDF,
879{
880    type Output = HashSet<RDF::Term>;
881
882    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<HashSet<RDF::Term>> {
883        let subject = rdf.get_focus_as_subject()?;
884        let pred: RDF::IRI = self.property.clone().into();
885        let values = rdf
886            .triples_matching(subject, pred, Any)
887            .map_err(|e| RDFParseError::SRDFError { err: e.to_string() })?
888            .map(Triple::into_object)
889            .collect();
890        Ok(values)
891    }
892}
893
894/// Creates a parser that returns the value associated with the current focus node for `property`
895///
896/// It doesn't move the current focus node
897pub fn property_value<RDF>(property: &IriS) -> PropertyValue<RDF>
898where
899    RDF: Query,
900{
901    PropertyValue {
902        property: property.clone(),
903        _marker_rdf: PhantomData,
904    }
905}
906
907pub struct PropertyValue<RDF: Query> {
908    property: IriS,
909    _marker_rdf: PhantomData<RDF>,
910}
911
912impl<RDF> RDFNodeParse<RDF> for PropertyValue<RDF>
913where
914    RDF: FocusRDF,
915{
916    type Output = RDF::Term;
917
918    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<RDF::Term> {
919        let mut p: PropertyValues<RDF> = property_values(&self.property);
920        let focus_node_str = match rdf.get_focus() {
921            None => "No focus node".to_string(),
922            Some(focus_node) => {
923                format!("{focus_node}")
924            }
925        };
926        let mut values_iter = p.parse_impl(rdf)?.into_iter();
927        if let Some(value1) = values_iter.next() {
928            // TODO: Add the following for strict parsing an rdf-list
929            /* if let Some(value2) = values_iter.next() {
930                Err(RDFParseError::MoreThanOneValuePredicate {
931                    node: focus_node_str.to_string(),
932                    pred: format!("{}", self.property),
933                    value1: format!("{value1:?}"),
934                    value2: format!("{value2:?}"),
935                })
936            } else { */
937            Ok(value1)
938            /* } */
939        } else {
940            Err(RDFParseError::NoValuesPredicate {
941                node: focus_node_str.to_string(),
942                pred: format!("{}", self.property),
943            })
944        }
945    }
946}
947
948/// Creates a parser that returns the value associated with the current focus node for `property`
949///
950/// It doesn't move the current focus node
951///
952/// This method can be used to debug the parser, because it is less efficient as in case that it fails,
953/// it shows the neighbourhood of the current node
954pub fn property_value_debug<RDF>(property: &IriS) -> PropertyValueDebug<RDF>
955where
956    RDF: Query,
957{
958    PropertyValueDebug {
959        property: property.clone().into(),
960        _marker_rdf: PhantomData,
961    }
962}
963
964pub struct PropertyValueDebug<RDF: Query> {
965    property: RDF::IRI,
966    _marker_rdf: PhantomData<RDF>,
967}
968
969impl<RDF> RDFNodeParse<RDF> for PropertyValueDebug<RDF>
970where
971    RDF: FocusRDF + Debug,
972{
973    type Output = RDF::Term;
974
975    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<RDF::Term> {
976        let mut p: Neighs<RDF> = neighs();
977        let focus_node_str = match rdf.get_focus() {
978            None => "No focus node".to_string(),
979            Some(focus_node) => {
980                format!("{focus_node:?}")
981            }
982        };
983        let outgoing_arcs = p.parse_impl(rdf)?;
984        if let Some(values) = outgoing_arcs.get(&self.property) {
985            let mut values_iter = values.iter();
986            if let Some(value1) = values_iter.next() {
987                if let Some(value2) = values_iter.next() {
988                    Err(RDFParseError::MoreThanOneValuePredicate {
989                        node: focus_node_str.to_string(),
990                        pred: format!("{}", self.property),
991                        value1: format!("{value1:?}"),
992                        value2: format!("{value2:?}"),
993                    })
994                } else {
995                    Ok(value1.clone())
996                }
997            } else {
998                panic!("Internal error: Node {} has no value for predicate {}...but this case should be handled in the outer else...", focus_node_str, self.property)
999            }
1000        } else {
1001            Err(RDFParseError::NoValuesPredicateDebug {
1002                node: focus_node_str.to_string(),
1003                pred: format!("{}", self.property),
1004                outgoing_arcs: format!("{outgoing_arcs:?}"),
1005            })
1006        }
1007    }
1008}
1009
1010/// Creates a parser that returns the value associated with the current focus node for `property`
1011///
1012/// It doesn't move the current focus node
1013///
1014/// This method can be used to debug the parser, because it is less efficient as in case that it fails,
1015/// it shows the neighbourhood of the current node
1016pub fn neighs<RDF>() -> Neighs<RDF>
1017where
1018    RDF: Query,
1019{
1020    Neighs {
1021        _marker_rdf: PhantomData,
1022    }
1023}
1024
1025pub struct Neighs<RDF: Query> {
1026    _marker_rdf: PhantomData<RDF>,
1027}
1028
1029impl<RDF> RDFNodeParse<RDF> for Neighs<RDF>
1030where
1031    RDF: FocusRDF,
1032{
1033    type Output = HashMap<RDF::IRI, HashSet<RDF::Term>>;
1034
1035    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<HashMap<RDF::IRI, HashSet<RDF::Term>>> {
1036        match rdf.get_focus() {
1037            Some(focus) => {
1038                let subj = focus.clone().try_into().map_err(|_| {
1039                    RDFParseError::ExpectedFocusAsSubject {
1040                        focus: focus.to_string(),
1041                    }
1042                })?;
1043                rdf.outgoing_arcs(subj).map_err(|e| RDFParseError::Custom {
1044                    msg: format!("Error obtaining outgoing arcs from {focus}: {e}"),
1045                })
1046            }
1047            None => todo!(),
1048        }
1049    }
1050}
1051
1052/// Returns the integer values of `property` for the focus node
1053///
1054/// If there is no value, it returns an empty set
1055pub fn property_integers<RDF>(property: &IriS) -> impl RDFNodeParse<RDF, Output = HashSet<isize>>
1056where
1057    RDF: FocusRDF,
1058{
1059    property_values(property).flat_map(|terms| {
1060        let is = terms_to_ints::<RDF>(terms)?;
1061        Ok(is)
1062    })
1063}
1064
1065/// Returns the IRI value of `property` for the focus node
1066///
1067pub fn property_iri<'a, RDF>(property: &'a IriS) -> impl RDFNodeParse<RDF, Output = IriS> + 'a
1068where
1069    RDF: FocusRDF + 'a,
1070{
1071    get_focus().then(move |focus| {
1072        property_value(property).flat_map(move |term| {
1073            let i =
1074                term_to_iri::<RDF>(&term).map_err(|e| RDFParseError::PropertyValueExpectedIRI {
1075                    focus: format!("{focus}"),
1076                    property: property.clone(),
1077                    error: format!("{e}"),
1078                })?;
1079            Ok(i)
1080        })
1081    })
1082}
1083
1084/// Returns the integer value of `property` for the focus node
1085///
1086pub fn property_integer<RDF>(property: &IriS) -> impl RDFNodeParse<RDF, Output = isize>
1087where
1088    RDF: FocusRDF,
1089{
1090    property_value(property).flat_map(|term| {
1091        let i = term_to_int::<RDF>(&term)?;
1092        Ok(i)
1093    })
1094}
1095
1096/// Returns the string value of `property` for the focus node
1097///
1098pub fn property_string<RDF>(property: &IriS) -> impl RDFNodeParse<RDF, Output = String>
1099where
1100    RDF: FocusRDF,
1101{
1102    property_value(property).flat_map(|term| {
1103        let i = term_to_string::<RDF>(&term)?;
1104        Ok(i)
1105    })
1106}
1107
1108fn terms_to_ints<RDF>(terms: HashSet<RDF::Term>) -> Result<HashSet<isize>, RDFParseError>
1109where
1110    RDF: Rdf,
1111{
1112    let ints: HashSet<_> = terms.iter().flat_map(|t| term_to_int::<RDF>(t)).collect();
1113    Ok(ints)
1114}
1115
1116fn term_to_int<R>(term: &R::Term) -> Result<isize, RDFParseError>
1117where
1118    R: Rdf,
1119{
1120    let literal: R::Literal =
1121        term.clone()
1122            .try_into()
1123            .map_err(|_| RDFParseError::ExpectedLiteral {
1124                term: format!("{term}"),
1125            })?;
1126    let n = literal
1127        .as_integer()
1128        .ok_or_else(|| RDFParseError::ExpectedInteger {
1129            term: format!("{term}"),
1130        })?;
1131    Ok(n)
1132}
1133
1134fn term_to_iri<R>(term: &R::Term) -> Result<IriS, RDFParseError>
1135where
1136    R: Rdf,
1137{
1138    let iri: R::IRI = term
1139        .clone() // TODO: this clone could be removed?
1140        .try_into()
1141        .map_err(|_| RDFParseError::ExpectedIRI {
1142            term: format!("{term}"),
1143        })?;
1144    let iri_string = iri.as_str();
1145    Ok(iri!(iri_string))
1146}
1147
1148fn term_to_string<R>(term: &R::Term) -> Result<String, RDFParseError>
1149where
1150    R: Rdf,
1151{
1152    let literal: R::Literal =
1153        term.clone()
1154            .try_into()
1155            .map_err(|_| RDFParseError::ExpectedLiteral {
1156                term: format!("{term}"),
1157            })?;
1158    Ok(literal.lexical_form().to_string())
1159}
1160
1161/// Combines the results of parsers that return vectors of values
1162///
1163pub fn combine_vec<RDF, P1, P2, A>(parser1: P1, parser2: P2) -> CombineVec<P1, P2>
1164where
1165    RDF: FocusRDF,
1166    P1: RDFNodeParse<RDF, Output = Vec<A>>,
1167    P2: RDFNodeParse<RDF, Output = Vec<A>>,
1168{
1169    CombineVec { parser1, parser2 }
1170}
1171
1172pub struct CombineVec<P1, P2> {
1173    parser1: P1,
1174    parser2: P2,
1175}
1176
1177impl<RDF, P1, P2, A> RDFNodeParse<RDF> for CombineVec<P1, P2>
1178where
1179    RDF: FocusRDF,
1180    P1: RDFNodeParse<RDF, Output = Vec<A>>,
1181    P2: RDFNodeParse<RDF, Output = Vec<A>>,
1182{
1183    type Output = Vec<A>;
1184
1185    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Vec<A>> {
1186        match self.parser1.parse_impl(rdf) {
1187            Err(e) => Err(e),
1188            Ok(vs1) => match self.parser2.parse_impl(rdf) {
1189                Err(e) => Err(e),
1190                Ok(vs2) => {
1191                    let mut result = vs1;
1192                    result.extend(vs2);
1193                    Ok(result)
1194                }
1195            },
1196        }
1197    }
1198}
1199
1200/// Parses a node as a bool
1201///
1202pub fn bool<R>() -> impl RDFNodeParse<R, Output = bool>
1203where
1204    R: FocusRDF,
1205{
1206    get_focus().flat_map(|term: R::Term| {
1207        let literal: R::Literal =
1208            term.clone()
1209                .try_into()
1210                .map_err(|_| RDFParseError::ExpectedLiteral {
1211                    term: format!("{term}"),
1212                })?;
1213        let boolean = literal
1214            .as_bool()
1215            .ok_or_else(|| RDFParseError::ExpectedInteger {
1216                term: format!("{term}"),
1217            })?;
1218        Ok(boolean)
1219    })
1220}
1221
1222/// Parses the current focus node as an RDF List
1223///
1224/// ```
1225/// use iri_s::{IriS, iri};
1226/// use srdf::SRDFGraph;
1227/// use srdf::{property_value, then, RDFFormat, ReaderMode, RDFNodeParse, rdf_list, set_focus};
1228/// use oxrdf::{Literal, Term};
1229///
1230/// let s = r#"prefix : <http://example.org/>
1231///  :x :p (1 2).
1232/// "#;
1233/// let graph = SRDFGraph::from_str(s, &RDFFormat::Turtle, None, &ReaderMode::default()).unwrap();
1234/// let x = iri!("http://example.org/x");
1235/// let p = iri!("http://example.org/p");
1236/// let mut parser = property_value(&p).then(move |obj| {
1237///   set_focus(&obj).with(rdf_list())
1238/// });
1239/// assert_eq!(parser.parse(&x, graph).unwrap(),
1240///   vec![Term::from(Literal::from(1)), Term::from(Literal::from(2))])
1241/// ```
1242pub fn rdf_list<RDF>() -> RDFList<RDF>
1243where
1244    RDF: Query,
1245{
1246    RDFList {
1247        _marker_rdf: PhantomData,
1248    }
1249}
1250
1251/// Creates a parser that returns the focus node
1252pub fn get_focus<RDF>() -> GetFocus<RDF>
1253where
1254    RDF: FocusRDF,
1255{
1256    GetFocus {
1257        _marker_rdf: PhantomData,
1258    }
1259}
1260
1261#[derive(Debug, Clone)]
1262pub struct GetFocus<RDF>
1263where
1264    RDF: FocusRDF,
1265{
1266    _marker_rdf: PhantomData<RDF>,
1267}
1268
1269impl<RDF> RDFNodeParse<RDF> for GetFocus<RDF>
1270where
1271    RDF: FocusRDF,
1272{
1273    type Output = RDF::Term;
1274
1275    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<RDF::Term> {
1276        match rdf.get_focus() {
1277            Some(focus) => Ok(focus.clone()),
1278            None => Err(RDFParseError::NoFocusNode),
1279        }
1280    }
1281}
1282
1283/// Creates a parser that sets the focus node and returns `()`
1284pub fn set_focus<RDF>(node: &RDF::Term) -> SetFocus<RDF>
1285where
1286    RDF: FocusRDF,
1287{
1288    SetFocus {
1289        node: node.clone(),
1290        _marker_rdf: PhantomData,
1291    }
1292}
1293
1294#[derive(Debug, Clone)]
1295pub struct SetFocus<RDF>
1296where
1297    RDF: FocusRDF,
1298{
1299    node: RDF::Term,
1300    _marker_rdf: PhantomData<RDF>,
1301}
1302
1303impl<RDF> RDFNodeParse<RDF> for SetFocus<RDF>
1304where
1305    RDF: FocusRDF,
1306{
1307    type Output = ();
1308
1309    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<()> {
1310        rdf.set_focus(&self.node);
1311        Ok(())
1312    }
1313}
1314
1315pub struct RDFList<RDF: Query> {
1316    _marker_rdf: PhantomData<RDF>,
1317}
1318
1319impl<RDF> RDFNodeParse<RDF> for RDFList<RDF>
1320where
1321    RDF: FocusRDF,
1322{
1323    type Output = Vec<RDF::Term>;
1324
1325    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Vec<RDF::Term>> {
1326        let focus = rdf.get_focus_as_term()?;
1327        let visited = vec![focus.clone()];
1328        parse_list(visited, rdf)
1329    }
1330}
1331
1332/* I would like the following code to work but it complains that:
1333cannot move out of `parser`, a captured variable in an `FnMut` closure
1334pub fn parse_rdf_list_for_property<RDF, P, A>(property: IriS, parser: P) -> impl RDFNodeParse<RDF, Output = Vec<A>>
1335where
1336   RDF: FocusRDF,
1337   P: RDFNodeParse<RDF, Output = A> + Clone
1338{
1339    property_value(&property).then(|ref node| {
1340        set_focus(node).and(
1341            parse_rdf_list::<RDF,P>(parser)).map(|(_, vs)| { vs }
1342        )
1343    })
1344}*/
1345
1346/// Parses a node as an RDF List applying each element of the list a parser
1347pub fn parse_rdf_list<RDF, P>(parser: P) -> ParseRDFList<P>
1348where
1349    RDF: Query,
1350{
1351    ParseRDFList { parser }
1352}
1353
1354#[derive(Copy, Clone)]
1355pub struct ParseRDFList<P> {
1356    parser: P,
1357}
1358
1359impl<RDF, P, A> RDFNodeParse<RDF> for ParseRDFList<P>
1360where
1361    RDF: FocusRDF,
1362    P: RDFNodeParse<RDF, Output = A>,
1363{
1364    type Output = Vec<A>;
1365
1366    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Vec<A>> {
1367        let focus = rdf.get_focus_as_term()?;
1368        let visited = vec![focus.clone()];
1369        parse_list(visited, rdf).and_then(|nodes| {
1370            let mut result = Vec::new();
1371            for node in nodes {
1372                rdf.set_focus(&node);
1373                match self.parser.parse_impl(rdf) {
1374                    Ok(a) => result.push(a),
1375                    Err(e) => return Err(e),
1376                }
1377            }
1378            Ok(result)
1379        })
1380    }
1381}
1382
1383// Auxiliary function to parse a node as an RDF list checking that the RDF list if non-cyclic
1384// by collecting a vector of visited terms
1385fn parse_list<RDF>(
1386    mut visited: Vec<RDF::Term>,
1387    rdf: &mut RDF,
1388) -> Result<Vec<RDF::Term>, RDFParseError>
1389where
1390    RDF: FocusRDF,
1391{
1392    let focus = rdf.get_focus_as_term()?;
1393    if node_is_rdf_nil::<RDF>(focus) {
1394        Ok(Vec::new())
1395    } else {
1396        let value = property_value(&RDF_FIRST).parse_impl(rdf)?;
1397        let rest = property_value(&RDF_REST).parse_impl(rdf)?;
1398        if visited.contains(&rest) {
1399            Err(RDFParseError::RecursiveRDFList {
1400                node: format!("{rest}"),
1401            })
1402        } else {
1403            visited.push(rest.clone());
1404            let mut rest_ls = vec![value];
1405            rdf.set_focus(&rest);
1406            rest_ls.extend(parse_list(visited, rdf)?);
1407            Ok(rest_ls)
1408        }
1409    }
1410}
1411
1412fn node_is_rdf_nil<R>(node: &R::Term) -> bool
1413where
1414    R: Query,
1415{
1416    let tmp: Result<R::IRI, _> = node.clone().try_into();
1417    match tmp {
1418        Ok(iri) => iri.as_str() == RDF_NIL_STR,
1419        Err(_) => false,
1420    }
1421}
1422
1423/// Succeeds if current term is the expected IRI
1424pub fn is_iri<RDF>(expected_iri: IriS) -> impl RDFNodeParse<RDF, Output = ()>
1425where
1426    RDF: FocusRDF,
1427{
1428    let name = format!("Is {}", expected_iri.as_str());
1429    satisfy(
1430        // TODO: this clone can be removed
1431        move |node: &RDF::Term| {
1432            let tmp: Result<RDF::IRI, _> = node.clone().try_into();
1433            match tmp {
1434                Ok(iri) => iri.as_str() == expected_iri.as_str(),
1435                Err(_) => false,
1436            }
1437        },
1438        name.as_str(),
1439    )
1440}
1441
1442/// Returns the node that is an instance of the expected IRI in the RDF data
1443/// It moves the focus to point to that node
1444pub fn instance_of<RDF>(expected: &IriS) -> impl RDFNodeParse<RDF, Output = RDF::Subject>
1445where
1446    RDF: FocusRDF,
1447{
1448    // TODO: Review that this code seems to overlap with code at line 73 of rdf_parser.rs
1449    // We should probably replace this code by the other one
1450    let str = format!("{expected}");
1451    instances_of(expected).flat_map(move |vs| {
1452        let mut values = vs.into_iter();
1453        match values.next() {
1454            Some(value) => match values.next() {
1455                Some(_other_value) => todo!(),
1456                None => Ok(value),
1457            },
1458            None => Err(RDFParseError::NoInstancesOf {
1459                object: str.to_string(),
1460            }),
1461        }
1462    })
1463}
1464
1465pub fn set_focus_subject<RDF>(subject: RDF::Subject) -> impl RDFNodeParse<RDF, Output = ()>
1466where
1467    RDF: FocusRDF,
1468{
1469    ApplyRDF {
1470        function: move |rdf: &mut RDF| {
1471            let term = subject.clone().into();
1472            rdf.set_focus(&term);
1473            Ok(())
1474        },
1475    }
1476}
1477
1478/*pub fn term_as_iri<RDF>(term: RDF::Term) -> impl RDFNodeParse<RDF, Output = IriS>
1479where
1480    RDF: FocusRDF,
1481{
1482    ApplyRDF {
1483        function: move |_: &mut RDF| match RDF::object_as_iri(&term) {
1484            Some(iri) => {
1485                let iri_s = RDF::iri2iri_s(&iri);
1486                Ok(iri_s)
1487            }
1488            None => todo!(),
1489        },
1490    }
1491}*/
1492
1493pub fn term_as_iri<RDF>(term: &RDF::Term) -> impl RDFNodeParse<RDF, Output = IriS>
1494where
1495    RDF: FocusRDF,
1496{
1497    apply(term, |term| {
1498        let iri: RDF::IRI = term
1499            .clone()
1500            .try_into()
1501            .map_err(|_| RDFParseError::ExpectedIRI {
1502                term: format!("{term}"),
1503            })?;
1504        let iri_string = iri.as_str();
1505        Ok(iri!(iri_string))
1506    })
1507}
1508
1509/*fn term_as_iri_s<RDF>(term: &RDF::Term) -> PResult<IriS>
1510where
1511    RDF: FocusRDF,
1512{
1513    let iri = RDF::object_as_iri(term).ok_or_else(|| RDFParseError::Custom {
1514        msg: "Expected IRI".to_string(),
1515    })?;
1516    let iri_s = RDF::iri2iri_s(&iri);
1517    Ok(iri_s)
1518}*/
1519
1520/// Succeeds with a given value
1521pub fn ok<RDF, A>(value: &A) -> impl RDFNodeParse<RDF, Output = A>
1522where
1523    RDF: FocusRDF,
1524    A: Clone,
1525{
1526    Ok {
1527        value: value.clone(),
1528    }
1529}
1530
1531#[derive(Debug, Clone)]
1532struct Ok<A> {
1533    value: A,
1534}
1535
1536impl<RDF, A> RDFNodeParse<RDF> for Ok<A>
1537where
1538    RDF: FocusRDF,
1539    A: Clone,
1540{
1541    type Output = A;
1542
1543    fn parse_impl(&mut self, _rdf: &mut RDF) -> PResult<Self::Output> {
1544        Ok(self.value.clone())
1545    }
1546}
1547
1548/// Fails with a given massage
1549pub fn fail_msg<A, RDF>(msg: String) -> impl RDFNodeParse<RDF, Output = A>
1550where
1551    RDF: FocusRDF,
1552{
1553    Fail {
1554        msg: msg.clone(),
1555        _marker: PhantomData,
1556    }
1557}
1558
1559#[derive(Debug, Clone)]
1560struct Fail<A> {
1561    msg: String,
1562    _marker: PhantomData<A>,
1563}
1564
1565impl<A, RDF> RDFNodeParse<RDF> for Fail<A>
1566where
1567    RDF: FocusRDF,
1568{
1569    type Output = A;
1570
1571    fn parse_impl(&mut self, _rdf: &mut RDF) -> PResult<Self::Output> {
1572        Err(RDFParseError::Custom {
1573            msg: self.msg.clone(),
1574        })
1575    }
1576}
1577
1578/// Applies a function and returns its result
1579///
1580///
1581pub fn cond<RDF, A>(
1582    value: &A,
1583    pred: impl FnMut(&A) -> bool,
1584    fail_msg: String,
1585) -> impl RDFNodeParse<RDF, Output = ()>
1586where
1587    RDF: FocusRDF,
1588    A: Clone,
1589{
1590    Cond {
1591        value: value.clone(),
1592        pred,
1593        fail_msg: fail_msg.clone(),
1594    }
1595}
1596
1597#[derive(Debug, Clone)]
1598struct Cond<A, P> {
1599    value: A,
1600    pred: P,
1601    fail_msg: String,
1602}
1603
1604impl<RDF, A, P> RDFNodeParse<RDF> for Cond<A, P>
1605where
1606    RDF: FocusRDF,
1607    P: FnMut(&A) -> bool,
1608    A: Clone,
1609{
1610    type Output = ();
1611
1612    fn parse_impl(&mut self, _rdf: &mut RDF) -> PResult<Self::Output> {
1613        match (self.pred)(&self.value) {
1614            true => Ok(()),
1615            false => Err(RDFParseError::Custom {
1616                msg: self.fail_msg.clone(),
1617            }),
1618        }
1619    }
1620}
1621
1622/// Applies a function and returns its result
1623pub fn apply<RDF, A, B>(
1624    value: &A,
1625    function: impl FnMut(&A) -> Result<B, RDFParseError>,
1626) -> impl RDFNodeParse<RDF, Output = B>
1627where
1628    RDF: FocusRDF,
1629    A: Clone,
1630{
1631    Apply {
1632        value: value.clone(),
1633        function,
1634    }
1635}
1636
1637#[derive(Debug, Clone)]
1638struct Apply<A, F> {
1639    value: A,
1640    function: F,
1641}
1642
1643impl<RDF, A, B, F> RDFNodeParse<RDF> for Apply<A, F>
1644where
1645    RDF: FocusRDF,
1646    F: FnMut(&A) -> Result<B, RDFParseError>,
1647    A: Clone,
1648{
1649    type Output = B;
1650
1651    fn parse_impl(&mut self, _rdf: &mut RDF) -> PResult<Self::Output> {
1652        match (self.function)(&self.value) {
1653            Ok(b) => Ok(b),
1654            Err(e) => Err(e),
1655        }
1656    }
1657}
1658
1659/// Applies a function over the RDF graph and returns the result of that function
1660pub fn apply_rdf<RDF, A>(
1661    function: impl FnMut(&mut RDF) -> Result<A, RDFParseError>,
1662) -> impl RDFNodeParse<RDF, Output = A>
1663where
1664    RDF: FocusRDF,
1665{
1666    ApplyRDF { function }
1667}
1668
1669#[derive(Debug, Clone)]
1670struct ApplyRDF<F> {
1671    function: F,
1672}
1673
1674impl<RDF, A, F> RDFNodeParse<RDF> for ApplyRDF<F>
1675where
1676    RDF: FocusRDF,
1677    F: FnMut(&mut RDF) -> Result<A, RDFParseError>,
1678{
1679    type Output = A;
1680
1681    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
1682        match (self.function)(rdf) {
1683            Ok(a) => Ok(a),
1684            Err(e) => Err(e),
1685        }
1686    }
1687}
1688
1689/// Returns all nodes that are instances of the expected IRI in the RDF data
1690pub fn instances_of<RDF>(expected: &IriS) -> impl RDFNodeParse<RDF, Output = Vec<RDF::Subject>>
1691where
1692    RDF: FocusRDF,
1693{
1694    subjects_with_property_value::<RDF>(&RDF_TYPE, &expected.clone().into())
1695}
1696
1697pub fn parse_rdf_type<RDF>() -> impl RDFNodeParse<RDF, Output = RDF::Term>
1698where
1699    RDF: FocusRDF,
1700{
1701    property_value(&RDF_TYPE)
1702}
1703
1704pub fn has_type<RDF>(expected: IriS) -> impl RDFNodeParse<RDF, Output = ()>
1705where
1706    RDF: FocusRDF,
1707{
1708    parse_rdf_type().then(move |term: RDF::Term| equals(term.clone(), expected.clone().into()))
1709}
1710
1711pub fn equals<RDF>(term: RDF::Term, expected: RDF::Term) -> impl RDFNodeParse<RDF, Output = ()>
1712where
1713    RDF: FocusRDF,
1714{
1715    let expected_str = format!("{expected}");
1716    cond(
1717        &term,
1718        move |t| t == &expected,
1719        format!("Term {term} not equals {}", expected_str),
1720    )
1721}
1722
1723/// Returns all nodes that are instances of the expected IRI in the RDF data
1724pub fn subjects_with_property_value<RDF>(
1725    property: &IriS,
1726    value: &RDF::Term,
1727) -> SubjectsPropertyValue<RDF>
1728where
1729    RDF: FocusRDF,
1730{
1731    SubjectsPropertyValue {
1732        property: property.clone().into(),
1733        value: value.clone(),
1734        _marker_rdf: PhantomData,
1735    }
1736}
1737
1738pub struct SubjectsPropertyValue<RDF: Query> {
1739    property: RDF::IRI,
1740    value: RDF::Term,
1741    _marker_rdf: PhantomData<RDF>,
1742}
1743
1744impl<RDF> RDFNodeParse<RDF> for SubjectsPropertyValue<RDF>
1745where
1746    RDF: FocusRDF,
1747{
1748    type Output = Vec<RDF::Subject>;
1749
1750    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Vec<RDF::Subject>> {
1751        let subjects = rdf
1752            .triples_matching(Any, self.property.clone(), self.value.clone())
1753            .map_err(|e| RDFParseError::SRDFError { err: e.to_string() })?
1754            .map(Triple::into_subject)
1755            .collect();
1756        Ok(subjects)
1757    }
1758}
1759
1760rdf_parser! {
1761    /// Parses the value of `property` as an RDF list
1762    pub fn parse_property_value_as_list['a, RDF](property: &'a IriS)(RDF) -> Vec<RDF::Term>
1763        where [
1764        ] {
1765            property_value(property)
1766            .then(|node|
1767                set_focus(&node).then(|_|
1768                    rdf_list())
1769             )
1770    }
1771}
1772
1773/// Apply a parser to an RDF node associated with the value of it's `rdf:type` property
1774pub fn parse_by_type<RDF, P, A>(
1775    values: Vec<(IriS, P)>,
1776    default: P,
1777) -> impl RDFNodeParse<RDF, Output = A>
1778where
1779    RDF: FocusRDF,
1780    P: RDFNodeParse<RDF, Output = A>,
1781{
1782    ParseByType {
1783        values: HashMap::from_iter(values),
1784        default,
1785    }
1786}
1787
1788pub struct ParseByType<I, P> {
1789    values: HashMap<I, P>,
1790    default: P,
1791}
1792
1793impl<RDF, P, A> RDFNodeParse<RDF> for ParseByType<IriS, P>
1794where
1795    RDF: FocusRDF,
1796    P: RDFNodeParse<RDF, Output = A>,
1797{
1798    type Output = A;
1799
1800    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
1801        let rdf_type = parse_rdf_type().parse_impl(rdf)?;
1802        let iri: RDF::IRI =
1803            rdf_type
1804                .clone()
1805                .try_into()
1806                .map_err(|_| RDFParseError::ExpectedIRI {
1807                    term: format!("{rdf_type}"),
1808                })?;
1809        let iri_string = iri.as_str();
1810        match self.values.get_mut(&iri!(iri_string)) {
1811            Some(p) => p.parse_impl(rdf),
1812            None => self.default.parse_impl(rdf),
1813        }
1814    }
1815}
1816
1817/// Equivalent to [`parser1.with(parser2)`]
1818///
1819/// Discards the value of the first parser and returns the value of the second parser
1820///
1821pub fn with<RDF, P1, P2>(parser1: P1, parser2: P2) -> With<P1, P2>
1822where
1823    RDF: FocusRDF,
1824    P1: RDFNodeParse<RDF>,
1825    P2: RDFNodeParse<RDF>,
1826{
1827    With { parser1, parser2 }
1828}
1829
1830#[derive(Copy, Clone)]
1831pub struct With<P1, P2> {
1832    parser1: P1,
1833    parser2: P2,
1834}
1835
1836impl<RDF, A, B, P1, P2> RDFNodeParse<RDF> for With<P1, P2>
1837where
1838    RDF: FocusRDF,
1839    P1: RDFNodeParse<RDF, Output = A>,
1840    P2: RDFNodeParse<RDF, Output = B>,
1841{
1842    type Output = B;
1843
1844    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
1845        match self.parser1.parse_impl(rdf) {
1846            Ok(_) => match self.parser2.parse_impl(rdf) {
1847                Ok(b) => Ok(b),
1848                Err(e) => Err(e),
1849            },
1850            Err(e) => Err(e),
1851        }
1852    }
1853}
1854
1855/// Applies a parser over a list of nodes and returns the list of values
1856///
1857pub fn parse_nodes<RDF, P>(nodes: Vec<RDF::Term>, parser: P) -> ParserNodes<RDF, P>
1858where
1859    RDF: FocusRDF,
1860    P: RDFNodeParse<RDF>,
1861{
1862    ParserNodes { nodes, parser }
1863}
1864
1865#[derive(Clone)]
1866pub struct ParserNodes<RDF, P>
1867where
1868    RDF: FocusRDF,
1869{
1870    nodes: Vec<RDF::Term>,
1871    parser: P,
1872}
1873
1874impl<RDF, A, P> RDFNodeParse<RDF> for ParserNodes<RDF, P>
1875where
1876    RDF: FocusRDF,
1877    P: RDFNodeParse<RDF, Output = A>,
1878{
1879    type Output = Vec<A>;
1880
1881    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
1882        let mut results = Vec::new();
1883        for node in self.nodes.iter() {
1884            rdf.set_focus(node);
1885            let value = self.parser.parse_impl(rdf)?;
1886            results.push(value)
1887        }
1888        Ok(results)
1889    }
1890}
1891
1892/// Implementation of [`RDFNodeParse::by_ref`]
1893pub struct ByRef<'p, P> {
1894    p: &'p mut P,
1895}
1896
1897impl<'p, P> ByRef<'p, P> {
1898    #[inline(always)]
1899    pub(crate) fn new(p: &'p mut P) -> Self {
1900        Self { p }
1901    }
1902}
1903
1904impl<RDF, P, O> RDFNodeParse<RDF> for ByRef<'_, P>
1905where
1906    RDF: FocusRDF,
1907    P: RDFNodeParse<RDF, Output = O>,
1908{
1909    type Output = O;
1910
1911    #[inline(always)]
1912    fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output> {
1913        self.p.parse_impl(rdf)
1914    }
1915}