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
use iref::{Iri, IriRef, IriRefBuf};
use smallvec::SmallVec;

pub mod definition;
mod print;
pub mod term_definition;
mod try_from_json;

pub use definition::Definition;
pub use term_definition::TermDefinition;
pub use try_from_json::InvalidContext;

/// JSON-LD Context.
///
/// Can represent a single context entry, or a list of context entries.
#[derive(PartialEq, Eq, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(untagged))]
pub enum Context {
	One(ContextEntry),
	Many(Vec<ContextEntry>),
}

impl Default for Context {
	fn default() -> Self {
		Self::Many(Vec::new())
	}
}

impl Context {
	/// Creates a new context with a single entry.
	pub fn one(context: ContextEntry) -> Self {
		Self::One(context)
	}

	/// Creates the `null` context.
	pub fn null() -> Self {
		Self::one(ContextEntry::Null)
	}

	/// Creates a new context with a single IRI-reference entry.
	pub fn iri_ref(iri_ref: IriRefBuf) -> Self {
		Self::one(ContextEntry::IriRef(iri_ref))
	}

	/// Creates a new context with a single context definition entry.
	pub fn definition(def: Definition) -> Self {
		Self::one(ContextEntry::Definition(def))
	}
}

impl Context {
	pub fn len(&self) -> usize {
		match self {
			Self::One(_) => 1,
			Self::Many(l) => l.len(),
		}
	}

	pub fn is_empty(&self) -> bool {
		match self {
			Self::One(_) => false,
			Self::Many(l) => l.is_empty(),
		}
	}

	pub fn as_slice(&self) -> &[ContextEntry] {
		match self {
			Self::One(c) => std::slice::from_ref(c),
			Self::Many(list) => list,
		}
	}

	pub fn is_object(&self) -> bool {
		match self {
			Self::One(c) => c.is_object(),
			_ => false,
		}
	}

	pub fn is_array(&self) -> bool {
		matches!(self, Self::Many(_))
	}

	pub fn traverse(&self) -> Traverse {
		match self {
			Self::One(c) => Traverse::new(FragmentRef::Context(c)),
			Self::Many(m) => Traverse::new(FragmentRef::ContextArray(m)),
		}
	}

	pub fn iter(&self) -> std::slice::Iter<ContextEntry> {
		self.as_slice().iter()
	}
}

pub enum IntoIter {
	One(Option<ContextEntry>),
	Many(std::vec::IntoIter<ContextEntry>),
}

impl Iterator for IntoIter {
	type Item = ContextEntry;

	fn next(&mut self) -> Option<Self::Item> {
		match self {
			Self::One(t) => t.take(),
			Self::Many(t) => t.next(),
		}
	}
}

impl IntoIterator for Context {
	type Item = ContextEntry;
	type IntoIter = IntoIter;

	fn into_iter(self) -> Self::IntoIter {
		match self {
			Self::One(t) => IntoIter::One(Some(t)),
			Self::Many(t) => IntoIter::Many(t.into_iter()),
		}
	}
}

impl<'a> IntoIterator for &'a Context {
	type IntoIter = std::slice::Iter<'a, ContextEntry>;
	type Item = &'a ContextEntry;

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

impl From<ContextEntry> for Context {
	fn from(c: ContextEntry) -> Self {
		Self::One(c)
	}
}

impl From<IriRefBuf> for Context {
	fn from(i: IriRefBuf) -> Self {
		Self::One(ContextEntry::IriRef(i))
	}
}

impl<'a> From<&'a IriRef> for Context {
	fn from(i: &'a IriRef) -> Self {
		Self::One(ContextEntry::IriRef(i.to_owned()))
	}
}

impl From<iref::IriBuf> for Context {
	fn from(i: iref::IriBuf) -> Self {
		Self::One(ContextEntry::IriRef(i.into()))
	}
}

impl<'a> From<&'a Iri> for Context {
	fn from(i: &'a Iri) -> Self {
		Self::One(ContextEntry::IriRef(i.to_owned().into()))
	}
}

impl From<Definition> for Context {
	fn from(c: Definition) -> Self {
		Self::One(ContextEntry::Definition(c))
	}
}

/// Context.
#[derive(PartialEq, Eq, Clone, Debug)]
#[cfg_attr(
	feature = "serde",
	derive(serde::Serialize, serde::Deserialize),
	serde(untagged)
)]
pub enum ContextEntry {
	Null,
	IriRef(IriRefBuf),
	Definition(Definition),
}

impl ContextEntry {
	fn sub_items(&self) -> ContextSubFragments {
		match self {
			Self::Definition(d) => ContextSubFragments::Definition(Box::new(d.iter())),
			_ => ContextSubFragments::None,
		}
	}

	pub fn is_object(&self) -> bool {
		matches!(self, Self::Definition(_))
	}
}

impl From<IriRefBuf> for ContextEntry {
	fn from(i: IriRefBuf) -> Self {
		ContextEntry::IriRef(i)
	}
}

impl<'a> From<&'a IriRef> for ContextEntry {
	fn from(i: &'a IriRef) -> Self {
		ContextEntry::IriRef(i.to_owned())
	}
}

impl From<iref::IriBuf> for ContextEntry {
	fn from(i: iref::IriBuf) -> Self {
		ContextEntry::IriRef(i.into())
	}
}

impl<'a> From<&'a Iri> for ContextEntry {
	fn from(i: &'a Iri) -> Self {
		ContextEntry::IriRef(i.to_owned().into())
	}
}

impl From<Definition> for ContextEntry {
	fn from(c: Definition) -> Self {
		ContextEntry::Definition(c)
	}
}

/// Context value fragment.
pub enum FragmentRef<'a> {
	/// Context array.
	ContextArray(&'a [ContextEntry]),

	/// Context.
	Context(&'a ContextEntry),

	/// Context definition fragment.
	DefinitionFragment(definition::FragmentRef<'a>),
}

impl<'a> FragmentRef<'a> {
	pub fn is_array(&self) -> bool {
		match self {
			Self::ContextArray(_) => true,
			Self::DefinitionFragment(i) => i.is_array(),
			_ => false,
		}
	}

	pub fn is_object(&self) -> bool {
		match self {
			Self::Context(c) => c.is_object(),
			Self::DefinitionFragment(i) => i.is_object(),
			_ => false,
		}
	}

	pub fn sub_items(&self) -> SubFragments<'a> {
		match self {
			Self::ContextArray(a) => SubFragments::ContextArray(a.iter()),
			Self::Context(c) => SubFragments::Context(c.sub_items()),
			Self::DefinitionFragment(d) => SubFragments::Definition(Box::new(d.sub_items())),
		}
	}
}

pub enum ContextSubFragments<'a> {
	None,
	Definition(Box<definition::Entries<'a>>),
}

impl<'a> Iterator for ContextSubFragments<'a> {
	type Item = FragmentRef<'a>;

	fn next(&mut self) -> Option<Self::Item> {
		match self {
			Self::None => None,
			Self::Definition(e) => e
				.next()
				.map(|e| FragmentRef::DefinitionFragment(definition::FragmentRef::Entry(e))),
		}
	}
}

pub enum SubFragments<'a> {
	ContextArray(std::slice::Iter<'a, ContextEntry>),
	Context(ContextSubFragments<'a>),
	Definition(Box<definition::SubItems<'a>>),
}

impl<'a> Iterator for SubFragments<'a> {
	type Item = FragmentRef<'a>;

	fn next(&mut self) -> Option<Self::Item> {
		match self {
			Self::ContextArray(a) => a.next().map(FragmentRef::Context),
			Self::Context(i) => i.next(),
			Self::Definition(i) => i.next().map(FragmentRef::DefinitionFragment),
		}
	}
}

pub struct Traverse<'a> {
	stack: SmallVec<[FragmentRef<'a>; 8]>,
}

impl<'a> Traverse<'a> {
	pub(crate) fn new(item: FragmentRef<'a>) -> Self {
		let mut stack = SmallVec::new();
		stack.push(item);
		Self { stack }
	}
}

impl<'a> Iterator for Traverse<'a> {
	type Item = FragmentRef<'a>;

	fn next(&mut self) -> Option<Self::Item> {
		match self.stack.pop() {
			Some(item) => {
				self.stack.extend(item.sub_items());
				Some(item)
			}
			None => None,
		}
	}
}

/// Context document.
///
/// A context document is a JSON-LD document containing an object with a single
/// `@context` entry.
#[derive(PartialEq, Eq, Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ContextDocument {
	#[cfg_attr(feature = "serde", serde(rename = "@context"))]
	pub context: Context,
}