summaryrefslogtreecommitdiff
path: root/src/context.rs
blob: 18b556caf02d25c3508005c02f0864e7ab46f7b2 (plain)
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
#![allow(dead_code, unused_variables, clippy::upper_case_acronyms)]
use std::{collections::HashMap, str::FromStr};
use json::{JsonValue, object::Object};
//use curl::Curl;

#[derive(Clone, Debug, PartialEq)]
pub enum Direction {
    LTR, RTL, NULL
}

impl FromStr for Direction {
    type Err = JsonLdError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s == "ltr" {
            Ok(Direction::LTR)
        } else if s == "rtl" {
            Ok(Direction::RTL)
        } else if s == "null" {
            Ok(Direction::NULL)
        } else {
            Err(JsonLdError::InvalidBaseDirection)
        }
    }
}

#[derive(Clone, Default, Debug, PartialEq)]
pub struct Context {
    remote_iri: String,
    base_iri: String,
    original_iri: String,
    // inverse context
    vocab: Option<String>,
    default_language: Option<String>,
    base_direction: Option<Direction>,
    previous_context: Option<Box<Context>>,
    terms: HashMap<String, Term>
}

#[derive(Clone, Default, Debug, PartialEq)]
pub struct Term {
    iri_mapping: String,
    prefix: bool,
    protected: bool,
    reverse: bool,
    base_iri: Option<String>,
    context: Option<Context>,
    container: Option<Vec<String>>,
    direction: Option<Direction>,
    index: Option<String>,
    language: Option<String>,
    nest: Option<String>,
    term_type: Option<String>
}

#[derive(Debug)]
pub enum JsonLdError {
    CollidingKeywords,
    ConflictingIndexes,
    ContextOverflow,
    CyclicIRIMapping,
    InvalidIdValue,
    InvalidImportValue,
    InvalidIncludedValue,
    InvalidIndexValue,
    InvalidNestValue,
    InvalidPrefixValue,
    InvalidPropagateValue,
    InvalidProtectedValue,
    InvalidReverseValue,
    InvalidVersionValue,
    InvalidBaseDirection,
    InvalidBaseIRI,
    InvalidContainerMapping,
    InvalidContextEntry,
    InvalidContextNullification,
    InvalidDefaultLanguage,
    InvalidIRIMapping,
    InvalidJSONLiteral,
    InvalidKeywordAlias,
    InvalidLanguageMapValue,
    InvalidLanguageMapping,
    InvalidLanguageTaggedString,
    InvalidLanguageTaggedValue,
    InvalidLocalContext,
    InvalidRemoteContext,
    InvalidReversePropertyMap,
    InvalidReversePropertyValue,
    InvalidReverseProperty,
    InvalidScopedContext,
    InvalidScriptElement,
    InvalidSetOrListObject,
    InvalidTermDefinition,
    InvalidTypeMapping,
    InvalidTypeValue,
    InvalidTypedValue,
    InvalidValueObjectValue,
    InvalidValueObject,
    InvalidVocabMapping,
    IRIConfusedWithPrefix,
    KeywordRedefinition,
    LoadingDocumentFailed,
    LoadingRemoteContextFailed,
    MultipleContextLinkHeaders,
    ProcessingModeConflict,
    ProtectedTermRedefinition
}

struct ContextOpts {
    override_protected: Option<bool>,
    propagate: Option<bool>,
    validate_scoped: Option<bool>
}

impl ContextOpts {
    fn new(override_protected: Option<bool>, propagate: Option<bool>, validate_scoped: Option<bool>) -> Self {
        Self { override_protected, propagate, validate_scoped }
    }
}

#[derive(Default)]
struct TermOpts {
    override_protected: Option<bool>,
    protected: Option<bool>,
    validate_scoped: Option<bool>
}

impl TermOpts {
    fn new(override_protected: Option<bool>, protected: Option<bool>, validate_scoped: Option<bool>) -> Self {
        Self { override_protected, protected, validate_scoped }
    }
}

pub impl From<JsonValue> for Context {
    
}

impl Context {
    fn parse_context(active_context: &mut Context, local_context: &JsonValue, base_url: &String,
                         remote_contexts: Option<Vec<Context>>, opts: ContextOpts) -> Result<Context, JsonLdError> {
        let mut result = active_context.clone();
        let remote_contexts = remote_contexts.unwrap_or(Vec::new());
        let override_protected = opts.override_protected.unwrap_or(false);
        let mut propagate = opts.propagate.unwrap_or(true);
        let validate_scoped = opts.validate_scoped.unwrap_or(true);
        let local_context = local_context.clone();

        let local_context = match local_context {
            JsonValue::Array(ctx) => ctx,
            JsonValue::Object(ref ctx) => {
                // TODO: can we move this later so we don't need to check for Object(_) twice?
                if let Some(prop) = ctx.get("@propagate") {
                    if let JsonValue::Boolean(prop) = prop {
                        propagate = *prop;
                    } else {
                        return Err(JsonLdError::InvalidPropagateValue);
                    }
                }
                vec![local_context]
            }
            _ => vec![local_context]
        };

        if !propagate && result.previous_context.is_none() {
            result.previous_context = Some(Box::new(active_context.clone()));
        }

        for context in local_context {
            let context = match &context {
                JsonValue::Null => {
                    if !override_protected {
                        for term in active_context.terms.values() {
                            if term.protected {
                                return Err(JsonLdError::InvalidContextNullification);
                            }
                        }
                    }
                    let old_result = result;
                    result = Context::default();
                    result.base_iri = base_url.clone();
                    result.original_iri = base_url.clone();
                    if !propagate {
                        result.previous_context = Some(Box::new(old_result));
                    }
                    continue;
                },
                JsonValue::String(value) => {
                    todo!()
                    // Remote context stuff
                },
                JsonValue::Object(definition) => definition,
                _ => { return Err(JsonLdError::InvalidLocalContext); }
            };

            let mut defined: HashMap<String, bool> = HashMap::new();

            if let Some(version) = context.get("@version") {
                if let JsonValue::String(version) = version {
                    if version != "1.1" {
                        return Err(JsonLdError::InvalidVersionValue);
                    }
                } else {
                    return Err(JsonLdError::InvalidVersionValue);
                }
            }

            if let Some(import) = context.get("@import") {
                if let JsonValue::String(import) = import {
                    todo!()
                } else {
                    return Err(JsonLdError::InvalidImportValue);
                }
            }

            if let Some(base) = context.get("@base") {
                if !remote_contexts.is_empty() {
                    match base {
                        JsonValue::Null => {
                            result.base_iri.clear();
                        }
                        JsonValue::String(base) => {
                            if base.contains("://") {
                                result.base_iri = base.to_string();
                            } else if base.contains(':') {
                                todo!();
                            } else {
                                return Err(JsonLdError::InvalidBaseIRI);
                            }
                        }
                        _ => return Err(JsonLdError::InvalidBaseIRI)
                    }
                }
            }

            if let Some(vocab) = context.get("@vocab") {
                match vocab {
                    JsonValue::Null => {
                        result.vocab = None;
                    },
                    JsonValue::String(vocab) => {
                        if vocab.contains("://") || vocab.starts_with("_:") {
                            Context::iri_expansion(active_context, vocab, &mut defined, Some(true), None, Some(context))?;
                        }
                    },
                    _ => return Err(JsonLdError::InvalidVocabMapping)
                }
            }

            if let Some(language) = context.get("@language") {
                match language {
                    JsonValue::Null => {
                        result.default_language = None;
                    },
                    JsonValue::String(language) => {
                        result.default_language = Some(language.to_string().to_lowercase());
                    },
                    _ => return Err(JsonLdError::InvalidDefaultLanguage)
                }
            }

            if let Some(direction) = context.get("@direction") {
                match direction {
                    JsonValue::Null => {
                        result.base_direction = None;
                    }
                    JsonValue::String(direction) => {
                        result.base_direction = Some(Direction::from_str(direction)?);
                    }
                    _ => return Err(JsonLdError::InvalidBaseDirection)
                }
            }

            if let Some(propagate) = context.get("@propagate") {
                if !propagate.is_boolean() {
                    return Err(JsonLdError::InvalidPropagateValue);
                }
            }

            let mut protected = false;
            if let Some(JsonValue::Boolean(prot)) = context.get("@protected") {
                protected = *prot;
            }

            for (key, term) in context.iter() {
                Context::create_term_definition(&mut result, context, (key, term), &mut defined, base_url,
                &remote_contexts, TermOpts::new(Some(protected), Some(override_protected), Some(validate_scoped)))?;
            }
        }

        Ok(result)
    }

    fn create_term_definition(active_context: &mut Context, local_context: &Object, term: (&str, &JsonValue),
                              defined: &mut HashMap<String, bool>, base_url: &String, remote_contexts: &Vec<Context>,
                              opts: TermOpts) -> Result<(), JsonLdError> {
        let protected = opts.protected.unwrap_or(false);
        let override_protected = opts.override_protected.unwrap_or(false);
        let validate_scoped = opts.validate_scoped.unwrap_or(true);
        let (key, term) = term;

        if key.starts_with('@') {
            return Err(JsonLdError::KeywordRedefinition);
        }

        if let Some(defined) = defined.get(key) {
            if *defined {
                return Ok(());
            } else {
                return Err(JsonLdError::CyclicIRIMapping);
            }
        }

        if key.is_empty() {
            return Err(JsonLdError::InvalidTermDefinition);
        }

        defined.insert(key.to_string(), false);

        let previous_definition = active_context.terms.remove(key);
        let value = match term {
            JsonValue::Null => {
                let mut obj = Object::new();
                obj.insert("@id", term.clone());
                obj
            }
            JsonValue::String(value) => {
                let mut obj = Object::new();
                obj.insert("@id", JsonValue::String(value.clone()));
                obj
            }
            JsonValue::Object(value) => value.clone(),
            _ => return Err(JsonLdError::InvalidTermDefinition)
        };

        let mut definition = Term {
            prefix: false,
            protected,
            reverse: false,
            ..Term::default()
        };

        let mut has_type = false;

        if let Some(protected) = value.get("@protected") {
            if let JsonValue::Boolean(protected) = protected {
                definition.protected = *protected;
            } else {
                return Err(JsonLdError::InvalidProtectedValue);
            }
        }

        if let Some(term_type) = value.get("@type") {
            has_type = true;
            if let JsonValue::String(term_type) = term_type {
                definition.term_type = Some(Context::iri_expansion(active_context, term_type, defined, None, None, Some(local_context))?);
            } else {
                return Err(JsonLdError::InvalidTypeValue);
            }
        }

        if let Some(reverse) = value.get("@reverse") {
            if let (Some(_), Some(_)) = (value.get("@id"), value.get("@nest")) {
                return Err(JsonLdError::InvalidReverseProperty);
            }

            if let JsonValue::String(reverse) = reverse {
                definition.iri_mapping = Context::iri_expansion(active_context, reverse, defined, None, None, Some(local_context))?;
                definition.reverse = true;
                if let Some(container) = value.get("@container") {
                    if container != "@set" && container != "@index" && container != "null" {
                        return Err(JsonLdError::InvalidReverseProperty);
                    }
                }
                active_context.terms.insert(key.to_string(), definition);
                defined.insert(key.to_string(), true);

                return Ok(());
            } else {
                return Err(JsonLdError::InvalidIRIMapping);
            }
        }

        if let Some(id) = value.get("@id") {
            match id {
                JsonValue::String(id) if id != key => {
                    let iri = Context::iri_expansion(active_context, id, defined, None, None, Some(local_context))?;
                    if !(iri.contains("://") || iri.starts_with("_:") || iri.starts_with('@')) {
                        return Err(JsonLdError::InvalidIRIMapping);
                    }
                    if iri == "@context" {
                        return Err(JsonLdError::InvalidKeywordAlias);
                    }
                    if key.contains(':') && !key.starts_with(':') && key.contains('/') {
                        defined.insert(key.to_string(), true);
                        let term = Context::iri_expansion(active_context, key, defined, None, None, Some(local_context))?;
                        if term != iri {
                            return Err(JsonLdError::InvalidIRIMapping);
                        }
                    } else if iri == "_" || (iri.contains("://") && iri.ends_with([':', '/', '?', '#', '[', ']', '@'])) {
                        definition.prefix = true;
                    }
                    definition.iri_mapping = iri;
                },
                _ => return Err(JsonLdError::InvalidIRIMapping)
            }
        } else if let Some(idx) = key.find(':') {
            let (prefix, suffix) = key.split_at(idx);
            if !suffix.starts_with('/') {
                if let Some(prefix_term) = local_context.get(prefix) {
                    Context::create_term_definition(active_context, local_context, (prefix, prefix_term), defined, 
                                                    base_url, remote_contexts, TermOpts::new(Some(protected),
                                                    Some(override_protected), Some(validate_scoped)))?;
                }
            }
        } else if key.contains('/') {
            let iri = Context::iri_expansion(active_context, key, defined, Some(true), Some(true), Some(local_context))?;
            if !iri.contains("://") {
                return Err(JsonLdError::InvalidIRIMapping);
            }
            definition.iri_mapping = iri;
        } else if key == "@type" {
            definition.iri_mapping = "@type".to_string();
        } else if let Some(vocab) = &active_context.vocab {
            definition.iri_mapping = format!("{}{}", vocab, key);
        } else {
            return Err(JsonLdError::InvalidIRIMapping);
        }

        if let Some(container) = value.get("@container") {
            todo!()
        }

        if let Some(index) = value.get("@index") {
            if let Some(container) = &definition.container {
                if let (JsonValue::String(index), true) = (index, container.contains(&"@index".to_string())) {
                    let iri = Context::iri_expansion(active_context, index, defined, None, None, Some(local_context))?;
                    if !iri.contains("://") {
                        return Err(JsonLdError::InvalidTermDefinition);
                    }
                } else {
                    return Err(JsonLdError::InvalidTermDefinition);
                }
            }
        }

        if let Some(context) = value.get("@context") {
            todo!()//Context::parse_context(active_context, context, base_url, Some(remote_contexts.clone()), Some(true), None, None)?;
        }

        if let (Some(lang), true) = (value.get("@language"), has_type) {
            definition.language = match lang {
                JsonValue::Null => None,
                JsonValue::String(str) => Some(str.to_owned()),
                _ => return Err(JsonLdError::InvalidLanguageMapping)
            }
        }

        if let (Some(direction), true) = (value.get("@direction"), has_type) {
            definition.direction = match direction {
                JsonValue::Null => Some(Direction::NULL),
                JsonValue::String(str) => Some(Direction::from_str(str)?),
                _ => return Err(JsonLdError::InvalidLanguageMapping)
            }
        }

        if let Some(nest) = value.get("@nest") {
            if let JsonValue::String(nest) = nest {
                definition.nest = if nest == "@nest" { Some("@nest".to_owned()) } else { return Err(JsonLdError::InvalidNestValue) };
            } else {
                return Err(JsonLdError::InvalidNestValue);
            }
        }

        if let Some(prefix) = value.get("@prefix") {
            if key.contains(':') || key.contains('/') {
                return Err(JsonLdError::InvalidTermDefinition);
            }

            if let JsonValue::Boolean(prefix) = prefix {
                if *prefix && definition.iri_mapping.starts_with('@') {
                    return Err(JsonLdError::InvalidTermDefinition);
                }
                definition.prefix = *prefix;
            }
        }

        if let (Some(prev), false) = (previous_definition, override_protected) {
            if prev.protected {
                if definition != prev {
                    return Err(JsonLdError::ProtectedTermRedefinition);
                }
                definition = prev;
            }
        }

        active_context.terms.insert(key.to_string(), definition);
        defined.insert(key.to_string(), true)  ;

        Ok(())
    }

    fn iri_expansion(active_context: &mut Context, value: &str, defined: &mut HashMap<String, bool>,
                     document_relative: Option<bool>, vocab: Option<bool>, local_context: Option<&Object>) -> Result<String, JsonLdError> {
        if value.starts_with('@') {
            return Ok(value.to_string());
        }

        let document_relative = document_relative.unwrap_or(false);
        let vocab = vocab.unwrap_or(false);

        if let Some(ctx) = local_context {
            if let Some(JsonValue::String(value)) = ctx.get(value) {
                if let Some(is_defined) = defined.get(value) {
                    if !*is_defined {
                        let term = ctx.get(value).unwrap();
                        Context::create_term_definition(active_context, ctx, (value, term), defined, &String::new(), &Vec::new(), TermOpts::default())?;
                    }
                }
            }
        }

        if let Some(term) = active_context.terms.get(value) {
            if term.iri_mapping.starts_with('@') || vocab {
                return Ok(term.iri_mapping.clone());
            }
        }

        let split_idx = value.find(':').unwrap_or(0);
        if split_idx > 0 {
            let (prefix, suffix) = value.split_at(split_idx);
            let suffix = &suffix[1..];
            if prefix == "_" || suffix.starts_with("//") {
                return Ok(value.to_string());
            }

            if let Some(ctx) = local_context {
                if let Some(JsonValue::String(value)) = ctx.get(prefix) {
                    if let Some(is_defined) = defined.get(value) {
                        if !is_defined {
                            let term = ctx.get(value).unwrap();
                            Context::create_term_definition(active_context, ctx, (value, term), defined, &String::new(), &Vec::new(), TermOpts::default())?;
                        }
                    }
                }
            }

            if let Some(term) = active_context.terms.get(prefix) {
                if term.prefix {
                    // TODO: concatenate this better
                    return Ok(format!("{}{}", term.iri_mapping, suffix));
                }
            }
        }

        if let Some(vocab_map) = &active_context.vocab {
            if vocab {
                return Ok(format!("{}{}", vocab_map, value));
            }
        }

        if document_relative {
            todo!()
        }

        Ok(value.to_string())
    }
}

#[cfg(test)]
mod tests {
    use std::{fs::File, path::Path, io::{Read, self}};

    use json::JsonValue;

    use super::{Context, ContextOpts};

    #[test]
    fn parse_context() -> Result<(), io::Error> {
        let mut json_context = String::new();
        File::open(Path::new("./person.jsonld"))?.read_to_string(&mut json_context)?;

        let context = match json::parse(json_context.as_str()).expect("Failed to parse example context") {
            JsonValue::Object(mut context) => context.remove("@context").unwrap(),
            _ => panic!()
        };

        let context = Context::parse_context(&mut Context::default(), &context, &"https://vlhl.dev".to_owned(), Some(Vec::new()), ContextOpts::new(Some(false), Some(true), Some(false)));

        println!("context: {:#?}", context);

        Ok(())
    }
}