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
use json_ld_core::{ExpandedDocument, FlattenedDocument, Loader, Term};
use json_ld_syntax::{IntoJson, Keyword};
use rdf_types::{vocabulary, Vocabulary};
use std::hash::Hash;

use crate::{
	iri::{compact_iri, IriConfusedWithPrefix},
	CompactFragment,
};

pub type CompactDocumentResult = Result<json_syntax::Value, crate::Error>;

/// Context embeding method.
///
/// This trait provides the `embed_context` method that can be used
/// to include a JSON-LD context to a JSON-LD document.
/// It is used at the end of compaction algorithm to embed to
/// context used to compact the document into the compacted output.
pub trait EmbedContext {
	/// Embeds the given context into the document.
	fn embed_context<N>(
		&mut self,
		vocabulary: &N,
		context: json_ld_context_processing::ProcessedRef<N::Iri, N::BlankId>,
		options: crate::Options,
	) -> Result<(), IriConfusedWithPrefix>
	where
		N: Vocabulary,
		N::Iri: Clone + Hash + Eq,
		N::BlankId: Clone + Hash + Eq;
}

/// Compaction function.
pub trait Compact<I, B> {
	/// Compacts the input document with full options.
	#[allow(async_fn_in_trait)]
	async fn compact_full<'a, N, L>(
		&'a self,
		vocabulary: &'a mut N,
		context: json_ld_context_processing::ProcessedRef<'a, 'a, I, B>,
		loader: &'a L,
		options: crate::Options,
	) -> CompactDocumentResult
	where
		N: rdf_types::VocabularyMut<Iri = I, BlankId = B>,
		I: Clone + Hash + Eq,
		B: Clone + Hash + Eq,
		L: Loader;

	/// Compacts the input document with the given `vocabulary` to
	/// interpret identifiers.
	#[allow(async_fn_in_trait)]
	async fn compact_with<'a, N, L>(
		&'a self,
		vocabulary: &'a mut N,
		context: json_ld_context_processing::ProcessedRef<'a, 'a, I, B>,
		loader: &'a L,
	) -> CompactDocumentResult
	where
		N: rdf_types::VocabularyMut<Iri = I, BlankId = B>,
		I: Clone + Hash + Eq,
		B: Clone + Hash + Eq,
		L: Loader,
	{
		self.compact_full(vocabulary, context, loader, crate::Options::default())
			.await
	}

	/// Compacts the input document.
	#[allow(async_fn_in_trait)]
	async fn compact<'a, L>(
		&'a self,
		context: json_ld_context_processing::ProcessedRef<'a, 'a, I, B>,
		loader: &'a L,
	) -> CompactDocumentResult
	where
		(): rdf_types::VocabularyMut<Iri = I, BlankId = B>,
		I: Clone + Hash + Eq,
		B: Clone + Hash + Eq,
		L: Loader,
	{
		self.compact_with(vocabulary::no_vocabulary_mut(), context, loader)
			.await
	}
}

impl<I, B> Compact<I, B> for ExpandedDocument<I, B> {
	async fn compact_full<'a, N, L>(
		&'a self,
		vocabulary: &'a mut N,
		context: json_ld_context_processing::ProcessedRef<'a, 'a, I, B>,
		loader: &'a L,
		options: crate::Options,
	) -> CompactDocumentResult
	where
		N: rdf_types::VocabularyMut<Iri = I, BlankId = B>,
		I: Clone + Hash + Eq,
		B: Clone + Hash + Eq,
		L: Loader,
	{
		let mut compacted_output = self
			.objects()
			.compact_fragment_full(
				vocabulary,
				context.processed(),
				context.processed(),
				None,
				loader,
				options,
			)
			.await?;

		compacted_output.embed_context(vocabulary, context, options)?;

		Ok(compacted_output)
	}
}

impl<I, B> Compact<I, B> for FlattenedDocument<I, B> {
	async fn compact_full<'a, N, L>(
		&'a self,
		vocabulary: &'a mut N,
		context: json_ld_context_processing::ProcessedRef<'a, 'a, I, B>,
		loader: &'a L,
		options: crate::Options,
	) -> CompactDocumentResult
	where
		N: rdf_types::VocabularyMut<Iri = I, BlankId = B>,
		I: Clone + Hash + Eq,
		B: Clone + Hash + Eq,
		L: Loader,
	{
		let mut compacted_output = self
			.compact_fragment_full(
				vocabulary,
				context.processed(),
				context.processed(),
				None,
				loader,
				options,
			)
			.await?;

		compacted_output.embed_context(vocabulary, context, options)?;

		Ok(compacted_output)
	}
}

impl EmbedContext for json_syntax::Value {
	fn embed_context<N>(
		&mut self,
		vocabulary: &N,
		context: json_ld_context_processing::ProcessedRef<N::Iri, N::BlankId>,
		options: crate::Options,
	) -> Result<(), IriConfusedWithPrefix>
	where
		N: Vocabulary,
		N::Iri: Clone + Hash + Eq,
		N::BlankId: Clone + Hash + Eq,
	{
		let value = self.take();

		let obj = match value {
			json_syntax::Value::Array(array) => {
				let mut obj = json_syntax::Object::new();

				if !array.is_empty() {
					let key = compact_iri(
						vocabulary,
						context.processed(),
						&Term::Keyword(Keyword::Graph),
						true,
						false,
						options,
					)?;

					obj.insert(key.unwrap().into(), array.into());
				}

				Some(obj)
			}
			json_syntax::Value::Object(obj) => Some(obj),
			_null => None,
		};

		if let Some(mut obj) = obj {
			let json_context = IntoJson::into_json(context.unprocessed().clone());

			if !obj.is_empty()
				&& !json_context.is_null()
				&& !json_context.is_empty_array_or_object()
			{
				obj.insert_front("@context".into(), json_context);
			}

			*self = obj.into()
		};

		Ok(())
	}
}