oxirs-star 0.2.4

RDF-star and SPARQL-star grammar support for quoted triples
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
//! # SPARQL-Star BIND/VALUES Extensions
//!
//! Extends SPARQL BIND and VALUES clauses to handle quoted triples (RDF-star),
//! enabling patterns like:
//!
//! ```sparql
//! BIND(<< ?s ?p ?o >> AS ?qt)
//! VALUES ?qt { << ex:s ex:p "o" >> << ex:s2 ex:p2 "o2" >> }
//! ```
//!
//! ## Features
//!
//! - BIND with quoted triple construction
//! - VALUES clause with inline quoted triples
//! - Quoted triple decomposition (extracting s/p/o from a bound QT variable)
//! - Nested quoted triple support in BIND/VALUES
//! - Coalesce/If expressions over quoted triples
//!
//! ## References
//!
//! - RDF-star and SPARQL-star Community Group Report
//! - W3C RDF-star Working Group specifications

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;

// ---------------------------------------------------------------------------
// Quoted triple representation
// ---------------------------------------------------------------------------

/// An RDF-star term that may be a quoted triple.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum StarTerm {
    /// An IRI reference.
    Iri(String),
    /// A literal with optional datatype and language tag.
    Literal {
        value: String,
        datatype: Option<String>,
        lang: Option<String>,
    },
    /// A blank node.
    BlankNode(String),
    /// A quoted triple (RDF-star).
    QuotedTriple(Box<QuotedTriple>),
    /// A SPARQL variable (for pattern matching).
    Variable(String),
}

impl fmt::Display for StarTerm {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Iri(iri) => write!(f, "<{iri}>"),
            Self::Literal {
                value,
                datatype,
                lang,
            } => {
                write!(f, "\"{value}\"")?;
                if let Some(dt) = datatype {
                    write!(f, "^^<{dt}>")?;
                }
                if let Some(l) = lang {
                    write!(f, "@{l}")?;
                }
                Ok(())
            }
            Self::BlankNode(id) => write!(f, "_:{id}"),
            Self::QuotedTriple(qt) => write!(f, "<< {qt} >>"),
            Self::Variable(name) => write!(f, "?{name}"),
        }
    }
}

impl StarTerm {
    /// Create an IRI term.
    pub fn iri(s: impl Into<String>) -> Self {
        Self::Iri(s.into())
    }

    /// Create a string literal.
    pub fn literal(s: impl Into<String>) -> Self {
        Self::Literal {
            value: s.into(),
            datatype: None,
            lang: None,
        }
    }

    /// Create a typed literal.
    pub fn typed_literal(s: impl Into<String>, dt: impl Into<String>) -> Self {
        Self::Literal {
            value: s.into(),
            datatype: Some(dt.into()),
            lang: None,
        }
    }

    /// Create a quoted triple term.
    pub fn quoted(subject: StarTerm, predicate: StarTerm, object: StarTerm) -> Self {
        Self::QuotedTriple(Box::new(QuotedTriple {
            subject,
            predicate,
            object,
        }))
    }

    /// Create a variable.
    pub fn var(name: impl Into<String>) -> Self {
        Self::Variable(name.into())
    }

    /// Check if this is a quoted triple.
    pub fn is_quoted_triple(&self) -> bool {
        matches!(self, Self::QuotedTriple(_))
    }

    /// Get the inner quoted triple if this is one.
    pub fn as_quoted_triple(&self) -> Option<&QuotedTriple> {
        match self {
            Self::QuotedTriple(qt) => Some(qt),
            _ => None,
        }
    }

    /// Check if this term is a variable.
    pub fn is_variable(&self) -> bool {
        matches!(self, Self::Variable(_))
    }

    /// Nesting depth (0 for non-quoted, 1+ for quoted with possible nesting).
    pub fn nesting_depth(&self) -> usize {
        match self {
            Self::QuotedTriple(qt) => {
                1 + qt
                    .subject
                    .nesting_depth()
                    .max(qt.predicate.nesting_depth())
                    .max(qt.object.nesting_depth())
            }
            _ => 0,
        }
    }
}

/// A quoted triple (RDF-star triple used as a term).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct QuotedTriple {
    /// Subject of the quoted triple.
    pub subject: StarTerm,
    /// Predicate of the quoted triple.
    pub predicate: StarTerm,
    /// Object of the quoted triple.
    pub object: StarTerm,
}

impl fmt::Display for QuotedTriple {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {} {}", self.subject, self.predicate, self.object)
    }
}

// ---------------------------------------------------------------------------
// BIND expression for quoted triples
// ---------------------------------------------------------------------------

/// A BIND expression that may involve quoted triples.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum StarBindExpr {
    /// Bind a quoted triple to a variable.
    /// `BIND(<< ?s ?p ?o >> AS ?qt)`
    ConstructQuotedTriple {
        subject: StarTerm,
        predicate: StarTerm,
        object: StarTerm,
        target_var: String,
    },

    /// Decompose a quoted triple variable into s/p/o.
    /// `BIND(SUBJECT(?qt) AS ?s)`, etc.
    DecomposeSubject {
        source_var: String,
        target_var: String,
    },
    /// Decompose predicate.
    DecomposePredicate {
        source_var: String,
        target_var: String,
    },
    /// Decompose object.
    DecomposeObject {
        source_var: String,
        target_var: String,
    },

    /// COALESCE over quoted triple expressions.
    Coalesce {
        alternatives: Vec<StarTerm>,
        target_var: String,
    },

    /// IF/THEN/ELSE with quoted triple awareness.
    IfThenElse {
        condition: StarCondition,
        then_value: StarTerm,
        else_value: StarTerm,
        target_var: String,
    },

    /// Bind a constant term.
    Constant { value: StarTerm, target_var: String },
}

/// A condition for IF expressions in BIND.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum StarCondition {
    /// Check if a variable is bound.
    IsBound(String),
    /// Check if a term is a quoted triple.
    IsTriple(String),
    /// Equality check.
    Equals(StarTerm, StarTerm),
}

// ---------------------------------------------------------------------------
// VALUES clause for quoted triples
// ---------------------------------------------------------------------------

/// A VALUES clause that may contain quoted triples.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StarValuesClause {
    /// Variable names in the VALUES clause.
    pub variables: Vec<String>,
    /// Rows of bindings (each row maps variable name -> term).
    pub rows: Vec<HashMap<String, StarTerm>>,
}

impl StarValuesClause {
    /// Create a new empty VALUES clause with the given variables.
    pub fn new(variables: Vec<String>) -> Self {
        Self {
            variables,
            rows: Vec::new(),
        }
    }

    /// Add a row of bindings.
    pub fn add_row(&mut self, bindings: HashMap<String, StarTerm>) -> &mut Self {
        self.rows.push(bindings);
        self
    }

    /// Number of rows.
    pub fn len(&self) -> usize {
        self.rows.len()
    }

    /// Check if empty.
    pub fn is_empty(&self) -> bool {
        self.rows.is_empty()
    }

    /// Check if any row contains a quoted triple.
    pub fn has_quoted_triples(&self) -> bool {
        self.rows
            .iter()
            .any(|row| row.values().any(|t| t.is_quoted_triple()))
    }

    /// Maximum nesting depth across all values.
    pub fn max_nesting_depth(&self) -> usize {
        self.rows
            .iter()
            .flat_map(|row| row.values())
            .map(|t| t.nesting_depth())
            .max()
            .unwrap_or(0)
    }

    /// Get all unique values for a variable.
    pub fn unique_values(&self, variable: &str) -> Vec<&StarTerm> {
        let mut seen = std::collections::HashSet::new();
        let mut result = Vec::new();
        for row in &self.rows {
            if let Some(val) = row.get(variable) {
                let key = format!("{val}");
                if seen.insert(key) {
                    result.push(val);
                }
            }
        }
        result
    }
}

// ---------------------------------------------------------------------------
// BIND evaluator
// ---------------------------------------------------------------------------

/// Evaluates BIND expressions involving quoted triples.
pub struct StarBindEvaluator;

/// A solution binding: variable name -> term.
pub type StarBindings = HashMap<String, StarTerm>;

/// Error from BIND evaluation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum StarBindError {
    /// Variable is not bound.
    UnboundVariable(String),
    /// Term is not a quoted triple (when decomposition was requested).
    NotAQuotedTriple(String),
    /// Type error.
    TypeError(String),
}

impl fmt::Display for StarBindError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnboundVariable(v) => write!(f, "Variable ?{v} is not bound"),
            Self::NotAQuotedTriple(v) => write!(f, "Variable ?{v} is not a quoted triple"),
            Self::TypeError(msg) => write!(f, "Type error: {msg}"),
        }
    }
}

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

impl StarBindEvaluator {
    /// Evaluate a BIND expression against the current bindings.
    pub fn evaluate(
        expr: &StarBindExpr,
        bindings: &StarBindings,
    ) -> Result<StarBindings, StarBindError> {
        let mut result = bindings.clone();

        match expr {
            StarBindExpr::ConstructQuotedTriple {
                subject,
                predicate,
                object,
                target_var,
            } => {
                let s = Self::resolve_term(subject, bindings)?;
                let p = Self::resolve_term(predicate, bindings)?;
                let o = Self::resolve_term(object, bindings)?;
                let qt = StarTerm::quoted(s, p, o);
                result.insert(target_var.clone(), qt);
            }

            StarBindExpr::DecomposeSubject {
                source_var,
                target_var,
            } => {
                let qt = Self::get_quoted_triple(source_var, bindings)?;
                result.insert(target_var.clone(), qt.subject.clone());
            }

            StarBindExpr::DecomposePredicate {
                source_var,
                target_var,
            } => {
                let qt = Self::get_quoted_triple(source_var, bindings)?;
                result.insert(target_var.clone(), qt.predicate.clone());
            }

            StarBindExpr::DecomposeObject {
                source_var,
                target_var,
            } => {
                let qt = Self::get_quoted_triple(source_var, bindings)?;
                result.insert(target_var.clone(), qt.object.clone());
            }

            StarBindExpr::Coalesce {
                alternatives,
                target_var,
            } => {
                for alt in alternatives {
                    if let Ok(resolved) = Self::resolve_term(alt, bindings) {
                        result.insert(target_var.clone(), resolved);
                        return Ok(result);
                    }
                }
                // All alternatives failed — variable remains unbound
            }

            StarBindExpr::IfThenElse {
                condition,
                then_value,
                else_value,
                target_var,
            } => {
                let cond_result = Self::evaluate_condition(condition, bindings);
                let value = if cond_result {
                    Self::resolve_term(then_value, bindings)?
                } else {
                    Self::resolve_term(else_value, bindings)?
                };
                result.insert(target_var.clone(), value);
            }

            StarBindExpr::Constant { value, target_var } => {
                result.insert(target_var.clone(), value.clone());
            }
        }

        Ok(result)
    }

    /// Resolve a StarTerm, substituting variables from bindings.
    fn resolve_term(term: &StarTerm, bindings: &StarBindings) -> Result<StarTerm, StarBindError> {
        match term {
            StarTerm::Variable(name) => bindings
                .get(name)
                .cloned()
                .ok_or_else(|| StarBindError::UnboundVariable(name.clone())),
            StarTerm::QuotedTriple(qt) => {
                let s = Self::resolve_term(&qt.subject, bindings)?;
                let p = Self::resolve_term(&qt.predicate, bindings)?;
                let o = Self::resolve_term(&qt.object, bindings)?;
                Ok(StarTerm::quoted(s, p, o))
            }
            other => Ok(other.clone()),
        }
    }

    /// Get a quoted triple from a variable binding.
    fn get_quoted_triple<'a>(
        var: &str,
        bindings: &'a StarBindings,
    ) -> Result<&'a QuotedTriple, StarBindError> {
        let term = bindings
            .get(var)
            .ok_or_else(|| StarBindError::UnboundVariable(var.to_string()))?;
        term.as_quoted_triple()
            .ok_or_else(|| StarBindError::NotAQuotedTriple(var.to_string()))
    }

    /// Evaluate a condition.
    fn evaluate_condition(condition: &StarCondition, bindings: &StarBindings) -> bool {
        match condition {
            StarCondition::IsBound(var) => bindings.contains_key(var),
            StarCondition::IsTriple(var) => bindings
                .get(var)
                .map(|t| t.is_quoted_triple())
                .unwrap_or(false),
            StarCondition::Equals(a, b) => {
                let resolved_a = Self::resolve_term(a, bindings).ok();
                let resolved_b = Self::resolve_term(b, bindings).ok();
                match (resolved_a, resolved_b) {
                    (Some(ra), Some(rb)) => ra == rb,
                    _ => false,
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// VALUES evaluator
// ---------------------------------------------------------------------------

/// Evaluates VALUES clauses with quoted triple support.
pub struct StarValuesEvaluator;

impl StarValuesEvaluator {
    /// Join the VALUES rows with existing bindings.
    ///
    /// For each row in the VALUES clause, check compatibility with the
    /// input bindings and produce merged results.
    pub fn evaluate(
        clause: &StarValuesClause,
        input_bindings: &[StarBindings],
    ) -> Vec<StarBindings> {
        let mut results = Vec::new();

        if input_bindings.is_empty() {
            // No input bindings — just return the VALUES rows
            return clause.rows.clone();
        }

        for input in input_bindings {
            for row in &clause.rows {
                if Self::is_compatible(input, row) {
                    let mut merged = input.clone();
                    for (var, val) in row {
                        merged.insert(var.clone(), val.clone());
                    }
                    results.push(merged);
                }
            }
        }

        results
    }

    /// Check if two binding sets are compatible (shared variables have equal values).
    fn is_compatible(a: &StarBindings, b: &StarBindings) -> bool {
        for (var, val_a) in a {
            if let Some(val_b) = b.get(var) {
                if val_a != val_b {
                    return false;
                }
            }
        }
        true
    }

    /// Filter VALUES rows that match a pattern.
    pub fn filter_rows(
        clause: &StarValuesClause,
        variable: &str,
        predicate: impl Fn(&StarTerm) -> bool,
    ) -> Vec<HashMap<String, StarTerm>> {
        clause
            .rows
            .iter()
            .filter(|row| row.get(variable).map(&predicate).unwrap_or(false))
            .cloned()
            .collect()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    fn ex(s: &str) -> String {
        format!("http://example.org/{s}")
    }

    fn ex_iri(s: &str) -> StarTerm {
        StarTerm::iri(ex(s))
    }

    fn make_qt(s: &str, p: &str, o: &str) -> StarTerm {
        StarTerm::quoted(ex_iri(s), ex_iri(p), StarTerm::literal(o))
    }

    // ── StarTerm tests ────────────────────────────────────────────────────

    #[test]
    fn test_star_term_display_iri() {
        let t = ex_iri("foo");
        assert_eq!(format!("{t}"), "<http://example.org/foo>");
    }

    #[test]
    fn test_star_term_display_literal() {
        let t = StarTerm::literal("hello");
        assert_eq!(format!("{t}"), "\"hello\"");
    }

    #[test]
    fn test_star_term_display_typed_literal() {
        let t = StarTerm::typed_literal("42", "xsd:integer");
        assert_eq!(format!("{t}"), "\"42\"^^<xsd:integer>");
    }

    #[test]
    fn test_star_term_display_quoted() {
        let t = make_qt("alice", "knows", "Bob");
        let s = format!("{t}");
        assert!(s.contains("<<"));
        assert!(s.contains(">>"));
        assert!(s.contains("alice"));
    }

    #[test]
    fn test_star_term_display_variable() {
        let t = StarTerm::var("x");
        assert_eq!(format!("{t}"), "?x");
    }

    #[test]
    fn test_star_term_is_quoted_triple() {
        assert!(make_qt("s", "p", "o").is_quoted_triple());
        assert!(!ex_iri("x").is_quoted_triple());
    }

    #[test]
    fn test_star_term_is_variable() {
        assert!(StarTerm::var("x").is_variable());
        assert!(!ex_iri("x").is_variable());
    }

    #[test]
    fn test_star_term_nesting_depth() {
        assert_eq!(ex_iri("x").nesting_depth(), 0);
        assert_eq!(make_qt("s", "p", "o").nesting_depth(), 1);

        // Nested: << << s p o >> p2 o2 >>
        let nested = StarTerm::quoted(
            make_qt("s", "p", "o"),
            ex_iri("p2"),
            StarTerm::literal("o2"),
        );
        assert_eq!(nested.nesting_depth(), 2);
    }

    #[test]
    fn test_star_term_as_quoted_triple() {
        let qt = make_qt("s", "p", "o");
        assert!(qt.as_quoted_triple().is_some());
        assert!(ex_iri("x").as_quoted_triple().is_none());
    }

    // ── QuotedTriple display ──────────────────────────────────────────────

    #[test]
    fn test_quoted_triple_display() {
        let qt = QuotedTriple {
            subject: ex_iri("s"),
            predicate: ex_iri("p"),
            object: StarTerm::literal("o"),
        };
        let s = format!("{qt}");
        assert!(s.contains("s"));
        assert!(s.contains("p"));
        assert!(s.contains("o"));
    }

    // ── BIND: construct quoted triple ─────────────────────────────────────

    #[test]
    fn test_bind_construct_qt() {
        let mut bindings = StarBindings::new();
        bindings.insert("s".to_string(), ex_iri("alice"));
        bindings.insert("p".to_string(), ex_iri("knows"));
        bindings.insert("o".to_string(), ex_iri("bob"));

        let expr = StarBindExpr::ConstructQuotedTriple {
            subject: StarTerm::var("s"),
            predicate: StarTerm::var("p"),
            object: StarTerm::var("o"),
            target_var: "qt".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings).expect("should succeed");
        let qt = result.get("qt").expect("qt should be bound");
        assert!(qt.is_quoted_triple());
    }

    #[test]
    fn test_bind_construct_qt_with_constants() {
        let bindings = StarBindings::new();

        let expr = StarBindExpr::ConstructQuotedTriple {
            subject: ex_iri("alice"),
            predicate: ex_iri("age"),
            object: StarTerm::typed_literal("30", "xsd:integer"),
            target_var: "qt".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings).expect("should succeed");
        let qt = result.get("qt").expect("qt should be bound");
        assert!(qt.is_quoted_triple());
    }

    // ── BIND: decompose ───────────────────────────────────────────────────

    #[test]
    fn test_bind_decompose_subject() {
        let mut bindings = StarBindings::new();
        bindings.insert("qt".to_string(), make_qt("alice", "knows", "Bob"));

        let expr = StarBindExpr::DecomposeSubject {
            source_var: "qt".to_string(),
            target_var: "subj".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings).expect("should succeed");
        let subj = result.get("subj").expect("subj should be bound");
        assert_eq!(*subj, ex_iri("alice"));
    }

    #[test]
    fn test_bind_decompose_predicate() {
        let mut bindings = StarBindings::new();
        bindings.insert("qt".to_string(), make_qt("alice", "knows", "Bob"));

        let expr = StarBindExpr::DecomposePredicate {
            source_var: "qt".to_string(),
            target_var: "pred".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings).expect("should succeed");
        let pred = result.get("pred").expect("pred should be bound");
        assert_eq!(*pred, ex_iri("knows"));
    }

    #[test]
    fn test_bind_decompose_object() {
        let mut bindings = StarBindings::new();
        bindings.insert("qt".to_string(), make_qt("alice", "knows", "Bob"));

        let expr = StarBindExpr::DecomposeObject {
            source_var: "qt".to_string(),
            target_var: "obj".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings).expect("should succeed");
        let obj = result.get("obj").expect("obj should be bound");
        assert_eq!(*obj, StarTerm::literal("Bob"));
    }

    #[test]
    fn test_bind_decompose_not_a_qt() {
        let mut bindings = StarBindings::new();
        bindings.insert("x".to_string(), ex_iri("alice"));

        let expr = StarBindExpr::DecomposeSubject {
            source_var: "x".to_string(),
            target_var: "subj".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings);
        assert!(matches!(result, Err(StarBindError::NotAQuotedTriple(_))));
    }

    #[test]
    fn test_bind_decompose_unbound() {
        let bindings = StarBindings::new();

        let expr = StarBindExpr::DecomposeSubject {
            source_var: "missing".to_string(),
            target_var: "subj".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings);
        assert!(matches!(result, Err(StarBindError::UnboundVariable(_))));
    }

    // ── BIND: coalesce ────────────────────────────────────────────────────

    #[test]
    fn test_bind_coalesce_first_bound() {
        let mut bindings = StarBindings::new();
        bindings.insert("a".to_string(), ex_iri("first"));

        let expr = StarBindExpr::Coalesce {
            alternatives: vec![StarTerm::var("a"), StarTerm::var("b")],
            target_var: "result".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings).expect("should succeed");
        assert_eq!(result.get("result"), Some(&ex_iri("first")));
    }

    #[test]
    fn test_bind_coalesce_fallback() {
        let mut bindings = StarBindings::new();
        bindings.insert("b".to_string(), ex_iri("second"));

        let expr = StarBindExpr::Coalesce {
            alternatives: vec![StarTerm::var("a"), StarTerm::var("b")],
            target_var: "result".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings).expect("should succeed");
        assert_eq!(result.get("result"), Some(&ex_iri("second")));
    }

    #[test]
    fn test_bind_coalesce_constant_fallback() {
        let bindings = StarBindings::new();

        let expr = StarBindExpr::Coalesce {
            alternatives: vec![StarTerm::var("missing"), StarTerm::literal("default")],
            target_var: "result".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings).expect("should succeed");
        assert_eq!(result.get("result"), Some(&StarTerm::literal("default")));
    }

    // ── BIND: if-then-else ────────────────────────────────────────────────

    #[test]
    fn test_bind_if_is_bound_true() {
        let mut bindings = StarBindings::new();
        bindings.insert("x".to_string(), ex_iri("val"));

        let expr = StarBindExpr::IfThenElse {
            condition: StarCondition::IsBound("x".to_string()),
            then_value: StarTerm::literal("yes"),
            else_value: StarTerm::literal("no"),
            target_var: "result".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings).expect("should succeed");
        assert_eq!(result.get("result"), Some(&StarTerm::literal("yes")));
    }

    #[test]
    fn test_bind_if_is_bound_false() {
        let bindings = StarBindings::new();

        let expr = StarBindExpr::IfThenElse {
            condition: StarCondition::IsBound("x".to_string()),
            then_value: StarTerm::literal("yes"),
            else_value: StarTerm::literal("no"),
            target_var: "result".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings).expect("should succeed");
        assert_eq!(result.get("result"), Some(&StarTerm::literal("no")));
    }

    #[test]
    fn test_bind_if_is_triple() {
        let mut bindings = StarBindings::new();
        bindings.insert("qt".to_string(), make_qt("s", "p", "o"));

        let expr = StarBindExpr::IfThenElse {
            condition: StarCondition::IsTriple("qt".to_string()),
            then_value: StarTerm::literal("is_triple"),
            else_value: StarTerm::literal("not_triple"),
            target_var: "result".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings).expect("should succeed");
        assert_eq!(result.get("result"), Some(&StarTerm::literal("is_triple")));
    }

    #[test]
    fn test_bind_if_equals() {
        let mut bindings = StarBindings::new();
        bindings.insert("x".to_string(), ex_iri("alice"));

        let expr = StarBindExpr::IfThenElse {
            condition: StarCondition::Equals(StarTerm::var("x"), ex_iri("alice")),
            then_value: StarTerm::literal("match"),
            else_value: StarTerm::literal("no_match"),
            target_var: "result".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings).expect("should succeed");
        assert_eq!(result.get("result"), Some(&StarTerm::literal("match")));
    }

    // ── BIND: constant ────────────────────────────────────────────────────

    #[test]
    fn test_bind_constant() {
        let bindings = StarBindings::new();
        let expr = StarBindExpr::Constant {
            value: make_qt("s", "p", "o"),
            target_var: "qt".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings).expect("should succeed");
        assert!(result.get("qt").expect("bound").is_quoted_triple());
    }

    // ── VALUES clause ─────────────────────────────────────────────────────

    #[test]
    fn test_values_clause_new() {
        let clause = StarValuesClause::new(vec!["x".to_string()]);
        assert!(clause.is_empty());
        assert_eq!(clause.len(), 0);
    }

    #[test]
    fn test_values_clause_add_rows() {
        let mut clause = StarValuesClause::new(vec!["x".to_string()]);
        let mut row = HashMap::new();
        row.insert("x".to_string(), ex_iri("alice"));
        clause.add_row(row);
        assert_eq!(clause.len(), 1);
    }

    #[test]
    fn test_values_has_quoted_triples() {
        let mut clause = StarValuesClause::new(vec!["qt".to_string()]);
        let mut row = HashMap::new();
        row.insert("qt".to_string(), make_qt("s", "p", "o"));
        clause.add_row(row);
        assert!(clause.has_quoted_triples());
    }

    #[test]
    fn test_values_no_quoted_triples() {
        let mut clause = StarValuesClause::new(vec!["x".to_string()]);
        let mut row = HashMap::new();
        row.insert("x".to_string(), ex_iri("alice"));
        clause.add_row(row);
        assert!(!clause.has_quoted_triples());
    }

    #[test]
    fn test_values_max_nesting_depth() {
        let mut clause = StarValuesClause::new(vec!["qt".to_string()]);
        let nested = StarTerm::quoted(
            make_qt("s", "p", "o"),
            ex_iri("p2"),
            StarTerm::literal("o2"),
        );
        let mut row = HashMap::new();
        row.insert("qt".to_string(), nested);
        clause.add_row(row);
        assert_eq!(clause.max_nesting_depth(), 2);
    }

    #[test]
    fn test_values_unique_values() {
        let mut clause = StarValuesClause::new(vec!["x".to_string()]);
        for _ in 0..3 {
            let mut row = HashMap::new();
            row.insert("x".to_string(), ex_iri("same"));
            clause.add_row(row);
        }
        let mut row = HashMap::new();
        row.insert("x".to_string(), ex_iri("different"));
        clause.add_row(row);

        let unique = clause.unique_values("x");
        assert_eq!(unique.len(), 2);
    }

    // ── VALUES evaluator ──────────────────────────────────────────────────

    #[test]
    fn test_values_evaluate_no_input() {
        let mut clause = StarValuesClause::new(vec!["x".to_string()]);
        let mut row = HashMap::new();
        row.insert("x".to_string(), ex_iri("alice"));
        clause.add_row(row);

        let results = StarValuesEvaluator::evaluate(&clause, &[]);
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn test_values_evaluate_with_compatible_bindings() {
        let mut clause = StarValuesClause::new(vec!["name".to_string()]);
        let mut row1 = HashMap::new();
        row1.insert("name".to_string(), StarTerm::literal("Alice"));
        clause.add_row(row1);
        let mut row2 = HashMap::new();
        row2.insert("name".to_string(), StarTerm::literal("Bob"));
        clause.add_row(row2);

        let mut input = StarBindings::new();
        input.insert("age".to_string(), StarTerm::literal("30"));

        let results = StarValuesEvaluator::evaluate(&clause, &[input]);
        assert_eq!(results.len(), 2);
        assert!(results[0].contains_key("name"));
        assert!(results[0].contains_key("age"));
    }

    #[test]
    fn test_values_evaluate_with_conflict() {
        let mut clause = StarValuesClause::new(vec!["x".to_string()]);
        let mut row = HashMap::new();
        row.insert("x".to_string(), ex_iri("alice"));
        clause.add_row(row);

        let mut input = StarBindings::new();
        input.insert("x".to_string(), ex_iri("bob")); // conflicts!

        let results = StarValuesEvaluator::evaluate(&clause, &[input]);
        assert!(results.is_empty()); // No compatible rows
    }

    #[test]
    fn test_values_evaluate_with_qt_bindings() {
        let mut clause = StarValuesClause::new(vec!["qt".to_string()]);
        let mut row = HashMap::new();
        row.insert("qt".to_string(), make_qt("alice", "knows", "Bob"));
        clause.add_row(row);

        let results = StarValuesEvaluator::evaluate(&clause, &[]);
        assert_eq!(results.len(), 1);
        assert!(results[0].get("qt").expect("bound").is_quoted_triple());
    }

    #[test]
    fn test_values_filter_rows() {
        let mut clause = StarValuesClause::new(vec!["x".to_string()]);
        for name in &["alice", "bob", "charlie"] {
            let mut row = HashMap::new();
            row.insert("x".to_string(), ex_iri(name));
            clause.add_row(row);
        }

        let filtered =
            StarValuesEvaluator::filter_rows(&clause, "x", |t| format!("{t}").contains("alice"));
        assert_eq!(filtered.len(), 1);
    }

    // ── Error display ─────────────────────────────────────────────────────

    #[test]
    fn test_error_display() {
        let e = StarBindError::UnboundVariable("x".to_string());
        assert!(format!("{e}").contains("x"));

        let e = StarBindError::NotAQuotedTriple("y".to_string());
        assert!(format!("{e}").contains("y"));

        let e = StarBindError::TypeError("bad".to_string());
        assert!(format!("{e}").contains("bad"));
    }

    // ── Nested quoted triple in BIND ──────────────────────────────────────

    #[test]
    fn test_bind_nested_qt() {
        let inner_qt = make_qt("alice", "knows", "Bob");
        let mut bindings = StarBindings::new();
        bindings.insert("inner".to_string(), inner_qt);

        let expr = StarBindExpr::ConstructQuotedTriple {
            subject: StarTerm::var("inner"),
            predicate: ex_iri("certainty"),
            object: StarTerm::literal("0.9"),
            target_var: "outer".to_string(),
        };

        let result = StarBindEvaluator::evaluate(&expr, &bindings).expect("should succeed");
        let outer = result.get("outer").expect("outer bound");
        assert_eq!(outer.nesting_depth(), 2);
    }

    // ── Multiple BIND expressions in sequence ─────────────────────────────

    #[test]
    fn test_bind_chain() {
        let mut bindings = StarBindings::new();
        bindings.insert("s".to_string(), ex_iri("alice"));
        bindings.insert("p".to_string(), ex_iri("knows"));
        bindings.insert("o".to_string(), ex_iri("bob"));

        // Step 1: Construct QT
        let expr1 = StarBindExpr::ConstructQuotedTriple {
            subject: StarTerm::var("s"),
            predicate: StarTerm::var("p"),
            object: StarTerm::var("o"),
            target_var: "qt".to_string(),
        };
        let bindings = StarBindEvaluator::evaluate(&expr1, &bindings).expect("step 1");

        // Step 2: Decompose subject
        let expr2 = StarBindExpr::DecomposeSubject {
            source_var: "qt".to_string(),
            target_var: "extracted_s".to_string(),
        };
        let bindings = StarBindEvaluator::evaluate(&expr2, &bindings).expect("step 2");

        assert_eq!(bindings.get("extracted_s"), Some(&ex_iri("alice")));
    }
}