linked_data/
quads.rs

1use educe::Educe;
2use iref::IriBuf;
3use rdf_types::{
4	interpretation::{
5		self, BlankIdInterpretationMut, IriInterpretationMut, LiteralInterpretationMut,
6		ReverseBlankIdInterpretation, ReverseIriInterpretation, ReverseTermInterpretation,
7		TermInterpretationMut,
8	},
9	vocabulary::{
10		EmbedIntoVocabulary, ExtractedFromVocabulary, IriVocabularyMut, LiteralVocabularyMut,
11	},
12	Generator, Id, Interpretation, InterpretationMut, Quad, Term, Vocabulary,
13};
14
15use crate::{
16	CowRdfTerm, GraphVisitor, InterpretedQuad, LinkedData, LinkedDataGraph, LinkedDataResource,
17	LinkedDataSubject, PredicateObjectsVisitor, RdfId, RdfQuad, ResourceInterpretation,
18	SubjectVisitor, Visitor,
19};
20
21pub fn to_interpreted_quads<I: Interpretation, V: Vocabulary>(
22	vocabulary: &mut V,
23	interpretation: &mut I,
24	value: &impl LinkedData<I, V>,
25) -> Result<Vec<InterpretedQuad<I>>, IntoQuadsError>
26where
27	I: InterpretationMut<V> + TermInterpretationMut<V::Iri, V::BlankId, V::Literal>,
28	I::Resource: Clone,
29	V: IriVocabularyMut + LiteralVocabularyMut,
30	V::Iri: Clone,
31	V::BlankId: Clone,
32{
33	value.visit(QuadSerializer {
34		vocabulary,
35		interpretation,
36		domain: &mut InterpretationDomain,
37		result: Vec::new(),
38	})
39}
40
41pub fn to_interpreted_subject_quads<I: Interpretation, V: Vocabulary>(
42	vocabulary: &mut V,
43	interpretation: &mut I,
44	graph: Option<&I::Resource>,
45	value: &(impl LinkedDataSubject<I, V> + LinkedDataResource<I, V>),
46) -> Result<(I::Resource, Vec<InterpretedQuad<I>>), IntoQuadsError>
47where
48	I: InterpretationMut<V>
49		+ IriInterpretationMut<V::Iri>
50		+ BlankIdInterpretationMut<V::BlankId>
51		+ LiteralInterpretationMut<V::Literal>,
52	I::Resource: Clone,
53	V: IriVocabularyMut + LiteralVocabularyMut,
54	V::Iri: Clone,
55	V::BlankId: Clone,
56{
57	let mut result = Vec::new();
58
59	let subject = match value.interpretation(vocabulary, interpretation) {
60		ResourceInterpretation::Interpreted(r) => r.clone(),
61		ResourceInterpretation::Uninterpreted(_) => interpretation.new_resource(vocabulary),
62	};
63
64	value.visit_subject(QuadPropertiesSerializer {
65		vocabulary,
66		interpretation,
67		domain: &mut InterpretationDomain,
68		graph,
69		subject: SubjectOrObject::Subject(&subject),
70		result: &mut result,
71	})?;
72
73	Ok((subject, result))
74}
75
76pub fn to_interpreted_graph_quads<I: Interpretation, V: Vocabulary>(
77	vocabulary: &mut V,
78	interpretation: &mut I,
79	value: &(impl LinkedDataGraph<I, V> + LinkedDataResource<I, V>),
80) -> Result<(I::Resource, Vec<InterpretedQuad<I>>), IntoQuadsError>
81where
82	I: InterpretationMut<V>
83		+ IriInterpretationMut<V::Iri>
84		+ BlankIdInterpretationMut<V::BlankId>
85		+ LiteralInterpretationMut<V::Literal>,
86	I::Resource: Clone,
87	V: IriVocabularyMut + LiteralVocabularyMut,
88	V::Iri: Clone,
89	V::BlankId: Clone,
90{
91	let mut result = Vec::new();
92
93	let graph = match value.interpretation(vocabulary, interpretation) {
94		ResourceInterpretation::Interpreted(r) => r.clone(),
95		ResourceInterpretation::Uninterpreted(_) => interpretation.new_resource(vocabulary),
96	};
97
98	value.visit_graph(QuadGraphSerializer {
99		vocabulary,
100		interpretation,
101		domain: &mut InterpretationDomain,
102		graph: Some(&graph),
103		result: &mut result,
104	})?;
105
106	Ok((graph, result))
107}
108
109pub fn to_lexical_quads_with<I: Interpretation, V: Vocabulary>(
110	vocabulary: &mut V,
111	interpretation: &mut I,
112	value: &impl LinkedData<I, V>,
113) -> Result<Vec<RdfQuad>, IntoQuadsError>
114where
115	I: InterpretationMut<V>
116		+ ReverseTermInterpretation<Iri = V::Iri, BlankId = V::BlankId, Literal = V::Literal>,
117{
118	let mut domain = LexicalDomain;
119
120	value.visit(QuadSerializer {
121		vocabulary,
122		interpretation,
123		domain: &mut domain,
124		result: Vec::new(),
125	})
126}
127
128pub fn to_lexical_subject_quads_with<I: Interpretation, V: Vocabulary>(
129	vocabulary: &mut V,
130	interpretation: &mut I,
131	graph: Option<&Id>,
132	value: &(impl LinkedDataSubject<I, V> + LinkedDataResource<I, V>),
133) -> Result<(Id, Vec<RdfQuad>), IntoQuadsError>
134where
135	I: InterpretationMut<V>
136		+ ReverseTermInterpretation<Iri = V::Iri, BlankId = V::BlankId, Literal = V::Literal>,
137	I::Resource: Clone,
138{
139	let mut result = Vec::new();
140
141	let i = value.interpretation(vocabulary, interpretation);
142	let subject = LexicalDomain.subject(vocabulary, interpretation, i)?;
143
144	value.visit_subject(QuadPropertiesSerializer {
145		vocabulary,
146		interpretation,
147		domain: &mut LexicalDomain,
148		graph,
149		subject: SubjectOrObject::Subject(&subject),
150		result: &mut result,
151	})?;
152
153	Ok((subject, result))
154}
155
156pub fn to_lexical_quads<G: Generator>(
157	generator: G,
158	value: &impl LinkedData<interpretation::WithGenerator<G>>,
159) -> Result<Vec<RdfQuad>, IntoQuadsError> {
160	let mut interpretation = rdf_types::interpretation::WithGenerator::new((), generator);
161	to_lexical_quads_with(&mut (), &mut interpretation, value)
162}
163
164pub fn to_lexical_subject_quads<G: Generator>(
165	generator: G,
166	graph: Option<&Id>,
167	value: &(impl LinkedDataSubject<interpretation::WithGenerator<G>>
168	      + LinkedDataResource<interpretation::WithGenerator<G>>),
169) -> Result<(Id, Vec<RdfQuad>), IntoQuadsError> {
170	let mut interpretation = rdf_types::interpretation::WithGenerator::new((), generator);
171	to_lexical_subject_quads_with(&mut (), &mut interpretation, graph, value)
172}
173
174pub fn to_quads_with<I: InterpretationMut<V>, V: Vocabulary>(
175	vocabulary: &mut V,
176	interpretation: &mut I,
177	value: &impl LinkedData<I, V>,
178) -> Result<Vec<RdfQuad<V>>, IntoQuadsError>
179where
180	V: IriVocabularyMut + LiteralVocabularyMut,
181	V::BlankId: Clone,
182	V::Iri: Clone,
183	V::Literal: Clone,
184	I: ReverseTermInterpretation<Iri = V::Iri, BlankId = V::BlankId, Literal = V::Literal>,
185{
186	let mut domain = VocabularyDomain;
187
188	value.visit(QuadSerializer {
189		vocabulary,
190		interpretation,
191		domain: &mut domain,
192		result: Vec::new(),
193	})
194}
195
196pub fn to_quads<G: Generator>(
197	generator: G,
198	value: &impl LinkedData<interpretation::WithGenerator<G>>,
199) -> Result<Vec<RdfQuad>, IntoQuadsError> {
200	let mut interpretation = interpretation::WithGenerator::new((), generator);
201	to_quads_with(&mut (), &mut interpretation, value)
202}
203
204#[derive(Debug, thiserror::Error)]
205pub enum IntoQuadsError {
206	#[error("invalid graph label")]
207	Graph,
208
209	#[error("invalid subject")]
210	Subject,
211
212	#[error("invalid predicate")]
213	Predicate,
214
215	#[error("missing lexical representation")]
216	MissingLexicalRepresentation,
217}
218
219trait Domain<I: Interpretation, V: Vocabulary> {
220	type Subject: Clone;
221	type Predicate: Clone;
222	type Object;
223	type ObjectRef<'a>: Copy
224	where
225		V::Iri: 'a,
226		V::BlankId: 'a,
227		V::Literal: 'a,
228		I::Resource: 'a;
229
230	fn subject(
231		&mut self,
232		vocabulary: &mut V,
233		interpretation: &mut I,
234		value: ResourceInterpretation<I, V>,
235	) -> Result<Self::Subject, IntoQuadsError>;
236
237	fn predicate(
238		&mut self,
239		vocabulary: &mut V,
240		interpretation: &mut I,
241		value: ResourceInterpretation<I, V>,
242	) -> Result<Self::Predicate, IntoQuadsError>;
243
244	fn object(
245		&mut self,
246		vocabulary: &mut V,
247		interpretation: &mut I,
248		value: ResourceInterpretation<I, V>,
249	) -> Result<Self::Object, IntoQuadsError>;
250
251	fn graph(
252		&mut self,
253		vocabulary: &mut V,
254		interpretation: &mut I,
255		value: ResourceInterpretation<I, V>,
256	) -> Result<Self::Subject, IntoQuadsError>;
257
258	fn object_as_subject<'a>(
259		&self,
260		object: &'a Self::Object,
261	) -> Result<&'a Self::Subject, IntoQuadsError>;
262
263	fn subject_as_object<'a>(
264		&self,
265		subject: &'a Self::Subject,
266	) -> Result<Self::ObjectRef<'a>, IntoQuadsError>
267	where
268		V::Iri: 'a,
269		V::BlankId: 'a,
270		V::Literal: 'a,
271		I::Resource: 'a;
272
273	fn object_as_ref<'a>(object: &'a Self::Object) -> Self::ObjectRef<'a>
274	where
275		V::Iri: 'a,
276		V::BlankId: 'a,
277		V::Literal: 'a,
278		I::Resource: 'a;
279
280	fn cloned_object_ref<'a>(object_ref: Self::ObjectRef<'a>) -> Self::Object
281	where
282		V::Iri: 'a,
283		V::BlankId: 'a,
284		V::Literal: 'a,
285		I::Resource: 'a;
286}
287
288type DomainQuad<I, V, D> = Quad<
289	<D as Domain<I, V>>::Subject,
290	<D as Domain<I, V>>::Predicate,
291	<D as Domain<I, V>>::Object,
292	<D as Domain<I, V>>::Subject,
293>;
294
295struct VocabularyDomain;
296
297#[allow(clippy::type_complexity)]
298fn resource_term<I>(
299	interpretation: &I,
300	r: &I::Resource,
301) -> Result<Term<Id<I::Iri, I::BlankId>, I::Literal>, IntoQuadsError>
302where
303	I: ReverseTermInterpretation,
304	I::Iri: Clone,
305	I::BlankId: Clone,
306	I::Literal: Clone,
307{
308	if let Some(iri) = interpretation.iris_of(r).next() {
309		return Ok(Term::Id(Id::Iri(iri.clone())));
310	}
311
312	if let Some(lit) = interpretation.literals_of(r).next() {
313		return Ok(Term::Literal(lit.clone()));
314	}
315
316	if let Some(blank_id) = interpretation.blank_ids_of(r).next() {
317		return Ok(Term::Id(Id::Blank(blank_id.clone())));
318	}
319
320	Err(IntoQuadsError::MissingLexicalRepresentation)
321}
322
323impl<I: InterpretationMut<V>, V: Vocabulary> Domain<I, V> for VocabularyDomain
324where
325	V: IriVocabularyMut + LiteralVocabularyMut,
326	V::Iri: Clone,
327	V::BlankId: Clone,
328	V::Literal: Clone,
329	I: ReverseTermInterpretation<Iri = V::Iri, BlankId = V::BlankId, Literal = V::Literal>,
330{
331	type Subject = RdfId<V>;
332	type Predicate = V::Iri;
333	type Object = Term<RdfId<V>, V::Literal>;
334	type ObjectRef<'a> = Term<&'a RdfId<V>, &'a V::Literal> where V::Iri: 'a, V::BlankId: 'a, V::Literal: 'a, I::Resource: 'a;
335
336	fn subject(
337		&mut self,
338		vocabulary: &mut V,
339		interpretation: &mut I,
340		value: ResourceInterpretation<I, V>,
341	) -> Result<Self::Subject, IntoQuadsError> {
342		match value {
343			ResourceInterpretation::Interpreted(r) => {
344				if let Some(iri) = interpretation.iris_of(r).next() {
345					return Ok(Id::Iri(iri.clone()));
346				}
347
348				if let Some(blank_id) = interpretation.blank_ids_of(r).next() {
349					return Ok(Id::Blank(blank_id.clone()));
350				}
351
352				Err(IntoQuadsError::MissingLexicalRepresentation)
353			}
354			ResourceInterpretation::Uninterpreted(u) => match u {
355				Some(u) => u.into_owned().into_id(),
356				None => {
357					let r = interpretation.new_resource(vocabulary);
358					resource_term(interpretation, &r)?.into_id()
359				}
360			}
361			.ok_or(IntoQuadsError::Subject),
362		}
363	}
364
365	fn predicate(
366		&mut self,
367		_vocabulary: &mut V,
368		interpretation: &mut I,
369		value: ResourceInterpretation<I, V>,
370	) -> Result<Self::Predicate, IntoQuadsError> {
371		match value {
372			ResourceInterpretation::Interpreted(r) => {
373				if let Some(iri) = interpretation.iris_of(r).next() {
374					return Ok(iri.clone());
375				}
376
377				Err(IntoQuadsError::Predicate)
378			}
379			ResourceInterpretation::Uninterpreted(u) => match u {
380				Some(CowRdfTerm::Owned(Term::Id(Id::Iri(iri)))) => Ok(iri),
381				Some(CowRdfTerm::Borrowed(Term::Id(Id::Iri(iri)))) => Ok(iri.clone()),
382				_ => Err(IntoQuadsError::Predicate),
383			},
384		}
385	}
386
387	fn object(
388		&mut self,
389		vocabulary: &mut V,
390		interpretation: &mut I,
391		value: ResourceInterpretation<I, V>,
392	) -> Result<Self::Object, IntoQuadsError> {
393		match value {
394			ResourceInterpretation::Interpreted(r) => resource_term(interpretation, r),
395			ResourceInterpretation::Uninterpreted(u) => {
396				let term = match u {
397					Some(CowRdfTerm::Owned(Term::Id(id))) => Term::Id(id),
398					Some(CowRdfTerm::Owned(Term::Literal(l))) => {
399						Term::Literal(l.embed_into_vocabulary(vocabulary))
400					}
401					Some(CowRdfTerm::Borrowed(Term::Id(id))) => Term::Id(id.cloned()),
402					Some(CowRdfTerm::Borrowed(Term::Literal(l))) => {
403						Term::Literal(l.into_owned().embed_into_vocabulary(vocabulary))
404					}
405					None => {
406						let r = interpretation.new_resource(vocabulary);
407						resource_term(interpretation, &r)?
408					}
409				};
410
411				Ok(term)
412			}
413		}
414	}
415
416	fn graph(
417		&mut self,
418		vocabulary: &mut V,
419		interpretation: &mut I,
420		value: ResourceInterpretation<I, V>,
421	) -> Result<Self::Subject, IntoQuadsError> {
422		match value {
423			ResourceInterpretation::Interpreted(r) => {
424				if let Some(iri) = interpretation.iris_of(r).next() {
425					return Ok(Id::Iri(iri.clone()));
426				}
427
428				if let Some(blank_id) = interpretation.blank_ids_of(r).next() {
429					return Ok(Id::Blank(blank_id.clone()));
430				}
431
432				Err(IntoQuadsError::MissingLexicalRepresentation)
433			}
434			ResourceInterpretation::Uninterpreted(u) => match u {
435				Some(u) => u.into_owned().into_id(),
436				None => {
437					let r = interpretation.new_resource(vocabulary);
438					resource_term(interpretation, &r)?.into_id()
439				}
440			}
441			.ok_or(IntoQuadsError::Subject),
442		}
443	}
444
445	fn object_as_subject<'a>(
446		&self,
447		object: &'a Self::Object,
448	) -> Result<&'a Self::Subject, IntoQuadsError> {
449		match object {
450			Term::Id(id) => Ok(id),
451			Term::Literal(_) => Err(IntoQuadsError::Subject),
452		}
453	}
454
455	fn subject_as_object<'a>(
456		&self,
457		subject: &'a Self::Subject,
458	) -> Result<Self::ObjectRef<'a>, IntoQuadsError>
459	where
460		V::Iri: 'a,
461		V::BlankId: 'a,
462		V::Literal: 'a,
463		I::Resource: 'a,
464	{
465		Ok(Term::Id(subject))
466	}
467
468	fn object_as_ref<'a>(object: &'a Self::Object) -> Self::ObjectRef<'a>
469	where
470		V::Iri: 'a,
471		V::BlankId: 'a,
472		V::Literal: 'a,
473		I::Resource: 'a,
474	{
475		object.as_ref()
476	}
477
478	fn cloned_object_ref<'a>(object_ref: Self::ObjectRef<'a>) -> Self::Object
479	where
480		V::Iri: 'a,
481		V::BlankId: 'a,
482		V::Literal: 'a,
483		I::Resource: 'a,
484	{
485		object_ref.cloned()
486	}
487}
488
489struct InterpretationDomain;
490
491impl<I: Interpretation, V: Vocabulary> Domain<I, V> for InterpretationDomain
492where
493	I: InterpretationMut<V>
494		+ IriInterpretationMut<V::Iri>
495		+ BlankIdInterpretationMut<V::BlankId>
496		+ LiteralInterpretationMut<V::Literal>,
497	I::Resource: Clone,
498	V: IriVocabularyMut + LiteralVocabularyMut,
499	V::Iri: Clone,
500	V::BlankId: Clone,
501{
502	type Subject = I::Resource;
503	type Predicate = I::Resource;
504	type Object = I::Resource;
505	type ObjectRef<'a> = &'a I::Resource where V::Iri: 'a, V::BlankId: 'a, V::Literal: 'a, I::Resource: 'a;
506
507	fn subject(
508		&mut self,
509		vocabulary: &mut V,
510		interpretation: &mut I,
511		value: ResourceInterpretation<I, V>,
512	) -> Result<Self::Subject, IntoQuadsError> {
513		match value {
514			ResourceInterpretation::Interpreted(r) => Ok(r.clone()),
515			ResourceInterpretation::Uninterpreted(u) => match u {
516				Some(CowRdfTerm::Owned(Term::Id(Id::Iri(iri)))) => {
517					Ok(interpretation.interpret_iri(iri))
518				}
519				Some(CowRdfTerm::Borrowed(Term::Id(Id::Iri(iri)))) => {
520					Ok(interpretation.interpret_iri(iri.clone()))
521				}
522				Some(CowRdfTerm::Owned(Term::Id(Id::Blank(b)))) => {
523					Ok(interpretation.interpret_blank_id(b))
524				}
525				Some(CowRdfTerm::Borrowed(Term::Id(Id::Blank(b)))) => {
526					Ok(interpretation.interpret_blank_id(b.clone()))
527				}
528				Some(CowRdfTerm::Owned(Term::Literal(_))) => Err(IntoQuadsError::Subject),
529				Some(CowRdfTerm::Borrowed(Term::Literal(_))) => Err(IntoQuadsError::Subject),
530				None => Ok(interpretation.new_resource(vocabulary)),
531			},
532		}
533	}
534
535	fn predicate(
536		&mut self,
537		_vocabulary: &mut V,
538		interpretation: &mut I,
539		value: ResourceInterpretation<I, V>,
540	) -> Result<Self::Predicate, IntoQuadsError> {
541		match value {
542			ResourceInterpretation::Interpreted(r) => Ok(r.clone()),
543			ResourceInterpretation::Uninterpreted(u) => match u {
544				Some(CowRdfTerm::Owned(Term::Id(Id::Iri(iri)))) => {
545					Ok(interpretation.interpret_iri(iri))
546				}
547				Some(CowRdfTerm::Borrowed(Term::Id(Id::Iri(iri)))) => {
548					Ok(interpretation.interpret_iri(iri.clone()))
549				}
550				_ => Err(IntoQuadsError::Predicate),
551			},
552		}
553	}
554
555	fn object(
556		&mut self,
557		vocabulary: &mut V,
558		interpretation: &mut I,
559		value: ResourceInterpretation<I, V>,
560	) -> Result<Self::Object, IntoQuadsError> {
561		match value {
562			ResourceInterpretation::Interpreted(r) => Ok(r.clone()),
563			ResourceInterpretation::Uninterpreted(u) => match u {
564				Some(CowRdfTerm::Owned(Term::Id(Id::Iri(iri)))) => {
565					Ok(interpretation.interpret_iri(iri))
566				}
567				Some(CowRdfTerm::Borrowed(Term::Id(Id::Iri(iri)))) => {
568					Ok(interpretation.interpret_iri(iri.clone()))
569				}
570				Some(CowRdfTerm::Owned(Term::Id(Id::Blank(b)))) => {
571					Ok(interpretation.interpret_blank_id(b))
572				}
573				Some(CowRdfTerm::Borrowed(Term::Id(Id::Blank(b)))) => {
574					Ok(interpretation.interpret_blank_id(b.clone()))
575				}
576				Some(CowRdfTerm::Owned(Term::Literal(l))) => {
577					let l = l.embed_into_vocabulary(vocabulary);
578					let l = interpretation.interpret_literal(l);
579					Ok(l)
580				}
581				Some(CowRdfTerm::Borrowed(Term::Literal(l))) => {
582					let l = l.into_owned().embed_into_vocabulary(vocabulary);
583					let l = interpretation.interpret_literal(l);
584					Ok(l)
585				}
586				None => Ok(interpretation.new_resource(vocabulary)),
587			},
588		}
589	}
590
591	fn graph(
592		&mut self,
593		vocabulary: &mut V,
594		interpretation: &mut I,
595		value: ResourceInterpretation<I, V>,
596	) -> Result<Self::Subject, IntoQuadsError> {
597		match value {
598			ResourceInterpretation::Interpreted(r) => Ok(r.clone()),
599			ResourceInterpretation::Uninterpreted(u) => match u {
600				Some(CowRdfTerm::Owned(Term::Id(Id::Iri(iri)))) => {
601					Ok(interpretation.interpret_iri(iri))
602				}
603				Some(CowRdfTerm::Borrowed(Term::Id(Id::Iri(iri)))) => {
604					Ok(interpretation.interpret_iri(iri.clone()))
605				}
606				Some(CowRdfTerm::Owned(Term::Id(Id::Blank(b)))) => {
607					Ok(interpretation.interpret_blank_id(b))
608				}
609				Some(CowRdfTerm::Borrowed(Term::Id(Id::Blank(b)))) => {
610					Ok(interpretation.interpret_blank_id(b.clone()))
611				}
612				Some(CowRdfTerm::Owned(Term::Literal(_))) => Err(IntoQuadsError::Graph),
613				Some(CowRdfTerm::Borrowed(Term::Literal(_))) => Err(IntoQuadsError::Graph),
614				None => Ok(interpretation.new_resource(vocabulary)),
615			},
616		}
617	}
618
619	fn object_as_subject<'a>(
620		&self,
621		object: &'a Self::Object,
622	) -> Result<&'a Self::Subject, IntoQuadsError> {
623		Ok(object)
624	}
625
626	fn subject_as_object<'a>(
627		&self,
628		subject: &'a Self::Subject,
629	) -> Result<Self::ObjectRef<'a>, IntoQuadsError>
630	where
631		V::Iri: 'a,
632		V::BlankId: 'a,
633		V::Literal: 'a,
634		I::Resource: 'a,
635	{
636		Ok(subject)
637	}
638
639	fn object_as_ref<'a>(object: &'a Self::Object) -> Self::ObjectRef<'a>
640	where
641		V::Iri: 'a,
642		V::BlankId: 'a,
643		V::Literal: 'a,
644		I::Resource: 'a,
645	{
646		object
647	}
648
649	fn cloned_object_ref<'a>(object_ref: Self::ObjectRef<'a>) -> Self::Object
650	where
651		V::Iri: 'a,
652		V::BlankId: 'a,
653		V::Literal: 'a,
654		I::Resource: 'a,
655	{
656		object_ref.clone()
657	}
658}
659
660struct LexicalDomain;
661
662fn lexical_term<V: Vocabulary>(vocabulary: &V, term: CowRdfTerm<V>) -> Term {
663	match term {
664		CowRdfTerm::Borrowed(Term::Id(Id::Iri(iri))) => {
665			Term::Id(Id::Iri(vocabulary.iri(iri).unwrap().to_owned()))
666		}
667		CowRdfTerm::Owned(Term::Id(Id::Iri(iri))) => {
668			Term::Id(Id::Iri(vocabulary.owned_iri(iri).ok().unwrap()))
669		}
670		CowRdfTerm::Borrowed(Term::Id(Id::Blank(blank_id))) => {
671			Term::Id(Id::Blank(vocabulary.blank_id(blank_id).unwrap().to_owned()))
672		}
673		CowRdfTerm::Owned(Term::Id(Id::Blank(blank_id))) => {
674			Term::Id(Id::Blank(vocabulary.owned_blank_id(blank_id).ok().unwrap()))
675		}
676		CowRdfTerm::Borrowed(Term::Literal(lit)) => Term::Literal(lit.into_lexical(vocabulary)),
677		CowRdfTerm::Owned(Term::Literal(lit)) => Term::Literal(lit.into_lexical(vocabulary)),
678	}
679}
680
681fn resource_lexical_term<V: Vocabulary, I>(
682	vocabulary: &V,
683	interpretation: &I,
684	r: &I::Resource,
685) -> Result<Term<Id, rdf_types::Literal>, IntoQuadsError>
686where
687	I: ReverseTermInterpretation<Iri = V::Iri, BlankId = V::BlankId, Literal = V::Literal>,
688{
689	if let Some(iri) = interpretation.iris_of(r).next() {
690		let iri = vocabulary.iri(iri).unwrap();
691		return Ok(Term::Id(Id::Iri(iri.to_owned())));
692	}
693
694	if let Some(lit) = interpretation.literals_of(r).next() {
695		return Ok(Term::Literal(
696			vocabulary
697				.literal(lit)
698				.unwrap()
699				.extracted_from_vocabulary(vocabulary),
700		));
701	}
702
703	if let Some(blank_id) = interpretation.blank_ids_of(r).next() {
704		let blank_id = vocabulary.blank_id(blank_id).unwrap();
705		return Ok(Term::Id(Id::Blank(blank_id.to_owned())));
706	}
707
708	Err(IntoQuadsError::MissingLexicalRepresentation)
709}
710
711impl<I: InterpretationMut<V>, V: Vocabulary> Domain<I, V> for LexicalDomain
712where
713	I: ReverseTermInterpretation<Iri = V::Iri, BlankId = V::BlankId, Literal = V::Literal>,
714{
715	type Subject = Id;
716	type Predicate = IriBuf;
717	type Object = Term;
718	type ObjectRef<'a> = Term<&'a Id, &'a rdf_types::Literal> where V::Iri: 'a, V::BlankId: 'a, V::Literal: 'a, I::Resource: 'a;
719
720	fn subject(
721		&mut self,
722		vocabulary: &mut V,
723		interpretation: &mut I,
724		value: ResourceInterpretation<I, V>,
725	) -> Result<Self::Subject, IntoQuadsError> {
726		match value {
727			ResourceInterpretation::Interpreted(r) => {
728				if let Some(iri) = interpretation.iris_of(r).next() {
729					let iri = vocabulary.iri(iri).unwrap();
730					return Ok(Id::Iri(iri.to_owned()));
731				}
732
733				if let Some(blank_id) = interpretation.blank_ids_of(r).next() {
734					let blank_id = vocabulary.blank_id(blank_id).unwrap();
735					return Ok(Id::Blank(blank_id.to_owned()));
736				}
737
738				Err(IntoQuadsError::MissingLexicalRepresentation)
739			}
740			ResourceInterpretation::Uninterpreted(u) => u
741				.map(|t| Ok(lexical_term(vocabulary, t)))
742				.unwrap_or_else(|| {
743					let r = interpretation.new_resource(vocabulary);
744					resource_lexical_term(vocabulary, interpretation, &r)
745				})?
746				.into_id()
747				.ok_or(IntoQuadsError::Subject),
748		}
749	}
750
751	fn predicate(
752		&mut self,
753		vocabulary: &mut V,
754		interpretation: &mut I,
755		value: ResourceInterpretation<I, V>,
756	) -> Result<Self::Predicate, IntoQuadsError> {
757		match value {
758			ResourceInterpretation::Interpreted(r) => {
759				if let Some(iri) = interpretation.iris_of(r).next() {
760					let iri = vocabulary.iri(iri).unwrap();
761					return Ok(iri.to_owned());
762				}
763
764				Err(IntoQuadsError::Predicate)
765			}
766			ResourceInterpretation::Uninterpreted(u) => match u {
767				Some(CowRdfTerm::Owned(Term::Id(Id::Iri(iri)))) => {
768					Ok(vocabulary.owned_iri(iri).ok().unwrap())
769				}
770				Some(CowRdfTerm::Borrowed(Term::Id(Id::Iri(iri)))) => {
771					Ok(vocabulary.iri(iri).unwrap().to_owned())
772				}
773				_ => Err(IntoQuadsError::Predicate),
774			},
775		}
776	}
777
778	fn object(
779		&mut self,
780		vocabulary: &mut V,
781		interpretation: &mut I,
782		value: ResourceInterpretation<I, V>,
783	) -> Result<Self::Object, IntoQuadsError> {
784		match value {
785			ResourceInterpretation::Interpreted(r) => {
786				resource_lexical_term(vocabulary, interpretation, r)
787			}
788			ResourceInterpretation::Uninterpreted(u) => {
789				let term = match u {
790					Some(CowRdfTerm::Owned(Term::Id(Id::Iri(iri)))) => {
791						Term::Id(Id::Iri(vocabulary.owned_iri(iri).ok().unwrap()))
792					}
793					Some(CowRdfTerm::Borrowed(Term::Id(Id::Iri(iri)))) => {
794						Term::Id(Id::Iri(vocabulary.iri(iri).unwrap().to_owned()))
795					}
796					Some(CowRdfTerm::Owned(Term::Id(Id::Blank(blank_id)))) => {
797						Term::Id(Id::Blank(vocabulary.owned_blank_id(blank_id).ok().unwrap()))
798					}
799					Some(CowRdfTerm::Borrowed(Term::Id(Id::Blank(blank_id)))) => {
800						Term::Id(Id::Blank(vocabulary.blank_id(blank_id).unwrap().to_owned()))
801					}
802					Some(CowRdfTerm::Owned(Term::Literal(lit))) => {
803						Term::Literal(lit.into_lexical(vocabulary))
804					}
805					Some(CowRdfTerm::Borrowed(Term::Literal(lit))) => {
806						Term::Literal(lit.into_lexical(vocabulary))
807					}
808					None => {
809						let r = interpretation.new_resource(vocabulary);
810						resource_lexical_term(vocabulary, interpretation, &r)?
811					}
812				};
813
814				Ok(term)
815			}
816		}
817	}
818
819	fn graph(
820		&mut self,
821		vocabulary: &mut V,
822		interpretation: &mut I,
823		value: ResourceInterpretation<I, V>,
824	) -> Result<Self::Subject, IntoQuadsError> {
825		match value {
826			ResourceInterpretation::Interpreted(r) => {
827				if let Some(iri) = interpretation.iris_of(r).next() {
828					let iri = vocabulary.iri(iri).unwrap();
829					return Ok(Id::Iri(iri.to_owned()));
830				}
831
832				if let Some(blank_id) = interpretation.blank_ids_of(r).next() {
833					let blank_id = vocabulary.blank_id(blank_id).unwrap();
834					return Ok(Id::Blank(blank_id.to_owned()));
835				}
836
837				Err(IntoQuadsError::MissingLexicalRepresentation)
838			}
839			ResourceInterpretation::Uninterpreted(u) => u
840				.map(|t| Ok(lexical_term(vocabulary, t)))
841				.unwrap_or_else(|| {
842					let r = interpretation.new_resource(vocabulary);
843					resource_lexical_term(vocabulary, interpretation, &r)
844				})?
845				.into_id()
846				.ok_or(IntoQuadsError::Graph),
847		}
848	}
849
850	fn object_as_subject<'a>(
851		&self,
852		object: &'a Self::Object,
853	) -> Result<&'a Self::Subject, IntoQuadsError> {
854		match object {
855			Term::Id(id) => Ok(id),
856			Term::Literal(_) => Err(IntoQuadsError::Subject),
857		}
858	}
859
860	fn subject_as_object<'a>(
861		&self,
862		subject: &'a Self::Subject,
863	) -> Result<Self::ObjectRef<'a>, IntoQuadsError>
864	where
865		V::Iri: 'a,
866		V::BlankId: 'a,
867		V::Literal: 'a,
868		I::Resource: 'a,
869	{
870		Ok(Term::Id(subject))
871	}
872
873	fn object_as_ref<'a>(object: &'a Self::Object) -> Self::ObjectRef<'a>
874	where
875		V::Iri: 'a,
876		V::BlankId: 'a,
877		V::Literal: 'a,
878		I::Resource: 'a,
879	{
880		object.as_ref()
881	}
882
883	fn cloned_object_ref<'a>(object_ref: Self::ObjectRef<'a>) -> Self::Object
884	where
885		V::Iri: 'a,
886		V::BlankId: 'a,
887		V::Literal: 'a,
888		I::Resource: 'a,
889	{
890		object_ref.cloned()
891	}
892}
893
894/// A simple serializer generating a list of `Quad`s.
895struct QuadSerializer<'a, I: Interpretation, V: Vocabulary, D: Domain<I, V>> {
896	vocabulary: &'a mut V,
897	interpretation: &'a mut I,
898	domain: &'a mut D,
899	result: Vec<DomainQuad<I, V, D>>,
900}
901
902impl<'a, I: Interpretation, V: Vocabulary, D: Domain<I, V>> Visitor<I, V>
903	for QuadSerializer<'a, I, V, D>
904{
905	type Ok = Vec<DomainQuad<I, V, D>>;
906	type Error = IntoQuadsError;
907
908	fn default_graph<T>(&mut self, value: &T) -> Result<(), Self::Error>
909	where
910		T: ?Sized + crate::LinkedDataGraph<I, V>,
911	{
912		let graph_serializer = QuadGraphSerializer {
913			vocabulary: self.vocabulary,
914			interpretation: self.interpretation,
915			domain: self.domain,
916			result: &mut self.result,
917			graph: None,
918		};
919
920		value.visit_graph(graph_serializer)
921	}
922
923	fn named_graph<T>(&mut self, value: &T) -> Result<(), Self::Error>
924	where
925		T: ?Sized + LinkedDataResource<I, V> + crate::LinkedDataGraph<I, V>,
926	{
927		let i = value.interpretation(self.vocabulary, self.interpretation);
928		let graph = self.domain.graph(self.vocabulary, self.interpretation, i)?;
929
930		let graph_serializer = QuadGraphSerializer {
931			vocabulary: self.vocabulary,
932			interpretation: self.interpretation,
933			domain: self.domain,
934			result: &mut self.result,
935			graph: Some(&graph),
936		};
937
938		value.visit_graph(graph_serializer)
939	}
940
941	fn end(self) -> Result<Self::Ok, Self::Error> {
942		Ok(self.result)
943	}
944}
945
946struct QuadGraphSerializer<'a, I: Interpretation, V: Vocabulary, D: Domain<I, V>> {
947	vocabulary: &'a mut V,
948	interpretation: &'a mut I,
949	domain: &'a mut D,
950	result: &'a mut Vec<DomainQuad<I, V, D>>,
951	graph: Option<&'a D::Subject>,
952}
953
954impl<'a, I: Interpretation, V: Vocabulary, D: Domain<I, V>> GraphVisitor<I, V>
955	for QuadGraphSerializer<'a, I, V, D>
956{
957	type Ok = ();
958	type Error = IntoQuadsError;
959
960	fn subject<T>(&mut self, value: &T) -> Result<(), Self::Error>
961	where
962		T: ?Sized + LinkedDataResource<I, V> + crate::LinkedDataSubject<I, V>,
963	{
964		let i = value.interpretation(self.vocabulary, self.interpretation);
965		let term = self
966			.domain
967			.subject(self.vocabulary, self.interpretation, i)?;
968
969		let properties_serializer = QuadPropertiesSerializer {
970			vocabulary: self.vocabulary,
971			interpretation: self.interpretation,
972			domain: self.domain,
973			result: self.result,
974			graph: self.graph,
975			subject: SubjectOrObject::Subject(&term),
976		};
977
978		value.visit_subject(properties_serializer)
979	}
980
981	fn end(self) -> Result<Self::Ok, Self::Error> {
982		Ok(())
983	}
984}
985
986struct QuadPropertiesSerializer<'a, I: Interpretation, V: Vocabulary, D: Domain<I, V>> {
987	vocabulary: &'a mut V,
988	interpretation: &'a mut I,
989	domain: &'a mut D,
990	result: &'a mut Vec<DomainQuad<I, V, D>>,
991	graph: Option<&'a D::Subject>,
992	subject: SubjectOrObject<'a, I, V, D>,
993}
994
995#[derive(Educe)]
996#[educe(Clone, Copy)]
997enum SubjectOrObject<'a, I: Interpretation, V: Vocabulary, D: Domain<I, V>> {
998	Subject(&'a D::Subject),
999	Object(&'a D::Object),
1000}
1001
1002impl<'a, I: Interpretation, V: Vocabulary, D: Domain<I, V>> SubjectOrObject<'a, I, V, D> {
1003	fn into_subject(self, domain: &D) -> Result<&'a D::Subject, IntoQuadsError> {
1004		match self {
1005			Self::Subject(s) => Ok(s),
1006			Self::Object(o) => domain.object_as_subject(o),
1007		}
1008	}
1009
1010	fn into_object(self, domain: &D) -> Result<D::ObjectRef<'a>, IntoQuadsError> {
1011		match self {
1012			Self::Subject(s) => domain.subject_as_object(s),
1013			Self::Object(o) => Ok(D::object_as_ref(o)),
1014		}
1015	}
1016}
1017
1018impl<'a, I: Interpretation, V: Vocabulary, D: Domain<I, V>> SubjectVisitor<I, V>
1019	for QuadPropertiesSerializer<'a, I, V, D>
1020{
1021	type Ok = ();
1022	type Error = IntoQuadsError;
1023
1024	fn predicate<L, T>(&mut self, predicate: &L, value: &T) -> Result<(), Self::Error>
1025	where
1026		L: ?Sized + LinkedDataResource<I, V>,
1027		T: ?Sized + crate::LinkedDataPredicateObjects<I, V>,
1028	{
1029		let subject = self.subject.into_subject(self.domain)?;
1030
1031		let i = predicate.interpretation(self.vocabulary, self.interpretation);
1032		let term = self
1033			.domain
1034			.predicate(self.vocabulary, self.interpretation, i)?;
1035
1036		let objects_serializer = ObjectsSerializer {
1037			vocabulary: self.vocabulary,
1038			interpretation: self.interpretation,
1039			domain: self.domain,
1040			result: self.result,
1041			graph: self.graph,
1042			subject,
1043			predicate: term,
1044		};
1045
1046		value.visit_objects(objects_serializer)
1047	}
1048
1049	fn reverse_predicate<L, T>(&mut self, predicate: &L, subjects: &T) -> Result<(), Self::Error>
1050	where
1051		L: ?Sized + LinkedDataResource<I, V>,
1052		T: ?Sized + crate::LinkedDataPredicateObjects<I, V>,
1053	{
1054		let object = self.subject.into_object(self.domain)?;
1055
1056		let i = predicate.interpretation(self.vocabulary, self.interpretation);
1057		let term = self
1058			.domain
1059			.predicate(self.vocabulary, self.interpretation, i)?;
1060
1061		let subjects_serializer = ReversePredicateSerializer {
1062			vocabulary: self.vocabulary,
1063			interpretation: self.interpretation,
1064			domain: self.domain,
1065			result: self.result,
1066			graph: self.graph,
1067			object,
1068			predicate: term,
1069		};
1070
1071		subjects.visit_objects(subjects_serializer)
1072	}
1073
1074	fn graph<T>(&mut self, value: &T) -> Result<(), Self::Error>
1075	where
1076		T: ?Sized + LinkedDataGraph<I, V>,
1077	{
1078		let graph = self.subject.into_subject(self.domain)?;
1079
1080		let graph_serializer = QuadGraphSerializer {
1081			vocabulary: self.vocabulary,
1082			interpretation: self.interpretation,
1083			domain: self.domain,
1084			result: self.result,
1085			graph: Some(graph),
1086		};
1087
1088		value.visit_graph(graph_serializer)
1089	}
1090
1091	fn include<T>(&mut self, value: &T) -> Result<(), Self::Error>
1092	where
1093		T: ?Sized + LinkedDataResource<I, V> + LinkedDataSubject<I, V>,
1094	{
1095		let i = value.interpretation(self.vocabulary, self.interpretation);
1096		let subject = self
1097			.domain
1098			.subject(self.vocabulary, self.interpretation, i)?;
1099
1100		value.visit_subject(QuadPropertiesSerializer {
1101			vocabulary: self.vocabulary,
1102			interpretation: self.interpretation,
1103			domain: self.domain,
1104			graph: self.graph,
1105			subject: SubjectOrObject::Subject(&subject),
1106			result: self.result,
1107		})?;
1108
1109		Ok(())
1110	}
1111
1112	fn end(self) -> Result<Self::Ok, Self::Error> {
1113		Ok(())
1114	}
1115}
1116
1117struct ObjectsSerializer<'a, I: Interpretation, V: Vocabulary, D: Domain<I, V>> {
1118	vocabulary: &'a mut V,
1119	interpretation: &'a mut I,
1120	domain: &'a mut D,
1121	result: &'a mut Vec<DomainQuad<I, V, D>>,
1122	graph: Option<&'a D::Subject>,
1123	subject: &'a D::Subject,
1124	predicate: D::Predicate,
1125}
1126
1127impl<'a, I: Interpretation, V: Vocabulary, D: Domain<I, V>> PredicateObjectsVisitor<I, V>
1128	for ObjectsSerializer<'a, I, V, D>
1129{
1130	type Ok = ();
1131	type Error = IntoQuadsError;
1132
1133	fn object<T>(&mut self, value: &T) -> Result<(), Self::Error>
1134	where
1135		T: ?Sized + LinkedDataResource<I, V> + crate::LinkedDataSubject<I, V>,
1136	{
1137		let i = value.interpretation(self.vocabulary, self.interpretation);
1138		let term = self
1139			.domain
1140			.object(self.vocabulary, self.interpretation, i)?;
1141		let subject_serializer = QuadPropertiesSerializer {
1142			vocabulary: self.vocabulary,
1143			interpretation: self.interpretation,
1144			domain: self.domain,
1145			result: self.result,
1146			graph: self.graph,
1147			subject: SubjectOrObject::Object(&term),
1148		};
1149
1150		value.visit_subject(subject_serializer)?;
1151		self.result.push(Quad(
1152			self.subject.clone(),
1153			self.predicate.clone(),
1154			term,
1155			self.graph.cloned(),
1156		));
1157		Ok(())
1158	}
1159
1160	fn end(self) -> Result<Self::Ok, Self::Error> {
1161		Ok(())
1162	}
1163}
1164
1165struct ReversePredicateSerializer<'a, I: Interpretation, V: Vocabulary, D: Domain<I, V>> {
1166	vocabulary: &'a mut V,
1167	interpretation: &'a mut I,
1168	domain: &'a mut D,
1169	result: &'a mut Vec<DomainQuad<I, V, D>>,
1170	graph: Option<&'a D::Subject>,
1171	object: D::ObjectRef<'a>,
1172	predicate: D::Predicate,
1173}
1174
1175impl<'a, I: Interpretation, V: Vocabulary, D: Domain<I, V>> PredicateObjectsVisitor<I, V>
1176	for ReversePredicateSerializer<'a, I, V, D>
1177{
1178	type Ok = ();
1179	type Error = IntoQuadsError;
1180
1181	fn object<T>(&mut self, value: &T) -> Result<(), Self::Error>
1182	where
1183		T: ?Sized + LinkedDataResource<I, V> + crate::LinkedDataSubject<I, V>,
1184	{
1185		let i = value.interpretation(self.vocabulary, self.interpretation);
1186		let subject = self
1187			.domain
1188			.subject(self.vocabulary, self.interpretation, i)?;
1189
1190		let subject_serializer = QuadPropertiesSerializer {
1191			vocabulary: self.vocabulary,
1192			interpretation: self.interpretation,
1193			domain: self.domain,
1194			result: self.result,
1195			graph: self.graph,
1196			subject: SubjectOrObject::Subject(&subject),
1197		};
1198
1199		value.visit_subject(subject_serializer)?;
1200		self.result.push(Quad(
1201			subject,
1202			self.predicate.clone(),
1203			D::cloned_object_ref(self.object),
1204			self.graph.cloned(),
1205		));
1206		Ok(())
1207	}
1208
1209	fn end(self) -> Result<Self::Ok, Self::Error> {
1210		Ok(())
1211	}
1212}