Skip to main content

jsonld_context_processing/algorithm/
iri.rs

1use std::{hash::Hash, sync::Arc};
2
3use super::{DefinedTerms, Environment, Merged};
4use crate::{Error, Options, ProcessingStack, Warning, WarningHandler};
5use contextual::WithContext;
6use iri_rs::{Iri, IriRef};
7use jsonld_core::{Context, Id, Loader, NoLoader, ProcessingMode, Term, warning};
8use jsonld_syntax::{self as syntax, ExpandableRef, Nullable, native_stack::Recursion};
9use rdfx::{
10    BlankId,
11    vocabulary::{BlankIdVocabulary, IriVocabulary, Vocabulary, VocabularyMut},
12};
13use syntax::{CompactIri, context::definition::KeyOrKeywordRef, is_keyword_like};
14
15/// Warning reporting that a value expanded to something that is not a valid IRI.
16///
17/// Carries the value as it was written. A dedicated type rather than a
18/// [`Warning`] variant so that the algorithm can raise it against any warning
19/// vocabulary that knows how to build itself `From<MalformedIri>` —
20/// `jsonld-expansion` has its own warning enum and reuses this.
21pub struct MalformedIri(pub String);
22
23impl From<MalformedIri> for Warning {
24    fn from(MalformedIri(s): MalformedIri) -> Self {
25        Self::MalformedIri(s)
26    }
27}
28
29/// Result of [`expand_iri_with`].
30///
31/// `Ok(None)` means the value was dropped under [`Action::Drop`], as opposed to
32/// expanding to [`Term::Null`].
33pub type ExpandIriResult<T, B, E> = Result<Option<Arc<Term<T, B>>>, Error<E>>;
34
35/// Runs the [IRI expansion algorithm][1] on `value`, defining terms of
36/// `local_context` on demand.
37///
38/// Used while a context is still being processed, which is why it can recurse
39/// into [`define`][super::define]: expanding a term may require first defining
40/// that term, or the prefix of a compact IRI, from the context currently being
41/// built. `defined` guards that recursion against cycles.
42///
43/// `document_relative` allows a value that is otherwise unresolvable to be
44/// resolved against the active context's base IRI. `vocab` enables expansion
45/// through the vocabulary mapping and selects what to do when that is the only
46/// thing that would make the value expand; `None` disables it entirely.
47///
48/// A value that resolves to nothing usable is returned as an invalid identifier
49/// and reported through the warning handler, rather than failing.
50///
51/// [1]: https://www.w3.org/TR/json-ld11-api/#iri-expansion
52///
53/// # Errors
54///
55/// Returns an error when a term definition needed for the expansion is invalid, or when loading a remote context fails.
56pub async fn expand_iri_with<'a, N, L, W>(
57    mut env: Environment<'a, N, L, W>,
58    active_context: &'a mut Context<N::Iri, N::BlankId>,
59    value: Nullable<ExpandableRef<'a>>,
60    document_relative: bool,
61    vocab: Option<Action>,
62    local_context: &'a Merged<'a>,
63    defined: &'a mut DefinedTerms,
64    remote_contexts: ProcessingStack<N::Iri>,
65    options: Options,
66) -> ExpandIriResult<N::Iri, N::BlankId, L::Error>
67where
68    N: VocabularyMut,
69    N::Iri: Clone + Eq + Hash,
70    N::BlankId: Clone + PartialEq,
71    L: Loader,
72    W: WarningHandler<N>,
73{
74    match value {
75        Nullable::Null => Ok(Some(Arc::new(Term::Null))),
76        Nullable::Some(ExpandableRef::Keyword(k)) => Ok(Some(Arc::new(Term::Keyword(k)))),
77        Nullable::Some(ExpandableRef::String(value)) => {
78            if is_keyword_like(value) {
79                return Ok(Some(Arc::new(Term::Null)));
80            }
81
82            // If `local_context` is not null, it contains an entry with a key that equals value, and the
83            // value of the entry for value in defined is not true, invoke the Create Term Definition
84            // algorithm, passing active context, local context, value as term, and defined. This will
85            // ensure that a term definition is created for value in active context during Context
86            // Processing.
87            Recursion::new(super::define(
88                Environment {
89                    vocabulary: env.vocabulary,
90                    loader: env.loader,
91                    warnings: env.warnings,
92                },
93                active_context,
94                local_context,
95                value.into(),
96                defined,
97                remote_contexts.clone(),
98                None,
99                false,
100                options.with_no_override(),
101            ))
102            .await?;
103
104            if let Some(term_definition) = active_context.get(value) {
105                // If active context has a term definition for value, and the associated IRI mapping
106                // is a keyword, return that keyword.
107                if let Some(arc) = term_definition.value_arc()
108                    && arc.is_keyword()
109                {
110                    return Ok(Some(Arc::clone(arc)));
111                }
112
113                // If vocab is true and the active context has a term definition for value, return the
114                // associated IRI mapping.
115                if vocab.is_some() {
116                    return match term_definition.value_arc() {
117                        Some(arc) => Ok(Some(Arc::clone(arc))),
118                        None => Ok(Some(Arc::new(Term::Null))),
119                    };
120                }
121            }
122
123            if value.find(':').is_some_and(|i| i > 0) {
124                if let Ok(blank_id) = BlankId::new(value) {
125                    return Ok(Some(Arc::new(Term::Id(Id::blank(env.vocabulary.insert_blank_id(blank_id))))));
126                }
127
128                if value == "_:" {
129                    return Ok(Some(Arc::new(Term::Id(Id::Invalid("_:".to_string())))));
130                }
131
132                if let Ok(compact_iri) = CompactIri::new(value) {
133                    // If local context is not null, it contains a `prefix` entry, and the value of the
134                    // prefix entry in defined is not true, invoke the Create Term Definition
135                    // algorithm, passing active context, local context, prefix as term, and defined.
136                    // This will ensure that a term definition is created for prefix in active context
137                    // during Context Processing.
138                    Recursion::new(super::define(
139                        Environment {
140                            vocabulary: env.vocabulary,
141                            loader: env.loader,
142                            warnings: env.warnings,
143                        },
144                        active_context,
145                        local_context,
146                        KeyOrKeywordRef::Key(compact_iri.prefix().into()),
147                        defined,
148                        remote_contexts,
149                        None,
150                        false,
151                        options.with_no_override(),
152                    ))
153                    .await?;
154
155                    // If active context contains a term definition for prefix having a non-null IRI
156                    // mapping and the prefix flag of the term definition is true, return the result
157                    // of concatenating the IRI mapping associated with prefix and suffix.
158                    // The `prefix` flag is a JSON-LD 1.1 addition: in 1.0 any term
159                    // definition with an IRI mapping expands a compact IRI
160                    // (`flatten#t0014`). Compaction keeps the 1.1 rule, which is why
161                    // this is relaxed here and not on the flag itself (`compact#tp001`).
162                    if let Some(term_definition) = active_context.get_normal(compact_iri.prefix())
163                        && (term_definition.prefix || active_context.processing_mode() == ProcessingMode::JsonLd1_0)
164                        && let Some(mapping) = term_definition.value()
165                    {
166                        let mut result = mapping.with(&*env.vocabulary).as_str().to_string();
167                        result.push_str(compact_iri.suffix());
168
169                        return Ok(Some(Arc::new(Term::Id(Id::from_string_in(env.vocabulary, result)))));
170                    }
171                }
172
173                if let Ok(iri) = Iri::parse(value) {
174                    return Ok(Some(Arc::new(Term::Id(Id::iri(env.vocabulary.insert(iri))))));
175                }
176            }
177
178            // If vocab is true, and active context has a vocabulary mapping, return the result of
179            // concatenating the vocabulary mapping with value.
180            if let Some(action) = vocab {
181                match active_context.vocabulary() {
182                    Some(Term::Id(mapping)) => {
183                        return match action {
184                            Action::Keep => {
185                                let mut result = mapping.with(&*env.vocabulary).as_str().to_string();
186                                result.push_str(value);
187
188                                Ok(Some(Arc::new(Term::Id(Id::from_string_in(env.vocabulary, result)))))
189                            }
190                            Action::Drop => Ok(None),
191                            Action::Reject => Err(Error::ForbiddenVocab),
192                        };
193                    }
194                    Some(_) => return Ok(Some(Arc::new(invalid_iri(&mut env, value.to_string())))),
195                    None => (),
196                }
197            }
198
199            // Otherwise, if document relative is true set value to the result of resolving value
200            // against the base IRI from active context. Only the basic algorithm in section 5.2 of
201            // [RFC3986] is used; neither Syntax-Based Normalization nor Scheme-Based Normalization
202            // are performed. Characters additionally allowed in IRI references are treated in the
203            // same way that unreserved characters are treated in URI references, per section 6.5 of
204            // [RFC3987].
205            if document_relative
206                && let Ok(iri_ref) = IriRef::parse(value)
207                && let Some(iri) = super::resolve_iri(env.vocabulary, iri_ref, active_context.base_iri())
208            {
209                return Ok(Some(Arc::new(Term::from(iri))));
210            }
211
212            // Return value as is.
213            Ok(Some(Arc::new(invalid_iri(&mut env, value.to_string()))))
214        }
215    }
216}
217
218/// Reports `value` as a malformed IRI and returns it as an invalid identifier.
219///
220/// Expansion never fails on an unresolvable value: it keeps it verbatim so the
221/// entry survives, and leaves it to the caller's policy to reject it later.
222fn invalid_iri<N, L, W: jsonld_core::warning::Handler<N, Warning>>(env: &mut Environment<N, L, W>, value: String) -> Term<N::Iri, N::BlankId>
223where
224    N: Vocabulary,
225{
226    env.warnings.handle(env.vocabulary, MalformedIri(value.clone()).into());
227    Term::Id(Id::Invalid(value))
228}
229
230#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
231/// How strictly to treat a term whose expansion is questionable.
232///
233/// Used by this crate for terms that only expand because the active context
234/// defines a vocabulary mapping (see [`Options::vocab`][crate::Options::vocab]),
235/// and by `jsonld-expansion` for those as well as for terms that expand to a
236/// malformed IRI.
237pub enum Action {
238    #[default]
239    /// Accept the expansion. This is the behaviour the specification requires.
240    Keep,
241    /// Treat the term as unexpandable, so that whatever entry carries it is
242    /// dropped.
243    Drop,
244    /// Abort processing with an error.
245    Reject,
246}
247
248impl Action {
249    /// Checks whether this action aborts processing rather than accepting or
250    /// dropping the term.
251    #[must_use]
252    pub fn is_reject(&self) -> bool {
253        matches!(self, Self::Reject)
254    }
255}
256
257#[derive(Debug)]
258/// A term could only be expanded through the vocabulary mapping, while
259/// [`Options::vocab`][crate::Options::vocab] was set to [`Action::Reject`].
260///
261/// Reported by the loader-free expansion path, which cannot construct an
262/// [`Error`]; callers convert it into [`Error::ForbiddenVocab`].
263pub struct RejectVocab;
264
265/// Result of expanding a term into an IRI without a loader.
266///
267/// `Ok(None)` means the term was dropped under [`Action::Drop`], as opposed to
268/// expanding to [`Term::Null`].
269pub type IriExpansionResult<N> = Result<Option<Arc<Term<<N as IriVocabulary>::Iri, <N as BlankIdVocabulary>::BlankId>>>, RejectVocab>;
270// `needless_pass_by_value`: `ProcessingStack` is a single `Arc` handle and
271// `Nullable<ExpandableRef>` wraps a borrow, so by-value is the cheaper calling
272// convention here, and callers `.clone()` the stack deliberately to fork it per
273// branch. Taking references would add an indirection and push the clones inside.
274/// Expands `value` into an IRI using only the term definitions `active_context`
275/// already has.
276///
277/// The loader-free counterpart of [`expand_iri_with`]: it never creates a term
278/// definition on demand, so it can only be used once the enclosing context has
279/// been processed, or for values that cannot introduce a dependency (`@vocab`,
280/// `@index`, a relative-IRI term).
281///
282/// `document_relative` allows a value that is otherwise unresolvable to be
283/// resolved against the active context's base IRI. `vocab` enables expansion
284/// through the vocabulary mapping and selects what to do when that is the only
285/// thing that would make the value expand; `None` disables it entirely.
286///
287/// Results are memoized per active context for the dominant call shape — a
288/// string value with `vocab: Some(Action::Keep)` and `document_relative` off —
289/// which is what makes repeated keys across the nodes of a document cheap.
290///
291/// # Errors
292///
293/// Returns an error when the value cannot be expanded into an IRI with the definitions already in the active context.
294#[allow(clippy::needless_pass_by_value)]
295pub fn expand_iri_simple<W, N, L, H>(
296    env: &mut Environment<N, L, H>,
297    active_context: &Context<N::Iri, N::BlankId>,
298    value: Nullable<ExpandableRef>,
299    document_relative: bool,
300    vocab: Option<Action>,
301) -> IriExpansionResult<N>
302where
303    N: VocabularyMut,
304    N::Iri: Clone,
305    N::BlankId: Clone,
306    W: From<MalformedIri>,
307    H: warning::Handler<N, W>,
308{
309    // Per-context memoization of the dominant key-expansion call shape:
310    // `vocab=Some(Keep)`, `document_relative=false`, value is a string. Hits
311    // skip term-definition lookup, blank/CompactIRI/Iri::parse validators and
312    // the vocab-fallback string concat + IRI re-parse + Arc::new for repeated
313    // keys (the common NGSI-LD / schema.org pattern).
314    let cache_value: Option<&str> = if !document_relative && matches!(vocab, Some(Action::Keep)) {
315        if let Nullable::Some(ExpandableRef::String(s)) = &value {
316            Some(*s)
317        } else {
318            None
319        }
320    } else {
321        None
322    };
323
324    if let Some(s) = cache_value
325        && let Some(arc) = active_context.term_resolution_cache().get(s)
326    {
327        return Ok(Some(arc));
328    }
329
330    let result = expand_iri_simple_inner::<W, N, L, H>(env, active_context, value, document_relative, vocab)?;
331
332    if let (Some(s), Some(arc)) = (cache_value, &result) {
333        active_context.term_resolution_cache().insert(Box::from(s), Arc::clone(arc));
334    }
335
336    Ok(result)
337}
338
339/// The body of [`expand_iri_simple`], without the memoization wrapper.
340#[allow(clippy::needless_pass_by_value)]
341fn expand_iri_simple_inner<W, N, L, H>(
342    env: &mut Environment<N, L, H>,
343    active_context: &Context<N::Iri, N::BlankId>,
344    value: Nullable<ExpandableRef>,
345    document_relative: bool,
346    vocab: Option<Action>,
347) -> IriExpansionResult<N>
348where
349    N: VocabularyMut,
350    N::Iri: Clone,
351    N::BlankId: Clone,
352    W: From<MalformedIri>,
353    H: warning::Handler<N, W>,
354{
355    match value {
356        Nullable::Null => Ok(Some(Arc::new(Term::Null))),
357        Nullable::Some(ExpandableRef::Keyword(k)) => Ok(Some(Arc::new(Term::Keyword(k)))),
358        Nullable::Some(ExpandableRef::String(value)) => {
359            if is_keyword_like(value) {
360                return Ok(Some(Arc::new(Term::Null)));
361            }
362
363            if let Some(term_definition) = active_context.get(value) {
364                // If active context has a term definition for value, and the associated IRI mapping
365                // is a keyword, return that keyword.
366                if let Some(arc) = term_definition.value_arc()
367                    && arc.is_keyword()
368                {
369                    return Ok(Some(Arc::clone(arc)));
370                }
371
372                // If vocab is true and the active context has a term definition for value, return the
373                // associated IRI mapping.
374                if vocab.is_some() {
375                    return match term_definition.value_arc() {
376                        Some(arc) => Ok(Some(Arc::clone(arc))),
377                        None => Ok(Some(Arc::new(Term::Null))),
378                    };
379                }
380            }
381
382            if value.find(':').is_some_and(|i| i > 0) {
383                if let Ok(blank_id) = BlankId::new(value) {
384                    return Ok(Some(Arc::new(Term::Id(Id::blank(env.vocabulary.insert_blank_id(blank_id))))));
385                }
386
387                if value == "_:" {
388                    return Ok(Some(Arc::new(Term::Id(Id::Invalid("_:".to_string())))));
389                }
390
391                if let Ok(compact_iri) = CompactIri::new(value) {
392                    // If active context contains a term definition for prefix having a non-null IRI
393                    // mapping and the prefix flag of the term definition is true, return the result
394                    // of concatenating the IRI mapping associated with prefix and suffix.
395                    // The `prefix` flag is a JSON-LD 1.1 addition: in 1.0 any term
396                    // definition with an IRI mapping expands a compact IRI
397                    // (`flatten#t0014`). Compaction keeps the 1.1 rule, which is why
398                    // this is relaxed here and not on the flag itself (`compact#tp001`).
399                    if let Some(term_definition) = active_context.get_normal(compact_iri.prefix())
400                        && (term_definition.prefix || active_context.processing_mode() == ProcessingMode::JsonLd1_0)
401                        && let Some(mapping) = term_definition.value()
402                    {
403                        let mut result = mapping.with(&*env.vocabulary).as_str().to_string();
404                        result.push_str(compact_iri.suffix());
405
406                        return Ok(Some(Arc::new(Term::Id(Id::from_string_in(env.vocabulary, result)))));
407                    }
408                }
409
410                if let Ok(iri) = Iri::parse(value) {
411                    return Ok(Some(Arc::new(Term::Id(Id::iri(env.vocabulary.insert(iri))))));
412                }
413            }
414
415            // If vocab is true, and active context has a vocabulary mapping, return the result of
416            // concatenating the vocabulary mapping with value.
417            if let Some(action) = vocab {
418                match active_context.vocabulary() {
419                    Some(Term::Id(mapping)) => {
420                        return match action {
421                            Action::Keep => {
422                                let mut result = mapping.with(&*env.vocabulary).as_str().to_string();
423                                result.push_str(value);
424
425                                Ok(Some(Arc::new(Term::Id(Id::from_string_in(env.vocabulary, result)))))
426                            }
427                            Action::Drop => Ok(None),
428                            Action::Reject => Err(RejectVocab),
429                        };
430                    }
431                    Some(_) => return Ok(Some(Arc::new(invalid_iri_simple(env, value.to_string())))),
432                    None => (),
433                }
434            }
435
436            // Otherwise, if document relative is true set value to the result of resolving value
437            // against the base IRI from active context. Only the basic algorithm in section 5.2 of
438            // [RFC3986] is used; neither Syntax-Based Normalization nor Scheme-Based Normalization
439            // are performed. Characters additionally allowed in IRI references are treated in the
440            // same way that unreserved characters are treated in URI references, per section 6.5 of
441            // [RFC3987].
442            if document_relative
443                && let Ok(iri_ref) = IriRef::parse(value)
444                && let Some(iri) = super::resolve_iri(env.vocabulary, iri_ref, active_context.base_iri())
445            {
446                return Ok(Some(Arc::new(Term::from(iri))));
447            }
448
449            // Return value as is.
450            Ok(Some(Arc::new(invalid_iri_simple(env, value.to_string()))))
451        }
452    }
453}
454
455/// Reports `value` as a malformed IRI and returns it as an invalid identifier.
456///
457/// Same as [`invalid_iri`], for the loader-free path's more general warning
458/// handler.
459fn invalid_iri_simple<W, N, L, H>(env: &mut Environment<N, L, H>, value: String) -> Term<N::Iri, N::BlankId>
460where
461    N: Vocabulary,
462    W: From<MalformedIri>,
463    H: warning::Handler<N, W>,
464{
465    env.warnings.handle(env.vocabulary, MalformedIri(value.clone()).into());
466    Term::Id(Id::Invalid(value))
467}
468
469/// Expands `term` as the Expansion algorithm expands a member key of a
470/// node object under `active_context`: `vocab` on, not document-relative
471/// (JSON-LD 1.1 API, Expansion Algorithm step 13.2).
472///
473/// Returns the expanded term (an IRI, a blank node identifier, a keyword,
474/// or an invalid identifier carrying the text as written), or `None` when
475/// `policy` is [`Action::Drop`] and only `@vocab` would expand it. Warnings
476/// are discarded; no loader is involved, since the active context is already
477/// processed.
478///
479/// # Errors
480///
481/// [`RejectVocab`] when `policy` is [`Action::Reject`] and only `@vocab` would
482/// expand it.
483pub fn expand_property_key<N: VocabularyMut>(
484    vocabulary: &mut N,
485    active_context: &Context<N::Iri, N::BlankId>,
486    term: &str,
487    policy: Action,
488) -> IriExpansionResult<N>
489where
490    N::Iri: Clone,
491    N::BlankId: Clone,
492{
493    expand_iri_simple::<MalformedIri, N, NoLoader, ()>(
494        &mut Environment {
495            vocabulary,
496            loader: &NoLoader,
497            warnings: &mut (),
498        },
499        active_context,
500        Nullable::Some(term.into()),
501        false,
502        Some(policy),
503    )
504}
505
506/// Expands `value` as the Expansion algorithm expands an `@type` value of a
507/// node object under `active_context`: `vocab` on, document-relative against
508/// the context's base IRI (Expansion Algorithm step 13.4.4.4).
509///
510/// Same results and errors as [`expand_property_key`].
511///
512/// # Errors
513///
514/// [`RejectVocab`] when `policy` is [`Action::Reject`] and only `@vocab` would
515/// expand it.
516pub fn expand_type_value<N: VocabularyMut>(
517    vocabulary: &mut N,
518    active_context: &Context<N::Iri, N::BlankId>,
519    value: &str,
520    policy: Action,
521) -> IriExpansionResult<N>
522where
523    N::Iri: Clone,
524    N::BlankId: Clone,
525{
526    expand_iri_simple::<MalformedIri, N, NoLoader, ()>(
527        &mut Environment {
528            vocabulary,
529            loader: &NoLoader,
530            warnings: &mut (),
531        },
532        active_context,
533        Nullable::Some(value.into()),
534        true,
535        Some(policy),
536    )
537}
538
539#[cfg(test)]
540mod tests {
541    #![allow(clippy::unwrap_used)]
542    use super::*;
543    use crate::{Options, algorithm::sync::process_context_sync};
544    use iri_rs::IriBuf;
545    use jsonld_core::NoLoader;
546    use jsonld_syntax::{Keyword, Parse, TryFromJson};
547    use rdfx::{BlankIdBuf, vocabulary::no_vocabulary_mut};
548
549    const CONTEXT: &str = r#"{
550        "@vocab": "https://vocab.example/",
551        "ex": "https://example.com/",
552        "name": "https://example.com/name",
553        "type": "@type"
554    }"#;
555
556    /// Processes [`CONTEXT`] as the `@context` of a document.
557    fn processed_context() -> Context<IriBuf, BlankIdBuf> {
558        let (json, _) = jsonld_syntax::Value::parse_str(CONTEXT).unwrap();
559        let local = syntax::context::Context::try_from_json(&json).unwrap();
560        let active = Context::new(None);
561        let mut warnings = ();
562
563        process_context_sync(
564            Environment {
565                vocabulary: no_vocabulary_mut(),
566                loader: &NoLoader,
567                warnings: &mut warnings,
568            },
569            &active,
570            &local,
571            ProcessingStack::default(),
572            None,
573            Options::default(),
574            0,
575        )
576        .unwrap()
577        .into_processed()
578    }
579
580    /// Expands `value` against `context` the way keys and `@type` values
581    /// (`vocab`) or `@id` values (not `vocab`) are expanded, without resolving
582    /// against a base IRI.
583    fn expand(context: &Context<IriBuf, BlankIdBuf>, value: &str, vocab: bool) -> Term<IriBuf, BlankIdBuf> {
584        let mut warnings = ();
585        let mut env = Environment {
586            vocabulary: no_vocabulary_mut(),
587            loader: &NoLoader,
588            warnings: &mut warnings,
589        };
590
591        let expanded = expand_iri_simple::<Warning, _, _, _>(&mut env, context, Nullable::Some(value.into()), false, vocab.then_some(Action::Keep))
592            .unwrap()
593            .unwrap();
594        Arc::unwrap_or_clone(expanded)
595    }
596
597    fn iri(source: &str) -> Term<IriBuf, BlankIdBuf> {
598        Term::Id(Id::iri(IriBuf::new(source.to_owned()).unwrap()))
599    }
600
601    /// A processed context expands terms, compact IRIs, absolute IRIs and
602    /// `@vocab`-relative terms without a loader; term definitions and `@vocab`
603    /// only apply where `vocab` does.
604    #[test]
605    fn processed_context_expands_terms_compact_iris_and_vocab_relative_terms() {
606        let context = processed_context();
607
608        let cases = [
609            ("name", true, iri("https://example.com/name")),
610            ("name", false, Term::Id(Id::Invalid("name".to_owned()))),
611            ("ex:thing", true, iri("https://example.com/thing")),
612            ("ex:thing", false, iri("https://example.com/thing")),
613            ("http://other.example/x", true, iri("http://other.example/x")),
614            ("http://other.example/x", false, iri("http://other.example/x")),
615            ("temperature", true, iri("https://vocab.example/temperature")),
616            ("temperature", false, Term::Id(Id::Invalid("temperature".to_owned()))),
617            ("type", true, Term::Keyword(Keyword::Type)),
618            ("_:b0", false, Term::Id(Id::blank(BlankIdBuf::new("_:b0".to_owned()).unwrap()))),
619        ];
620
621        for (value, vocab, expected) in cases {
622            assert_eq!(expand(&context, value, vocab), expected, "{value} (vocab: {vocab})");
623        }
624    }
625}