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
use futures::future::{BoxFuture, FutureExt};
pub use json_ld_core::{warning, Context, ContextLoader, ProcessingMode};
use json_ld_syntax::ErrorCode;
use locspan::Meta;
use rdf_types::VocabularyMut;
use std::fmt;

mod processed;
mod stack;
pub mod syntax;

pub use processed::*;
pub use stack::ProcessingStack;

/// Warnings that can be raised during context processing.
pub enum Warning {
	KeywordLikeTerm(String),
	KeywordLikeValue(String),
	MalformedIri(String),
}

impl fmt::Display for Warning {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		match self {
			Self::KeywordLikeTerm(s) => write!(f, "keyword-like term `{}`", s),
			Self::KeywordLikeValue(s) => write!(f, "keyword-like value `{}`", s),
			Self::MalformedIri(s) => write!(f, "malformed IRI `{}`", s),
		}
	}
}

/// Located warning.
pub type MetaWarning<M> = Meta<Warning, M>;

pub trait WarningHandler<N, M>: json_ld_core::warning::Handler<N, MetaWarning<M>> {}

impl<N, M, H> WarningHandler<N, M> for H where H: json_ld_core::warning::Handler<N, MetaWarning<M>> {}

/// Errors that can happen during context processing.
#[derive(Debug)]
pub enum Error<E> {
	InvalidContextNullification,
	LoadingDocumentFailed,
	ProcessingModeConflict,
	InvalidContextEntry,
	InvalidImportValue,
	InvalidRemoteContext,
	InvalidBaseIri,
	InvalidVocabMapping,
	CyclicIriMapping,
	InvalidTermDefinition,
	KeywordRedefinition,
	InvalidProtectedValue,
	InvalidTypeMapping,
	InvalidReverseProperty,
	InvalidIriMapping,
	InvalidKeywordAlias,
	InvalidContainerMapping,
	InvalidScopedContext,
	ProtectedTermRedefinition,
	ContextLoadingFailed(E),
}

impl<E> Error<E> {
	pub fn code(&self) -> ErrorCode {
		match self {
			Self::InvalidContextNullification => ErrorCode::InvalidContextNullification,
			Self::LoadingDocumentFailed => ErrorCode::LoadingDocumentFailed,
			Self::ProcessingModeConflict => ErrorCode::ProcessingModeConflict,
			Self::InvalidContextEntry => ErrorCode::InvalidContextEntry,
			Self::InvalidImportValue => ErrorCode::InvalidImportValue,
			Self::InvalidRemoteContext => ErrorCode::InvalidRemoteContext,
			Self::InvalidBaseIri => ErrorCode::InvalidBaseIri,
			Self::InvalidVocabMapping => ErrorCode::InvalidVocabMapping,
			Self::CyclicIriMapping => ErrorCode::CyclicIriMapping,
			Self::InvalidTermDefinition => ErrorCode::InvalidTermDefinition,
			Self::KeywordRedefinition => ErrorCode::KeywordRedefinition,
			Self::InvalidProtectedValue => ErrorCode::InvalidPropagateValue,
			Self::InvalidTypeMapping => ErrorCode::InvalidTypeMapping,
			Self::InvalidReverseProperty => ErrorCode::InvalidReverseProperty,
			Self::InvalidIriMapping => ErrorCode::InvalidIriMapping,
			Self::InvalidKeywordAlias => ErrorCode::InvalidKeywordAlias,
			Self::InvalidContainerMapping => ErrorCode::InvalidContainerMapping,
			Self::InvalidScopedContext => ErrorCode::InvalidScopedContext,
			Self::ProtectedTermRedefinition => ErrorCode::ProtectedTermRedefinition,
			Self::ContextLoadingFailed(_) => ErrorCode::LoadingRemoteContextFailed,
		}
	}
}

impl<E: fmt::Display> fmt::Display for Error<E> {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		match self {
			Self::InvalidContextNullification => write!(f, "invalid context nullification"),
			Self::LoadingDocumentFailed => write!(f, "loading document failed"),
			Self::ProcessingModeConflict => write!(f, "processing mode conflict"),
			Self::InvalidContextEntry => write!(f, "invalid context entry"),
			Self::InvalidImportValue => write!(f, "invalid import value"),
			Self::InvalidRemoteContext => write!(f, "invalid remote context"),
			Self::InvalidBaseIri => write!(f, "invalid base IRI"),
			Self::InvalidVocabMapping => write!(f, "invalid vocabulary mapping"),
			Self::CyclicIriMapping => write!(f, "cyclic IRI mapping"),
			Self::InvalidTermDefinition => write!(f, "invalid term definition"),
			Self::KeywordRedefinition => write!(f, "keyword redefinition"),
			Self::InvalidProtectedValue => write!(f, "invalid protected value"),
			Self::InvalidTypeMapping => write!(f, "invalid type mapping"),
			Self::InvalidReverseProperty => write!(f, "invalid reverse property"),
			Self::InvalidIriMapping => write!(f, "invalid IRI mapping"),
			Self::InvalidKeywordAlias => write!(f, "invalid keyword alias"),
			Self::InvalidContainerMapping => write!(f, "invalid container mapping"),
			Self::InvalidScopedContext => write!(f, "invalid scoped context"),
			Self::ProtectedTermRedefinition => write!(f, "protected term redefinition"),
			Self::ContextLoadingFailed(e) => write!(f, "context loading failed: {}", e),
		}
	}
}

/// Located error.
pub type MetaError<M, E> = Meta<Error<E>, M>;

/// Result of context processing functions.
pub type ProcessingResult<'a, T, B, M, C, E> = Result<Processed<'a, T, B, C, M>, MetaError<M, E>>;

/// Context processing functions.
// FIXME: unclear why the `'static` lifetime is now required.
pub trait ProcessMeta<T, B, M>:
	json_ld_syntax::IntoJsonMeta<M> + json_ld_syntax::context::AnyValue<M>
{
	/// Process the local context with specific options.
	fn process_meta<'l: 'a, 'a, N, L: ContextLoader<T, M> + Send + Sync>(
		&'l self,
		meta: &'l M,
		vocabulary: &'a mut N,
		active_context: &'a Context<T, B, Self, M>,
		stack: ProcessingStack<T>,
		loader: &'a mut L,
		base_url: Option<T>,
		options: Options,
		warnings: impl 'a + Send + WarningHandler<N, M>,
	) -> BoxFuture<'a, ProcessingResult<'l, T, B, M, Self, L::ContextError>>
	where
		N: Send + Sync + VocabularyMut<Iri = T, BlankId = B>,
		T: Clone + PartialEq + Send + Sync,
		B: Clone + PartialEq + Send + Sync,
		M: 'a + Clone + Send + Sync,
		L::Context: Into<Self>;
}

pub trait Process<T, B, M>: Send + Sync {
	type Stripped: Send + Sync;

	/// Process the local context with specific options.
	#[allow(clippy::type_complexity)]
	fn process_full<'l: 'a, 'a, N, L: ContextLoader<T, M> + Send + Sync>(
		&'l self,
		vocabulary: &'a mut N,
		active_context: &'a Context<T, B, Self::Stripped, M>,
		loader: &'a mut L,
		base_url: Option<T>,
		options: Options,
		warnings: impl 'a + Send + WarningHandler<N, M>,
	) -> BoxFuture<'a, ProcessingResult<'l, T, B, M, Self::Stripped, L::ContextError>>
	where
		N: Send + Sync + VocabularyMut<Iri = T, BlankId = B>,
		T: Clone + PartialEq + Send + Sync,
		B: Clone + PartialEq + Send + Sync,
		M: 'a + Clone + Send + Sync,
		L::Context: Into<Self::Stripped>;

	/// Process the local context with specific options.
	#[allow(clippy::type_complexity)]
	fn process_with<'l: 'a, 'a, N, L: ContextLoader<T, M> + Send + Sync>(
		&'l self,
		vocabulary: &'a mut N,
		active_context: &'a Context<T, B, Self::Stripped, M>,
		loader: &'a mut L,
		base_url: Option<T>,
		options: Options,
	) -> BoxFuture<'a, ProcessingResult<'l, T, B, M, Self::Stripped, L::ContextError>>
	where
		N: Send + Sync + VocabularyMut<Iri = T, BlankId = B>,
		T: Clone + PartialEq + Send + Sync,
		B: Clone + PartialEq + Send + Sync,
		M: 'a + Clone + Send + Sync,
		L::Context: Into<Self::Stripped>,
	{
		self.process_full(
			vocabulary,
			active_context,
			loader,
			base_url,
			options,
			warning::Print,
		)
	}

	/// Process the local context with the given initial active context with the default options:
	/// `is_remote` is `false`, `override_protected` is `false` and `propagate` is `true`.
	#[allow(clippy::type_complexity)]
	fn process<'l: 'a, 'a, N, L: ContextLoader<T, M> + Send + Sync>(
		&'l self,
		vocabulary: &'a mut N,
		loader: &'a mut L,
		base_url: Option<T>,
	) -> BoxFuture<'a, ProcessingResult<'l, T, B, M, Self::Stripped, L::ContextError>>
	where
		N: Send + Sync + VocabularyMut<Iri = T, BlankId = B>,
		T: 'a + Clone + PartialEq + Send + Sync,
		B: 'a + Clone + PartialEq + Send + Sync,
		M: 'a + Clone + Send + Sync,
		L::Context: Into<Self::Stripped>,
	{
		async move {
			let active_context = Context::default();
			self.process_full(
				vocabulary,
				&active_context,
				loader,
				base_url,
				Options::default(),
				warning::Print,
			)
			.await
		}
		.boxed()
	}
}

impl<C: ProcessMeta<T, B, M>, T, B, M: Send + Sync> Process<T, B, M> for Meta<C, M> {
	type Stripped = C;

	/// Process the local context with specific options.
	fn process_full<'l: 'a, 'a, N, L: ContextLoader<T, M> + Send + Sync>(
		&'l self,
		vocabulary: &'a mut N,
		active_context: &'a Context<T, B, Self::Stripped, M>,
		loader: &'a mut L,
		base_url: Option<T>,
		options: Options,
		warnings: impl 'a + Send + WarningHandler<N, M>,
	) -> BoxFuture<'a, ProcessingResult<'l, T, B, M, Self::Stripped, L::ContextError>>
	where
		N: Send + Sync + VocabularyMut<Iri = T, BlankId = B>,
		T: Clone + PartialEq + Send + Sync,
		B: Clone + PartialEq + Send + Sync,
		M: 'a + Clone,
		L::Context: Into<Self::Stripped>,
	{
		self.value().process_meta(
			self.metadata(),
			vocabulary,
			active_context,
			ProcessingStack::new(),
			loader,
			base_url,
			options,
			warnings,
		)
	}
}

/// Options of the Context Processing Algorithm.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Options {
	/// The processing mode
	pub processing_mode: ProcessingMode,

	/// Override protected definitions.
	pub override_protected: bool,

	/// Propagate the processed context.
	pub propagate: bool,
}

impl Options {
	/// Return the same set of options, but with `override_protected` set to `true`.
	#[must_use]
	pub fn with_override(&self) -> Options {
		let mut opt = *self;
		opt.override_protected = true;
		opt
	}

	/// Return the same set of options, but with `override_protected` set to `false`.
	#[must_use]
	pub fn with_no_override(&self) -> Options {
		let mut opt = *self;
		opt.override_protected = false;
		opt
	}

	/// Return the same set of options, but with `propagate` set to `false`.
	#[must_use]
	pub fn without_propagation(&self) -> Options {
		let mut opt = *self;
		opt.propagate = false;
		opt
	}
}

impl Default for Options {
	fn default() -> Options {
		Options {
			processing_mode: ProcessingMode::default(),
			override_protected: false,
			propagate: true,
		}
	}
}