Skip to main content

json_ld/algorithms/expansion/
mod.rs

1//! JSON-LD expansion algorithms.
2//!
3//! See: <https://www.w3.org/TR/json-ld-api/#expansion-algorithms>
4use crate::{
5	JsonLdBacktraceBuilder, JsonLdDocument, JsonLdExpandedDocument, JsonLdIndexedObject,
6	JsonLdLocatedError, JsonLdObject, JsonLdSourceFileRef, algorithms::AsyncJsonLdEnvironment,
7	context::RawJsonLdProcessedContext,
8};
9
10mod array;
11mod document;
12mod element;
13mod environment;
14mod expanded;
15mod literal;
16mod node;
17mod options;
18mod value;
19
20use element::*;
21use environment::*;
22use expanded::*;
23use literal::*;
24use node::node_id_of_term;
25pub use options::*;
26
27/// Low-level expansion trait.
28///
29/// This provides direct access to the expansion algorithm with full control
30/// over the active context and options. For the high-level processor entry
31/// point, use [`JsonLdProcessor::expand_with`](crate::JsonLdProcessor::expand_with).
32pub trait JsonLdExpand {
33	/// Expand this document with the default expansion options.
34	#[allow(async_fn_in_trait)]
35	async fn expand(
36		&self,
37		env: impl AsyncJsonLdEnvironment,
38	) -> Result<JsonLdExpandedDocument, JsonLdLocatedError>;
39
40	/// Expand this document with the given expansion options and active
41	/// context.
42	#[allow(async_fn_in_trait)]
43	async fn expand_with(
44		&self,
45		env: impl AsyncJsonLdEnvironment,
46		active_context: &RawJsonLdProcessedContext,
47		options: JsonLdExpansionOptions,
48	) -> Result<JsonLdExpandedDocument, JsonLdLocatedError>;
49}
50
51impl JsonLdExpand for JsonLdDocument {
52	async fn expand(
53		&self,
54		env: impl AsyncJsonLdEnvironment,
55	) -> Result<JsonLdExpandedDocument, JsonLdLocatedError> {
56		let active_context = RawJsonLdProcessedContext::new(self.url().map(ToOwned::to_owned));
57		self.expand_with(env, &active_context, JsonLdExpansionOptions::default())
58			.await
59	}
60
61	async fn expand_with(
62		&self,
63		env: impl AsyncJsonLdEnvironment,
64		active_context: &RawJsonLdProcessedContext,
65		options: JsonLdExpansionOptions,
66	) -> Result<JsonLdExpandedDocument, JsonLdLocatedError> {
67		let loc = JsonLdBacktraceBuilder::new().file(JsonLdSourceFileRef::original(self.url()));
68		Expander {
69			base_url: self.url(),
70			options,
71			active_context,
72			active_property: None,
73		}
74		.expand_document(&env, self.document(), loc)
75		.await
76	}
77}
78
79fn filter_top_level_item(item: &JsonLdIndexedObject) -> bool {
80	// Remove dangling values.
81	!matches!(item.inner(), JsonLdObject::Value(_))
82}