jsonld-syntax 0.24.0

JSON-LD syntax
Documentation
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
use super::{
    Context,
    ContextEntry,
    Definition,
    TermDefinition,
    definition,
    term_definition::{self, InvalidNest},
};
use crate::{Container, ErrorCode, Keyword, Nullable, TryFromJson, native_stack::on_sufficient_stack};
use iri_rs::IriRefBuf;

#[derive(Debug, Clone, thiserror::Error)]
/// Error raised when a JSON value is not a valid context.
pub enum InvalidContext {
    #[error("Invalid IRI reference: {0}")]
    /// A context entry was a string that is not a valid IRI reference. Holds
    /// the rejected string.
    InvalidIriRef(String),

    #[error("Unexpected {0}")]
    /// A value had the wrong JSON kind. Holds the kind that was found and the
    /// kinds that would have been accepted.
    Unexpected(jstrict::Kind, &'static [jstrict::Kind]),

    #[error("Invalid `@direction`")]
    /// A `@direction` entry was a string other than `"ltr"` or `"rtl"`.
    InvalidDirection,

    #[error("Duplicate key")]
    /// The same key appeared twice in a context definition or in a term
    /// definition.
    DuplicateKey,

    #[error("Invalid term definition")]
    /// A term definition, or a structured entry of a context definition such as
    /// `@type` or `@version`, held an entry or a value the grammar does not
    /// allow there.
    InvalidTermDefinition,

    #[error("Invalid `@nest` value `{0}`")]
    /// A `@nest` entry held a keyword other than `@nest`. Holds the rejected
    /// string.
    InvalidNestValue(String),

    #[error("Context too deeply nested")]
    /// Scoped-context nesting exceeds [`MAX_CONTEXT_DEPTH`].
    TooDeep,
}

/// Maximum nesting depth of scoped contexts (`@context` inside a term
/// definition) accepted when converting JSON into a [`Context`].
///
/// Deeper nesting is refused with [`InvalidContext::TooDeep`]. Genuine contexts
/// nest a handful of levels at most.
pub const MAX_CONTEXT_DEPTH: usize = 128;

/// Converts a scoped context nested in a term definition, on a fresh stack
/// segment when the current one is nearly used.
///
/// The conversion recurses once per nesting level, and an embedder may call it
/// on a thread whose stack it has already partly used, so without this a
/// nesting well inside [`MAX_CONTEXT_DEPTH`] could abort the process on a stack
/// overflow instead of converting or failing with
/// [`InvalidContext::TooDeep`].
fn nested_context_try_from_json(value: &jstrict::Value, depth: usize) -> Result<Context, InvalidContext> {
    on_sufficient_stack(|| context_try_from_json(value, depth))
}

impl InvalidContext {
    /// Returns the JSON-LD error code this error reports as.
    #[must_use]
    pub fn code(&self) -> ErrorCode {
        match self {
            Self::InvalidIriRef(_) => ErrorCode::InvalidIriMapping,
            Self::Unexpected(_, _) => ErrorCode::InvalidContextEntry,
            Self::InvalidDirection => ErrorCode::InvalidBaseDirection,
            Self::DuplicateKey => ErrorCode::DuplicateKey,
            Self::InvalidTermDefinition => ErrorCode::InvalidTermDefinition,
            Self::InvalidNestValue(_) => ErrorCode::InvalidNestValue,
            Self::TooDeep => ErrorCode::ContextOverflow,
        }
    }
}

impl From<crate::Unexpected> for InvalidContext {
    fn from(crate::Unexpected(u, e): crate::Unexpected) -> Self {
        Self::Unexpected(u, e)
    }
}

impl TryFromJson for TermDefinition {
    type Error = InvalidContext;

    fn try_from_json(value: &jstrict::Value) -> Result<Self, InvalidContext> {
        term_definition_try_from_json(value, 0)
    }
}

/// Stores an entry value into an `Option` field, failing with
/// [`InvalidContext::DuplicateKey`] when the field was already set — the same
/// policy applied to duplicate term bindings.
macro_rules! set_unique {
    ($field:expr, $value:expr) => {
        if $field.replace($value).is_some() {
            return Err(InvalidContext::DuplicateKey);
        }
    };
}

fn term_definition_try_from_json(value: &jstrict::Value, depth: usize) -> Result<TermDefinition, InvalidContext> {
    match value {
        jstrict::Value::String(s) => Ok(TermDefinition::Simple(term_definition::Simple(s.as_str().to_owned()))),
        jstrict::Value::Object(o) => {
            let mut def = term_definition::Expanded::new();

            for jstrict::object::Entry { key, value } in o {
                match Keyword::try_from(key.as_str()) {
                    Ok(Keyword::Id) => set_unique!(def.id, Nullable::try_from_json(value)?),
                    Ok(Keyword::Type) => set_unique!(def.type_, Nullable::try_from_json(value)?),
                    Ok(Keyword::Context) => set_unique!(def.context, Box::new(nested_context_try_from_json(value, depth + 1)?)),
                    Ok(Keyword::Reverse) => set_unique!(def.reverse, definition::Key::try_from_json(value)?),
                    Ok(Keyword::Index) => set_unique!(def.index, term_definition::Index::try_from_json(value)?),
                    Ok(Keyword::Language) => set_unique!(def.language, Nullable::try_from_json(value)?),
                    Ok(Keyword::Direction) => set_unique!(def.direction, Nullable::try_from_json(value)?),
                    Ok(Keyword::Container) => {
                        let container = match value {
                            jstrict::Value::Null => Nullable::Null,
                            other => {
                                let container = Container::try_from_json(other)?;
                                Nullable::Some(container)
                            }
                        };

                        set_unique!(def.container, container);
                    }
                    Ok(Keyword::Nest) => set_unique!(def.nest, term_definition::Nest::try_from_json(value)?),
                    Ok(Keyword::Prefix) => set_unique!(def.prefix, bool::try_from_json(value)?),
                    Ok(Keyword::Propagate) => set_unique!(def.propagate, bool::try_from_json(value)?),
                    Ok(Keyword::Protected) => set_unique!(def.protected, bool::try_from_json(value)?),
                    _ => return Err(InvalidContext::InvalidTermDefinition),
                }
            }

            Ok(TermDefinition::Expanded(Box::new(def)))
        }
        unexpected => Err(InvalidContext::Unexpected(unexpected.kind(), &[jstrict::Kind::String, jstrict::Kind::Object])),
    }
}

impl TryFromJson for term_definition::Type {
    type Error = InvalidContext;

    fn try_from_json(value: &jstrict::Value) -> Result<Self, InvalidContext> {
        match value {
            jstrict::Value::String(s) => Ok(Self::from(s.as_str().to_owned())),
            unexpected => Err(InvalidContext::Unexpected(unexpected.kind(), &[jstrict::Kind::String])),
        }
    }
}

impl TryFromJson for definition::TypeContainer {
    type Error = InvalidContext;

    fn try_from_json(value: &jstrict::Value) -> Result<Self, InvalidContext> {
        match value {
            jstrict::Value::String(s) => match Keyword::try_from(s.as_str()) {
                Ok(Keyword::Set) => Ok(Self::Set),
                _ => Err(InvalidContext::InvalidTermDefinition),
            },
            unexpected => Err(InvalidContext::Unexpected(unexpected.kind(), &[jstrict::Kind::String])),
        }
    }
}

impl TryFromJson for definition::Type {
    type Error = InvalidContext;

    fn try_from_json(value: &jstrict::Value) -> Result<Self, InvalidContext> {
        match value {
            jstrict::Value::Object(o) => {
                let mut container = None;
                let mut protected = None;

                for jstrict::object::Entry { key, value } in o {
                    match Keyword::try_from(key.as_str()) {
                        Ok(Keyword::Container) => {
                            if container.replace(definition::TypeContainer::try_from_json(value)?).is_some() {
                                return Err(InvalidContext::DuplicateKey);
                            }
                        }
                        Ok(Keyword::Protected) => {
                            if protected.replace(bool::try_from_json(value)?).is_some() {
                                return Err(InvalidContext::DuplicateKey);
                            }
                        }
                        _ => return Err(InvalidContext::InvalidTermDefinition),
                    }
                }

                match container {
                    Some(container) => Ok(Self { container, protected }),
                    None => Err(InvalidContext::InvalidTermDefinition),
                }
            }
            unexpected => Err(InvalidContext::Unexpected(unexpected.kind(), &[jstrict::Kind::Object])),
        }
    }
}

impl TryFromJson for definition::Version {
    type Error = InvalidContext;

    fn try_from_json(value: &jstrict::Value) -> Result<Self, InvalidContext> {
        match value {
            jstrict::Value::Number(n) => match n.as_str() {
                "1.1" => Ok(Self::V1_1),
                _ => Err(InvalidContext::InvalidTermDefinition),
            },
            unexpected => Err(InvalidContext::Unexpected(unexpected.kind(), &[jstrict::Kind::Number])),
        }
    }
}

impl TryFromJson for definition::Vocab {
    type Error = InvalidContext;

    fn try_from_json(value: &jstrict::Value) -> Result<Self, InvalidContext> {
        match value {
            jstrict::Value::String(s) => Ok(Self::from(s.as_str().to_owned())),
            unexpected => Err(InvalidContext::Unexpected(unexpected.kind(), &[jstrict::Kind::String])),
        }
    }
}

impl TryFromJson for term_definition::Id {
    type Error = InvalidContext;

    fn try_from_json(value: &jstrict::Value) -> Result<Self, InvalidContext> {
        match value {
            jstrict::Value::String(s) => Ok(Self::from(s.as_str().to_owned())),
            unexpected => Err(InvalidContext::Unexpected(unexpected.kind(), &[jstrict::Kind::String])),
        }
    }
}

impl TryFromJson for definition::Key {
    type Error = InvalidContext;

    fn try_from_json(value: &jstrict::Value) -> Result<Self, Self::Error> {
        match value {
            jstrict::Value::String(s) => Ok(Self::from(s.as_str().to_owned())),
            unexpected => Err(InvalidContext::Unexpected(unexpected.kind(), &[jstrict::Kind::String])),
        }
    }
}

impl TryFromJson for term_definition::Index {
    type Error = InvalidContext;

    fn try_from_json(value: &jstrict::Value) -> Result<Self, InvalidContext> {
        match value {
            jstrict::Value::String(s) => Ok(Self::from(s.as_str().to_owned())),
            unexpected => Err(InvalidContext::Unexpected(unexpected.kind(), &[jstrict::Kind::String])),
        }
    }
}

impl TryFromJson for term_definition::Nest {
    type Error = InvalidContext;

    fn try_from_json(value: &jstrict::Value) -> Result<Self, InvalidContext> {
        match value {
            jstrict::Value::String(s) => match Self::try_from(s.as_str().to_owned()) {
                Ok(nest) => Ok(nest),
                Err(InvalidNest(s)) => Err(InvalidContext::InvalidNestValue(s)),
            },
            unexpected => Err(InvalidContext::Unexpected(unexpected.kind(), &[jstrict::Kind::String])),
        }
    }
}

impl TryFromJson for Context {
    type Error = InvalidContext;

    fn try_from_json(value: &jstrict::Value) -> Result<Self, InvalidContext> {
        context_try_from_json(value, 0)
    }
}

fn context_try_from_json(value: &jstrict::Value, depth: usize) -> Result<Context, InvalidContext> {
    if depth >= MAX_CONTEXT_DEPTH {
        return Err(InvalidContext::TooDeep);
    }

    match value {
        jstrict::Value::Array(a) => {
            let mut many = Vec::with_capacity(a.len());

            for item in a {
                many.push(context_entry_try_from_json(item, depth)?);
            }

            Ok(Context::Many(many))
        }
        context => Ok(Context::One(context_entry_try_from_json(context, depth)?)),
    }
}

impl TryFromJson for ContextEntry {
    type Error = InvalidContext;

    fn try_from_json(value: &jstrict::Value) -> Result<Self, InvalidContext> {
        context_entry_try_from_json(value, 0)
    }
}

fn context_entry_try_from_json(value: &jstrict::Value, depth: usize) -> Result<ContextEntry, InvalidContext> {
    match value {
        jstrict::Value::Null => Ok(ContextEntry::Null),
        jstrict::Value::String(s) => match IriRefBuf::new(s.as_str().to_owned()) {
            Ok(iri_ref) => Ok(ContextEntry::IriRef(iri_ref)),
            Err(e) => Err(InvalidContext::InvalidIriRef(e.0)),
        },
        jstrict::Value::Object(o) => {
            let mut def = Definition::new();

            for jstrict::object::Entry { key, value } in o {
                match Keyword::try_from(key.as_str()) {
                    Ok(Keyword::Base) => set_unique!(def.base, Nullable::try_from_json(value)?),
                    Ok(Keyword::Import) => set_unique!(def.import, IriRefBuf::try_from_json(value)?),
                    Ok(Keyword::Language) => set_unique!(def.language, Nullable::try_from_json(value)?),
                    Ok(Keyword::Direction) => set_unique!(def.direction, Nullable::try_from_json(value)?),
                    Ok(Keyword::Propagate) => set_unique!(def.propagate, bool::try_from_json(value)?),
                    Ok(Keyword::Protected) => set_unique!(def.protected, bool::try_from_json(value)?),
                    Ok(Keyword::Type) => set_unique!(def.type_, definition::Type::try_from_json(value)?),
                    Ok(Keyword::Version) => set_unique!(def.version, definition::Version::try_from_json(value)?),
                    Ok(Keyword::Vocab) => set_unique!(def.vocab, Nullable::try_from_json(value)?),
                    _ => {
                        let term_def = match value {
                            jstrict::Value::Null => Nullable::Null,
                            other => Nullable::Some(term_definition_try_from_json(other, depth)?),
                        };

                        if def.bindings.insert_with(key.as_str().to_owned().into(), term_def).is_some() {
                            return Err(InvalidContext::DuplicateKey);
                        }
                    }
                }
            }

            Ok(ContextEntry::Definition(def))
        }
        unexpected => Err(InvalidContext::Unexpected(
            unexpected.kind(),
            &[jstrict::Kind::Null, jstrict::Kind::String, jstrict::Kind::Object],
        )),
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)]
    use super::*;
    use crate::Parse;

    fn nested_json(levels: usize) -> jstrict::Value {
        let mut json = String::new();
        for _ in 0..levels {
            json.push_str("{\"a\":{\"@context\":");
        }
        json.push_str("{}");
        for _ in 0..levels {
            json.push_str("}}");
        }

        jstrict::Value::parse_str(&json).unwrap().0
    }

    /// A crafted deeply-nested `@context` must fail with an error instead of
    /// exhausting the native stack during conversion.
    #[test]
    fn deeply_nested_context_conversion_fails_gracefully() {
        let json = nested_json(MAX_CONTEXT_DEPTH + 1);
        assert!(matches!(Context::try_from_json(&json), Err(InvalidContext::TooDeep)));
    }

    #[test]
    fn reasonable_nesting_converts() {
        let json = nested_json(MAX_CONTEXT_DEPTH - 1);
        assert!(Context::try_from_json(&json).is_ok());
    }

    /// The deepest accepted nesting converts, and one level more is refused,
    /// on a thread whose stack is far smaller than the conversion of that
    /// nesting needs, so an embedder that already used most of its stack gets
    /// a result rather than an abort.
    #[test]
    fn nesting_up_to_the_bound_converts_on_a_small_stack() {
        let deepest = nested_json(MAX_CONTEXT_DEPTH - 1);
        let too_deep = nested_json(MAX_CONTEXT_DEPTH + 1);

        let (converted, refused) = std::thread::Builder::new()
            .stack_size(256 * 1024)
            .spawn(move || (Context::try_from_json(&deepest).is_ok(), Context::try_from_json(&too_deep)))
            .unwrap()
            .join()
            .unwrap();

        assert!(converted);
        assert!(matches!(refused, Err(InvalidContext::TooDeep)));
    }

    /// Duplicate keyword entries fail like duplicate term bindings do,
    /// instead of silently keeping the last value.
    #[test]
    fn duplicate_keyword_entries_are_rejected() {
        let json = jstrict::Value::parse_str(r#"{"@vocab": "http://a/", "@vocab": "http://b/"}"#).unwrap().0;
        assert!(matches!(Context::try_from_json(&json), Err(InvalidContext::DuplicateKey)));

        let json = jstrict::Value::parse_str(r#"{"@id": "http://a/x", "@id": "http://b/x"}"#).unwrap().0;
        assert!(matches!(TermDefinition::try_from_json(&json), Err(InvalidContext::DuplicateKey)));
    }
}