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
16pub trait RDFNodeParse<RDF: FocusRDF> {
19 type Output;
21
22 #[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 fn parse_impl(&mut self, rdf: &mut RDF) -> PResult<Self::Output>;
43
44 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 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 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 fn and<P2>(self, parser: P2) -> (Self, P2)
151 where
152 Self: Sized,
153 P2: RDFNodeParse<RDF>,
154 {
155 (self, parser)
156 }
157
158 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 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 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 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 fn focus(self, node: &RDF::Term) -> SetFocus<RDF>
238 where
239 Self: Sized,
240 {
241 set_focus(node)
242 }
243
244 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
306pub 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
437pub 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
477pub 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
513pub 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
549pub 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
585pub 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
627pub fn iri<R>() -> impl RDFNodeParse<R, Output = IriS>
637where
638 R: FocusRDF,
639{
640 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
654pub 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
676pub 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
707pub 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
716pub 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
754pub 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
800pub 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
819pub 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
838pub 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
858pub 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
894pub 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 Ok(value1)
938 } else {
940 Err(RDFParseError::NoValuesPredicate {
941 node: focus_node_str.to_string(),
942 pred: format!("{}", self.property),
943 })
944 }
945 }
946}
947
948pub 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
1010pub 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
1052pub 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
1065pub 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
1084pub 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
1096pub 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() .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
1161pub 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
1200pub 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
1222pub fn rdf_list<RDF>() -> RDFList<RDF>
1243where
1244 RDF: Query,
1245{
1246 RDFList {
1247 _marker_rdf: PhantomData,
1248 }
1249}
1250
1251pub 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
1283pub 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
1332pub 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
1383fn 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
1423pub 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 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
1442pub fn instance_of<RDF>(expected: &IriS) -> impl RDFNodeParse<RDF, Output = RDF::Subject>
1445where
1446 RDF: FocusRDF,
1447{
1448 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
1478pub 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
1509pub 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
1548pub 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
1578pub 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
1622pub 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
1659pub 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
1689pub 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
1723pub 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 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
1773pub 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
1817pub 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
1855pub 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
1892pub 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}