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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
use super::{Environment, Merged, expand_iri_simple, expand_iri_with};
use crate::{Error, Options, ProcessingStack, Warning, WarningHandler};
use iri_rs::{Iri, IriRef};
use jsonld_core::{
Container,
Context,
HashMap,
Id,
Loader,
ProcessingMode,
Term,
Type,
ValidId,
context::{NormalTermDefinition, TypeTermDefinition},
};
use jsonld_syntax::{
CompactIri,
ContainerKind,
ExpandableRef,
Keyword,
LenientLangTag,
Nullable,
context::{
definition::{EntryValueRef, KeyOrKeyword, KeyOrKeywordRef},
term_definition::{self, IdRef},
},
native_stack::Recursion,
};
use rdfx::{BlankId, vocabulary::VocabularyMut};
use std::{hash::Hash, sync::Arc};
/// Checks whether `c` is one of RFC 3986's generic delimiters.
fn is_gen_delim(c: char) -> bool {
matches!(c, ':' | '/' | '?' | '#' | '[' | ']' | '@')
}
/// Checks whether `t` is a blank node identifier, or an IRI whose last character
/// is a generic delimiter.
///
/// These are the IRI mappings a simple term may be used as a prefix for, since
/// concatenating a suffix onto them yields a syntactically separate component.
fn is_gen_delim_or_blank<T, B>(vocabulary: &impl VocabularyMut<Iri = T, BlankId = B>, t: &Term<T, B>) -> bool {
match t {
Term::Id(Id::Valid(ValidId::Blank(_))) => true,
Term::Id(Id::Valid(ValidId::Iri(id))) => match vocabulary.iri(id).and_then(|i| i.as_str().chars().last()) {
Some(c) => is_gen_delim(c),
None => false,
},
_ => false,
}
}
/// Checks whether `c` occurs in `id`, but as neither its first nor its last
/// character.
///
/// A term shaped like that (a colon somewhere in the middle) looks like a compact
/// IRI, which is what makes the round-trip check in [`define`] apply to it.
fn contains_between_boundaries(id: &str, c: char) -> bool {
if let Some(i) = id.find(c) {
// SAFETY: `find` matched, so `rfind` must also match.
let j = unsafe { id.rfind(c).unwrap_unchecked() };
i > 0 && j < id.len() - 1
} else {
false
}
}
#[derive(Default)]
/// Tracks which terms of one context definition are already defined and which
/// are still being defined, so that cyclic definitions can be detected.
///
/// Defining a term can require defining others first — its prefix, or the term
/// its `@id` names — so [`define`] recurses. A term that is reached again while
/// its own definition is still in progress is a cycle.
pub struct DefinedTerms(HashMap<KeyOrKeyword, DefinedTerm>);
impl DefinedTerms {
/// Creates an empty tracker, with no term defined or in progress.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Marks `key` as being defined, and reports whether the caller should go on
/// to build its definition.
///
/// Returns `Ok(true)` for a term seen for the first time, `Ok(false)` for one
/// already fully defined (the caller should do nothing), and
/// `Err(Error::CyclicIriMapping)` for one whose definition is still in
/// progress further up the recursion.
///
/// # Errors
///
/// Returns an error when the term is already being defined further up the stack, which is a cyclic IRI mapping.
pub fn begin<E>(&mut self, key: &KeyOrKeyword) -> Result<bool, Error<E>> {
if let Some(d) = self.0.get(key) {
if d.pending { Err(Error::CyclicIriMapping) } else { Ok(false) }
} else {
self.0.insert(key.clone(), DefinedTerm { pending: true });
Ok(true)
}
}
/// Marks `key` as fully defined, so that reaching it again is no longer a
/// cycle.
///
/// Does nothing if the term was never passed to [`Self::begin`].
pub fn end(&mut self, key: &KeyOrKeyword) {
if let Some(term) = self.0.get_mut(key) {
term.pending = false;
}
}
}
/// A term's state within a [`DefinedTerms`] tracker: either fully defined, or
/// still being defined further up the recursion.
pub struct DefinedTerm {
pending: bool,
}
/// Runs the [create term definition algorithm][1] for `term`, adding the
/// resulting definition to `active_context`.
///
/// Reads `term`'s entry from `local_context`, resolves its `@id`, `@reverse`,
/// `@type`, `@container`, `@index`, `@context`, `@language`, `@direction`,
/// `@nest` and `@prefix`, and installs the definition. Recurses through
/// `expand_iri_with` for terms this one depends on, using `defined` to detect
/// cycles; a term already defined is a no-op.
///
/// `base_url` is what a scoped `@context` inside the definition resolves its own
/// references against. `protected` is the context-wide `@protected` default,
/// which an explicit `@protected` in the term definition overrides. Whether a
/// previously protected definition may be replaced is governed by
/// `options.override_protected`.
///
/// [1]: https://www.w3.org/TR/json-ld11-api/#create-term-definition
///
/// # Errors
///
/// Returns an error when a term definition is cyclic, protected and being redefined, or otherwise invalid, and propagates loader errors for remote contexts.
pub async fn define<'a, N, L, W>(
mut env: Environment<'a, N, L, W>,
active_context: &'a mut Context<N::Iri, N::BlankId>,
local_context: &'a Merged<'a>,
term: KeyOrKeywordRef<'a>,
defined: &'a mut DefinedTerms,
remote_contexts: ProcessingStack<N::Iri>,
base_url: Option<N::Iri>,
protected: bool,
options: Options,
) -> Result<(), Error<L::Error>>
where
N: VocabularyMut,
N::Iri: Clone + Eq + Hash,
N::BlankId: Clone + PartialEq,
L: Loader,
W: WarningHandler<N>,
{
let term = term.to_owned();
if defined.begin(&term)? {
if term.is_empty() {
return Err(Error::InvalidTermDefinition);
}
// Initialize `value` to a copy of the value associated with the entry `term` in
// `local_context`.
if let Some(value) = local_context.get(&term) {
// Set the value associated with defined's term entry to false.
// This indicates that the term definition is now being created but is not yet
// complete.
// Done with `defined.begin`.
match value {
// If term is @type, ...
EntryValueRef::Type(d) => {
// ... and processing mode is json-ld-1.0, a keyword
// redefinition error has been detected and processing is aborted.
if options.processing_mode == ProcessingMode::JsonLd1_0 {
return Err(Error::KeywordRedefinition);
}
let previous_definition = active_context.set_type(None);
// At this point, `value` MUST be a map with only either or both of the
// following entries:
// An entry for @container with value @set.
// An entry for @protected.
// Any other value means that a keyword redefinition error has been detected
// and processing is aborted.
// Checked during parsing.
let mut definition = TypeTermDefinition {
container: d.container,
..Default::default()
};
if let Some(protected) = d.protected {
if options.processing_mode == ProcessingMode::JsonLd1_0 {
return Err(Error::InvalidTermDefinition);
}
definition.protected = protected;
}
// If override protected is false and previous_definition exists and is protected;
if !options.override_protected
&& let Some(previous_definition) = previous_definition
&& previous_definition.protected
{
// If `definition` is not the same as `previous_definition`
// (other than the value of protected), a protected term
// redefinition error has been detected, and processing is aborted.
if definition.modulo_protected_field() != previous_definition.modulo_protected_field() {
return Err(Error::ProtectedTermRedefinition);
}
// Set `definition` to `previous definition` to retain the value of
// protected.
definition.protected = true;
}
active_context.set_type(Some(definition));
}
EntryValueRef::Definition(d) => {
// SAFETY: at this point `term` is a `KeyOrKeyword::Key`,
// since the `Type` arm above returns early.
let key = unsafe { term.as_key().unwrap_unchecked() };
// Initialize `previous_definition` to any existing term definition for `term` in
// `active_context`, removing that term definition from active context.
let previous_definition = active_context.set_normal(*key, None);
let simple_term = !d.map(jsonld_syntax::context::TermDefinition::is_expanded).unwrap_or(false);
let value = term_definition::ExpandedRef::from(d);
// Create a new term definition, `definition`, initializing `prefix` flag to
// `false`, `protected` to `protected`, and `reverse_property` to `false`.
let mut definition = NormalTermDefinition::<N::Iri, N::BlankId> {
protected,
..Default::default()
};
// If the @protected entry in value is true set the protected flag in
// definition to true.
if let Some(protected) = value.protected {
// If processing mode is json-ld-1.0, an invalid term definition has
// been detected and processing is aborted.
if options.processing_mode == ProcessingMode::JsonLd1_0 {
return Err(Error::InvalidTermDefinition);
}
definition.protected = protected;
}
// If value contains the entry @type:
if let Some(type_) = value.type_ {
// Set `typ` to the result of IRI expanding type, using local context,
// and defined.
let typ = expand_iri_with(
Environment {
vocabulary: env.vocabulary,
loader: env.loader,
warnings: env.warnings,
},
active_context,
type_.cast(),
false,
Some(options.vocab),
local_context,
defined,
remote_contexts.clone(),
options,
)
.await?;
if let Some(typ) = typ {
let typ = Arc::try_unwrap(typ).unwrap_or_else(|a| (*a).clone());
// If the expanded type is @json or @none, and processing mode is
// json-ld-1.0, an invalid type mapping error has been detected and
// processing is aborted.
if options.processing_mode == ProcessingMode::JsonLd1_0
&& (typ == Term::Keyword(Keyword::Json) || typ == Term::Keyword(Keyword::None))
{
return Err(Error::InvalidTypeMapping);
}
if let Ok(typ) = typ.try_into() {
// Set the type mapping for definition to type.
definition.typ = Some(typ);
} else {
return Err(Error::InvalidTypeMapping);
}
}
}
// If `value` contains the entry @reverse:
if let Some(reverse_value) = value.reverse {
// If `value` contains `@id` or `@nest`, entries, an invalid reverse
// property error has been detected and processing is aborted.
if value.id.is_some() || value.nest.is_some() {
return Err(Error::InvalidReverseProperty);
}
// If the value associated with the @reverse entry is a string having
// the form of a keyword, return; processors SHOULD generate a warning.
if reverse_value.is_keyword_like() {
env.warnings.handle(env.vocabulary, Warning::KeywordLikeValue(reverse_value.to_string()));
return Ok(());
}
// Otherwise, set the IRI mapping of definition to the result of IRI
// expanding the value associated with the @reverse entry, using
// local context, and defined.
// If the result does not have the form of an IRI or a blank node
// identifier, an invalid IRI mapping error has been detected and
// processing is aborted.
match expand_iri_with(
Environment {
vocabulary: env.vocabulary,
loader: env.loader,
warnings: env.warnings,
},
active_context,
Nullable::Some(reverse_value.as_str().into()),
false,
Some(options.vocab),
local_context,
defined,
remote_contexts.clone(),
options,
)
.await?
{
Some(arc) if matches!(arc.as_ref(), Term::Id(m) if m.is_valid()) => definition.value = Some(arc),
_ => return Err(Error::InvalidIriMapping),
}
// If `value` contains an `@container` entry, set the `container`
// mapping of `definition` to an array containing its value;
// if its value is neither `@set`, nor `@index`, nor null, an
// invalid reverse property error has been detected (reverse properties
// only support set- and index-containers) and processing is aborted.
if let Some(container_value) = value.container {
match container_value {
Nullable::Null => (),
Nullable::Some(container_value) => {
let container_value = Container::from_syntax(Nullable::Some(container_value)).map_err(|_| Error::InvalidReverseProperty)?;
if matches!(container_value, Container::Set | Container::Index) {
definition.container = container_value;
} else {
return Err(Error::InvalidReverseProperty);
}
}
}
}
// Set the `reverse_property` flag of `definition` to `true`.
definition.reverse_property = true;
}
// The specification's step 14 onwards is skipped for reverse
// properties: as amended, the algorithm falls through from
// `@reverse` but takes the "Otherwise" branch. See
// https://github.com/w3c/json-ld-api/issues/565.
if !definition.reverse_property {
match value.id {
// If `value` contains the entry `@id` and its value does not equal `term`:
Some(id_value) if id_value.cast::<KeyOrKeywordRef>() != Nullable::Some(key.into()) => {
match id_value {
// If the `@id` entry of value is `null`, the term is not used for IRI
// expansion, but is retained to be able to detect future redefinitions
// of this term.
Nullable::Null => (),
Nullable::Some(id_value) => {
// Otherwise:
// If the value associated with the `@id` entry is not a
// keyword, but has the form of a keyword, return;
// processors SHOULD generate a warning.
if id_value.is_keyword_like() && !id_value.is_keyword() {
debug_assert!(Keyword::try_from(id_value.as_str()).is_err());
env.warnings.handle(env.vocabulary, Warning::KeywordLikeValue(id_value.to_string()));
return Ok(());
}
// Otherwise, set the IRI mapping of `definition` to the result
// of IRI expanding the value associated with the `@id` entry,
// using `local_context`, and `defined`.
definition.value = match expand_iri_with(
Environment {
vocabulary: env.vocabulary,
loader: env.loader,
warnings: env.warnings,
},
active_context,
Nullable::Some(id_value.into()),
false,
Some(options.vocab),
local_context,
defined,
remote_contexts.clone(),
options,
)
.await?
{
Some(arc) if arc.as_ref() == &Term::Keyword(Keyword::Context) => {
// if it equals `@context`, an invalid keyword alias error has
// been detected and processing is aborted.
return Err(Error::InvalidKeywordAlias);
}
Some(arc) if matches!(arc.as_ref(), Term::Id(p) if !p.is_valid()) => {
// If the resulting IRI mapping is neither a keyword,
// nor an IRI, nor a blank node identifier, an
// invalid IRI mapping error has been detected and processing
// is aborted;
return Err(Error::InvalidIriMapping);
}
value => value,
};
// If `term` contains a colon (:) anywhere but as the first or
// last character of `term`, or if it contains a slash (/)
// anywhere:
//
// This round-trip check was introduced in JSON-LD 1.1; 1.0 let
// a term that looks like a compact IRI expand to something else
// (`expand#t0026`, `expand#t0071`).
if options.processing_mode != ProcessingMode::JsonLd1_0
&& (contains_between_boundaries(key.as_str(), ':') || key.as_str().contains('/'))
{
// Set the value associated with `defined`'s `term` entry
// to `true`.
defined.end(&term);
// If the result of IRI expanding `term` using
// `local_context`, and `defined`, is not the same as the
// IRI mapping of definition, an invalid IRI mapping error
// has been detected and processing is aborted.
let expanded_term = expand_iri_with(
Environment {
vocabulary: env.vocabulary,
loader: env.loader,
warnings: env.warnings,
},
active_context,
Nullable::Some((&term).into()),
false,
Some(options.vocab),
local_context,
defined,
remote_contexts.clone(),
options,
)
.await?;
if definition.value.as_deref() != expanded_term.as_deref() {
return Err(Error::InvalidIriMapping);
}
}
// If `term` contains neither a colon (:) nor a slash (/),
// simple term is true, and if the IRI mapping of definition
// is either an IRI ending with a gen-delim character,
// or a blank node identifier, set the `prefix` flag in
// `definition` to true.
if !key.as_str().contains(':')
&& !key.as_str().contains('/')
&& simple_term
&& definition.value.as_ref().is_some_and(|v| is_gen_delim_or_blank(env.vocabulary, v))
{
definition.prefix = true;
}
}
}
}
Some(Nullable::Some(IdRef::Keyword(Keyword::Type))) => {
// Otherwise, if `term` is ``@type`, set the IRI mapping of definition to
// `@type`.
definition.value = Some(Arc::new(Term::Keyword(Keyword::Type)));
}
_ => {
// Otherwise if the `term` contains a colon (:) anywhere after the first
// character.
if let KeyOrKeyword::Key(term) = &term {
if let Ok(compact_iri) = CompactIri::new(term.as_str()) {
// If `term` is a compact IRI with a prefix that is an entry in local
// context a dependency has been found.
// Use this algorithm recursively passing `active_context`,
// `local_context`, the prefix as term, and `defined`.
Recursion::new(define(
Environment {
vocabulary: env.vocabulary,
loader: env.loader,
warnings: env.warnings,
},
active_context,
local_context,
KeyOrKeywordRef::Key(compact_iri.prefix().into()),
defined,
remote_contexts.clone(),
None,
false,
options.with_no_override(),
))
.await?;
// If `term`'s prefix has a term definition in `active_context`, set the
// IRI mapping of `definition` to the result of concatenating the value
// associated with the prefix's IRI mapping and the term's suffix.
if let Some(prefix_definition) = active_context.get(compact_iri.prefix()) {
let mut result = String::new();
if let Some(prefix_key) = prefix_definition.value()
&& let Some(prefix_iri) = prefix_key.as_iri()
&& let Some(iri) = env.vocabulary.iri(prefix_iri)
{
result = iri.to_string();
}
result.push_str(compact_iri.suffix());
if let Ok(iri) = Iri::parse(result.as_str()) {
definition.value = Some(Arc::new(Term::Id(Id::iri(env.vocabulary.insert(iri)))));
} else {
return Err(Error::InvalidIriMapping);
}
}
}
// not a compact IRI
if definition.value.is_none() {
if let Ok(blank_id) = BlankId::new(term.as_str()) {
definition.value = Some(Arc::new(Term::Id(Id::blank(env.vocabulary.insert_blank_id(blank_id)))));
} else if let Ok(iri_ref) = IriRef::parse(term.as_str()) {
match Iri::try_from(iri_ref) {
Ok(iri) => definition.value = Some(Arc::new(Term::Id(Id::iri(env.vocabulary.insert(iri))))),
Err(_) => {
if iri_ref.as_str().contains('/') {
// Term is a relative IRI reference.
// Set the IRI mapping of definition to the result of IRI expanding
// term.
match expand_iri_simple(
&mut env,
active_context,
Nullable::Some(ExpandableRef::String(iri_ref.as_str())),
false,
Some(options.vocab),
)? {
Some(arc) if matches!(arc.as_ref(), Term::Id(Id::Valid(ValidId::Iri(_)))) => {
definition.value = Some(arc);
}
// If the resulting IRI mapping is not an IRI, an invalid IRI mapping
// error has been detected and processing is aborted.
_ => return Err(Error::InvalidIriMapping),
}
}
}
}
}
// not a compact IRI, IRI, IRI reference or blank node id.
if definition.value.is_none() {
if let Some(context_vocabulary) = active_context.vocabulary() {
// Otherwise, if `active_context` has a vocabulary mapping, the IRI mapping
// of `definition` is set to the result of concatenating the value
// associated with the vocabulary mapping and `term`.
// If it does not have a vocabulary mapping, an invalid IRI mapping error
// has been detected and processing is aborted.
if let Some(vocabulary_iri) = context_vocabulary.as_iri() {
let mut result = env.vocabulary.iri(vocabulary_iri).map(|i| i.to_string()).unwrap_or_default();
result.push_str(key.as_str());
if let Ok(iri) = Iri::parse(result.as_str()) {
definition.value = Some(Arc::new(Term::<N::Iri, N::BlankId>::from(env.vocabulary.insert(iri))));
} else {
return Err(Error::InvalidIriMapping);
}
} else {
return Err(Error::InvalidIriMapping);
}
} else {
// If it does not have a vocabulary mapping, an invalid IRI mapping error
// has been detected and processing is aborted.
return Err(Error::InvalidIriMapping);
}
}
}
}
}
}
}
// If value contains the entry @container:
if let Some(container_value) = value.container {
// If the container value is @graph, @id, or @type, or is otherwise not a
// string, generate an invalid container mapping error and abort processing
// if processing mode is json-ld-1.0.
if options.processing_mode == ProcessingMode::JsonLd1_0 {
match container_value {
Nullable::Null
| Nullable::Some(
jsonld_syntax::Container::Many(_)
| jsonld_syntax::Container::One(ContainerKind::Graph | ContainerKind::Id | ContainerKind::Type),
) => return Err(Error::InvalidContainerMapping),
Nullable::Some(_) => (),
}
}
let container_value = Container::from_syntax(container_value).map_err(|_| Error::InvalidContainerMapping)?;
// Initialize `container` to the value associated with the `@container`
// entry, which MUST be either `@graph`, `@id`, `@index`, `@language`,
// `@list`, `@set`, `@type`, or an array containing exactly any one of
// those keywords, an array containing `@graph` and either `@id` or
// `@index` optionally including `@set`, or an array containing a
// combination of `@set` and any of `@index`, `@graph`, `@id`, `@type`,
// `@language` in any order.
// Otherwise, an invalid container mapping has been detected and processing
// is aborted.
definition.container = container_value;
// Set the container mapping of definition to container coercing to an
// array, if necessary.
// already done.
// If the `container` mapping of definition includes `@type`:
if definition.container.contains(ContainerKind::Type) {
if let Some(typ) = &definition.typ {
// If type mapping in definition is neither `@id` nor `@vocab`,
// an invalid type mapping error has been detected and processing
// is aborted.
match typ {
Type::Id | Type::Vocab => (),
_ => return Err(Error::InvalidTypeMapping),
}
} else {
// If type mapping in definition is undefined, set it to @id.
definition.typ = Some(Type::Id);
}
}
}
// If value contains the entry @index:
if let Some(index_value) = value.index {
// If processing mode is json-ld-1.0 or container mapping does not include
// `@index`, an invalid term definition has been detected and processing
// is aborted.
if !definition.container.contains(ContainerKind::Index) || options.processing_mode == ProcessingMode::JsonLd1_0 {
return Err(Error::InvalidTermDefinition);
}
// Initialize `index` to the value associated with the `@index` entry,
// which MUST be a string expanding to an IRI.
// Otherwise, an invalid term definition has been detected and processing
// is aborted.
match expand_iri_simple(
&mut env,
active_context,
Nullable::Some(index_value.as_str().into()),
false,
Some(options.vocab),
)?
.as_deref()
{
Some(Term::Id(Id::Valid(ValidId::Iri(_)))) => (),
_ => return Err(Error::InvalidTermDefinition),
}
definition.index = Some(index_value.to_owned());
}
// If `value` contains the entry `@context`:
if let Some(context) = value.context {
// If processing mode is json-ld-1.0, an invalid term definition has been
// detected and processing is aborted.
if options.processing_mode == ProcessingMode::JsonLd1_0 {
return Err(Error::InvalidTermDefinition);
}
// Initialize `context` to the value associated with the @context entry,
// which is treated as a local context.
// done.
// Invoke the Context Processing algorithm using the `active_context`,
// `context` as local context, `base_url`, `true` for override protected,
// a copy of remote contexts, and `false` for validate scoped context.
// If any error is detected, an invalid scoped context error has been
// detected and processing is aborted.
Recursion::new(super::process_context(
env,
active_context,
context,
remote_contexts.clone(),
base_url.clone(),
options.with_override(),
false,
))
.await
.map_err(|e| match e {
// A resource-limit abort is not a context error:
// let it surface instead of masking it.
Error::ContextOverflow => Error::ContextOverflow,
_ => Error::InvalidScopedContext,
})?;
// Set the local context of definition to context, and base URL to base URL.
definition.context = Some(Box::new(context.clone()));
definition.base_url = base_url;
}
// If `value` contains the entry `@language` and does not contain the entry
// `@type`:
if value.type_.is_none() {
if let Some(language_value) = value.language {
// Initialize `language` to the value associated with the `@language`
// entry, which MUST be either null or a string.
// If `language` is not well-formed according to section 2.2.9 of
// [BCP47], processors SHOULD issue a warning.
// Otherwise, an invalid language mapping error has been detected and
// processing is aborted.
// Set the `language` mapping of definition to `language`.
definition.language = Some(language_value.map(LenientLangTag::to_owned));
}
// If `value` contains the entry `@direction` and does not contain the
// entry `@type`:
if let Some(direction_value) = value.direction {
// Initialize `direction` to the value associated with the `@direction`
// entry, which MUST be either null, "ltr", or "rtl".
definition.direction = Some(direction_value);
}
}
// If value contains the entry @nest:
if let Some(nest_value) = value.nest {
// If processing mode is json-ld-1.0, an invalid term definition has been
// detected and processing is aborted.
if options.processing_mode == ProcessingMode::JsonLd1_0 {
return Err(Error::InvalidTermDefinition);
}
definition.nest = Some(nest_value.clone());
}
// If value contains the entry @prefix:
if let Some(prefix_value) = value.prefix {
// If processing mode is json-ld-1.0, or if `term` contains a colon (:) or
// slash (/), an invalid term definition has been detected and processing
// is aborted.
if key.as_str().contains(':') || key.as_str().contains('/') || options.processing_mode == ProcessingMode::JsonLd1_0 {
return Err(Error::InvalidTermDefinition);
}
// Set the `prefix` flag to the value associated with the @prefix entry,
// which MUST be a boolean.
// Otherwise, an invalid @prefix value error has been detected and
// processing is aborted.
definition.prefix = prefix_value;
// If the `prefix` flag of `definition` is set to `true`, and its IRI
// mapping is a keyword, an invalid term definition has been detected and
// processing is aborted.
if definition.prefix && definition.value.as_ref().is_some_and(|v| v.is_keyword()) {
return Err(Error::InvalidTermDefinition);
}
}
// If value contains any entry other than @id, @reverse, @container, @context,
// @direction, @index, @language, @nest, @prefix, @protected, or @type, an
// invalid term definition error has been detected and processing is aborted.
if value.propagate.is_some() {
return Err(Error::InvalidTermDefinition);
}
// If override protected is false and previous_definition exists and is protected;
if !options.override_protected
&& let Some(previous_definition) = previous_definition
&& previous_definition.protected
{
// If `definition` is not the same as `previous_definition`
// (other than the value of protected), a protected term
// redefinition error has been detected, and processing is aborted.
if definition.modulo_protected_field() != previous_definition.modulo_protected_field() {
return Err(Error::ProtectedTermRedefinition);
}
// Set `definition` to `previous definition` to retain the value of
// protected.
definition.protected = true;
}
// Set the term definition of `term` in `active_context` to `definition` and
// set the value associated with `defined`'s entry term to true.
active_context.set_normal(key.to_owned(), Some(definition));
}
_ => {
// Otherwise, since keywords cannot be overridden, term MUST NOT be a keyword and
// a keyword redefinition error has been detected and processing is aborted.
return Err(Error::KeywordRedefinition);
}
}
}
defined.end(&term);
}
Ok(())
}