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
//! Flattening algorithm and related types.
use crate::flattened::UnorderedFlattenedDocument;
use crate::{ExpandedDocument, FlattenedDocument, IndexedNode, IndexedObject, Object};
use contextual::WithContext;
use rdf_types::{Generator, Vocabulary};
use std::collections::HashSet;
use std::hash::Hash;

mod environment;
mod node_map;

pub use environment::Environment;
pub use node_map::*;

pub type FlattenResult<I, B> = Result<FlattenedDocument<I, B>, ConflictingIndexes<I, B>>;

pub type FlattenUnorderedResult<I, B> =
	Result<UnorderedFlattenedDocument<I, B>, ConflictingIndexes<I, B>>;

pub trait Flatten<I, B> {
	fn flatten_with<V, G: Generator<V>>(
		self,
		vocabulary: &mut V,
		generator: G,
		ordered: bool,
	) -> FlattenResult<I, B>
	where
		V: Vocabulary<Iri = I, BlankId = B>;

	fn flatten_unordered_with<V, G: Generator<V>>(
		self,
		vocabulary: &mut V,
		generator: G,
	) -> FlattenUnorderedResult<I, B>
	where
		V: Vocabulary<Iri = I, BlankId = B>;

	fn flatten<G: Generator>(self, generator: G, ordered: bool) -> FlattenResult<I, B>
	where
		(): Vocabulary<Iri = I, BlankId = B>,
		Self: Sized,
	{
		self.flatten_with(
			rdf_types::vocabulary::no_vocabulary_mut(),
			generator,
			ordered,
		)
	}

	fn flatten_unordered<G: Generator>(self, generator: G) -> FlattenUnorderedResult<I, B>
	where
		(): Vocabulary<Iri = I, BlankId = B>,
		Self: Sized,
	{
		self.flatten_unordered_with(rdf_types::vocabulary::no_vocabulary_mut(), generator)
	}
}

impl<I: Clone + Eq + Hash, B: Clone + Eq + Hash> Flatten<I, B> for ExpandedDocument<I, B> {
	fn flatten_with<V, G: Generator<V>>(
		self,
		vocabulary: &mut V,
		generator: G,
		ordered: bool,
	) -> FlattenResult<I, B>
	where
		V: Vocabulary<Iri = I, BlankId = B>,
	{
		Ok(self
			.generate_node_map_with(vocabulary, generator)?
			.flatten_with(vocabulary, ordered))
	}

	fn flatten_unordered_with<V, G: Generator<V>>(
		self,
		vocabulary: &mut V,
		generator: G,
	) -> FlattenUnorderedResult<I, B>
	where
		V: Vocabulary<Iri = I, BlankId = B>,
	{
		Ok(self
			.generate_node_map_with(vocabulary, generator)?
			.flatten_unordered())
	}
}

fn filter_graph<T, B>(node: IndexedNode<T, B>) -> Option<IndexedNode<T, B>> {
	if node.index().is_none() && node.is_empty() {
		None
	} else {
		Some(node)
	}
}

fn filter_sub_graph<T, B>(mut node: IndexedNode<T, B>) -> Option<IndexedObject<T, B>> {
	if node.index().is_none() && node.properties().is_empty() {
		None
	} else {
		node.set_graph_entry(None);
		node.set_included(None);
		node.set_reverse_properties(None);
		Some(node.map_inner(Object::node))
	}
}

impl<T: Clone + Eq + Hash, B: Clone + Eq + Hash> NodeMap<T, B> {
	pub fn flatten(self, ordered: bool) -> FlattenedDocument<T, B>
	where
		(): Vocabulary<Iri = T, BlankId = B>,
	{
		self.flatten_with(&(), ordered)
	}

	pub fn flatten_with<V>(self, vocabulary: &V, ordered: bool) -> FlattenedDocument<T, B>
	where
		V: Vocabulary<Iri = T, BlankId = B>,
	{
		let (mut default_graph, named_graphs) = self.into_parts();

		let mut named_graphs: Vec<_> = named_graphs.into_iter().collect();
		if ordered {
			named_graphs.sort_by(|a, b| {
				a.0.with(vocabulary)
					.as_str()
					.cmp(b.0.with(vocabulary).as_str())
			});
		}

		for (graph_id, graph) in named_graphs {
			let entry = default_graph.declare_node(graph_id, None).ok().unwrap();
			let mut nodes: Vec<_> = graph.into_nodes().collect();
			if ordered {
				nodes.sort_by(|a, b| {
					a.id.as_ref()
						.unwrap()
						.with(vocabulary)
						.as_str()
						.cmp(b.id.as_ref().unwrap().with(vocabulary).as_str())
				});
			}
			entry.set_graph_entry(Some(
				nodes.into_iter().filter_map(filter_sub_graph).collect(),
			));
		}

		let mut nodes: Vec<_> = default_graph
			.into_nodes()
			.filter_map(filter_graph)
			.collect();

		if ordered {
			nodes.sort_by(|a, b| {
				a.id.as_ref()
					.unwrap()
					.with(vocabulary)
					.as_str()
					.cmp(b.id.as_ref().unwrap().with(vocabulary).as_str())
			});
		}

		nodes
	}

	pub fn flatten_unordered(self) -> HashSet<IndexedNode<T, B>> {
		let (mut default_graph, named_graphs) = self.into_parts();

		for (graph_id, graph) in named_graphs {
			let entry = default_graph.declare_node(graph_id, None).ok().unwrap();
			entry.set_graph_entry(Some(
				graph.into_nodes().filter_map(filter_sub_graph).collect(),
			));
		}

		default_graph
			.into_nodes()
			.filter_map(filter_graph)
			.collect()
	}
}