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
use super::{
	expand_array, expand_iri, expand_literal, expand_node, expand_value, ActiveProperty, Entry,
	Expanded, ExpandedEntry, JsonExpand, LiteralValue, Options,
};
use crate::util::as_array;
use crate::{
	context::{ContextMut, Loader, Local, ProcessingOptions},
	object::*,
	syntax::{Keyword, Term},
	Error, ErrorCode, Id, Indexed, Loc, Reference, Warning,
};
use cc_traits::{CollectionRef, Get, KeyedRef, Len, MapIter};
use futures::future::{BoxFuture, FutureExt};
use generic_json::{Json, Key, ValueRef};
use iref::Iri;
use mown::Mown;

pub type ElementExpansionResult<T, J> = Result<Expanded<J, T>, Loc<Error, <J as Json>::MetaData>>;

/// Expand an element.
///
/// See <https://www.w3.org/TR/json-ld11-api/#expansion-algorithm>.
/// The default specified value for `ordered` and `from_map` is `false`.
pub fn expand_element<
	'a,
	J: JsonExpand,
	T: 'a + Id + Send + Sync,
	C: ContextMut<T> + Send + Sync,
	L: Loader + Send + Sync,
>(
	active_context: &'a C,
	active_property: ActiveProperty<'a, J>,
	element: &'a J,
	base_url: Option<Iri<'a>>,
	loader: &'a mut L,
	options: Options,
	from_map: bool,
	warnings: &'a mut Vec<Loc<Warning, J::MetaData>>,
) -> BoxFuture<'a, ElementExpansionResult<T, J>>
where
	C::LocalContext: From<L::Output> + From<J> + Send + Sync,
	L::Output: Into<J>,
{
	let source = loader.id_opt(base_url);
	async move {
		// If `element` is null, return null.
		if element.is_null() {
			return Ok(Expanded::Null);
		}

		let active_property_definition = active_context.get_opt(active_property.id());

		// If `active_property` has a term definition in `active_context` with a local context,
		// initialize property-scoped context to that local context.
		let mut property_scoped_base_url = None;
		let property_scoped_context = if let Some(definition) = active_property_definition {
			if let Some(base_url) = &definition.base_url {
				property_scoped_base_url = Some(base_url.as_iri());
			}

			definition.context.as_ref()
		} else {
			None
		};

		match element.as_value_ref() {
			ValueRef::Null => unreachable!(),
			ValueRef::Array(element) => {
				expand_array(
					active_context,
					active_property,
					active_property_definition,
					element,
					base_url,
					loader,
					options,
					from_map,
					warnings,
				)
				.await
			}

			ValueRef::Object(element) => {
				// We will need to consider expanded keys, and maybe ordered keys.
				let mut entries: Vec<Entry<J>> = Vec::with_capacity(element.len());
				for (key, value) in element.iter() {
					entries.push(Entry(key, value));
				}

				if options.ordered {
					entries.sort()
				}

				let mut value_entry1 = None;
				let mut id_entry = None;

				for Entry(key, value) in entries.iter() {
					match expand_iri(
						source,
						active_context,
						key.as_ref(),
						key.metadata(),
						false,
						true,
						warnings,
					) {
						Term::Keyword(Keyword::Value) => value_entry1 = Some(value.clone()),
						Term::Keyword(Keyword::Id) => id_entry = Some(value.clone()),
						_ => (),
					}
				}

				// Otherwise element is a map.
				// If `active_context` has a `previous_context`, the active context is not
				// propagated.
				let mut active_context = Mown::Borrowed(active_context);
				if let Some(previous_context) = active_context.previous_context() {
					// If `from_map` is undefined or false, and `element` does not contain an entry
					// expanding to `@value`, and `element` does not consist of a single entry
					// expanding to `@id` (where entries are IRI expanded), set active context to
					// previous context from active context, as the scope of a term-scoped context
					// does not apply when processing new Object objects.
					if !from_map
						&& value_entry1.is_none()
						&& !(element.len() == 1 && id_entry.is_some())
					{
						active_context = Mown::Owned(previous_context.clone())
					}
				}

				// If `property_scoped_context` is defined, set `active_context` to the result of
				// the Context Processing algorithm, passing `active_context`,
				// `property_scoped_context` as `local_context`, `base_url` from the term
				// definition for `active_property`, in `active_context` and `true` for
				// `override_protected`.
				if let Some(property_scoped_context) = property_scoped_context {
					let options: ProcessingOptions = options.into();
					active_context = Mown::Owned(
						property_scoped_context
							.process_with(
								active_context.as_ref(),
								loader,
								property_scoped_base_url,
								options.with_override(),
							)
							.await
							.map_err(|e| {
								e.with_metadata(active_property.metadata().unwrap().clone())
							})?
							.into_inner(),
					);
				}

				// If `element` contains the entry `@context`, set `active_context` to the result
				// of the Context Processing algorithm, passing `active_context`, the value of the
				// `@context` entry as `local_context` and `base_url`.
				if let Some(local_context) = element.get("@context") {
					active_context = Mown::Owned(
						local_context
							.process_with(active_context.as_ref(), loader, base_url, options.into())
							.await?
							.into_inner(),
					);
				}

				let mut type_entries: Vec<Entry<J>> = Vec::new();
				for entry @ Entry(key, _) in entries.iter() {
					let expanded_key = expand_iri(
						source,
						active_context.as_ref(),
						key.as_ref(),
						key.metadata(),
						false,
						true,
						warnings,
					);
					if let Term::Keyword(Keyword::Type) = expanded_key {
						type_entries.push(entry.clone());
					}
				}

				type_entries.sort();

				// Initialize `type_scoped_context` to `active_context`.
				// This is used for expanding values that may be relevant to any previous
				// type-scoped context.
				let type_scoped_context = active_context.as_ref();
				let mut active_context = Mown::Borrowed(active_context.as_ref());

				// For each `key` and `value` in `element` ordered lexicographically by key where
				// key IRI expands to @type:
				for Entry(_, value) in &type_entries {
					// Convert `value` into an array, if necessary.
					let (value, len) = as_array(&**value);

					// For each `term` which is a value of `value` ordered lexicographically,
					let mut sorted_value = Vec::with_capacity(len);
					for term in value {
						if term.is_string() {
							sorted_value.push(term);
						}
					}
					sorted_value.sort_unstable_by(|a, b| a.as_str().cmp(&b.as_str()));

					// if `term` is a string, and `term`'s term definition in `type_scoped_context`
					// has a `local_context`,
					for term in sorted_value {
						let term_str = term.as_str().unwrap();
						if let Some(term_definition) = type_scoped_context.get(term_str) {
							if let Some(local_context) = &term_definition.context {
								// set `active_context` to the result of
								// Context Processing algorithm, passing `active_context`, the value of the
								// `term`'s local context as `local_context`, `base_url` from the term
								// definition for value in `active_context`, and `false` for `propagate`.
								let base_url =
									term_definition.base_url.as_ref().map(|url| url.as_iri());
								let options: ProcessingOptions = options.into();
								active_context = Mown::Owned(
									local_context
										.process_with(
											active_context.as_ref(),
											loader,
											base_url,
											options.without_propagation(),
										)
										.await
										.map_err(|e| e.with_metadata(term.metadata().clone()))?
										.into_inner(),
								);
							}
						}
					}
				}

				// Initialize `input_type` to expansion of the last value of the first entry in
				// `element` expanding to `@type` (if any), ordering entries lexicographically by
				// key.
				// Both the key and value of the matched entry are IRI expanded.
				let input_type = if let Some(Entry(_, value)) = type_entries.first() {
					let (value, _) = as_array(&**value);
					if let Some(input_type) = value.last() {
						input_type.as_str().map(|input_type_str| {
							expand_iri(
								source,
								active_context.as_ref(),
								input_type_str,
								input_type.metadata(),
								false,
								true,
								warnings,
							)
						})
					} else {
						None
					}
				} else {
					None
				};

				let mut expanded_entries: Vec<ExpandedEntry<J, Term<T>>> =
					Vec::with_capacity(element.len());
				let mut list_entry = None;
				let mut set_entry = None;
				let mut value_entry = None;
				for Entry(key, value) in entries {
					if key.is_empty() {
						warnings.push(Loc::new(Warning::EmptyTerm, source, key.metadata().clone()));
					}

					let expanded_key = expand_iri(
						source,
						active_context.as_ref(),
						key.as_ref(),
						key.metadata(),
						false,
						true,
						warnings,
					);
					match &expanded_key {
						Term::Keyword(Keyword::Value) => value_entry = Some(value.clone()),
						Term::Keyword(Keyword::List)
							if active_property.is_some() && active_property != Some("@graph") =>
						{
							list_entry = Some(value.clone())
						}
						Term::Keyword(Keyword::Set) => set_entry = Some(value.clone()),
						Term::Ref(Reference::Blank(id)) => {
							warnings.push(Loc::new(
								Warning::BlankNodeIdProperty(id.clone()),
								source,
								key.metadata().clone(),
							));
						}
						_ => (),
					}

					expanded_entries.push(ExpandedEntry(
						J::Object::upcast_key_ref(key),
						expanded_key,
						J::Object::upcast_item_ref(value),
					))
				}

				if let Some(list_entry) = list_entry {
					// List objects.
					let mut index = None;
					for ExpandedEntry(key, expanded_key, value) in expanded_entries {
						match expanded_key {
							Term::Keyword(Keyword::Index) => match value.as_str() {
								Some(value) => index = Some(value.to_string()),
								None => {
									return Err(ErrorCode::InvalidIndexValue
										.located(source, value.metadata().clone()))
								}
							},
							Term::Keyword(Keyword::List) => (),
							_ => {
								return Err(ErrorCode::InvalidSetOrListObject
									.located(source, key.metadata().clone()))
							}
						}
					}

					// Initialize expanded value to the result of using this algorithm
					// recursively passing active context, active property, value for element,
					// base URL, and the ordered flags, ensuring that the
					// result is an array..
					let mut result = Vec::new();
					let (list_entry, _) = as_array(&*list_entry);
					for item in list_entry {
						result.extend(
							expand_element(
								active_context.as_ref(),
								active_property,
								&*item,
								base_url,
								loader,
								options,
								false,
								warnings,
							)
							.await?,
						)
					}

					Ok(Expanded::Object(Indexed::new(Object::List(result), index)))
				} else if let Some(set_entry) = set_entry {
					// Set objects.
					for ExpandedEntry(key, expanded_key, _) in expanded_entries {
						match expanded_key {
							Term::Keyword(Keyword::Index) => {
								// having an `@index` here is tolerated,
								// but is ignored.
							}
							Term::Keyword(Keyword::Set) => (),
							_ => {
								return Err(ErrorCode::InvalidSetOrListObject
									.located(source, key.metadata().clone()))
							}
						}
					}

					// set expanded value to the result of using this algorithm recursively,
					// passing active context, active property, value for element, base URL,
					// and ordered flags.
					expand_element(
						active_context.as_ref(),
						active_property,
						&*set_entry,
						base_url,
						loader,
						options,
						false,
						warnings,
					)
					.await
				} else if let Some(value_entry) = value_entry {
					// Value objects.
					if let Some(value) = expand_value(
						source,
						input_type,
						type_scoped_context,
						expanded_entries,
						&*value_entry,
						warnings,
					)
					.map_err(|e| e.located(source, value_entry.metadata().clone()))?
					{
						Ok(Expanded::Object(value))
					} else {
						Ok(Expanded::Null)
					}
				} else {
					// Node objects.
					if let Some(result) = expand_node(
						active_context.as_ref(),
						type_scoped_context,
						active_property,
						expanded_entries,
						base_url,
						loader,
						options,
						warnings,
					)
					.await?
					{
						Ok(result.cast::<Object<J, T>>().into())
					} else {
						Ok(Expanded::Null)
					}
				}
			}

			_ => {
				// Literals.

				// If element is a scalar (bool, int, string, null),
				// If `active_property` is `null` or `@graph`, drop the free-floating scalar by
				// returning null.
				if active_property.is_none() || active_property == Some("@graph") {
					return Ok(Expanded::Null);
				}

				// If `property_scoped_context` is defined, set `active_context` to the result of the
				// Context Processing algorithm, passing `active_context`, `property_scoped_context` as
				// local context, and `base_url` from the term definition for `active_property` in
				// `active context`.
				let active_context = if let Some(property_scoped_context) = property_scoped_context
				{
					// FIXME it is unclear what we should use as `base_url` if there is no term definition for `active_context`.
					let base_url =
						active_context
							.get_opt(active_property.id())
							.and_then(|definition| {
								definition
									.base_url
									.as_ref()
									.map(|base_url| base_url.as_iri())
							});

					let result = property_scoped_context
						.process_with(active_context, loader, base_url, options.into())
						.await
						.map_err(|e| e.with_metadata(active_property.metadata().unwrap().clone()))?
						.into_inner();
					Mown::Owned(result)
				} else {
					Mown::Borrowed(active_context)
				};

				// Return the result of the Value Expansion algorithm, passing the `active_context`,
				// `active_property`, and `element` as value.
				return Ok(Expanded::Object(
					expand_literal(
						source,
						active_context.as_ref(),
						active_property,
						LiteralValue::Given(element),
						warnings,
					)
					.map_err(|e| e.located(source, element.metadata().clone()))?,
				));
			}
		}
	}
	.boxed()
}