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
//! SPARQL-star built-in functions for working with quoted triples.
//!
//! This module provides the standard SPARQL-star functions defined in the
//! specification for constructing and deconstructing quoted triples.

use crate::model::{StarTerm, StarTriple};
use crate::{StarError, StarResult};

/// SPARQL-star built-in functions
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum StarFunction {
    /// TRIPLE(s, p, o) - constructs a quoted triple
    Triple,
    /// SUBJECT(t) - extracts the subject from a quoted triple
    Subject,
    /// PREDICATE(t) - extracts the predicate from a quoted triple
    Predicate,
    /// OBJECT(t) - extracts the object from a quoted triple
    Object,
    /// isTRIPLE(t) - tests if a term is a quoted triple
    IsTriple,
}

impl StarFunction {
    /// Get the function name as a string
    pub fn name(&self) -> &'static str {
        match self {
            StarFunction::Triple => "TRIPLE",
            StarFunction::Subject => "SUBJECT",
            StarFunction::Predicate => "PREDICATE",
            StarFunction::Object => "OBJECT",
            StarFunction::IsTriple => "isTRIPLE",
        }
    }

    /// Get the expected number of arguments for this function
    pub fn arity(&self) -> usize {
        match self {
            StarFunction::Triple => 3,
            StarFunction::Subject => 1,
            StarFunction::Predicate => 1,
            StarFunction::Object => 1,
            StarFunction::IsTriple => 1,
        }
    }

    /// Parse a function name into a StarFunction
    pub fn from_name(name: &str) -> Option<Self> {
        match name.to_uppercase().as_str() {
            "TRIPLE" => Some(StarFunction::Triple),
            "SUBJECT" => Some(StarFunction::Subject),
            "PREDICATE" => Some(StarFunction::Predicate),
            "OBJECT" => Some(StarFunction::Object),
            "ISTRIPLE" => Some(StarFunction::IsTriple),
            _ => None,
        }
    }
}

/// SPARQL-star function evaluator
pub struct FunctionEvaluator;

impl FunctionEvaluator {
    /// Evaluate a SPARQL-star function with the given arguments
    pub fn evaluate(function: StarFunction, args: &[StarTerm]) -> StarResult<StarTerm> {
        // Check argument count
        let expected_arity = function.arity();
        if args.len() != expected_arity {
            return Err(StarError::QueryError {
                message: format!(
                    "Function {} expects {} arguments, got {}",
                    function.name(),
                    expected_arity,
                    args.len()
                ),
                query_fragment: None,
                position: None,
                suggestion: None,
            });
        }

        match function {
            StarFunction::Triple => Self::evaluate_triple(&args[0], &args[1], &args[2]),
            StarFunction::Subject => Self::evaluate_subject(&args[0]),
            StarFunction::Predicate => Self::evaluate_predicate(&args[0]),
            StarFunction::Object => Self::evaluate_object(&args[0]),
            StarFunction::IsTriple => Self::evaluate_is_triple(&args[0]),
        }
    }

    /// TRIPLE(s, p, o) - constructs a quoted triple from subject, predicate, object
    fn evaluate_triple(
        subject: &StarTerm,
        predicate: &StarTerm,
        object: &StarTerm,
    ) -> StarResult<StarTerm> {
        // Validate that the arguments can form a valid triple
        if !subject.can_be_subject() {
            return Err(StarError::QueryError {
                message: format!("Invalid subject for TRIPLE function: {subject:?}"),
                query_fragment: None,
                position: None,
                suggestion: None,
            });
        }

        if !predicate.can_be_predicate() {
            return Err(StarError::QueryError {
                message: format!("Invalid predicate for TRIPLE function: {predicate:?}"),
                query_fragment: None,
                position: None,
                suggestion: None,
            });
        }

        if !object.can_be_object() {
            return Err(StarError::QueryError {
                message: format!("Invalid object for TRIPLE function: {object:?}"),
                query_fragment: None,
                position: None,
                suggestion: None,
            });
        }

        // Create the quoted triple
        let triple = StarTriple::new(subject.clone(), predicate.clone(), object.clone());
        Ok(StarTerm::quoted_triple(triple))
    }

    /// SUBJECT(t) - extracts the subject from a quoted triple
    fn evaluate_subject(term: &StarTerm) -> StarResult<StarTerm> {
        match term {
            StarTerm::QuotedTriple(triple) => Ok(triple.subject.clone()),
            _ => Err(StarError::QueryError {
                message: format!("SUBJECT function expects a quoted triple, got: {term:?}"),
                query_fragment: None,
                position: None,
                suggestion: None,
            }),
        }
    }

    /// PREDICATE(t) - extracts the predicate from a quoted triple
    fn evaluate_predicate(term: &StarTerm) -> StarResult<StarTerm> {
        match term {
            StarTerm::QuotedTriple(triple) => Ok(triple.predicate.clone()),
            _ => Err(StarError::QueryError {
                message: format!("PREDICATE function expects a quoted triple, got: {term:?}"),
                query_fragment: None,
                position: None,
                suggestion: None,
            }),
        }
    }

    /// OBJECT(t) - extracts the object from a quoted triple
    fn evaluate_object(term: &StarTerm) -> StarResult<StarTerm> {
        match term {
            StarTerm::QuotedTriple(triple) => Ok(triple.object.clone()),
            _ => Err(StarError::QueryError {
                message: format!("OBJECT function expects a quoted triple, got: {term:?}"),
                query_fragment: None,
                position: None,
                suggestion: None,
            }),
        }
    }

    /// isTRIPLE(t) - tests if a term is a quoted triple
    fn evaluate_is_triple(term: &StarTerm) -> StarResult<StarTerm> {
        let result = term.is_quoted_triple();

        // Return a boolean literal (xsd:boolean)
        let value = if result { "true" } else { "false" };
        StarTerm::literal_with_datatype(value, "http://www.w3.org/2001/XMLSchema#boolean")
    }
}

/// Expression type for SPARQL-star expressions
#[derive(Debug, Clone, PartialEq)]
pub enum Expression {
    /// Constant term
    Term(StarTerm),
    /// Variable reference
    Variable(String),
    /// Function call
    FunctionCall {
        function: StarFunction,
        args: Vec<Expression>,
    },
    /// Binary operation (e.g., equality, comparison)
    BinaryOp {
        op: BinaryOperator,
        left: Box<Expression>,
        right: Box<Expression>,
    },
    /// Unary operation (e.g., negation)
    UnaryOp {
        op: UnaryOperator,
        expr: Box<Expression>,
    },
}

/// Binary operators for SPARQL expressions
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BinaryOperator {
    /// Equality (=)
    Equal,
    /// Inequality (!=)
    NotEqual,
    /// Less than (<)
    LessThan,
    /// Less than or equal (<=)
    LessThanOrEqual,
    /// Greater than (>)
    GreaterThan,
    /// Greater than or equal (>=)
    GreaterThanOrEqual,
    /// Logical AND (&&)
    And,
    /// Logical OR (||)
    Or,
}

/// Unary operators for SPARQL expressions
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum UnaryOperator {
    /// Logical NOT (!)
    Not,
    /// Arithmetic negation (-)
    Minus,
}

/// Expression evaluator for SPARQL-star expressions
pub struct ExpressionEvaluator;

impl ExpressionEvaluator {
    /// Evaluate an expression with the given variable bindings
    pub fn evaluate(
        expr: &Expression,
        bindings: &std::collections::HashMap<String, StarTerm>,
    ) -> StarResult<StarTerm> {
        match expr {
            Expression::Term(term) => Ok(term.clone()),
            Expression::Variable(var) => {
                bindings
                    .get(var)
                    .cloned()
                    .ok_or_else(|| StarError::QueryError {
                        message: format!("Unbound variable: {var}"),
                        query_fragment: None,
                        position: None,
                        suggestion: None,
                    })
            }
            Expression::FunctionCall { function, args } => {
                // Evaluate arguments first
                let evaluated_args: Result<Vec<_>, _> = args
                    .iter()
                    .map(|arg| Self::evaluate(arg, bindings))
                    .collect();

                let evaluated_args = evaluated_args?;
                FunctionEvaluator::evaluate(*function, &evaluated_args)
            }
            Expression::BinaryOp { op, left, right } => {
                let left_val = Self::evaluate(left, bindings)?;
                let right_val = Self::evaluate(right, bindings)?;
                Self::evaluate_binary_op(*op, &left_val, &right_val)
            }
            Expression::UnaryOp { op, expr } => {
                let val = Self::evaluate(expr, bindings)?;
                Self::evaluate_unary_op(*op, &val)
            }
        }
    }

    /// Evaluate a binary operation
    fn evaluate_binary_op(
        op: BinaryOperator,
        left: &StarTerm,
        right: &StarTerm,
    ) -> StarResult<StarTerm> {
        match op {
            BinaryOperator::Equal => {
                let result = left == right;
                StarTerm::literal_with_datatype(
                    if result { "true" } else { "false" },
                    "http://www.w3.org/2001/XMLSchema#boolean",
                )
            }
            BinaryOperator::NotEqual => {
                let result = left != right;
                StarTerm::literal_with_datatype(
                    if result { "true" } else { "false" },
                    "http://www.w3.org/2001/XMLSchema#boolean",
                )
            }
            // Other operators would require type checking and numeric comparisons
            _ => Err(StarError::QueryError {
                message: format!("Binary operator {op:?} not yet implemented"),
                query_fragment: None,
                position: None,
                suggestion: None,
            }),
        }
    }

    /// Evaluate a unary operation
    fn evaluate_unary_op(op: UnaryOperator, term: &StarTerm) -> StarResult<StarTerm> {
        match op {
            UnaryOperator::Not => {
                // Expects a boolean literal
                if let Some(literal) = term.as_literal() {
                    if let Some(datatype) = &literal.datatype {
                        if datatype.iri == "http://www.w3.org/2001/XMLSchema#boolean" {
                            let value = literal.value.as_str();
                            let negated = match value {
                                "true" => "false",
                                "false" => "true",
                                _ => {
                                    return Err(StarError::QueryError {
                                        message: "Invalid boolean value".to_string(),
                                        query_fragment: None,
                                        position: None,
                                        suggestion: None,
                                    })
                                }
                            };
                            return StarTerm::literal_with_datatype(
                                negated,
                                "http://www.w3.org/2001/XMLSchema#boolean",
                            );
                        }
                    }
                }
                Err(StarError::QueryError {
                    message: "NOT operator expects a boolean literal".to_string(),
                    query_fragment: None,
                    position: None,
                    suggestion: None,
                })
            }
            UnaryOperator::Minus => Err(StarError::QueryError {
                message: "Arithmetic operations not yet implemented".to_string(),
                query_fragment: None,
                position: None,
                suggestion: None,
            }),
        }
    }
}

/// Helper functions for constructing expressions
impl Expression {
    /// Create a TRIPLE function call expression
    pub fn triple(subject: Expression, predicate: Expression, object: Expression) -> Self {
        Expression::FunctionCall {
            function: StarFunction::Triple,
            args: vec![subject, predicate, object],
        }
    }

    /// Create a SUBJECT function call expression
    pub fn subject(expr: Expression) -> Self {
        Expression::FunctionCall {
            function: StarFunction::Subject,
            args: vec![expr],
        }
    }

    /// Create a PREDICATE function call expression
    pub fn predicate(expr: Expression) -> Self {
        Expression::FunctionCall {
            function: StarFunction::Predicate,
            args: vec![expr],
        }
    }

    /// Create an OBJECT function call expression
    pub fn object(expr: Expression) -> Self {
        Expression::FunctionCall {
            function: StarFunction::Object,
            args: vec![expr],
        }
    }

    /// Create an isTRIPLE function call expression
    pub fn is_triple(expr: Expression) -> Self {
        Expression::FunctionCall {
            function: StarFunction::IsTriple,
            args: vec![expr],
        }
    }

    /// Create an equality expression
    pub fn equal(left: Expression, right: Expression) -> Self {
        Expression::BinaryOp {
            op: BinaryOperator::Equal,
            left: Box::new(left),
            right: Box::new(right),
        }
    }

    /// Create a variable expression
    pub fn var(name: &str) -> Self {
        Expression::Variable(name.to_string())
    }

    /// Create a term expression
    pub fn term(term: StarTerm) -> Self {
        Expression::Term(term)
    }
}

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

    #[test]
    fn test_triple_function() {
        let subject = StarTerm::iri("http://example.org/alice").unwrap();
        let predicate = StarTerm::iri("http://example.org/age").unwrap();
        let object = StarTerm::literal("25").unwrap();

        let result = FunctionEvaluator::evaluate(
            StarFunction::Triple,
            &[subject.clone(), predicate.clone(), object.clone()],
        )
        .unwrap();

        assert!(result.is_quoted_triple());
        if let StarTerm::QuotedTriple(triple) = result {
            assert_eq!(triple.subject, subject);
            assert_eq!(triple.predicate, predicate);
            assert_eq!(triple.object, object);
        }
    }

    #[test]
    fn test_subject_function() {
        let triple = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/age").unwrap(),
            StarTerm::literal("25").unwrap(),
        );
        let quoted = StarTerm::quoted_triple(triple);

        let result = FunctionEvaluator::evaluate(StarFunction::Subject, &[quoted]).unwrap();

        assert_eq!(result, StarTerm::iri("http://example.org/alice").unwrap());
    }

    #[test]
    fn test_predicate_function() {
        let triple = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/age").unwrap(),
            StarTerm::literal("25").unwrap(),
        );
        let quoted = StarTerm::quoted_triple(triple);

        let result = FunctionEvaluator::evaluate(StarFunction::Predicate, &[quoted]).unwrap();

        assert_eq!(result, StarTerm::iri("http://example.org/age").unwrap());
    }

    #[test]
    fn test_object_function() {
        let triple = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/age").unwrap(),
            StarTerm::literal("25").unwrap(),
        );
        let quoted = StarTerm::quoted_triple(triple);

        let result = FunctionEvaluator::evaluate(StarFunction::Object, &[quoted]).unwrap();

        assert_eq!(result, StarTerm::literal("25").unwrap());
    }

    #[test]
    fn test_is_triple_function() {
        // Test with a quoted triple
        let triple = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/age").unwrap(),
            StarTerm::literal("25").unwrap(),
        );
        let quoted = StarTerm::quoted_triple(triple);

        let result = FunctionEvaluator::evaluate(StarFunction::IsTriple, &[quoted]).unwrap();

        assert_eq!(
            result,
            StarTerm::literal_with_datatype("true", "http://www.w3.org/2001/XMLSchema#boolean")
                .unwrap()
        );

        // Test with a non-quoted term
        let iri = StarTerm::iri("http://example.org/alice").unwrap();
        let result = FunctionEvaluator::evaluate(StarFunction::IsTriple, &[iri]).unwrap();

        assert_eq!(
            result,
            StarTerm::literal_with_datatype("false", "http://www.w3.org/2001/XMLSchema#boolean")
                .unwrap()
        );
    }

    #[test]
    fn test_expression_evaluation() {
        let mut bindings = HashMap::new();
        bindings.insert(
            "x".to_string(),
            StarTerm::iri("http://example.org/alice").unwrap(),
        );
        bindings.insert(
            "p".to_string(),
            StarTerm::iri("http://example.org/age").unwrap(),
        );
        bindings.insert("o".to_string(), StarTerm::literal("25").unwrap());

        // Test TRIPLE(?x, ?p, ?o)
        let expr = Expression::triple(
            Expression::var("x"),
            Expression::var("p"),
            Expression::var("o"),
        );

        let result = ExpressionEvaluator::evaluate(&expr, &bindings).unwrap();
        assert!(result.is_quoted_triple());

        // Test SUBJECT(TRIPLE(?x, ?p, ?o))
        let expr = Expression::subject(Expression::triple(
            Expression::var("x"),
            Expression::var("p"),
            Expression::var("o"),
        ));

        let result = ExpressionEvaluator::evaluate(&expr, &bindings).unwrap();
        assert_eq!(result, StarTerm::iri("http://example.org/alice").unwrap());
    }

    #[test]
    fn test_nested_function_calls() {
        let triple1 = StarTriple::new(
            StarTerm::iri("http://example.org/alice").unwrap(),
            StarTerm::iri("http://example.org/age").unwrap(),
            StarTerm::literal("25").unwrap(),
        );
        let quoted1 = StarTerm::quoted_triple(triple1);

        let triple2 = StarTriple::new(
            quoted1.clone(),
            StarTerm::iri("http://example.org/certainty").unwrap(),
            StarTerm::literal("0.9").unwrap(),
        );
        let quoted2 = StarTerm::quoted_triple(triple2);

        // Test SUBJECT(SUBJECT(<<...>>))
        let inner_subject =
            FunctionEvaluator::evaluate(StarFunction::Subject, std::slice::from_ref(&quoted2))
                .unwrap();

        let outer_subject =
            FunctionEvaluator::evaluate(StarFunction::Subject, &[inner_subject]).unwrap();

        assert_eq!(
            outer_subject,
            StarTerm::iri("http://example.org/alice").unwrap()
        );
    }

    #[test]
    fn test_error_cases() {
        // Wrong number of arguments
        let result = FunctionEvaluator::evaluate(
            StarFunction::Triple,
            &[StarTerm::iri("http://example.org/alice").unwrap()],
        );
        assert!(result.is_err());

        // Invalid subject for TRIPLE
        let result = FunctionEvaluator::evaluate(
            StarFunction::Triple,
            &[
                StarTerm::literal("invalid_subject").unwrap(),
                StarTerm::iri("http://example.org/p").unwrap(),
                StarTerm::literal("o").unwrap(),
            ],
        );
        assert!(result.is_err());

        // Non-triple argument to SUBJECT
        let result = FunctionEvaluator::evaluate(
            StarFunction::Subject,
            &[StarTerm::iri("http://example.org/notATriple").unwrap()],
        );
        assert!(result.is_err());
    }
}