jsonld-core 0.23.3

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
use super::Environment;
use crate::{ExpandedDocument, Id, Indexed, IndexedNode, IndexedObject, Node, Object, hash::IndexMap, object};
use derive_where::derive_where;
use rdfx::{
    LocalGenerator,
    vocabulary::{BlankIdVocabulary, IriVocabulary, VocabularyMut},
};
use std::hash::Hash;

/// Conflicting indexes error.
///
/// Raised when a single node is declared with two different indexes.
#[derive(Clone, Debug, thiserror::Error)]
#[error("Index `{defined_index}` conflicts with index `{conflicting_index}`")]
pub struct ConflictingIndexes<T, B> {
    /// Node carrying the conflicting indexes.
    pub node_id: Id<T, B>,
    /// Index already recorded for the node.
    pub defined_index: String,
    /// Index that contradicts the recorded one.
    pub conflicting_index: String,
}

/// Error returned by node-map construction.
#[derive(Debug, thiserror::Error)]
pub enum NodeMapError<T, B> {
    #[error(transparent)]
    /// A node was given two different `@index` values.
    Conflicting(#[from] ConflictingIndexes<T, B>),

    #[error(transparent)]
    /// A blank node identifier could not be generated.
    GeneratedId(#[from] crate::id::GeneratedIdError),
}

/// Default graph of a node map, paired with its named graphs.
///
/// Named graphs are yielded in the order they were first declared, which is
/// document traversal order.
pub type Parts<T, B> = (NodeMapGraph<T, B>, IndexMap<Id<T, B>, NodeMapGraph<T, B>>);

/// Node identifier to node definition map.
///
/// Graphs are stored in declaration order so that flattening is deterministic:
/// [§4.9 of the JSON-LD API][spec] assigns blank node identifiers in document
/// traversal order.
///
/// [spec]: https://www.w3.org/TR/json-ld11-api/#node-map-generation
#[derive_where(Default)]
pub struct NodeMap<T, B> {
    graphs: IndexMap<Id<T, B>, NodeMapGraph<T, B>>,
    default_graph: NodeMapGraph<T, B>,
}

impl<T, B> NodeMap<T, B> {
    /// Creates a new `NodeMap`.
    #[must_use]
    pub fn new() -> Self {
        Self {
            graphs: IndexMap::default(),
            default_graph: NodeMapGraph::new(),
        }
    }

    /// Consumes the node map, returning its default graph and named graphs.
    #[must_use]
    pub fn into_parts(self) -> Parts<T, B> {
        (self.default_graph, self.graphs)
    }

    /// Returns an iterator over the graphs of the node map: the default
    /// graph first, then the named graphs in declaration order.
    #[must_use]
    pub fn iter(&self) -> Iter<'_, T, B> {
        Iter {
            default_graph: Some(&self.default_graph),
            graphs: self.graphs.iter(),
        }
    }

    /// Returns an iterator over the named graphs only, in declaration order.
    #[must_use]
    pub fn iter_named(&self) -> indexmap::map::Iter<'_, Id<T, B>, NodeMapGraph<T, B>> {
        self.graphs.iter()
    }
}

impl<T: Eq + Hash, B: Eq + Hash> NodeMap<T, B> {
    /// Returns the graph of the given name, or the default graph for `None`,
    /// if it is declared.
    #[must_use]
    pub fn graph(&self, id: Option<&Id<T, B>>) -> Option<&NodeMapGraph<T, B>> {
        match id {
            Some(id) => self.graphs.get(id),
            None => Some(&self.default_graph),
        }
    }

    /// Mutably borrows the graph of the given name, if it is declared.
    pub fn graph_mut(&mut self, id: Option<&Id<T, B>>) -> Option<&mut NodeMapGraph<T, B>> {
        match id {
            Some(id) => self.graphs.get_mut(id),
            None => Some(&mut self.default_graph),
        }
    }

    /// Declares a named graph, leaving it untouched if it already exists.
    pub fn declare_graph(&mut self, id: Id<T, B>) {
        if let indexmap::map::Entry::Vacant(entry) = self.graphs.entry(id) {
            entry.insert(NodeMapGraph::new());
        }
    }

    /// Merge all the graphs into a single `NodeMapGraph`.
    ///
    /// Graphs are merged into the default graph in declaration order.
    #[must_use]
    pub fn merge(self) -> NodeMapGraph<T, B>
    where
        T: Clone,
        B: Clone,
    {
        let mut result = self.default_graph;

        for (_, graph) in self.graphs {
            result.merge_with(graph);
        }

        result
    }
}

/// Iterator over the graphs of a node map.
///
/// The default graph comes first, then the named graphs in declaration order.
pub struct Iter<'a, T, B> {
    default_graph: Option<&'a NodeMapGraph<T, B>>,
    graphs: indexmap::map::Iter<'a, Id<T, B>, NodeMapGraph<T, B>>,
}

impl<'a, T, B> Iterator for Iter<'a, T, B> {
    type Item = (Option<&'a Id<T, B>>, &'a NodeMapGraph<T, B>);

    fn next(&mut self) -> Option<Self::Item> {
        match self.default_graph.take() {
            Some(default_graph) => Some((None, default_graph)),
            None => self.graphs.next().map(|(id, graph)| (Some(id), graph)),
        }
    }
}

impl<'a, T, B> IntoIterator for &'a NodeMap<T, B> {
    type Item = (Option<&'a Id<T, B>>, &'a NodeMapGraph<T, B>);
    type IntoIter = Iter<'a, T, B>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Owning iterator over the graphs of a node map.
///
/// The default graph comes first, then the named graphs in declaration order.
pub struct IntoIter<T, B> {
    default_graph: Option<NodeMapGraph<T, B>>,
    graphs: indexmap::map::IntoIter<Id<T, B>, NodeMapGraph<T, B>>,
}

impl<T, B> Iterator for IntoIter<T, B> {
    type Item = (Option<Id<T, B>>, NodeMapGraph<T, B>);

    fn next(&mut self) -> Option<Self::Item> {
        match self.default_graph.take() {
            Some(default_graph) => Some((None, default_graph)),
            None => self.graphs.next().map(|(id, graph)| (Some(id), graph)),
        }
    }
}

impl<T, B> IntoIterator for NodeMap<T, B> {
    type Item = (Option<Id<T, B>>, NodeMapGraph<T, B>);
    type IntoIter = IntoIter<T, B>;

    fn into_iter(self) -> Self::IntoIter {
        IntoIter {
            default_graph: Some(self.default_graph),
            graphs: self.graphs.into_iter(),
        }
    }
}

#[derive_where(Default)]
/// Nodes of a single graph within a node map.
///
/// Nodes are stored in declaration order; see [`NodeMap`].
pub struct NodeMapGraph<T, B> {
    nodes: IndexMap<Id<T, B>, IndexedNode<T, B>>,
}

impl<T, B> NodeMapGraph<T, B> {
    /// Creates a new `NodeMapGraph`.
    #[must_use]
    pub fn new() -> Self {
        Self { nodes: IndexMap::default() }
    }
}

/// Result of declaring a node in a graph.
pub type DeclareNodeResult<'a, T, B> = Result<&'a mut Indexed<Node<T, B>>, ConflictingIndexes<T, B>>;

impl<T: Eq + Hash, B: Eq + Hash> NodeMapGraph<T, B> {
    /// Checks whether the graph declares a node with the given identifier.
    pub fn contains(&self, id: &Id<T, B>) -> bool {
        self.nodes.contains_key(id)
    }

    /// Returns the value bound to the given key, if any.
    pub fn get(&self, id: &Id<T, B>) -> Option<&IndexedNode<T, B>> {
        self.nodes.get(id)
    }

    /// Returns a mutable reference to the value bound to the given key, if any.
    pub fn get_mut(&mut self, id: &Id<T, B>) -> Option<&mut IndexedNode<T, B>> {
        self.nodes.get_mut(id)
    }

    /// Declares a node in this graph, failing if `index` contradicts the index
    /// already recorded for it.
    ///
    /// # Errors
    ///
    /// Returns an error when the node is already declared with a conflicting index, or when the generator runs out of identifiers.
    pub fn declare_node(&mut self, id: Id<T, B>, index: Option<&str>) -> DeclareNodeResult<'_, T, B>
    where
        T: Clone,
        B: Clone,
    {
        match self.nodes.entry(id) {
            indexmap::map::Entry::Occupied(occupied) => match (occupied.get().index(), index) {
                (Some(entry_index), Some(index)) if entry_index != index => Err(ConflictingIndexes {
                    node_id: occupied.key().clone(),
                    defined_index: entry_index.to_string(),
                    conflicting_index: index.to_string(),
                }),
                (None, Some(index)) => {
                    let entry = occupied.into_mut();
                    entry.set_index(Some(index.to_owned()));
                    Ok(entry)
                }
                _ => Ok(occupied.into_mut()),
            },
            indexmap::map::Entry::Vacant(vacant) => {
                let node = Indexed::new(Node::with_id(vacant.key().clone()), index.map(ToOwned::to_owned));
                Ok(vacant.insert(node))
            }
        }
    }

    /// Merges `other` into this graph.
    ///
    /// This calls [`merge_node`](Self::merge_node) with every node of `other`.
    pub fn merge_with(&mut self, other: Self)
    where
        T: Clone,
        B: Clone,
    {
        for (_, node) in other {
            self.merge_node(node);
        }
    }

    /// Merges the given `node` into the graph.
    ///
    /// The `node` must have an identifier, or this function has no effect.
    /// If there is already a node with the same identifier:
    /// - The index of `node`, if any, overrides the previously existing index.
    /// - The list of `node` types is concatenated after the preexisting types.
    /// - The graph and imported values are overridden.
    /// - Properties and reverse properties are merged.
    pub fn merge_node(&mut self, node: IndexedNode<T, B>)
    where
        T: Clone,
        B: Clone,
    {
        let (node, index) = node.into_parts();

        if let Some(id) = &node.id {
            let flat_node = match self.nodes.entry(id.clone()) {
                indexmap::map::Entry::Occupied(occupied) => {
                    let entry = occupied.into_mut();
                    if let Some(index) = index {
                        entry.set_index(Some(index));
                    }
                    entry
                }
                indexmap::map::Entry::Vacant(vacant) => vacant.insert(Indexed::new(Node::with_id(id.clone()), index)),
            };

            if let Some(types) = node.types {
                flat_node.types_mut_or_default().extend(types);
            }

            flat_node.set_graph_entry(node.graph);
            flat_node.set_included(node.included);
            flat_node.properties_mut().extend_unique(node.properties);

            if let Some(props) = node.reverse_properties {
                flat_node.reverse_properties_or_default().extend_unique(props);
            }
        }
    }

    /// Returns an iterator over the nodes of the graph, in declaration order.
    #[must_use]
    pub fn nodes(&self) -> NodeMapGraphNodes<'_, T, B> {
        self.nodes.values()
    }

    /// Consumes the graph, returning an iterator over its nodes in
    /// declaration order.
    #[must_use]
    pub fn into_nodes(self) -> IntoNodeMapGraphNodes<T, B> {
        self.nodes.into_values()
    }
}

/// Iterator over the nodes of a graph, in declaration order.
pub type NodeMapGraphNodes<'a, T, B> = indexmap::map::Values<'a, Id<T, B>, IndexedNode<T, B>>;
/// Owning iterator over the nodes of a graph, in declaration order.
pub type IntoNodeMapGraphNodes<T, B> = indexmap::map::IntoValues<Id<T, B>, IndexedNode<T, B>>;

impl<T, B> IntoIterator for NodeMapGraph<T, B> {
    type Item = (Id<T, B>, IndexedNode<T, B>);
    type IntoIter = indexmap::map::IntoIter<Id<T, B>, IndexedNode<T, B>>;

    fn into_iter(self) -> Self::IntoIter {
        self.nodes.into_iter()
    }
}

impl<T, B> NodeMapGraph<T, B> {
    /// Iterates over the nodes of this graph, keyed by identifier.
    #[must_use]
    pub fn iter(&self) -> indexmap::map::Iter<'_, Id<T, B>, IndexedNode<T, B>> {
        self.nodes.iter()
    }
}

impl<'a, T, B> IntoIterator for &'a NodeMapGraph<T, B> {
    type Item = (&'a Id<T, B>, &'a IndexedNode<T, B>);
    type IntoIter = indexmap::map::Iter<'a, Id<T, B>, IndexedNode<T, B>>;

    fn into_iter(self) -> Self::IntoIter {
        self.nodes.iter()
    }
}

impl<T: Clone + Eq + Hash, B: Clone + Eq + Hash> ExpandedDocument<T, B> {
    /// Builds the node map of this document using the given vocabulary and
    /// blank node generator.
    ///
    /// # Errors
    ///
    /// Returns an error when the generator runs out of identifiers, or when two nodes disagree on an `@index`.
    pub fn generate_node_map_with<V: VocabularyMut<Iri = T, BlankId = B>, G: LocalGenerator>(
        &self,
        vocabulary: &mut V,
        generator: G,
    ) -> Result<NodeMap<T, B>, NodeMapError<T, B>> {
        let mut node_map: NodeMap<T, B> = NodeMap::new();
        let mut env: Environment<V, G> = Environment::new(vocabulary, generator);
        for object in self {
            extend_node_map(&mut env, &mut node_map, object, None)?;
        }
        Ok(node_map)
    }
}

/// Result of extending a node map with a document fragment.
pub type ExtendNodeMapResult<V> = Result<
    IndexedObject<<V as IriVocabulary>::Iri, <V as BlankIdVocabulary>::BlankId>,
    NodeMapError<<V as IriVocabulary>::Iri, <V as BlankIdVocabulary>::BlankId>,
>;

/// Extends the `NodeMap` with the given `element` of an expanded JSON-LD document.
fn extend_node_map<N: VocabularyMut, G: LocalGenerator>(
    env: &mut Environment<N, G>,
    node_map: &mut NodeMap<N::Iri, N::BlankId>,
    element: &IndexedObject<N::Iri, N::BlankId>,
    active_graph: Option<&Id<N::Iri, N::BlankId>>,
) -> ExtendNodeMapResult<N>
where
    N::Iri: Clone + Eq + Hash,
    N::BlankId: Clone + Eq + Hash,
{
    match element.inner() {
        Object::Value(value) => {
            let flat_value = value.clone();
            Ok(Indexed::new(Object::Value(flat_value), element.index().map(ToOwned::to_owned)))
        }
        Object::List(list) => {
            let mut flat_list = Vec::new();

            for item in list {
                flat_list.push(extend_node_map(env, node_map, item, active_graph)?);
            }

            Ok(Indexed::new(Object::List(object::List::new(flat_list)), element.index().map(ToOwned::to_owned)))
        }
        Object::Node(node) => {
            let flat_node = extend_node_map_from_node(env, node_map, node, element.index(), active_graph)?;
            Ok(flat_node.map_inner(Object::node))
        }
    }
}

type ExtendNodeMapFromNodeResult<T, B> = Result<Indexed<Node<T, B>>, NodeMapError<T, B>>;

fn extend_node_map_from_node<N: VocabularyMut, G: LocalGenerator>(
    env: &mut Environment<N, G>,
    node_map: &mut NodeMap<N::Iri, N::BlankId>,
    node: &Node<N::Iri, N::BlankId>,
    index: Option<&str>,
    active_graph: Option<&Id<N::Iri, N::BlankId>>,
) -> ExtendNodeMapFromNodeResult<N::Iri, N::BlankId>
where
    N::Iri: Clone + Eq + Hash,
    N::BlankId: Clone + Eq + Hash,
{
    let id = env.assign_node_id(node.id.as_ref())?;

    {
        // SAFETY: `active_graph` is always either `None` (default graph) or a
        // graph id that was previously declared via `node_map.declare_graph`.
        let flat_node = unsafe { node_map.graph_mut(active_graph).unwrap_unchecked() }.declare_node(id.clone(), index)?;

        if let Some(entry) = node.types.as_deref() {
            let types: Result<Vec<_>, _> = entry.iter().map(|ty| env.assign_node_id(Some(ty))).collect();
            flat_node.types = Some(types?);
        }
    }

    if let Some(graph_entry) = node.graph_entry() {
        node_map.declare_graph(id.clone());

        let mut flat_graph: Vec<_> = Vec::new();
        for object in graph_entry {
            let flat_object = extend_node_map(env, node_map, object, Some(&id))?;
            flat_graph.push(flat_object);
        }

        // SAFETY: `id` was just declared above; `active_graph` is `None` or
        // declared earlier.
        let flat_node = unsafe { node_map.graph_mut(active_graph).unwrap_unchecked().get_mut(&id).unwrap_unchecked() };
        match flat_node.graph_entry_mut() {
            Some(graph) => graph.extend(flat_graph),
            None => flat_node.set_graph_entry(Some(flat_graph)),
        }
    }

    if let Some(included_entry) = node.included_entry() {
        for inode in included_entry {
            extend_node_map_from_node(env, node_map, inode.inner(), inode.index(), active_graph)?;
        }
    }

    for (property, objects) in node.properties() {
        // "If property is a blank node identifier, replace it with a newly
        // generated blank node identifier" — properties share the relabeling
        // map with node identifiers (`flatten#t0038`).
        let property = env.assign_node_id(Some(property))?;

        let mut flat_objects = Vec::new();
        for object in objects {
            let flat_object = extend_node_map(env, node_map, object, active_graph)?;
            flat_objects.push(flat_object);
        }
        // SAFETY: `id` was declared in this graph above.
        unsafe { node_map.graph_mut(active_graph).unwrap_unchecked().get_mut(&id).unwrap_unchecked() }
            .properties_mut()
            .insert_all_unique(property, flat_objects);
    }

    if let Some(reverse_properties) = node.reverse_properties_entry() {
        for (property, nodes) in reverse_properties {
            for subject in nodes {
                let flat_subject = extend_node_map_from_node(env, node_map, subject.inner(), subject.index(), active_graph)?;

                // SAFETY: every flat node produced by `extend_node_map_from_node`
                // has an `id` set.
                let subject_id = unsafe { flat_subject.id.as_ref().unwrap_unchecked() };

                // SAFETY: subject was just declared in this graph.
                let flat_subject = unsafe { node_map.graph_mut(active_graph).unwrap_unchecked().get_mut(subject_id).unwrap_unchecked() };

                flat_subject
                    .properties_mut()
                    .insert_unique(property.clone(), Indexed::none(Object::node(Node::with_id(id.clone()))));
            }
        }
    }

    Ok(Indexed::new(Node::with_id(id), None))
}