jsonld-core 0.23.4

JSON-LD core types and traits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
use super::{RDF_DIRECTION, RDF_FIRST, RDF_JSON, RDF_NIL, RDF_REST, RDF_VALUE, RdfDirection, XSD_BOOLEAN, XSD_DOUBLE, XSD_INTEGER, XSD_STRING};
use crate::{Direction, Id, Indexed, IndexedObject, Node, Object, ValidId, object::value};
use iri_rs::IriBuf;
use jstrict::Print;
use langtag::LangTagBuf;
use rdfx::{
    Literal,
    LocalGenerator,
    vocabulary::{IriVocabularyMut, Vocabulary, VocabularyMut},
};
use smallvec::SmallVec;

/// JSON-LD to RDF triple.
pub type Triple<T, B, L> = rdfx::GeneralizedTriple<ValidId<T, B>, ValidId<T, B>, Value<T, B, L>>;

/// Build a [`rdfx::Datatype`] from a static IRI constant. The IRIs used by
/// jsonld-core are never `rdf:langString` / `rdf:dirLangString`, so the
/// `xsd:string` fallback is unreachable.
fn static_datatype(iri: iri_rs::Iri<&'static str>) -> rdfx::Datatype {
    rdfx::Datatype::new(IriBuf::from(iri)).unwrap_or_else(|_| rdfx::Datatype::xsd_string())
}

/// Build a [`rdfx::Datatype`] from a vocabulary handle.
///
/// Returns `None` if the handle does not resolve in `vocabulary`, or if the
/// IRI is reserved and cannot be used as a plain datatype (`rdf:langString` /
/// `rdf:dirLangString`).
fn datatype_of<V: rdfx::vocabulary::IriVocabulary>(vocabulary: &V, iri: &V::Iri) -> Option<rdfx::Datatype> {
    let buf = IriBuf::from(vocabulary.iri(iri)?);
    rdfx::Datatype::new(buf).ok()
}

impl<T: Clone, B: Clone> Id<T, B> {
    fn rdf_value<L>(&self) -> Option<Value<T, B, L>> {
        match self {
            Id::Valid(id) => Some(Value::Id(id.clone())),
            Id::Invalid(_) => None,
        }
    }
}

/// Iterator over the triples of a compound literal representing a language
/// tagged string with direction.
pub struct CompoundLiteralTriples<T, B, L> {
    /// Compound literal identifier.
    id: ValidId<T, B>,

    /// String value.
    value: Option<Value<T, B, L>>,

    /// Direction value.
    direction: Option<Value<T, B, L>>,
}

impl<T: Clone, B: Clone, L: Clone> CompoundLiteralTriples<T, B, L> {
    fn next(&mut self, vocabulary: &mut impl IriVocabularyMut<Iri = T>) -> Option<Triple<T, B, L>> {
        if let Some(value) = self.value.take() {
            return Some(rdfx::GeneralizedTriple(self.id.clone(), ValidId::Iri(vocabulary.insert(RDF_VALUE)), value));
        }

        if let Some(direction) = self.direction.take() {
            return Some(rdfx::GeneralizedTriple(
                self.id.clone(),
                ValidId::Iri(vocabulary.insert(RDF_DIRECTION)),
                direction,
            ));
        }

        None
    }
}

/// Compound literal.
pub struct CompoundLiteral<T, B, L> {
    value: Value<T, B, L>,
    triples: Option<CompoundLiteralTriples<T, B, L>>,
}

impl<T: Clone> crate::object::Value<T> {
    fn rdf_value_with<V, G: LocalGenerator>(
        &self,
        vocabulary: &mut V,
        generator: &mut G,
        rdf_direction: Option<RdfDirection>,
    ) -> Option<CompoundLiteral<T, V::BlankId, V::Literal>>
    where
        V: Vocabulary<Iri = T> + VocabularyMut,
    {
        match self {
            Self::Json(json) => Some(CompoundLiteral {
                value: Value::Literal(vocabulary.insert_owned_literal(Literal::new(
                    json.compact_print().to_string(),
                    rdfx::LiteralType::Any(static_datatype(RDF_JSON)),
                ))),
                triples: None,
            }),
            Self::LangString(lang_string) => {
                let (string, language, direction) = lang_string.parts();

                let language = match language {
                    // A malformed language tag has no RDF representation, so
                    // the whole literal is dropped rather than emitted untagged.
                    Some(language) => Some(language.as_well_formed()?.to_owned()),
                    None => None,
                };

                match direction {
                    Some(direction) => match rdf_direction {
                        Some(RdfDirection::I18nDatatype) => {
                            // `i18n` IRIs are never reserved datatypes, so the
                            // fallback is unreachable.
                            let ty = rdfx::Datatype::new(i18n(language.as_ref(), *direction)).unwrap_or_else(|_| rdfx::Datatype::xsd_string());
                            Some(CompoundLiteral {
                                value: Value::Literal(vocabulary.insert_owned_literal(Literal::new(string.to_string(), rdfx::LiteralType::Any(ty)))),
                                triples: None,
                            })
                        }
                        Some(RdfDirection::CompoundLiteral) => {
                            // A generator yielding anything but a blank id or
                            // an IRI has no RDF representation; the literal is
                            // dropped like a malformed language tag.
                            let id = crate::id::generator_next_id(vocabulary, generator).ok()?;
                            Some(CompoundLiteral {
                                value: Value::from_id(id),
                                triples: None,
                            })
                        }
                        None => match language {
                            Some(tag) => Some(CompoundLiteral {
                                value: Value::Literal(vocabulary.insert_owned_literal(Literal::new(string.to_string(), rdfx::LiteralType::LangString(tag)))),
                                triples: None,
                            }),
                            None => Some(CompoundLiteral {
                                value: Value::Literal(
                                    vocabulary.insert_owned_literal(Literal::new(string.to_string(), rdfx::LiteralType::Any(static_datatype(XSD_STRING)))),
                                ),
                                triples: None,
                            }),
                        },
                    },
                    None => match language {
                        Some(tag) => Some(CompoundLiteral {
                            value: Value::Literal(vocabulary.insert_owned_literal(Literal::new(string.to_string(), rdfx::LiteralType::LangString(tag)))),
                            triples: None,
                        }),
                        None => Some(CompoundLiteral {
                            value: Value::Literal(
                                vocabulary.insert_owned_literal(Literal::new(string.to_string(), rdfx::LiteralType::Any(static_datatype(XSD_STRING)))),
                            ),
                            triples: None,
                        }),
                    },
                }
            }
            Self::Literal(lit, ty) => {
                let (rdf_lit, preferred_rdf_ty) = match lit {
                    value::Literal::Boolean(b) => {
                        let lit = if *b { "true".to_string() } else { "false".to_string() };

                        (lit, Some(static_datatype(XSD_BOOLEAN)))
                    }
                    value::Literal::Null => ("null".to_string(), None),
                    value::Literal::Number(n) => {
                        if n.is_i64() && ty.as_ref().and_then(|t| vocabulary.iri(t)).is_none_or(|i| i != XSD_DOUBLE) {
                            (n.to_string(), Some(static_datatype(XSD_INTEGER)))
                        } else {
                            (pretty_dtoa::dtoa(n.as_f64_lossy(), XSD_CANONICAL_FLOAT), Some(static_datatype(XSD_DOUBLE)))
                        }
                    }
                    value::Literal::String(s) => (s.to_string(), None),
                };

                let rdf_ty = match ty {
                    // A type without RDF representation (unresolvable handle,
                    // or a reserved datatype IRI like `rdf:langString` on a
                    // plain typed value) drops the whole literal, like a
                    // malformed language tag above.
                    Some(id) => Some(datatype_of(vocabulary, id)?),
                    None => preferred_rdf_ty,
                };

                Some(CompoundLiteral {
                    value: Value::Literal(vocabulary.insert_owned_literal(Literal::new(
                        rdf_lit,
                        rdfx::LiteralType::Any(rdf_ty.unwrap_or_else(|| static_datatype(XSD_STRING))),
                    ))),
                    triples: None,
                })
            }
        }
    }
}

// <https://www.w3.org/TR/xmlschema11-2/#f-doubleLexmap>
pub(crate) const XSD_CANONICAL_FLOAT: pretty_dtoa::FmtFloatConfig = pretty_dtoa::FmtFloatConfig::default().force_e_notation().capitalize_e(true);

impl<T: Clone, B: Clone> Node<T, B> {
    fn rdf_value<L>(&self) -> Option<Value<T, B, L>> {
        self.id.as_ref().and_then(Id::rdf_value)
    }
}

impl<T: Clone, B: Clone> Object<T, B> {
    fn rdf_value_with<V, G: LocalGenerator>(
        &self,
        vocabulary: &mut V,
        generator: &mut G,
        rdf_direction: Option<RdfDirection>,
    ) -> Option<CompoundValue<'_, T, B, V::Literal>>
    where
        V: Vocabulary<Iri = T, BlankId = B> + VocabularyMut,
    {
        match self {
            Self::Value(value) => value.rdf_value_with(vocabulary, generator, rdf_direction).map(|compound_value| CompoundValue {
                value: compound_value.value,
                triples: compound_value.triples.map(CompoundValueTriples::literal),
            }),
            Self::Node(node) => node.rdf_value().map(|value| CompoundValue { value, triples: None }),
            Self::List(list) => {
                if list.is_empty() {
                    Some(CompoundValue {
                        value: Value::Id(ValidId::Iri(vocabulary.insert(RDF_NIL))),
                        triples: None,
                    })
                } else {
                    // A generator yielding anything but a blank id or an IRI
                    // has no RDF representation; the list value is dropped.
                    let id = crate::id::generator_next_id(vocabulary, generator).ok()?;
                    Some(CompoundValue {
                        value: Value::from_id(id.clone()),
                        triples: Some(CompoundValueTriples::List(ListTriples::new(list.as_slice(), id))),
                    })
                }
            }
        }
    }
}

/// RDF value paired with the triples needed to describe it.
pub struct CompoundValue<'a, T, B, L> {
    /// The value itself.
    pub value: Value<T, B, L>,
    /// Triples describing the value, for lists and JSON literals.
    pub triples: Option<CompoundValueTriples<'a, T, B, L>>,
}

impl<'a, T: Clone, B: Clone> crate::quad::ObjectRef<'a, T, B> {
    /// Converts this object into an RDF value, emitting any triples it needs
    /// through the given vocabulary and generator.
    pub fn rdf_value_with<V, G: LocalGenerator>(
        &self,
        vocabulary: &mut V,
        generator: &mut G,
        rdf_direction: Option<RdfDirection>,
    ) -> Option<CompoundValue<'a, T, B, V::Literal>>
    where
        V: Vocabulary<Iri = T, BlankId = B> + VocabularyMut,
    {
        match self {
            Self::Object(object) => object.rdf_value_with(vocabulary, generator, rdf_direction),
            Self::Node(node) => node.rdf_value().map(|value| CompoundValue { value, triples: None }),
            Self::Ref(r) => r.rdf_value().map(|value| CompoundValue { value, triples: None }),
        }
    }
}

enum ListItemTriples<'a, T, B, L> {
    NestedList(NestedListTriples<'a, T, B>),
    CompoundLiteral(Box<CompoundLiteralTriples<T, B, L>>),
}

struct NestedListTriples<'a, T, B> {
    head_ref: Option<ValidId<T, B>>,
    previous: Option<ValidId<T, B>>,
    iter: std::slice::Iter<'a, IndexedObject<T, B>>,
}

struct ListNode<'a, 'i, T, B> {
    id: &'i ValidId<T, B>,
    object: &'a Indexed<Object<T, B>>,
}

impl<'a, T, B> NestedListTriples<'a, T, B> {
    fn new(list: &'a [IndexedObject<T, B>], head_ref: ValidId<T, B>) -> Self {
        Self {
            head_ref: Some(head_ref),
            previous: None,
            iter: list.iter(),
        }
    }

    fn previous(&self) -> Option<&ValidId<T, B>> {
        self.previous.as_ref()
    }

    /// Pull the next object of the list.
    ///
    /// Uses the given generator to assign as id to the list element.
    fn next<V: VocabularyMut<Iri = T, BlankId = B>, G: LocalGenerator>(&mut self, vocabulary: &mut V, generator: &mut G) -> Option<ListNode<'a, '_, T, B>> {
        if let Some(next) = self.iter.next() {
            let id = match self.head_ref.take() {
                Some(id) => id,
                // A generator yielding anything but a blank id or an IRI has
                // no RDF representation; the list is truncated here.
                None => crate::id::generator_next_id(vocabulary, generator).ok()?,
            };

            Some(ListNode {
                object: next,
                id: self.previous.insert(id),
            })
        } else {
            None
        }
    }
}

/// Triples describing a compound RDF value.
pub enum CompoundValueTriples<'a, T, B, L> {
    /// An RDF literal.
    Literal(Box<CompoundLiteralTriples<T, B, L>>),
    /// A list object.
    List(ListTriples<'a, T, B, L>),
}

impl<'a, T, B, L> CompoundValueTriples<'a, T, B, L> {
    /// Builds the triples of a JSON literal.
    pub fn literal(l: CompoundLiteralTriples<T, B, L>) -> Self {
        Self::Literal(Box::new(l))
    }

    /// Binds this iterator to a vocabulary and generator.
    pub fn with<'n, V: Vocabulary<Iri = T, BlankId = B, Literal = L>, G: LocalGenerator>(
        self,
        vocabulary: &'n mut V,
        generator: G,
        rdf_direction: Option<RdfDirection>,
    ) -> CompoundValueTriplesWith<'a, 'n, V, G> {
        CompoundValueTriplesWith {
            vocabulary,
            generator,
            rdf_direction,
            inner: self,
        }
    }

    /// Produces the next triple, allocating blank node identifiers as needed.
    pub fn next<V, G: LocalGenerator>(&mut self, vocabulary: &mut V, generator: &mut G, rdf_direction: Option<RdfDirection>) -> Option<Triple<T, B, L>>
    where
        T: Clone,
        B: Clone,
        L: Clone,
        V: Vocabulary<Iri = T, BlankId = B, Literal = L> + VocabularyMut,
    {
        match self {
            Self::Literal(l) => l.next(vocabulary),
            Self::List(l) => l.next(vocabulary, generator, rdf_direction),
        }
    }
}

/// Compound value triples bound to a vocabulary and a generator.
pub struct CompoundValueTriplesWith<'a, 'n, N: Vocabulary, G: LocalGenerator> {
    vocabulary: &'n mut N,
    generator: G,
    rdf_direction: Option<RdfDirection>,
    inner: CompoundValueTriples<'a, N::Iri, N::BlankId, N::Literal>,
}

impl<N: Vocabulary + VocabularyMut, G: LocalGenerator> Iterator for CompoundValueTriplesWith<'_, '_, N, G>
where
    N::Iri: Clone,
    N::BlankId: Clone,
    N::Literal: Clone,
{
    type Item = Triple<N::Iri, N::BlankId, N::Literal>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next(self.vocabulary, &mut self.generator, self.rdf_direction)
    }
}

/// Iterator over the RDF quads generated from a list of JSON-LD objects.
///
/// If the list contains nested lists, the iterator will also emit quads for those nested lists.
pub struct ListTriples<'a, T, B, L> {
    stack: SmallVec<[ListItemTriples<'a, T, B, L>; 2]>,
    pending: Option<Triple<T, B, L>>,
}

impl<'a, T, B, L> ListTriples<'a, T, B, L> {
    /// Creates a new `ListTriples`.
    pub fn new(list: &'a [IndexedObject<T, B>], head_ref: ValidId<T, B>) -> Self {
        let mut stack = SmallVec::new();
        stack.push(ListItemTriples::NestedList(NestedListTriples::new(list, head_ref)));

        Self { stack, pending: None }
    }

    /// Binds this iterator to a vocabulary and generator.
    pub fn with<'n, V: Vocabulary<Iri = T, BlankId = B, Literal = L>, G: LocalGenerator>(
        self,
        vocabulary: &'n mut V,
        generator: G,
        rdf_direction: Option<RdfDirection>,
    ) -> ListTriplesWith<'a, 'n, V, G> {
        ListTriplesWith {
            vocabulary,
            generator,
            rdf_direction,
            inner: self,
        }
    }

    /// Produces the next triple of the list, allocating blank node identifiers
    /// as needed.
    pub fn next<V, G: LocalGenerator>(&mut self, vocabulary: &mut V, generator: &mut G, rdf_direction: Option<RdfDirection>) -> Option<Triple<T, B, L>>
    where
        T: Clone,
        B: Clone,
        L: Clone,
        V: Vocabulary<Iri = T, BlankId = B, Literal = L> + VocabularyMut,
    {
        loop {
            if let Some(pending) = self.pending.take() {
                break Some(pending);
            }

            match self.stack.last_mut() {
                Some(ListItemTriples::CompoundLiteral(lit)) => match lit.next(vocabulary) {
                    Some(triple) => break Some(triple),
                    None => {
                        self.stack.pop();
                    }
                },
                Some(ListItemTriples::NestedList(list)) => {
                    let previous = list.previous().cloned();
                    if let Some(node) = list.next(vocabulary, generator) {
                        if let Some(compound_value) = node.object.rdf_value_with(vocabulary, generator, rdf_direction) {
                            let id = node.id.clone();

                            if let Some(compound_triples) = compound_value.triples {
                                match compound_triples {
                                    CompoundValueTriples::List(nested) => self.stack.extend(nested.stack),
                                    CompoundValueTriples::Literal(literal) => self.stack.push(ListItemTriples::CompoundLiteral(literal)),
                                }
                            }

                            self.pending = Some(rdfx::GeneralizedTriple(
                                id.clone(),
                                ValidId::Iri(vocabulary.insert(RDF_FIRST)),
                                compound_value.value,
                            ));

                            if let Some(previous_id) = previous {
                                break Some(rdfx::GeneralizedTriple(
                                    previous_id,
                                    ValidId::Iri(vocabulary.insert(RDF_REST)),
                                    Value::from_id(id),
                                ));
                            }
                        }
                    } else {
                        self.stack.pop();
                        if let Some(previous_id) = previous {
                            break Some(rdfx::GeneralizedTriple(
                                previous_id,
                                ValidId::Iri(vocabulary.insert(RDF_REST)),
                                Value::Id(ValidId::Iri(vocabulary.insert(RDF_NIL))),
                            ));
                        }
                    }
                }
                None => break None,
            }
        }
    }
}

/// List triples bound to a vocabulary and a generator.
pub struct ListTriplesWith<'a, 'n, V: Vocabulary, G: LocalGenerator> {
    vocabulary: &'n mut V,
    generator: G,
    rdf_direction: Option<RdfDirection>,
    inner: ListTriples<'a, V::Iri, V::BlankId, V::Literal>,
}

impl<N: Vocabulary + VocabularyMut, G: LocalGenerator> Iterator for ListTriplesWith<'_, '_, N, G>
where
    N::Iri: Clone,
    N::BlankId: Clone,
    N::Literal: Clone,
{
    type Item = Triple<N::Iri, N::BlankId, N::Literal>;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next(self.vocabulary, &mut self.generator, self.rdf_direction)
    }
}

fn i18n(language: Option<&LangTagBuf>, direction: Direction) -> IriBuf {
    let iri = match language {
        Some(language) => format!("https://www.w3.org/ns/i18n#{language}_{direction}"),
        None => format!("https://www.w3.org/ns/i18n#{direction}"),
    };

    // Built from constants and a parsed `LangTag` / `Direction`, so the
    // bare-namespace fallback is unreachable.
    IriBuf::new(iri).unwrap_or_else(|_| IriBuf::from(iri_rs::iri!("https://www.w3.org/ns/i18n#")))
}

/// RDF object value: either a node identifier or a literal handle.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Value<T, B, L> {
    /// A node identifier.
    Id(ValidId<T, B>),
    /// An RDF literal.
    Literal(L),
}

impl<T, B, L> Value<T, B, L> {
    /// Builds a value from a node identifier.
    pub fn from_id(id: ValidId<T, B>) -> Self {
        Self::Id(id)
    }
}