gmeow-gts 0.9.5

GTS (Graph Transport Substrate) format engine: CBOR-sequence append-only RDF 1.2 log reader, folder, and verifier
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
// SPDX-FileCopyrightText: 2026 Blackcat InformaticsĀ® Inc. <paudley@blackcatinformatics.ca>
// SPDX-License-Identifier: MIT OR Apache-2.0

//! The `YAML-LD-star -> gts` transform: inverse of [`crate::yamlld`].
//!
//! The parser accepts the deterministic profile emitted by `yamlld`, plus the
//! compact context form used by downstream authoring tools. It builds a
//! canonical segment through [`crate::writer::Writer`] rather than preserving
//! source syntax.

use std::collections::HashMap;
use std::fmt;

use serde_json::{Map, Number, Value};

use crate::model::{Graph, Quad, Term, TermKind, Triple3};
use crate::writer::Writer;
use crate::yamlld::{
    ANNOTATION, GTS_GRAPH, GTS_REIFIERS, GTS_SUBJECT, GTS_TRIPLE, RDF_TYPE, XSD_BOOLEAN,
    XSD_DECIMAL, XSD_INTEGER,
};

/// Raised when YAML-LD-star or JSON-LD-star input is outside the GTS core profile.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct YamlLdParseError {
    detail: String,
}

impl YamlLdParseError {
    fn new(detail: impl Into<String>) -> Self {
        Self {
            detail: detail.into(),
        }
    }
}

impl fmt::Display for YamlLdParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.detail)
    }
}

impl std::error::Error for YamlLdParseError {}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum TermKey {
    Atom {
        kind: TermKind,
        value: String,
        lang: Option<String>,
        direction: Option<String>,
        datatype: Option<String>,
    },
    Triple(usize, usize, usize),
}

struct Interner {
    ids: HashMap<TermKey, usize>,
    terms: Vec<Term>,
    generated_bnodes: usize,
}

impl Interner {
    fn new() -> Self {
        Self {
            ids: HashMap::new(),
            terms: Vec::new(),
            generated_bnodes: 0,
        }
    }

    fn atom(
        &mut self,
        kind: TermKind,
        value: String,
        lang: Option<String>,
        direction: Option<String>,
        datatype: Option<String>,
    ) -> usize {
        let key = TermKey::Atom {
            kind,
            value: value.clone(),
            lang: lang.clone(),
            direction: direction.clone(),
            datatype: datatype.clone(),
        };
        if let Some(id) = self.ids.get(&key) {
            return *id;
        }
        let datatype_id = if kind == TermKind::Literal {
            datatype
                .as_ref()
                .map(|iri| self.atom(TermKind::Iri, iri.clone(), None, None, None))
        } else {
            None
        };
        let id = self.terms.len();
        self.terms.push(Term {
            kind,
            value: Some(value),
            datatype: datatype_id,
            lang,
            direction,
            reifier: None,
        });
        self.ids.insert(key, id);
        id
    }

    fn triple(&mut self, statement: Triple3, reifiers: &mut Vec<(usize, Triple3)>) -> usize {
        let key = TermKey::Triple(statement.0, statement.1, statement.2);
        if let Some(id) = self.ids.get(&key) {
            return *id;
        }
        let id = self.terms.len();
        self.terms.push(Term {
            kind: TermKind::Triple,
            value: None,
            datatype: None,
            lang: None,
            direction: None,
            reifier: Some(id),
        });
        self.ids.insert(key, id);
        set_reifier(reifiers, id, statement);
        id
    }

    fn generated_bnode(&mut self, prefix: &str) -> usize {
        loop {
            let label = format!("{prefix}{}", self.generated_bnodes);
            self.generated_bnodes += 1;
            let key = TermKey::Atom {
                kind: TermKind::Bnode,
                value: label.clone(),
                lang: None,
                direction: None,
                datatype: None,
            };
            if !self.ids.contains_key(&key) {
                return self.atom(TermKind::Bnode, label, None, None, None);
            }
        }
    }
}

#[derive(Clone, Debug)]
struct Context {
    prefixes: HashMap<String, String>,
}

impl Context {
    fn from_document(value: &Value) -> Self {
        let mut context = Self {
            prefixes: HashMap::from([
                (
                    "rdf".to_string(),
                    "http://www.w3.org/1999/02/22-rdf-syntax-ns#".to_string(),
                ),
                (
                    "xsd".to_string(),
                    "http://www.w3.org/2001/XMLSchema#".to_string(),
                ),
            ]),
        };
        if let Value::Object(map) = value {
            if let Some(raw) = map.get("@context") {
                context.merge(raw);
            }
        }
        context
    }

    fn merge(&mut self, value: &Value) {
        match value {
            Value::Array(items) => {
                for item in items {
                    self.merge(item);
                }
            }
            Value::Object(map) => {
                for (prefix, definition) in map {
                    match definition {
                        Value::String(iri) => {
                            self.prefixes.insert(prefix.clone(), iri.clone());
                        }
                        Value::Object(definition) => {
                            if let Some(Value::String(iri)) = definition.get("@id") {
                                self.prefixes.insert(prefix.clone(), iri.clone());
                            }
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }

    fn expand(&self, value: &str) -> String {
        if value.starts_with("_:") || value.starts_with('<') && value.ends_with('>') {
            return value
                .strip_prefix('<')
                .and_then(|inner| inner.strip_suffix('>'))
                .unwrap_or(value)
                .to_string();
        }
        let Some((prefix, suffix)) = value.split_once(':') else {
            return value.to_string();
        };
        match self.prefixes.get(prefix) {
            Some(base) => format!("{base}{suffix}"),
            None => value.to_string(),
        }
    }
}

/// Parse YAML-LD-star text into a canonical GTS file.
pub fn from_yaml_ld(text: &str) -> Result<Vec<u8>, YamlLdParseError> {
    let value: Value = serde_yaml::from_str(text)
        .map_err(|error| YamlLdParseError::new(format!("invalid YAML-LD: {error}")))?;
    from_json_ld_value(&value)
}

/// Parse JSON-LD-star text into a canonical GTS file.
pub fn from_json_ld(text: &str) -> Result<Vec<u8>, YamlLdParseError> {
    let value: Value = serde_json::from_str(text)
        .map_err(|error| YamlLdParseError::new(format!("invalid JSON-LD: {error}")))?;
    from_json_ld_value(&value)
}

fn from_json_ld_value(value: &Value) -> Result<Vec<u8>, YamlLdParseError> {
    let context = Context::from_document(value);
    let mut interner = Interner::new();
    let mut quads: Vec<Quad> = Vec::new();
    let mut reifiers: Vec<(usize, Triple3)> = Vec::new();
    let mut annotations: Vec<Triple3> = Vec::new();

    for node in graph_nodes(value)? {
        parse_node(
            node,
            &context,
            &mut interner,
            &mut quads,
            &mut reifiers,
            &mut annotations,
        )?;
    }
    if let Value::Object(map) = value {
        if let Some(blocks) = map.get(GTS_REIFIERS) {
            parse_standalone_reifiers(
                blocks,
                &context,
                &mut interner,
                &mut reifiers,
                &mut annotations,
            )?;
        }
    }

    let graph = Graph {
        terms: interner.terms,
        quads,
        reifiers,
        annotations,
        ..Graph::default()
    };
    let writer = Writer::deterministic(&graph, "dist")
        .map_err(|error| YamlLdParseError::new(format!("cannot author GTS: {error}")))?;
    Ok(writer.to_bytes())
}

fn graph_nodes(value: &Value) -> Result<Vec<&Value>, YamlLdParseError> {
    match value {
        Value::Array(nodes) => Ok(nodes.iter().collect()),
        Value::Object(map) => match map.get("@graph") {
            Some(Value::Array(nodes)) => Ok(nodes.iter().collect()),
            Some(_) => Err(YamlLdParseError::new("@graph must be an array")),
            None => Ok(vec![value]),
        },
        _ => Err(YamlLdParseError::new(
            "YAML-LD document must be a node or graph",
        )),
    }
}

fn parse_node(
    value: &Value,
    context: &Context,
    interner: &mut Interner,
    quads: &mut Vec<Quad>,
    reifiers: &mut Vec<(usize, Triple3)>,
    annotations: &mut Vec<Triple3>,
) -> Result<(), YamlLdParseError> {
    let map = object(value, "graph node")?;
    let scoped_context = scoped_context(context, map);
    let subject = match (map.get("@id"), map.get(GTS_SUBJECT)) {
        (Some(id), None) => parse_id(id, &scoped_context, interner)?,
        (None, Some(subject)) => parse_term(subject, false, &scoped_context, interner, reifiers)?,
        (Some(_), Some(_)) => {
            return Err(YamlLdParseError::new(
                "graph node cannot contain both @id and gts:subject",
            ))
        }
        (None, None) => return Err(YamlLdParseError::new("graph node is missing @id")),
    };

    for (key, raw_values) in map {
        if matches!(
            key.as_str(),
            "@context" | "@id" | "@graph" | GTS_SUBJECT | GTS_REIFIERS
        ) {
            continue;
        }
        let type_position = key == "@type";
        if key.starts_with('@') && !type_position {
            return Err(YamlLdParseError::new(format!(
                "unsupported node keyword {key}"
            )));
        }
        let predicate = predicate_id(key, &scoped_context, interner);
        parse_property_values(
            raw_values,
            type_position,
            subject,
            predicate,
            &scoped_context,
            interner,
            quads,
            reifiers,
            annotations,
        )?;
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn parse_property_values(
    value: &Value,
    type_position: bool,
    subject: usize,
    predicate: usize,
    context: &Context,
    interner: &mut Interner,
    quads: &mut Vec<Quad>,
    reifiers: &mut Vec<(usize, Triple3)>,
    annotations: &mut Vec<Triple3>,
) -> Result<(), YamlLdParseError> {
    match value {
        Value::Array(items) => {
            for item in items {
                parse_property_values(
                    item,
                    type_position,
                    subject,
                    predicate,
                    context,
                    interner,
                    quads,
                    reifiers,
                    annotations,
                )?;
            }
        }
        item => {
            let active_context = match item {
                Value::Object(map) => scoped_context(context, map),
                _ => context.clone(),
            };
            let object_id = parse_term(item, type_position, &active_context, interner, reifiers)?;
            let graph_name = match item {
                Value::Object(map) => map
                    .get(GTS_GRAPH)
                    .map(|value| parse_term(value, false, &active_context, interner, reifiers))
                    .transpose()?,
                _ => None,
            };
            quads.push((subject, predicate, object_id, graph_name));
            if let Value::Object(map) = item {
                if let Some(blocks) = map.get(ANNOTATION) {
                    parse_annotation_blocks(
                        blocks,
                        (subject, predicate, object_id),
                        &active_context,
                        interner,
                        reifiers,
                        annotations,
                    )?;
                }
            }
        }
    }
    Ok(())
}

fn parse_standalone_reifiers(
    value: &Value,
    context: &Context,
    interner: &mut Interner,
    reifiers: &mut Vec<(usize, Triple3)>,
    annotations: &mut Vec<Triple3>,
) -> Result<(), YamlLdParseError> {
    match value {
        Value::Array(items) => {
            for item in items {
                parse_standalone_reifiers(item, context, interner, reifiers, annotations)?;
            }
        }
        item => {
            let map = object(item, "gts:reifiers entry")?;
            let scoped_context = scoped_context(context, map);
            let reifier = match map.get("@id") {
                Some(id) => parse_id(id, &scoped_context, interner)?,
                None => interner.generated_bnode("gts_reifier_"),
            };
            let triple = map
                .get(GTS_TRIPLE)
                .ok_or_else(|| YamlLdParseError::new("gts:reifiers entry is missing gts:triple"))
                .and_then(|value| parse_triple(value, &scoped_context, interner, reifiers))?;
            set_reifier(reifiers, reifier, triple);
            if let Some(block) = map.get(ANNOTATION) {
                parse_annotation_properties(
                    object(block, "@annotation")?,
                    reifier,
                    &scoped_context,
                    interner,
                    reifiers,
                    annotations,
                )?;
            }
        }
    }
    Ok(())
}

fn parse_annotation_blocks(
    value: &Value,
    statement: Triple3,
    context: &Context,
    interner: &mut Interner,
    reifiers: &mut Vec<(usize, Triple3)>,
    annotations: &mut Vec<Triple3>,
) -> Result<(), YamlLdParseError> {
    match value {
        Value::Array(items) => {
            for item in items {
                parse_annotation_blocks(item, statement, context, interner, reifiers, annotations)?;
            }
        }
        item => {
            let map = object(item, "@annotation")?;
            let scoped_context = scoped_context(context, map);
            let reifier = match map.get("@id") {
                Some(id) => parse_id(id, &scoped_context, interner)?,
                None => interner.generated_bnode("gts_annotation_"),
            };
            set_reifier(reifiers, reifier, statement);
            parse_annotation_properties(
                map,
                reifier,
                &scoped_context,
                interner,
                reifiers,
                annotations,
            )?;
        }
    }
    Ok(())
}

fn parse_annotation_properties(
    map: &Map<String, Value>,
    reifier: usize,
    context: &Context,
    interner: &mut Interner,
    reifiers: &mut Vec<(usize, Triple3)>,
    annotations: &mut Vec<Triple3>,
) -> Result<(), YamlLdParseError> {
    let scoped_context = scoped_context(context, map);
    for (key, value) in map {
        if matches!(key.as_str(), "@context" | "@id") {
            continue;
        }
        let type_position = key == "@type";
        if key.starts_with('@') && !type_position {
            return Err(YamlLdParseError::new(format!(
                "unsupported annotation keyword {key}"
            )));
        }
        let predicate = predicate_id(key, &scoped_context, interner);
        match value {
            Value::Array(items) => {
                for item in items {
                    let object =
                        parse_term(item, type_position, &scoped_context, interner, reifiers)?;
                    annotations.push((reifier, predicate, object));
                }
            }
            item => {
                let object = parse_term(item, type_position, &scoped_context, interner, reifiers)?;
                annotations.push((reifier, predicate, object));
            }
        }
    }
    Ok(())
}

fn parse_term(
    value: &Value,
    type_position: bool,
    context: &Context,
    interner: &mut Interner,
    reifiers: &mut Vec<(usize, Triple3)>,
) -> Result<usize, YamlLdParseError> {
    match value {
        Value::String(text) if type_position => {
            Ok(interner.atom(TermKind::Iri, context.expand(text), None, None, None))
        }
        Value::String(text) => Ok(interner.atom(TermKind::Literal, text.clone(), None, None, None)),
        Value::Bool(flag) => Ok(interner.atom(
            TermKind::Literal,
            flag.to_string(),
            None,
            None,
            Some(XSD_BOOLEAN.to_string()),
        )),
        Value::Number(number) => Ok(number_literal(number, interner)),
        Value::Object(map) => {
            let scoped_context = scoped_context(context, map);
            if let Some(id) = map.get("@id") {
                return parse_id(id, &scoped_context, interner);
            }
            if let Some(value) = map.get("@value") {
                return parse_literal_object(value, map, &scoped_context, interner);
            }
            if let Some(triple) = map.get(GTS_TRIPLE) {
                let statement = parse_triple(triple, &scoped_context, interner, reifiers)?;
                return Ok(interner.triple(statement, reifiers));
            }
            Err(YamlLdParseError::new(
                "term object must contain @id, @value, or gts:triple",
            ))
        }
        Value::Array(_) => Err(YamlLdParseError::new(
            "nested arrays are not valid term values in the GTS YAML-LD profile",
        )),
        Value::Null => Err(YamlLdParseError::new(
            "null is not a valid term value in the GTS YAML-LD profile",
        )),
    }
}

fn parse_literal_object(
    value: &Value,
    map: &Map<String, Value>,
    context: &Context,
    interner: &mut Interner,
) -> Result<usize, YamlLdParseError> {
    let lexical = scalar_lexical(value)?;
    let lang = match map.get("@language") {
        Some(Value::String(lang)) => Some(lang.clone()),
        Some(_) => return Err(YamlLdParseError::new("@language must be a string")),
        None => None,
    };
    let direction = match map.get("@direction") {
        Some(Value::String(direction)) if matches!(direction.as_str(), "ltr" | "rtl") => {
            Some(direction.clone())
        }
        Some(Value::String(_)) => {
            return Err(YamlLdParseError::new(
                "@direction must be \"ltr\" or \"rtl\"",
            ))
        }
        Some(_) => return Err(YamlLdParseError::new("@direction must be a string")),
        None => None,
    };
    if direction.is_some() && lang.is_none() {
        return Err(YamlLdParseError::new(
            "@direction requires a language-tagged literal",
        ));
    }
    if lang.is_some() {
        if !matches!(value, Value::String(_)) {
            return Err(YamlLdParseError::new(
                "@value must be a string for language-tagged literals",
            ));
        }
        if map.contains_key("@type") {
            return Err(YamlLdParseError::new(
                "@type cannot be combined with @language or @direction",
            ));
        }
        return Ok(interner.atom(TermKind::Literal, lexical, lang, direction, None));
    }
    let datatype = match map.get("@type") {
        Some(Value::String(datatype)) => Some(context.expand(datatype)),
        Some(_) => return Err(YamlLdParseError::new("@type must be a string")),
        None => inferred_datatype(value),
    };
    Ok(interner.atom(TermKind::Literal, lexical, None, None, datatype))
}

fn parse_triple(
    value: &Value,
    context: &Context,
    interner: &mut Interner,
    reifiers: &mut Vec<(usize, Triple3)>,
) -> Result<Triple3, YamlLdParseError> {
    let map = object(value, "gts:triple")?;
    let subject = map
        .get("subject")
        .ok_or_else(|| YamlLdParseError::new("gts:triple is missing subject"))
        .and_then(|value| parse_term(value, false, context, interner, reifiers))?;
    let predicate = map
        .get("predicate")
        .ok_or_else(|| YamlLdParseError::new("gts:triple is missing predicate"))
        .and_then(|value| parse_term(value, true, context, interner, reifiers))?;
    let object = map
        .get("object")
        .ok_or_else(|| YamlLdParseError::new("gts:triple is missing object"))
        .and_then(|value| parse_term(value, false, context, interner, reifiers))?;
    Ok((subject, predicate, object))
}

fn parse_id(
    value: &Value,
    context: &Context,
    interner: &mut Interner,
) -> Result<usize, YamlLdParseError> {
    let Value::String(id) = value else {
        return Err(YamlLdParseError::new("@id must be a string"));
    };
    if let Some(label) = id.strip_prefix("_:") {
        Ok(interner.atom(TermKind::Bnode, label.to_string(), None, None, None))
    } else {
        Ok(interner.atom(TermKind::Iri, context.expand(id), None, None, None))
    }
}

fn predicate_id(key: &str, context: &Context, interner: &mut Interner) -> usize {
    let iri = if key == "@type" {
        RDF_TYPE.to_string()
    } else {
        context.expand(key)
    };
    interner.atom(TermKind::Iri, iri, None, None, None)
}

fn number_literal(number: &Number, interner: &mut Interner) -> usize {
    let datatype = if number.is_i64() || number.is_u64() {
        XSD_INTEGER
    } else {
        XSD_DECIMAL
    };
    interner.atom(
        TermKind::Literal,
        number.to_string(),
        None,
        None,
        Some(datatype.to_string()),
    )
}

fn scalar_lexical(value: &Value) -> Result<String, YamlLdParseError> {
    match value {
        Value::String(text) => Ok(text.clone()),
        Value::Bool(flag) => Ok(flag.to_string()),
        Value::Number(number) => Ok(number.to_string()),
        _ => Err(YamlLdParseError::new("@value must be a scalar")),
    }
}

fn inferred_datatype(value: &Value) -> Option<String> {
    match value {
        Value::Bool(_) => Some(XSD_BOOLEAN.to_string()),
        Value::Number(number) if number.is_i64() || number.is_u64() => {
            Some(XSD_INTEGER.to_string())
        }
        Value::Number(_) => Some(XSD_DECIMAL.to_string()),
        _ => None,
    }
}

fn object<'a>(value: &'a Value, what: &str) -> Result<&'a Map<String, Value>, YamlLdParseError> {
    match value {
        Value::Object(map) => Ok(map),
        _ => Err(YamlLdParseError::new(format!("{what} must be an object"))),
    }
}

fn scoped_context(parent: &Context, map: &Map<String, Value>) -> Context {
    let mut context = parent.clone();
    if let Some(local) = map.get("@context") {
        context.merge(local);
    }
    context
}

fn set_reifier(reifiers: &mut Vec<(usize, Triple3)>, rid: usize, statement: Triple3) {
    if let Some((_, existing)) = reifiers.iter_mut().find(|(candidate, _)| *candidate == rid) {
        *existing = statement;
    } else {
        reifiers.push((rid, statement));
    }
}