oxirs-ttl 0.2.4

Turtle-family RDF parser and serializer for OxiRS - ported from Oxigraph
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
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
//! TriG format parser and serializer
//!
//! TriG (Terse RDF Triple Language + Named Graphs) is an extension of Turtle
//! that adds support for named graphs. It allows you to group triples into
//! different graphs within a single document.
//!
//! # Format Overview
//!
//! - **Default Graph**: Triples outside any graph block
//! - **Named Graphs**: `<graph-iri> { triples... }`
//! - **GRAPH Keyword**: `GRAPH <graph-iri> { triples... }`
//! - **Prefixes**: Same as Turtle (`@prefix ex: <http://example.org/> .`)
//! - **Base IRI**: Same as Turtle (`@base <http://example.org/> .`)
//!
//! # Examples
//!
//! ## Basic TriG Parsing
//!
//! ```rust
//! use oxirs_ttl::trig::TriGParser;
//! use oxirs_ttl::Parser;
//! use std::io::Cursor;
//!
//! let trig_data = r#"
//! @prefix ex: <http://example.org/> .
//! ex:alice ex:knows ex:bob .
//! ex:graph1 {
//!     ex:alice ex:age 30 .
//!     ex:bob ex:age 28 .
//! }
//! "#;
//!
//! let parser = TriGParser::new();
//! let quads = parser.parse(Cursor::new(trig_data))?;
//! assert!(quads.len() >= 3);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Multiple Named Graphs
//!
//! ```rust
//! use oxirs_ttl::trig::TriGParser;
//! use oxirs_ttl::Parser;
//! use std::io::Cursor;
//!
//! let trig_data = r#"
//! @prefix ex: <http://example.org/> .
//! @prefix foaf: <http://xmlns.com/foaf/0.1/> .
//!
//! ex:people {
//!     ex:alice foaf:name "Alice" .
//!     ex:bob foaf:name "Bob" .
//! }
//!
//! ex:connections {
//!     ex:alice foaf:knows ex:bob .
//!     ex:bob foaf:knows ex:charlie .
//! }
//! "#;
//!
//! let parser = TriGParser::new();
//! let quads = parser.parse(Cursor::new(trig_data))?;
//!
//! // Check that we have quads in different graphs
//! let graphs: std::collections::HashSet<_> = quads.iter()
//!     .map(|q| q.graph_name())
//!     .collect();
//! assert!(graphs.len() >= 2);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Using GRAPH Keyword
//!
//! ```rust
//! use oxirs_ttl::trig::TriGParser;
//! use oxirs_ttl::Parser;
//! use std::io::Cursor;
//!
//! let trig_data = r#"
//! @prefix ex: <http://example.org/> .
//!
//! GRAPH ex:metadata {
//!     ex:document ex:createdAt "2025-11-29" .
//!     ex:document ex:author "Alice" .
//! }
//! "#;
//!
//! let parser = TriGParser::new();
//! let quads = parser.parse(Cursor::new(trig_data))?;
//! assert_eq!(quads.len(), 2);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Advanced Turtle Syntax in Graphs
//!
//! ```rust
//! use oxirs_ttl::trig::TriGParser;
//! use oxirs_ttl::Parser;
//! use std::io::Cursor;
//!
//! let trig_data = r#"
//! @prefix ex: <http://example.org/> .
//! ex:graph1 {
//!     ex:alice ex:name "Alice" ;
//!              ex:age 30 ;
//!              ex:city "Wonderland" .
//!     ex:bob ex:knows ex:alice, ex:charlie .
//!     ex:list ex:items (1 2 3 4 5) .
//! }
//! "#;
//!
//! let parser = TriGParser::new();
//! let quads = parser.parse(Cursor::new(trig_data))?;
//! assert!(quads.len() >= 3);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! ## Default and Named Graphs Mixed
//!
//! ```rust
//! use oxirs_ttl::trig::TriGParser;
//! use oxirs_ttl::Parser;
//! use std::io::Cursor;
//!
//! let trig_data = r#"
//! @prefix ex: <http://example.org/> .
//! ex:alice ex:type ex:Person .
//! ex:bob ex:type ex:Person .
//! ex:relationships {
//!     ex:alice ex:knows ex:bob .
//! }
//! ex:charlie ex:type ex:Person .
//! "#;
//!
//! let parser = TriGParser::new();
//! let quads = parser.parse(Cursor::new(trig_data))?;
//!
//! let default_graph_count = quads.iter()
//!     .filter(|q| q.graph_name().is_default_graph())
//!     .count();
//! assert!(default_graph_count >= 3);
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use crate::error::{TextPosition, TurtleParseError, TurtleResult, TurtleSyntaxError};
use crate::formats::turtle::TurtleParser;
use crate::toolkit::{Parser, Serializer};
use oxirs_core::model::{BlankNode, GraphName, Literal, NamedNode, Quad, Triple};
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Read, Write};

/// TriG parser with support for named graphs
///
/// TriG extends Turtle with the ability to group triples into named graphs.
/// This parser supports both default graph triples and named graph syntax.
///
/// # Examples
///
/// ```rust
/// use oxirs_ttl::trig::TriGParser;
/// use oxirs_ttl::Parser;
/// use std::io::Cursor;
///
/// let trig = r#"
/// @prefix ex: <http://example.org/> .
/// ex:graph1 {
///     ex:s ex:p ex:o .
/// }
/// "#;
///
/// let parser = TriGParser::new();
/// let quads = parser.parse(Cursor::new(trig))?;
/// assert!(!quads.is_empty());
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug, Clone)]
pub struct TriGParser {
    /// Whether to continue parsing after errors
    pub lenient: bool,
    /// Base IRI for resolving relative IRIs
    pub base_iri: Option<String>,
    /// Initial prefix declarations
    pub prefixes: HashMap<String, String>,
}

impl Default for TriGParser {
    fn default() -> Self {
        Self::new()
    }
}

impl TriGParser {
    /// Create a new TriG parser
    pub fn new() -> Self {
        let mut prefixes = HashMap::new();

        // Add common prefixes
        prefixes.insert(
            "rdf".to_string(),
            "http://www.w3.org/1999/02/22-rdf-syntax-ns#".to_string(),
        );
        prefixes.insert(
            "rdfs".to_string(),
            "http://www.w3.org/2000/01/rdf-schema#".to_string(),
        );
        prefixes.insert(
            "xsd".to_string(),
            "http://www.w3.org/2001/XMLSchema#".to_string(),
        );

        Self {
            lenient: false,
            base_iri: None,
            prefixes,
        }
    }

    /// Parse TriG content into quads
    fn parse_trig_content<R: BufRead>(&self, reader: R) -> TurtleResult<Vec<Quad>> {
        let mut quads = Vec::new();
        let mut current_graph = GraphName::DefaultGraph;
        let mut graph_depth = 0; // Track whether we're inside a named graph
        let mut prefixes = self.prefixes.clone();
        let mut base_iri = self.base_iri.clone();

        let content = {
            let mut buffer = String::new();
            let mut reader = reader;
            reader.read_to_string(&mut buffer).map_err(|e| {
                TurtleParseError::Io(std::io::Error::new(std::io::ErrorKind::Other, e))
            })?;
            buffer
        };

        // Simple line-by-line parsing for basic TriG support
        let lines: Vec<&str> = content.lines().collect();
        let mut i = 0;

        while i < lines.len() {
            let line = lines[i].trim();

            // Skip empty lines and comments
            if line.is_empty() || line.starts_with('#') {
                i += 1;
                continue;
            }

            // Handle prefix declarations
            if line.starts_with("@prefix") {
                // Parse: @prefix ex: <http://example.org/> .
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 3 {
                    let prefix = parts[1].trim_end_matches(':');
                    let iri = parts[2]
                        .trim_start_matches('<')
                        .trim_end_matches('>')
                        .trim_end_matches('.');
                    // Resolve prefix IRI against base if it's relative
                    let resolved_iri = Self::resolve_iri(iri, &base_iri);
                    prefixes.insert(prefix.to_string(), resolved_iri);
                }
                i += 1;
                continue;
            }

            // Handle base declarations
            if line.starts_with("@base") {
                // Parse: @base <http://example.org/> .
                let parts: Vec<&str> = line.split_whitespace().collect();
                if parts.len() >= 2 {
                    let iri = parts[1]
                        .trim_start_matches('<')
                        .trim_end_matches('>')
                        .trim_end_matches('.');
                    base_iri = Some(iri.to_string());
                }
                i += 1;
                continue;
            }

            // Check for named graph start
            if line.contains('{') && !line.ends_with('.') {
                // Parse graph name
                let graph_part = line.split('{').next().unwrap_or("").trim();

                if graph_part.starts_with("GRAPH") {
                    // GRAPH <iri> { syntax
                    let graph_iri = graph_part.strip_prefix("GRAPH").unwrap_or("").trim();
                    current_graph = self
                        .parse_graph_name_with_prefixes_and_base(graph_iri, &prefixes, &base_iri)?;
                } else if !graph_part.is_empty() {
                    // <iri> { syntax
                    current_graph = self.parse_graph_name_with_prefixes_and_base(
                        graph_part, &prefixes, &base_iri,
                    )?;
                } else {
                    current_graph = GraphName::DefaultGraph;
                }

                graph_depth += 1;
                i += 1;
                continue;
            }

            // Check for graph end
            if line.trim() == "}" {
                if graph_depth == 0 {
                    return Err(TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                        message: "Unexpected closing brace '}'".to_string(),
                        position: TextPosition::default(),
                    }));
                }
                graph_depth -= 1;
                current_graph = GraphName::DefaultGraph;
                i += 1;
                continue;
            }

            // Accumulate multi-line statements (handle semicolons and commas)
            if !line.is_empty()
                && !line.starts_with('@')
                && !line.contains('{')
                && line.trim() != "}"
            {
                // Strip inline comments from the line
                let line_without_comment = if let Some(comment_pos) = line.find('#') {
                    line[..comment_pos].trim_end()
                } else {
                    line
                };

                let mut statement = line_without_comment.to_string();

                // Track if we're inside a multiline string literal
                let count_triple_quotes =
                    |s: &str| s.matches("\"\"\"").count() + s.matches("'''").count();

                // Continue accumulating lines until we find one ending with '.'
                // but only if we're not inside a multiline string literal
                while i + 1 < lines.len() {
                    let inside_multiline = count_triple_quotes(&statement) % 2 == 1;
                    if !inside_multiline && statement.trim_end().ends_with('.') {
                        break;
                    }
                    i += 1;
                    let next_line = lines[i].trim();
                    // Stop if we hit a graph closing brace
                    if next_line == "}" {
                        i -= 1; // Back up so the main loop processes the '}'
                        break;
                    }
                    if !next_line.is_empty() && !next_line.starts_with('#') {
                        // Strip inline comments from the next line as well
                        let next_line_without_comment =
                            if let Some(comment_pos) = next_line.find('#') {
                                next_line[..comment_pos].trim_end()
                            } else {
                                next_line
                            };

                        if !next_line_without_comment.is_empty() {
                            // Preserve newlines for multiline string literals
                            statement.push('\n');
                            statement.push_str(next_line_without_comment);
                        }
                    }
                }

                // Parse the complete statement using Turtle parser
                if statement.trim_end().ends_with('.') {
                    match self.parse_triple_with_turtle(&statement, &prefixes, &base_iri) {
                        Ok(triples) => {
                            for triple in triples {
                                let quad = Quad::new(
                                    triple.subject().clone(),
                                    triple.predicate().clone(),
                                    triple.object().clone(),
                                    current_graph.clone(),
                                );
                                quads.push(quad);
                            }
                        }
                        Err(_e) if self.lenient => {
                            // In lenient mode, skip failed triples
                        }
                        Err(e) => return Err(e),
                    }
                } else if !statement.trim().is_empty() && !self.lenient {
                    // Statement doesn't end with '.' - this is invalid syntax
                    return Err(TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                        message: format!("Statement must end with '.': {}", statement.trim()),
                        position: TextPosition::default(),
                    }));
                }
            }

            i += 1;
        }

        // Check for unclosed graphs
        if graph_depth > 0 && !self.lenient {
            return Err(TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                message: "Unclosed graph: missing closing brace '}'".to_string(),
                position: TextPosition::default(),
            }));
        }

        Ok(quads)
    }

    /// Parse triple(s) using Turtle parser for full syntax support
    fn parse_triple_with_turtle(
        &self,
        content: &str,
        prefixes: &HashMap<String, String>,
        base_iri: &Option<String>,
    ) -> TurtleResult<Vec<Triple>> {
        // Create a complete Turtle document by prepending prefix/base declarations
        let mut document = String::new();

        // Add base declaration if present
        if let Some(base) = base_iri {
            document.push_str(&format!("@base <{}> .\n", base));
        }

        // Add prefix declarations
        for (prefix, iri) in prefixes {
            document.push_str(&format!("@prefix {}: <{}> .\n", prefix, iri));
        }

        // Add the statement
        document.push_str(content);

        let mut turtle_parser = TurtleParser::new();
        if self.lenient {
            turtle_parser.lenient = true;
        }

        turtle_parser.parse_document(&document)
    }

    // Legacy parsing methods - kept for potential future use but currently unused
    // as we now use TurtleParser for all triple parsing
    #[allow(dead_code)]
    fn parse_simple_triple(&self, line: &str) -> TurtleResult<Triple> {
        self.parse_simple_triple_with_prefixes(line, &self.prefixes)
    }

    #[allow(dead_code)]
    fn parse_simple_triple_with_prefixes(
        &self,
        line: &str,
        prefixes: &HashMap<String, String>,
    ) -> TurtleResult<Triple> {
        // This is a simplified parser - in production you'd want full Turtle parsing
        let line = line.trim_end_matches('.').trim();
        let parts: Vec<&str> = line.split_whitespace().collect();

        if parts.len() < 3 {
            return Err(TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                message: "Invalid triple syntax".to_string(),
                position: TextPosition::start(),
            }));
        }

        // Very basic parsing - this should use proper Turtle tokenization
        let subject = self.parse_term_as_subject_with_prefixes(parts[0], prefixes)?;
        let predicate = self.parse_term_as_predicate_with_prefixes(parts[1], prefixes)?;
        let object = self.parse_term_as_object_with_prefixes(&parts[2..].join(" "), prefixes)?;

        Ok(Triple::new(subject, predicate, object))
    }

    #[allow(dead_code)]
    fn parse_graph_name(&self, graph_str: &str) -> TurtleResult<GraphName> {
        self.parse_graph_name_with_prefixes(graph_str, &self.prefixes)
    }

    /// Parse a graph name with provided prefixes
    fn parse_graph_name_with_prefixes(
        &self,
        graph_str: &str,
        prefixes: &HashMap<String, String>,
    ) -> TurtleResult<GraphName> {
        self.parse_graph_name_with_prefixes_and_base(graph_str, prefixes, &None)
    }

    /// Parse a graph name with provided prefixes and base IRI
    fn parse_graph_name_with_prefixes_and_base(
        &self,
        graph_str: &str,
        prefixes: &HashMap<String, String>,
        base_iri: &Option<String>,
    ) -> TurtleResult<GraphName> {
        let graph_str = graph_str.trim();

        if graph_str.starts_with('<') && graph_str.ends_with('>') {
            let iri = graph_str.trim_start_matches('<').trim_end_matches('>');
            // Resolve relative IRI against base if needed
            let resolved_iri = Self::resolve_iri(iri, base_iri);
            let named_node = NamedNode::new(&resolved_iri).map_err(|e| {
                TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                    message: format!("Invalid IRI: {e}"),
                    position: TextPosition::start(),
                })
            })?;
            Ok(GraphName::NamedNode(named_node))
        } else if graph_str.starts_with("_:") {
            // Handle blank nodes as graph names
            let label = graph_str.trim_start_matches("_:");
            let blank_node = BlankNode::new(label).map_err(|e| {
                TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                    message: format!("Invalid blank node: {e}"),
                    position: TextPosition::start(),
                })
            })?;
            Ok(GraphName::BlankNode(blank_node))
        } else if graph_str.contains(':') {
            // Handle prefixed names
            let expanded = Self::expand_prefixed_name_static(graph_str, prefixes)?;
            let named_node = NamedNode::new(&expanded).map_err(|e| {
                TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                    message: format!("Invalid IRI: {e}"),
                    position: TextPosition::start(),
                })
            })?;
            Ok(GraphName::NamedNode(named_node))
        } else {
            Err(TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                message: format!("Invalid graph name: {graph_str}"),
                position: TextPosition::start(),
            }))
        }
    }

    /// Resolve a potentially relative IRI against a base IRI
    fn resolve_iri(iri: &str, base_iri: &Option<String>) -> String {
        // If IRI is already absolute (has a scheme), return as-is
        if iri.contains("://")
            || iri.starts_with("http:")
            || iri.starts_with("https:")
            || iri.starts_with("urn:")
        {
            return iri.to_string();
        }

        // If we have a base IRI, resolve against it
        if let Some(base) = base_iri {
            // Simple resolution: concatenate base + relative
            // For a production system, you'd want proper IRI resolution per RFC 3986
            if base.ends_with('/') || base.ends_with('#') {
                format!("{}{}", base, iri)
            } else {
                format!("{}/{}", base, iri)
            }
        } else {
            // No base IRI, return as-is
            iri.to_string()
        }
    }

    #[allow(dead_code)]
    fn expand_prefixed_name(&self, prefixed: &str) -> TurtleResult<String> {
        Self::expand_prefixed_name_static(prefixed, &self.prefixes)
    }

    /// Static version of expand_prefixed_name
    fn expand_prefixed_name_static(
        prefixed: &str,
        prefixes: &HashMap<String, String>,
    ) -> TurtleResult<String> {
        if let Some(colon_pos) = prefixed.find(':') {
            let prefix = &prefixed[..colon_pos];
            let local = &prefixed[colon_pos + 1..];

            if let Some(namespace) = prefixes.get(prefix) {
                Ok(format!("{namespace}{local}"))
            } else {
                Err(TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                    message: format!("Unknown prefix: {prefix}"),
                    position: TextPosition::start(),
                }))
            }
        } else {
            Err(TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                message: format!("Invalid prefixed name: {prefixed}"),
                position: TextPosition::start(),
            }))
        }
    }

    #[allow(dead_code)]
    fn parse_term_as_subject(&self, term: &str) -> TurtleResult<oxirs_core::model::Subject> {
        self.parse_term_as_subject_with_prefixes(term, &self.prefixes)
    }

    #[allow(dead_code)]
    fn parse_term_as_subject_with_prefixes(
        &self,
        term: &str,
        prefixes: &HashMap<String, String>,
    ) -> TurtleResult<oxirs_core::model::Subject> {
        use oxirs_core::model::{BlankNode, Subject};

        if term.starts_with('<') && term.ends_with('>') {
            let iri = term.trim_start_matches('<').trim_end_matches('>');
            let named_node = NamedNode::new(iri).map_err(|e| {
                TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                    message: format!("Invalid IRI: {e}"),
                    position: TextPosition::start(),
                })
            })?;
            Ok(Subject::NamedNode(named_node))
        } else if let Some(stripped) = term.strip_prefix("_:") {
            let blank_node = BlankNode::new(stripped).map_err(|e| {
                TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                    message: format!("Invalid blank node: {e}"),
                    position: TextPosition::start(),
                })
            })?;
            Ok(Subject::BlankNode(blank_node))
        } else if term.contains(':') {
            let expanded = Self::expand_prefixed_name_static(term, prefixes)?;
            let named_node = NamedNode::new(&expanded).map_err(|e| {
                TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                    message: format!("Invalid IRI: {e}"),
                    position: TextPosition::start(),
                })
            })?;
            Ok(Subject::NamedNode(named_node))
        } else {
            Err(TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                message: format!("Invalid subject: {term}"),
                position: TextPosition::start(),
            }))
        }
    }

    #[allow(dead_code)]
    fn parse_term_as_predicate(&self, term: &str) -> TurtleResult<oxirs_core::model::Predicate> {
        self.parse_term_as_predicate_with_prefixes(term, &self.prefixes)
    }

    #[allow(dead_code)]
    fn parse_term_as_predicate_with_prefixes(
        &self,
        term: &str,
        prefixes: &HashMap<String, String>,
    ) -> TurtleResult<oxirs_core::model::Predicate> {
        use oxirs_core::model::Predicate;

        if term == "a" {
            // Handle rdf:type abbreviation
            let rdf_type = NamedNode::new("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
                .expect("valid IRI");
            Ok(Predicate::NamedNode(rdf_type))
        } else if term.starts_with('<') && term.ends_with('>') {
            let iri = term.trim_start_matches('<').trim_end_matches('>');
            let named_node = NamedNode::new(iri).map_err(|e| {
                TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                    message: format!("Invalid IRI: {e}"),
                    position: TextPosition::start(),
                })
            })?;
            Ok(Predicate::NamedNode(named_node))
        } else if term.contains(':') {
            let expanded = Self::expand_prefixed_name_static(term, prefixes)?;
            let named_node = NamedNode::new(&expanded).map_err(|e| {
                TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                    message: format!("Invalid IRI: {e}"),
                    position: TextPosition::start(),
                })
            })?;
            Ok(Predicate::NamedNode(named_node))
        } else {
            Err(TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                message: format!("Invalid predicate: {term}"),
                position: TextPosition::start(),
            }))
        }
    }

    #[allow(dead_code)]
    fn parse_term_as_object(&self, term: &str) -> TurtleResult<oxirs_core::model::Object> {
        self.parse_term_as_object_with_prefixes(term, &self.prefixes)
    }

    #[allow(dead_code)]
    fn parse_term_as_object_with_prefixes(
        &self,
        term: &str,
        prefixes: &HashMap<String, String>,
    ) -> TurtleResult<oxirs_core::model::Object> {
        use oxirs_core::model::{BlankNode, Literal, Object};

        let term = term.trim();

        if term.starts_with('"') && term.ends_with('"') {
            // String literal
            let content = &term[1..term.len() - 1];
            let literal = Literal::new_simple_literal(content);
            Ok(Object::Literal(literal))
        } else if term.starts_with('<') && term.ends_with('>') {
            let iri = term.trim_start_matches('<').trim_end_matches('>');
            let named_node = NamedNode::new(iri).map_err(|e| {
                TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                    message: format!("Invalid IRI: {e}"),
                    position: TextPosition::start(),
                })
            })?;
            Ok(Object::NamedNode(named_node))
        } else if let Some(stripped) = term.strip_prefix("_:") {
            let blank_node = BlankNode::new(stripped).map_err(|e| {
                TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                    message: format!("Invalid blank node: {e}"),
                    position: TextPosition::start(),
                })
            })?;
            Ok(Object::BlankNode(blank_node))
        } else if term.contains(':') {
            let expanded = Self::expand_prefixed_name_static(term, prefixes)?;
            let named_node = NamedNode::new(&expanded).map_err(|e| {
                TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                    message: format!("Invalid IRI: {e}"),
                    position: TextPosition::start(),
                })
            })?;
            Ok(Object::NamedNode(named_node))
        } else {
            // Try to parse as a typed literal
            let literal = Literal::new_simple_literal(term);
            Ok(Object::Literal(literal))
        }
    }
}

impl Parser<Quad> for TriGParser {
    fn parse<R: Read>(&self, reader: R) -> TurtleResult<Vec<Quad>> {
        let buf_reader = BufReader::new(reader);
        self.parse_trig_content(buf_reader)
    }

    fn for_reader<R: BufRead>(&self, reader: R) -> Box<dyn Iterator<Item = TurtleResult<Quad>>> {
        // For streaming, we'll return all quads at once for now
        // A proper implementation would use a streaming parser
        match self.parse_trig_content(reader) {
            Ok(quads) => Box::new(quads.into_iter().map(Ok)),
            Err(e) => Box::new(std::iter::once(Err(e))),
        }
    }
}

/// TriG serializer with support for named graphs
#[derive(Debug, Clone)]
pub struct TriGSerializer {
    /// Base IRI for relative IRI serialization
    pub base_iri: Option<String>,
    /// Prefix declarations for compact serialization
    pub prefixes: HashMap<String, String>,
}

impl Default for TriGSerializer {
    fn default() -> Self {
        Self::new()
    }
}

impl TriGSerializer {
    /// Create a new TriG serializer
    pub fn new() -> Self {
        let mut prefixes = HashMap::new();

        // Add common prefixes
        prefixes.insert(
            "rdf".to_string(),
            "http://www.w3.org/1999/02/22-rdf-syntax-ns#".to_string(),
        );
        prefixes.insert(
            "rdfs".to_string(),
            "http://www.w3.org/2000/01/rdf-schema#".to_string(),
        );
        prefixes.insert(
            "xsd".to_string(),
            "http://www.w3.org/2001/XMLSchema#".to_string(),
        );

        Self {
            base_iri: None,
            prefixes,
        }
    }

    /// Serialize a quad to TriG format
    fn serialize_quad<W: Write>(&self, quad: &Quad, writer: &mut W) -> TurtleResult<()> {
        // Serialize subject
        self.serialize_subject(quad.subject(), writer)?;
        write!(writer, " ").map_err(TurtleParseError::Io)?;

        // Serialize predicate
        self.serialize_predicate(quad.predicate(), writer)?;
        write!(writer, " ").map_err(TurtleParseError::Io)?;

        // Serialize object
        self.serialize_object(quad.object(), writer)?;

        Ok(())
    }

    /// Serialize a subject term
    fn serialize_subject<W: Write>(
        &self,
        subject: &oxirs_core::model::Subject,
        writer: &mut W,
    ) -> TurtleResult<()> {
        use oxirs_core::model::Subject;

        match subject {
            Subject::NamedNode(node) => {
                self.serialize_named_node(node, writer)?;
            }
            Subject::BlankNode(node) => {
                write!(writer, "_:{}", node.as_str()).map_err(TurtleParseError::Io)?;
            }
            Subject::QuotedTriple(triple) => {
                // RDF-star quoted triple
                write!(writer, "<< ").map_err(TurtleParseError::Io)?;
                self.serialize_subject(triple.subject(), writer)?;
                write!(writer, " ").map_err(TurtleParseError::Io)?;
                self.serialize_predicate(triple.predicate(), writer)?;
                write!(writer, " ").map_err(TurtleParseError::Io)?;
                self.serialize_object(triple.object(), writer)?;
                write!(writer, " >>").map_err(TurtleParseError::Io)?;
            }
            Subject::Variable(var) => {
                write!(writer, "?{}", var.name()).map_err(TurtleParseError::Io)?;
            }
        }
        Ok(())
    }

    /// Serialize a predicate term
    fn serialize_predicate<W: Write>(
        &self,
        predicate: &oxirs_core::model::Predicate,
        writer: &mut W,
    ) -> TurtleResult<()> {
        use oxirs_core::model::Predicate;

        match predicate {
            Predicate::NamedNode(node) => {
                // Check for rdf:type abbreviation
                if node.as_str() == "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" {
                    write!(writer, "a").map_err(TurtleParseError::Io)?;
                } else {
                    self.serialize_named_node(node, writer)?;
                }
            }
            Predicate::Variable(var) => {
                write!(writer, "?{}", var.name()).map_err(TurtleParseError::Io)?;
            }
        }
        Ok(())
    }

    /// Serialize an object term
    fn serialize_object<W: Write>(
        &self,
        object: &oxirs_core::model::Object,
        writer: &mut W,
    ) -> TurtleResult<()> {
        use oxirs_core::model::Object;

        match object {
            Object::NamedNode(node) => {
                self.serialize_named_node(node, writer)?;
            }
            Object::BlankNode(node) => {
                write!(writer, "_:{}", node.as_str()).map_err(TurtleParseError::Io)?;
            }
            Object::Literal(literal) => {
                self.serialize_literal(literal, writer)?;
            }
            Object::QuotedTriple(triple) => {
                // RDF-star quoted triple
                write!(writer, "<< ").map_err(TurtleParseError::Io)?;
                self.serialize_subject(triple.subject(), writer)?;
                write!(writer, " ").map_err(TurtleParseError::Io)?;
                self.serialize_predicate(triple.predicate(), writer)?;
                write!(writer, " ").map_err(TurtleParseError::Io)?;
                self.serialize_object(triple.object(), writer)?;
                write!(writer, " >>").map_err(TurtleParseError::Io)?;
            }
            Object::Variable(var) => {
                write!(writer, "?{}", var.name()).map_err(TurtleParseError::Io)?;
            }
        }
        Ok(())
    }

    /// Serialize a named node, using prefixes if possible
    fn serialize_named_node<W: Write>(&self, node: &NamedNode, writer: &mut W) -> TurtleResult<()> {
        let iri = node.as_str();

        // Try to use a prefix
        for (prefix, namespace) in &self.prefixes {
            if iri.starts_with(namespace) {
                let local = &iri[namespace.len()..];
                write!(writer, "{prefix}:{local}").map_err(TurtleParseError::Io)?;
                return Ok(());
            }
        }

        // Use full IRI
        write!(writer, "<{iri}>").map_err(TurtleParseError::Io)?;
        Ok(())
    }

    /// Serialize a literal
    fn serialize_literal<W: Write>(&self, literal: &Literal, writer: &mut W) -> TurtleResult<()> {
        let value = literal.value();

        // Escape quotes in the value
        let escaped = value.replace('\\', "\\\\").replace('"', "\\\"");
        write!(writer, "\"{escaped}\"").map_err(TurtleParseError::Io)?;

        // Add language tag if present
        if let Some(lang) = literal.language() {
            write!(writer, "@{lang}").map_err(TurtleParseError::Io)?;
        }
        // Add datatype if not a string literal
        else if literal.datatype().as_str() != "http://www.w3.org/2001/XMLSchema#string" {
            write!(writer, "^^").map_err(TurtleParseError::Io)?;
            self.serialize_named_node(&literal.datatype().into_owned(), writer)?;
        }

        Ok(())
    }

    /// Group quads by graph for efficient serialization
    fn group_quads_by_graph<'a>(
        &self,
        quads: &'a [Quad],
    ) -> std::collections::BTreeMap<GraphName, Vec<&'a Quad>> {
        let mut grouped = std::collections::BTreeMap::new();

        for quad in quads {
            grouped
                .entry(quad.graph_name().clone())
                .or_insert_with(Vec::new)
                .push(quad);
        }

        grouped
    }
}

impl Serializer<Quad> for TriGSerializer {
    fn serialize<W: Write>(&self, quads: &[Quad], mut writer: W) -> TurtleResult<()> {
        // Write prefix declarations
        for (prefix, namespace) in &self.prefixes {
            writeln!(writer, "@prefix {prefix}: <{namespace}> .").map_err(TurtleParseError::Io)?;
        }

        if !self.prefixes.is_empty() {
            writeln!(writer).map_err(TurtleParseError::Io)?;
        }

        // Group quads by graph
        let grouped = self.group_quads_by_graph(quads);

        for (graph_name, graph_quads) in grouped {
            match graph_name {
                GraphName::DefaultGraph => {
                    // Serialize default graph triples directly
                    for quad in graph_quads {
                        self.serialize_quad(quad, &mut writer)?;
                        writeln!(writer, " .").map_err(TurtleParseError::Io)?;
                    }
                }
                GraphName::NamedNode(node) => {
                    // Named graph
                    self.serialize_named_node(&node, &mut writer)?;
                    writeln!(writer, " {{").map_err(TurtleParseError::Io)?;

                    for quad in graph_quads {
                        write!(writer, "    ").map_err(TurtleParseError::Io)?;
                        self.serialize_quad(quad, &mut writer)?;
                        writeln!(writer, " .").map_err(TurtleParseError::Io)?;
                    }

                    writeln!(writer, "}}").map_err(TurtleParseError::Io)?;
                }
                GraphName::BlankNode(node) => {
                    // Blank node graph
                    writeln!(writer, "_:{} {{", node.as_str()).map_err(TurtleParseError::Io)?;

                    for quad in graph_quads {
                        write!(writer, "    ").map_err(TurtleParseError::Io)?;
                        self.serialize_quad(quad, &mut writer)?;
                        writeln!(writer, " .").map_err(TurtleParseError::Io)?;
                    }

                    writeln!(writer, "}}").map_err(TurtleParseError::Io)?;
                }
                GraphName::Variable(_) => {
                    // Variables shouldn't appear in concrete data
                    return Err(TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                        message: "Cannot serialize variable graph names".to_string(),
                        position: TextPosition::start(),
                    }));
                }
            }

            writeln!(writer).map_err(TurtleParseError::Io)?;
        }

        Ok(())
    }

    fn serialize_item<W: Write>(&self, quad: &Quad, mut writer: W) -> TurtleResult<()> {
        match quad.graph_name() {
            GraphName::DefaultGraph => {
                // Default graph - serialize as simple triple
                self.serialize_quad(quad, &mut writer)?;
                writeln!(writer, " .").map_err(TurtleParseError::Io)?;
            }
            GraphName::NamedNode(node) => {
                // Named graph - use GRAPH syntax for individual quad
                write!(writer, "GRAPH ").map_err(TurtleParseError::Io)?;
                self.serialize_named_node(node, &mut writer)?;
                write!(writer, " {{ ").map_err(TurtleParseError::Io)?;
                self.serialize_quad(quad, &mut writer)?;
                writeln!(writer, " . }}").map_err(TurtleParseError::Io)?;
            }
            GraphName::BlankNode(node) => {
                // Blank node graph
                write!(writer, "_:{} {{ ", node.as_str()).map_err(TurtleParseError::Io)?;
                self.serialize_quad(quad, &mut writer)?;
                writeln!(writer, " . }}").map_err(TurtleParseError::Io)?;
            }
            GraphName::Variable(_) => {
                return Err(TurtleParseError::Syntax(TurtleSyntaxError::Generic {
                    message: "Cannot serialize variable graph names".to_string(),
                    position: TextPosition::start(),
                }));
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use oxirs_core::model::Object;
    use std::io::Cursor;

    #[test]
    fn test_parse_default_graph_triples() {
        let parser = TriGParser::new();
        let input = r#"
@prefix ex: <http://example.org/> .
ex:alice ex:name "Alice" .
ex:bob ex:name "Bob" .
"#;
        let quads = parser
            .parse(Cursor::new(input))
            .expect("trig parsing should succeed");
        assert_eq!(quads.len(), 2);
        for quad in &quads {
            assert!(
                quad.graph_name().is_default_graph(),
                "triples outside graph block should be in default graph"
            );
        }
    }

    #[test]
    fn test_parse_named_graph_block() {
        let parser = TriGParser::new();
        let input = r#"
@prefix ex: <http://example.org/> .
ex:graph1 {
    ex:alice ex:knows ex:bob .
}
"#;
        let quads = parser
            .parse(Cursor::new(input))
            .expect("trig parsing should succeed");
        assert!(!quads.is_empty(), "named graph should produce quads");
        let in_named_graph = quads
            .iter()
            .filter(|q| !q.graph_name().is_default_graph())
            .count();
        assert!(in_named_graph > 0, "some quads should be in named graph");
    }

    #[test]
    fn test_parse_multiple_named_graphs() {
        let parser = TriGParser::new();
        let input = r#"
@prefix ex: <http://example.org/> .

ex:graph1 {
    ex:alice ex:name "Alice" .
}

ex:graph2 {
    ex:bob ex:name "Bob" .
}
"#;
        let quads = parser
            .parse(Cursor::new(input))
            .expect("trig parsing should succeed");
        assert!(
            quads.len() >= 2,
            "multiple graphs should produce multiple quads"
        );
    }

    #[test]
    fn test_parse_graph_keyword_syntax() {
        let parser = TriGParser::new();
        let input = r#"
@prefix ex: <http://example.org/> .
GRAPH ex:graph1 {
    ex:s ex:p ex:o .
}
"#;
        let quads = parser
            .parse(Cursor::new(input))
            .expect("trig GRAPH keyword syntax should succeed");
        assert!(
            !quads.is_empty(),
            "GRAPH keyword syntax should produce quads"
        );
    }

    #[test]
    fn test_parse_mixed_default_and_named_graphs() {
        let parser = TriGParser::new();
        let input = r#"
@prefix ex: <http://example.org/> .
ex:alice ex:type ex:Person .
ex:relationships {
    ex:alice ex:knows ex:bob .
}
ex:charlie ex:type ex:Person .
"#;
        let quads = parser
            .parse(Cursor::new(input))
            .expect("trig parsing should succeed");
        let default_count = quads
            .iter()
            .filter(|q| q.graph_name().is_default_graph())
            .count();
        assert!(default_count >= 2, "should have default graph triples");
    }

    #[test]
    fn test_parse_prefix_declarations() {
        let parser = TriGParser::new();
        let input = r#"
@prefix ex: <http://example.org/> .
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
ex:graph1 {
    ex:alice foaf:name "Alice" .
}
"#;
        let quads = parser
            .parse(Cursor::new(input))
            .expect("trig parsing with prefixes should succeed");
        assert!(!quads.is_empty());
    }

    #[test]
    fn test_parse_empty_document() {
        let parser = TriGParser::new();
        let input = "# only comments\n";
        let quads = parser
            .parse(Cursor::new(input))
            .expect("trig parsing empty document should succeed");
        assert!(quads.is_empty(), "empty document produces no quads");
    }

    #[test]
    fn test_for_reader_iterator() {
        let parser = TriGParser::new();
        let input = r#"
@prefix ex: <http://example.org/> .
ex:s ex:p "o" .
"#;
        let quads: Vec<_> = parser
            .for_reader(Cursor::new(input))
            .collect::<Result<Vec<_>, _>>()
            .expect("for_reader should succeed");
        assert_eq!(quads.len(), 1);
    }

    #[test]
    fn test_serialize_quads_default_graph() {
        let serializer = TriGSerializer::new();
        let quad = Quad::new(
            NamedNode::new("http://example.org/s").expect("valid IRI"),
            NamedNode::new("http://example.org/p").expect("valid IRI"),
            NamedNode::new("http://example.org/o").expect("valid IRI"),
            GraphName::DefaultGraph,
        );
        let mut output = Vec::new();
        serializer
            .serialize(&[quad], &mut output)
            .expect("trig serialization should succeed");
        let out_str = String::from_utf8(output).expect("valid UTF-8");
        assert!(out_str.contains("<http://example.org/s>"));
    }

    #[test]
    fn test_serialize_quads_named_graph() {
        let serializer = TriGSerializer::new();
        let quad = Quad::new(
            NamedNode::new("http://example.org/s").expect("valid IRI"),
            NamedNode::new("http://example.org/p").expect("valid IRI"),
            NamedNode::new("http://example.org/o").expect("valid IRI"),
            GraphName::NamedNode(NamedNode::new("http://example.org/g").expect("valid IRI")),
        );
        let mut output = Vec::new();
        serializer
            .serialize(&[quad], &mut output)
            .expect("trig serialization should succeed");
        let out_str = String::from_utf8(output).expect("valid UTF-8");
        assert!(out_str.contains("<http://example.org/g>"));
    }

    #[test]
    fn test_parse_literal_object_in_graph() {
        let parser = TriGParser::new();
        let input = r#"
@prefix ex: <http://example.org/> .
ex:data {
    ex:alice ex:age "30" .
}
"#;
        let quads = parser
            .parse(Cursor::new(input))
            .expect("trig parsing should succeed");
        assert!(!quads.is_empty());
        // Find the quad with the literal
        let has_literal = quads
            .iter()
            .any(|q| matches!(q.object(), Object::Literal(_)));
        assert!(has_literal, "should have quad with literal object");
    }

    #[test]
    fn test_parser_default_is_non_lenient() {
        let parser = TriGParser::new();
        assert!(!parser.lenient, "default parser should not be lenient");
    }

    #[test]
    fn test_parse_base_iri_declaration() {
        let parser = TriGParser::new();
        let input = r#"
@base <http://example.org/> .
@prefix ex: <http://example.org/> .
ex:g {
    <alice> <knows> <bob> .
}
"#;
        let quads = parser
            .parse(Cursor::new(input))
            .expect("trig parsing with base IRI should succeed");
        assert!(!quads.is_empty());
    }

    #[test]
    fn test_parse_multiple_triples_in_single_graph() {
        let parser = TriGParser::new();
        let input = r#"
@prefix ex: <http://example.org/> .
ex:graph1 {
    ex:s1 ex:p ex:o1 .
    ex:s2 ex:p ex:o2 .
    ex:s3 ex:p ex:o3 .
}
"#;
        let quads = parser
            .parse(Cursor::new(input))
            .expect("trig parsing should succeed");
        assert!(quads.len() >= 3, "single graph with 3 triples");
    }
}