jsonld-core 0.23.3

JSON-LD core types and traits
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
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
//! Context processing algorithm and related types.
mod definition;
/// Inverse context, used to pick terms during compaction.
pub mod inverse;
mod memo;

use crate::{Direction, LenientLangTag, LenientLangTagBuf, ProcessingMode, Term, ValidId as Id};
use contextual::WithContext;
use iri_rs::IriBuf;
use jsonld_syntax::{Keyword, KeywordType, Nullable};
use once_cell::sync::OnceCell;
use rdfx::{BlankIdBuf, vocabulary::Vocabulary};
use std::{borrow::Borrow, hash::Hash, sync::Arc};

pub use jsonld_syntax::context::{
    definition::{Key, KeyOrType, Type},
    term_definition::Nest,
};

pub use definition::*;
pub use inverse::InverseContext;
pub use memo::ShardedMemo;

/// Either a borrowed context or an owned one held behind a box.
///
/// Expansion and compaction repeatedly rebind an active context that may or may
/// not have been replaced by a processed one. A `Cow`-like type is the natural
/// fit, but [`Context`] is over 250 bytes and storing it inline makes every
/// async state machine holding one that much larger — the value is memmoved on
/// every recursion. Boxing the owned arm keeps this two words wide however
/// [`Context`] grows, at the cost of one allocation on a path that has just
/// built a whole context anyway.
pub enum ContextRef<'a, T = IriBuf, B = BlankIdBuf> {
    /// Borrowed from the caller.
    Borrowed(&'a Context<T, B>),

    /// Owned by this value.
    Owned(Box<Context<T, B>>),
}

impl<T, B> ContextRef<'_, T, B> {
    /// Takes ownership of `context`, boxing it.
    #[inline(always)]
    pub fn owned(context: Context<T, B>) -> Self {
        Self::Owned(Box::new(context))
    }

    /// Borrows the context, whichever arm holds it.
    //
    // Deliberately an inherent method rather than an `AsRef` impl, mirroring
    // `Option::as_ref`: callers reach for it on a concrete `ContextRef`, and a
    // trait impl would force type annotations at every call site.
    #[allow(clippy::should_implement_trait)]
    #[inline(always)]
    #[must_use]
    pub fn as_ref(&self) -> &Context<T, B> {
        match self {
            Self::Borrowed(context) => context,
            Self::Owned(context) => context,
        }
    }

    /// Returns `true` if the context is owned.
    ///
    /// Expansion uses this to detect that scoped-context processing replaced
    /// the active context, and that cached key expansions must be recomputed.
    #[inline(always)]
    #[must_use]
    pub fn is_owned(&self) -> bool {
        matches!(self, Self::Owned(_))
    }
}

impl<T, B> std::ops::Deref for ContextRef<'_, T, B> {
    type Target = Context<T, B>;

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        self.as_ref()
    }
}

/// Error returned when a context vocabulary is set to an invalid value.
#[derive(Debug, Clone, Copy, thiserror::Error)]
pub enum InvalidVocab {
    /// The vocabulary is a JSON-LD keyword.
    #[error("vocabulary cannot be a keyword")]
    Keyword,
}

/// Error returned when a context key cannot be expressed in syntax form.
#[derive(Debug, Clone, Copy, thiserror::Error)]
#[error("invalid context key")]
pub struct InvalidContextKey;

/// Error returned by [`Context::into_syntax_definition`] and related
/// conversions.
#[derive(Debug, Clone, Copy, thiserror::Error)]
pub enum InvalidContextError {
    #[error(transparent)]
    /// The `@vocab` entry is invalid.
    InvalidVocab(#[from] InvalidVocab),

    #[error(transparent)]
    /// A context key is invalid.
    InvalidContextKey(#[from] InvalidContextKey),

    #[error("IRI handle does not resolve in the given vocabulary")]
    /// An IRI handle of the context does not resolve in the vocabulary passed
    /// to [`Context::into_syntax_definition`]; the context was built with a
    /// different vocabulary.
    UnresolvedIri,
}

/// Cache key for [`Context::compact_iri_cache`]:
/// `(var, vocab, reverse, mode)`.
///
/// The processing mode is part of the key because compact-IRI selection is
/// mode-dependent (JSON-LD 1.1 considers `@index`/`@language` containers
/// that 1.0 may not): one processed context compacted under both modes must
/// not serve either mode the other's terms.
pub type CompactIriKey<T, B> = (Term<T, B>, bool, bool, ProcessingMode);

/// Borrowed view over a [`CompactIriKey`] for cache lookups that don't need
/// to allocate a fresh `Term`. Hashes byte-for-byte identically to the
/// owned tuple, so `HashMap::get` finds the same bucket.
pub struct CompactIriKeyRef<'a, T, B>(pub &'a Term<T, B>, pub bool, pub bool, pub ProcessingMode);

impl<T: std::hash::Hash, B: std::hash::Hash> std::hash::Hash for CompactIriKeyRef<'_, T, B> {
    #[inline]
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.0.hash(state);
        self.1.hash(state);
        self.2.hash(state);
        self.3.hash(state);
    }
}

impl<T: PartialEq, B: PartialEq> hashbrown::Equivalent<CompactIriKey<T, B>> for CompactIriKeyRef<'_, T, B> {
    #[inline]
    fn equivalent(&self, key: &CompactIriKey<T, B>) -> bool {
        self.0 == &key.0 && self.1 == key.1 && self.2 == key.2 && self.3 == key.3
    }
}

/// Cached fixed-keyword aliases for an active context.
///
/// 13 keywords appear repeatedly during compaction (`@id`, `@type`, `@value`,
/// `@list`, `@set`, `@graph`, `@index`, `@language`, `@direction`, `@reverse`,
/// `@none`, `@included`, `@json`). Their compact-IRI form is a pure function
/// of the active context and the processing mode, so the result is computed
/// once per `(context, mode)` and reused — saving per-element memo
/// lookups + alias-selection work in `compact_iri_full`.
pub struct KeywordAliases {
    aliases: [Box<str>; 13],
}

impl KeywordAliases {
    /// Creates a new `KeywordAliases`.
    #[must_use]
    pub fn new(aliases: [Box<str>; 13]) -> Self {
        Self { aliases }
    }

    /// Returns the cached alias for the given keyword. For one of the 13
    /// supported keywords, returns the alias selected during cache
    /// initialization; for any other keyword returns its literal name
    /// (e.g. `"@base"`).
    #[inline]
    #[must_use]
    pub fn get(&self, k: Keyword) -> &str {
        match keyword_alias_index(k) {
            Some(i) => self.aliases[i].as_ref(),
            None => k.into_str(),
        }
    }
}

/// 13 keywords supported by [`KeywordAliases`], in cache-array order.
pub const CACHED_KEYWORDS: [Keyword; 13] = [
    Keyword::Id,
    Keyword::Type,
    Keyword::Value,
    Keyword::List,
    Keyword::Set,
    Keyword::Graph,
    Keyword::Index,
    Keyword::Language,
    Keyword::Direction,
    Keyword::Reverse,
    Keyword::None,
    Keyword::Included,
    Keyword::Json,
];

#[inline]
fn keyword_aliases_slot(mode: ProcessingMode) -> usize {
    match mode {
        ProcessingMode::JsonLd1_0 => 0,
        ProcessingMode::JsonLd1_1 => 1,
    }
}

#[inline]
fn keyword_alias_index(k: Keyword) -> Option<usize> {
    Some(match k {
        Keyword::Id => 0,
        Keyword::Type => 1,
        Keyword::Value => 2,
        Keyword::List => 3,
        Keyword::Set => 4,
        Keyword::Graph => 5,
        Keyword::Index => 6,
        Keyword::Language => 7,
        Keyword::Direction => 8,
        Keyword::Reverse => 9,
        Keyword::None => 10,
        Keyword::Included => 11,
        Keyword::Json => 12,
        _ => return None,
    })
}

type CompactIriCache<T, B> = ShardedMemo<CompactIriKey<T, B>, Option<Arc<str>>>;
type TermResolutionCache<T, B> = ShardedMemo<Box<str>, Arc<Term<T, B>>>;

/// A prefix-eligible term paired with the term it maps to.
pub type PrefixTerm<T, B> = (Key, Arc<Term<T, B>>);

/// Active context: everything the algorithms need to expand or compact
/// against the current scope.
pub struct Context<T = IriBuf, B = BlankIdBuf> {
    original_base_url: Option<T>,
    base_iri: Option<T>,
    vocabulary: Option<Term<T, B>>,
    default_language: Option<LenientLangTagBuf>,
    default_base_direction: Option<Direction>,
    previous_context: Option<Arc<Self>>,
    definitions: Arc<Definitions<T, B>>,
    /// Mode this context was processed under.
    ///
    /// A handful of algorithm steps behave differently in JSON-LD 1.0 — most
    /// notably that any term definition may serve as a compact-IRI prefix
    /// during IRI expansion, the `@prefix` flag being a 1.1 addition. Carrying
    /// the mode here keeps those checks out of every IRI-expansion signature.
    processing_mode: ProcessingMode,
    // Caches are wrapped in `Arc` so that `Clone` shares them across
    // copies of a processed context. This is critical for the
    // `ProcessingCache` hit path, which clones a stored `Arc<Context>`
    // for each entity expansion — without sharing, every entity would
    // start with empty caches and the per-context memoization would
    // never see cross-entity hits.
    //
    // Invalidation (via [`Self::invalidate_iri_caches`]) replaces the
    // `Arc` with a fresh one, so other holders of the original `Arc`
    // keep their (still-valid) cached entries.
    inverse: Arc<OnceCell<InverseContext<T, B>>>,
    prefix_terms: Arc<OnceCell<Vec<PrefixTerm<T, B>>>>,
    compact_iri_cache: Arc<OnceCell<CompactIriCache<T, B>>>,
    term_resolution_cache: Arc<OnceCell<TermResolutionCache<T, B>>>,
    // One slot per processing mode: alias selection is mode-dependent.
    keyword_aliases: Arc<[OnceCell<KeywordAliases>; 2]>,
}

impl<T, B> Default for Context<T, B> {
    fn default() -> Self {
        Self {
            original_base_url: None,
            base_iri: None,
            vocabulary: None,
            default_language: None,
            default_base_direction: None,
            previous_context: None,
            definitions: Arc::new(Definitions::default()),
            processing_mode: ProcessingMode::default(),
            inverse: Arc::new(OnceCell::new()),
            prefix_terms: Arc::new(OnceCell::new()),
            compact_iri_cache: Arc::new(OnceCell::new()),
            term_resolution_cache: Arc::new(OnceCell::new()),
            keyword_aliases: Arc::new([OnceCell::new(), OnceCell::new()]),
        }
    }
}

/// Binding of a context definition, key and term definition together.
pub type DefinitionEntryRef<'a, T = IriBuf, B = BlankIdBuf> = (&'a Key, &'a TermDefinition<T, B>);

impl<T, B> Context<T, B> {
    /// Create a new context with the given base IRI.
    pub fn new(base_iri: Option<T>) -> Self
    where
        T: Clone,
    {
        Self {
            original_base_url: base_iri.clone(),
            base_iri,
            vocabulary: None,
            default_language: None,
            default_base_direction: None,
            previous_context: None,
            definitions: Arc::new(Definitions::default()),
            processing_mode: ProcessingMode::default(),
            inverse: Arc::new(OnceCell::new()),
            prefix_terms: Arc::new(OnceCell::new()),
            compact_iri_cache: Arc::new(OnceCell::new()),
            term_resolution_cache: Arc::new(OnceCell::new()),
            keyword_aliases: Arc::new([OnceCell::new(), OnceCell::new()]),
        }
    }

    /// Returns a copy of this context whose IRI memoisation caches are private
    /// to the copy.
    ///
    /// [`Self::term_resolution_cache`][c] maps a term to an already-resolved
    /// [`Term`], which carries `T`-typed identifiers. Sharing it across
    /// vocabulary forks is unsound: a term that one fork resolved by interning
    /// a *new* IRI would be served to another fork, where that identifier
    /// denotes something else entirely — or nothing. Concurrent expansion
    /// therefore gives each task a context of its own.
    ///
    /// Only the caches are fresh. Definitions, prefix terms and keyword
    /// aliases are shared through their `Arc`s: they are derived from the
    /// context's own definitions, whose identifiers every fork inherits, so
    /// they stay valid. The same reasoning covers the inverse context.
    ///
    /// [c]: Self::term_resolution_cache
    #[must_use]
    pub fn with_private_caches(&self) -> Context<T, B>
    where
        T: Clone,
        B: Clone,
    {
        Context {
            original_base_url: self.original_base_url.clone(),
            base_iri: self.base_iri.clone(),
            vocabulary: self.vocabulary.clone(),
            default_language: self.default_language.clone(),
            default_base_direction: self.default_base_direction,
            // A previous context is consulted on the same code paths, so its
            // caches have to be private too.
            previous_context: self.previous_context.as_ref().map(|previous| Arc::new(previous.with_private_caches())),
            definitions: Arc::clone(&self.definitions),
            processing_mode: self.processing_mode,
            inverse: Arc::clone(&self.inverse),
            prefix_terms: Arc::clone(&self.prefix_terms),
            compact_iri_cache: Arc::new(OnceCell::new()),
            term_resolution_cache: Arc::new(OnceCell::new()),
            keyword_aliases: Arc::clone(&self.keyword_aliases),
        }
    }

    /// Returns the processing mode this context was processed under.
    #[inline(always)]
    pub fn processing_mode(&self) -> ProcessingMode {
        self.processing_mode
    }

    /// Sets the processing mode of this context.
    #[inline(always)]
    pub fn set_processing_mode(&mut self, mode: ProcessingMode) {
        self.processing_mode = mode;
    }

    /// Returns a reference to the given `term` definition, if any.
    pub fn get<Q>(&self, term: &Q) -> Option<TermDefinitionRef<'_, T, B>>
    where
        Key: Borrow<Q>,
        KeywordType: Borrow<Q>,
        Q: ?Sized + Hash + Eq,
    {
        self.definitions.get(term)
    }

    /// Returns a reference to the given `term` normal definition, if any.
    pub fn get_normal<Q>(&self, term: &Q) -> Option<&NormalTermDefinition<T, B>>
    where
        Key: Borrow<Q>,
        Q: ?Sized + Hash + Eq,
    {
        self.definitions.get_normal(term)
    }

    /// Returns a reference to the `@type` definition, if any.
    pub fn get_type(&self) -> Option<&TypeTermDefinition> {
        self.definitions.get_type()
    }

    /// Checks if the given `term` is defined.
    pub fn contains_term<Q>(&self, term: &Q) -> bool
    where
        Key: Borrow<Q>,
        KeywordType: Borrow<Q>,
        Q: ?Sized + Hash + Eq,
    {
        self.definitions.contains_term(term)
    }

    /// Returns the original base URL of the context.
    pub fn original_base_url(&self) -> Option<&T> {
        self.original_base_url.as_ref()
    }

    /// Returns the base IRI of the context.
    pub fn base_iri(&self) -> Option<&T> {
        self.base_iri.as_ref()
    }

    /// Returns the `@vocab` value, if any.
    pub fn vocabulary(&self) -> Option<&Term<T, B>> {
        match &self.vocabulary {
            Some(v) => Some(v),
            None => None,
        }
    }

    /// Returns the default `@language` value.
    pub fn default_language(&self) -> Option<&LenientLangTag> {
        self.default_language.as_ref().map(jsonld_syntax::LenientLangTagBuf::as_lenient_lang_tag_ref)
    }

    /// Returns the default `@direction` value.
    pub fn default_base_direction(&self) -> Option<Direction> {
        self.default_base_direction
    }

    /// Returns a reference to the previous context.
    pub fn previous_context(&self) -> Option<&Self> {
        match &self.previous_context {
            Some(c) => Some(c),
            None => None,
        }
    }

    /// Returns the address of the `Arc` backing the term definitions.
    ///
    /// Two contexts that share this pointer share the exact same definitions
    /// (copy-on-write via [`Arc::make_mut`]). Useful as a cheap fingerprint
    /// for memoization keys.
    pub fn definitions_arc_ptr(&self) -> *const Definitions<T, B> {
        Arc::as_ptr(&self.definitions)
    }

    /// Returns the address of the `Arc` backing the previous context, or null
    /// when there is none. See [`Self::definitions_arc_ptr`].
    pub fn previous_context_arc_ptr(&self) -> *const Self {
        self.previous_context.as_ref().map_or(std::ptr::null(), Arc::as_ptr)
    }

    /// Returns the number of terms defined.
    pub fn len(&self) -> usize {
        self.definitions.len()
    }

    /// Checks if no terms are defined.
    pub fn is_empty(&self) -> bool {
        self.definitions.is_empty()
    }

    /// Returns a handle to the term definitions.
    pub fn definitions(&self) -> &Definitions<T, B> {
        &self.definitions
    }

    /// Checks if the context has a protected definition.
    pub fn has_protected_items(&self) -> bool {
        for binding in self.definitions() {
            if binding.definition().protected() {
                return true;
            }
        }

        false
    }

    /// Returns the inverse context, computing and caching it on first access.
    pub fn inverse(&self) -> &InverseContext<T, B>
    where
        T: Clone + Hash + Eq,
        B: Clone + Hash + Eq,
    {
        self.inverse.get_or_init(|| self.into())
    }

    /// Returns the term definitions whose `prefix` flag is `true`, each paired
    /// with its IRI mapping.
    ///
    /// The mapping is carried alongside the key so that compaction's
    /// candidate loop does not have to look the definition back up — which
    /// would re-hash the very key this list just handed it. Definitions with no
    /// IRI mapping cannot form a compact IRI and are left out.
    ///
    /// Lazily computed and cached; invalidated whenever a definition is added,
    /// removed, or replaced.
    pub fn prefix_terms(&self) -> &[PrefixTerm<T, B>] {
        self.prefix_terms.get_or_init(|| {
            self.definitions
                .iter()
                .filter_map(|binding| match binding {
                    BindingRef::Normal(key, def) if def.prefix => def.value_arc().map(|value| (*key, value.clone())),
                    _ => None,
                })
                .collect()
        })
    }

    /// Returns the per-context memoization map for the compact-IRI algorithm.
    ///
    /// The cache stores results keyed on `(var, vocab, reverse, mode)`. It is
    /// invalidated whenever the context's term definitions, base IRI,
    /// vocabulary, language, or direction change, since those affect
    /// compaction output.
    pub fn compact_iri_cache(&self) -> &CompactIriCache<T, B> {
        self.compact_iri_cache.get_or_init(ShardedMemo::default)
    }

    /// Returns the per-context memoization map for IRI expansion of term keys.
    ///
    /// Maps the input string to the resolved [`Arc<Term>`]. Populated only by
    /// the dominant key-expansion call shape (`vocab=Some(Keep)`,
    /// `document_relative=false`); other shapes bypass this cache. Invalidated
    /// alongside the compact-IRI / inverse caches whenever the context's term
    /// definitions, base IRI, vocabulary, language, or direction change.
    pub fn term_resolution_cache(&self) -> &TermResolutionCache<T, B> {
        self.term_resolution_cache.get_or_init(ShardedMemo::default)
    }

    /// Returns the cached keyword aliases of this context for the given
    /// processing mode, computing them via `init` on first access. The
    /// closure runs once per `(context, mode)`; subsequent calls return the
    /// cached value. Aliases are cached per mode because compact-IRI
    /// selection is mode-dependent.
    pub fn keyword_aliases_or_init<F: FnOnce() -> KeywordAliases>(&self, mode: ProcessingMode, init: F) -> &KeywordAliases {
        self.keyword_aliases[keyword_aliases_slot(mode)].get_or_init(init)
    }

    /// Drops the inverse-context and compact-IRI caches if they are populated.
    ///
    /// Replaces each cache `Arc` with a fresh empty one.
    ///
    /// We can't `take()` from a shared `Arc<OnceCell<_>>` (it requires `&mut`
    /// access to the `OnceCell`, which the Arc doesn't grant). Replacing the
    /// `Arc` itself diverges this context's caches from any sharers — which
    /// is exactly what we want: other holders had a context with the
    /// pre-mutation state and their caches are still valid for that state.
    #[inline]
    fn invalidate_iri_caches(&mut self) {
        if self.inverse.get().is_some() {
            self.inverse = Arc::new(OnceCell::new());
        }
        if self.compact_iri_cache.get().is_some() {
            self.compact_iri_cache = Arc::new(OnceCell::new());
        }
        if self.term_resolution_cache.get().is_some() {
            self.term_resolution_cache = Arc::new(OnceCell::new());
        }
        if self.keyword_aliases.iter().any(|slot| slot.get().is_some()) {
            self.keyword_aliases = Arc::new([OnceCell::new(), OnceCell::new()]);
        }
    }

    /// Sets the normal definition for the given term `key`.
    pub fn set_normal(&mut self, key: Key, definition: Option<NormalTermDefinition<T, B>>) -> Option<NormalTermDefinition<T, B>>
    where
        T: Clone,
        B: Clone,
    {
        self.invalidate_iri_caches();
        if self.prefix_terms.get().is_some() {
            self.prefix_terms = Arc::new(OnceCell::new());
        }
        Arc::make_mut(&mut self.definitions).set_normal(key, definition)
    }

    /// Sets the `@type` definition.
    pub fn set_type(&mut self, type_: Option<TypeTermDefinition>) -> Option<TypeTermDefinition>
    where
        T: Clone,
        B: Clone,
    {
        if self.compact_iri_cache.get().is_some() {
            self.compact_iri_cache = Arc::new(OnceCell::new());
        }
        if self.term_resolution_cache.get().is_some() {
            self.term_resolution_cache = Arc::new(OnceCell::new());
        }
        if self.keyword_aliases.iter().any(|slot| slot.get().is_some()) {
            self.keyword_aliases = Arc::new([OnceCell::new(), OnceCell::new()]);
        }
        Arc::make_mut(&mut self.definitions).set_type(type_)
    }

    /// Sets the base IRI.
    pub fn set_base_iri(&mut self, iri: Option<T>) {
        self.invalidate_iri_caches();
        self.base_iri = iri;
    }

    /// Sets the `@vocab` value.
    pub fn set_vocabulary(&mut self, vocab: Option<Term<T, B>>) {
        self.invalidate_iri_caches();
        self.vocabulary = vocab;
    }

    /// Sets the default `@language` value.
    pub fn set_default_language(&mut self, lang: Option<LenientLangTagBuf>) {
        self.invalidate_iri_caches();
        self.default_language = lang;
    }

    /// Sets the default `@direction` value.
    pub fn set_default_base_direction(&mut self, dir: Option<Direction>) {
        self.invalidate_iri_caches();
        self.default_base_direction = dir;
    }

    /// Sets the previous context.
    pub fn set_previous_context(&mut self, previous: Self) {
        self.invalidate_iri_caches();
        self.previous_context = Some(Arc::new(previous));
    }

    /// Converts this context into its syntactic definition.
    ///
    /// # Errors
    ///
    /// Returns an error when a term in the context cannot be represented in syntax form, which happens if the vocabulary has no IRI for an identifier it holds.
    pub fn into_syntax_definition(self, vocabulary: &impl Vocabulary<Iri = T, BlankId = B>) -> Result<jsonld_syntax::context::Definition, InvalidContextError>
    where
        T: Clone,
        B: Clone,
    {
        let (bindings, type_) = Arc::unwrap_or_clone(self.definitions).into_parts();

        let vocab = match self.vocabulary {
            Some(Term::Null) => Some(Nullable::Null),
            Some(Term::Id(r)) => Some(Nullable::Some(r.with(vocabulary).to_string().into())),
            Some(Term::Keyword(_)) => return Err(InvalidContextError::InvalidVocab(InvalidVocab::Keyword)),
            None => None,
        };

        let base = match self.base_iri {
            Some(i) => {
                // Fails only when `vocabulary` is not the vocabulary this
                // context was built with.
                let iri: iri_rs::IriBuf = vocabulary.iri(&i).ok_or(InvalidContextError::UnresolvedIri)?.into();
                Some(Nullable::Some(iri.into()))
            }
            None => None,
        };

        Ok(jsonld_syntax::context::Definition {
            base,
            import: None,
            language: self.default_language.map(Nullable::Some),
            direction: self.default_base_direction.map(Nullable::Some),
            propagate: None,
            protected: None,
            type_: type_.map(TypeTermDefinition::into_syntax_definition),
            version: None,
            vocab,
            bindings: {
                // `HashMap` iteration order is nondeterministic; sort by term
                // so the serialized definition is stable across runs.
                let mut entries: Vec<_> = bindings.into_iter().collect();
                entries.sort_unstable_by(|(a, _), (b, _)| a.as_str().cmp(b.as_str()));
                entries
                    .into_iter()
                    .map(|(key, definition)| definition.into_syntax_definition(vocabulary).map(|d| (key, d)))
                    .collect::<Result<_, _>>()?
            },
        })
    }

    /// Rewrites every IRI and identifier of this context with the given
    /// functions.
    pub fn map_ids<U, C>(self, mut map_iri: impl FnMut(T) -> U, mut map_id: impl FnMut(Id<T, B>) -> Id<U, C>) -> Context<U, C>
    where
        T: Clone,
        B: Clone,
    {
        self.map_ids_with(&mut map_iri, &mut map_id)
    }

    fn map_ids_with<U, C>(self, map_iri: &mut impl FnMut(T) -> U, map_id: &mut impl FnMut(Id<T, B>) -> Id<U, C>) -> Context<U, C>
    where
        T: Clone,
        B: Clone,
    {
        Context {
            original_base_url: self.original_base_url.map(&mut *map_iri),
            base_iri: self.base_iri.map(&mut *map_iri),
            vocabulary: self.vocabulary.map(|v| v.map_id(&mut *map_id)),
            default_language: self.default_language,
            default_base_direction: self.default_base_direction,
            previous_context: self.previous_context.map(|c| Arc::new(Arc::unwrap_or_clone(c).map_ids_with(map_iri, map_id))),
            definitions: Arc::new(Arc::unwrap_or_clone(self.definitions).map_ids(map_iri, map_id)),
            processing_mode: self.processing_mode,
            inverse: Arc::new(OnceCell::new()),
            prefix_terms: Arc::new(OnceCell::new()),
            compact_iri_cache: Arc::new(OnceCell::new()),
            term_resolution_cache: Arc::new(OnceCell::new()),
            keyword_aliases: Arc::new([OnceCell::new(), OnceCell::new()]),
        }
    }
}

/// Conversion of a processed context back into its syntactic form.
pub trait IntoSyntax<T = IriBuf, B = BlankIdBuf> {
    /// Consumes this value, returning the equivalent syntactic context. The
    /// given vocabulary must be the one the context was built with, so its
    /// IRI handles can be resolved back to actual IRIs.
    ///
    /// # Errors
    ///
    /// Returns an error when a term in the context cannot be represented in syntax form.
    fn into_syntax(self, vocabulary: &impl Vocabulary<Iri = T, BlankId = B>) -> Result<jsonld_syntax::context::Context, InvalidContextError>;
}

impl<T, B> IntoSyntax<T, B> for jsonld_syntax::context::Context {
    fn into_syntax(self, _namespace: &impl Vocabulary<Iri = T, BlankId = B>) -> Result<jsonld_syntax::context::Context, InvalidContextError> {
        Ok(self)
    }
}

impl<T: Clone, B: Clone> IntoSyntax<T, B> for Context<T, B> {
    fn into_syntax(self, vocabulary: &impl Vocabulary<Iri = T, BlankId = B>) -> Result<jsonld_syntax::context::Context, InvalidContextError> {
        Ok(jsonld_syntax::context::Context::One(jsonld_syntax::ContextEntry::Definition(
            self.into_syntax_definition(vocabulary)?,
        )))
    }
}

impl<T: Clone, B: Clone> Clone for Context<T, B> {
    fn clone(&self) -> Self {
        // Share caches across clones via `Arc::clone`. Sound because processed
        // contexts are not mutated post-processing — the only mutating APIs
        // (`set_normal`, `set_type`, `set_base_iri`, etc.) call
        // `invalidate_iri_caches`, which replaces the `Arc` with a fresh one
        // so the mutated copy diverges from any sharers.
        Self {
            original_base_url: self.original_base_url.clone(),
            base_iri: self.base_iri.clone(),
            vocabulary: self.vocabulary.clone(),
            default_language: self.default_language.clone(),
            default_base_direction: self.default_base_direction,
            previous_context: self.previous_context.clone(),
            definitions: Arc::clone(&self.definitions),
            processing_mode: self.processing_mode,
            inverse: Arc::clone(&self.inverse),
            prefix_terms: Arc::clone(&self.prefix_terms),
            compact_iri_cache: Arc::clone(&self.compact_iri_cache),
            term_resolution_cache: Arc::clone(&self.term_resolution_cache),
            keyword_aliases: Arc::clone(&self.keyword_aliases),
        }
    }
}

impl<T: PartialEq, B: PartialEq> PartialEq for Context<T, B> {
    fn eq(&self, other: &Self) -> bool {
        self.original_base_url == other.original_base_url
            && self.base_iri == other.base_iri
            && self.vocabulary == other.vocabulary
            && self.default_language == other.default_language
            && self.default_base_direction == other.default_base_direction
            && self.processing_mode == other.processing_mode
            // `ptr_eq` first: clones share their `Arc<Definitions>`, making
            // the common case free.
            && (Arc::ptr_eq(&self.definitions, &other.definitions) || self.definitions == other.definitions)
            && self.previous_context == other.previous_context
    }
}