oxirs-star 0.3.1

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
//! Lexer and low-level parsing primitives for RDF-star.
//!
//! This sibling module of `crate::parser` contains the lexical analysis helpers
//! and triple/quad/term parsing primitives that operate on individual tokens.

use anyhow::Result;

use crate::model::{StarQuad, StarTerm, StarTriple};
use crate::parser::context::{ErrorSeverity, ParseContext};
use crate::parser::tokenizer;
use crate::parser::StarParser;
use crate::{StarError, StarResult};

impl StarParser {
    /// Parse triple pattern with enhanced error handling
    pub(crate) fn parse_triple_pattern_safe(
        &self,
        pattern: &str,
        context: &mut ParseContext,
    ) -> StarResult<StarTriple> {
        self.parse_triple_pattern_safe_with_depth(pattern, context, 0)
    }

    /// Parse term with enhanced error handling
    pub(crate) fn parse_term_safe(
        &self,
        term_str: &str,
        context: &mut ParseContext,
    ) -> StarResult<StarTerm> {
        self.parse_term_safe_with_depth(term_str, context, 0)
    }

    /// Parse term with depth tracking for quoted triples
    pub(crate) fn parse_term_safe_with_depth(
        &self,
        term_str: &str,
        context: &mut ParseContext,
        depth: usize,
    ) -> StarResult<StarTerm> {
        const MAX_QUOTED_TRIPLE_DEPTH: usize = 100;

        let term_str = term_str.trim();

        // Check for empty input
        if term_str.is_empty() {
            let error_msg = "Empty term in triple".to_string();
            context.add_error(
                error_msg.clone(),
                term_str.to_string(),
                ErrorSeverity::Error,
            );
            return Err(StarError::parse_error(error_msg));
        }

        // Quoted triple: << ... >>
        if term_str.starts_with("<<") && term_str.ends_with(">>") {
            // Check depth limit to prevent stack overflow
            if depth >= MAX_QUOTED_TRIPLE_DEPTH {
                let error_msg = format!(
                    "Maximum quoted triple nesting depth ({MAX_QUOTED_TRIPLE_DEPTH}) exceeded"
                );
                context.add_error(
                    error_msg.clone(),
                    term_str.to_string(),
                    ErrorSeverity::Error,
                );
                return Err(StarError::parse_error(error_msg));
            }

            let inner = &term_str[2..term_str.len() - 2].trim();

            // Check for empty quoted triple
            if inner.is_empty() {
                let error_msg = "Empty quoted triple content".to_string();
                context.add_error(
                    error_msg.clone(),
                    term_str.to_string(),
                    ErrorSeverity::Error,
                );
                if context.strict_mode {
                    return Err(StarError::parse_error(error_msg));
                }
                // In non-strict mode, create a placeholder error term
                return self
                    .parse_term("<urn:error:empty-quoted-triple>", context)
                    .map_err(|e| StarError::parse_error(e.to_string()));
            }

            // Validate proper quoted triple delimiters
            if !self.validate_quoted_triple_delimiters(term_str) {
                let error_msg = "Malformed quoted triple delimiters".to_string();
                context.add_error(
                    error_msg.clone(),
                    term_str.to_string(),
                    ErrorSeverity::Error,
                );
                if context.strict_mode {
                    return Err(StarError::parse_error(error_msg));
                }
            }

            match self.parse_triple_pattern_safe_with_depth(inner, context, depth + 1) {
                Ok(inner_triple) => return Ok(StarTerm::quoted_triple(inner_triple)),
                Err(e) => {
                    let error_msg = format!("Failed to parse quoted triple content: {e}");
                    context.add_error(
                        error_msg.clone(),
                        term_str.to_string(),
                        ErrorSeverity::Error,
                    );
                    if context.strict_mode {
                        return Err(StarError::parse_error(error_msg));
                    }
                    // In non-strict mode, try to parse as regular term
                    // but with better error context
                    return self.parse_term_fallback(term_str, context, &error_msg);
                }
            }
        }

        // Continue with other term types...
        self.parse_term(term_str, context)
            .map_err(|e| StarError::parse_error(e.to_string()))
    }

    /// Validate quoted triple delimiter structure
    pub(crate) fn validate_quoted_triple_delimiters(&self, term_str: &str) -> bool {
        let mut depth = 0;
        let mut chars = term_str.chars().peekable();

        while let Some(ch) = chars.next() {
            match ch {
                '<' if chars.peek() == Some(&'<') => {
                    chars.next(); // consume second '<'
                    depth += 1;
                }
                '>' if chars.peek() == Some(&'>') => {
                    chars.next(); // consume second '>'
                    depth -= 1;
                    if depth < 0 {
                        return false; // More closing than opening
                    }
                }
                _ => {}
            }
        }

        depth == 0 // Should be balanced
    }

    /// Parse triple pattern with depth tracking
    pub(crate) fn parse_triple_pattern_safe_with_depth(
        &self,
        pattern: &str,
        context: &mut ParseContext,
        depth: usize,
    ) -> StarResult<StarTriple> {
        match self.tokenize_triple(pattern) {
            Ok(terms) => {
                if terms.len() != 3 {
                    let error_msg = format!(
                        "Triple must have exactly 3 terms, found {} (depth: {})",
                        terms.len(),
                        depth
                    );
                    context.add_error(error_msg.clone(), pattern.to_string(), ErrorSeverity::Error);
                    return Err(StarError::parse_error(error_msg));
                }

                let subject = self.parse_term_safe_with_depth(&terms[0], context, depth)?;
                let predicate = self.parse_term_safe_with_depth(&terms[1], context, depth)?;
                let object = self.parse_term_safe_with_depth(&terms[2], context, depth)?;

                let triple = StarTriple::new(subject, predicate, object);

                // Validate the constructed triple
                if let Err(validation_error) = triple.validate() {
                    let error_msg = format!("Invalid triple at depth {depth}: {validation_error}");
                    context.add_error(error_msg.clone(), pattern.to_string(), ErrorSeverity::Error);
                    return Err(StarError::parse_error(error_msg));
                }

                Ok(triple)
            }
            Err(e) => {
                let error_msg = format!("Failed to tokenize triple at depth {depth}: {e}");
                context.add_error(error_msg.clone(), pattern.to_string(), ErrorSeverity::Error);
                Err(StarError::parse_error(error_msg))
            }
        }
    }

    /// Fallback parsing with better error context
    pub(crate) fn parse_term_fallback(
        &self,
        term_str: &str,
        context: &mut ParseContext,
        original_error: &str,
    ) -> StarResult<StarTerm> {
        match self.parse_term(term_str, context) {
            Ok(term) => {
                // Log a warning that we fell back to regular parsing
                context.add_error(
                    format!(
                        "Quoted triple parsing failed, parsed as regular term: {original_error}"
                    ),
                    term_str.to_string(),
                    ErrorSeverity::Warning,
                );
                Ok(term)
            }
            Err(fallback_error) => {
                let combined_error = format!("Both quoted triple and regular term parsing failed. Quoted triple error: {original_error}. Regular term error: {fallback_error}");
                context.add_error(
                    combined_error.clone(),
                    term_str.to_string(),
                    ErrorSeverity::Error,
                );
                Err(StarError::parse_error(combined_error))
            }
        }
    }

    /// Parse a quad pattern with enhanced error handling
    pub(crate) fn parse_quad_pattern_safe(
        &self,
        pattern: &str,
        context: &mut ParseContext,
    ) -> StarResult<StarQuad> {
        match self.tokenize_quad(pattern) {
            Ok(terms) => {
                if terms.len() < 3 || terms.len() > 4 {
                    let error_msg = format!("Quad must have 3 or 4 terms, found {}", terms.len());
                    context.add_error(error_msg.clone(), pattern.to_string(), ErrorSeverity::Error);
                    return Err(StarError::parse_error(error_msg));
                }

                let subject = self.parse_term_safe(&terms[0], context)?;
                let predicate = self.parse_term_safe(&terms[1], context)?;
                let object = self.parse_term_safe(&terms[2], context)?;

                // Graph is optional in N-Quads (default graph if omitted)
                let graph = if terms.len() == 4 {
                    Some(self.parse_term_safe(&terms[3], context)?)
                } else {
                    None
                };

                let quad = StarQuad::new(subject, predicate, object, graph);

                // Validate the constructed quad
                if let Err(validation_error) = quad.validate() {
                    let error_msg = format!("Invalid quad: {validation_error}");
                    context.add_error(error_msg.clone(), pattern.to_string(), ErrorSeverity::Error);
                    return Err(StarError::parse_error(error_msg));
                }

                Ok(quad)
            }
            Err(e) => {
                let error_msg = format!("Failed to tokenize quad: {e}");
                context.add_error(error_msg.clone(), pattern.to_string(), ErrorSeverity::Error);
                Err(StarError::parse_error(error_msg))
            }
        }
    }

    /// Parse a quad pattern (subject predicate object graph)
    #[allow(dead_code)]
    pub(crate) fn parse_quad_pattern(
        &self,
        pattern: &str,
        context: &mut ParseContext,
    ) -> Result<StarQuad> {
        let terms = self.tokenize_quad(pattern)?;

        if terms.len() < 3 || terms.len() > 4 {
            return Err(anyhow::anyhow!(
                "Quad must have 3 or 4 terms, found {}",
                terms.len()
            ));
        }

        let subject = self.parse_term(&terms[0], context)?;
        let predicate = self.parse_term(&terms[1], context)?;
        let object = self.parse_term(&terms[2], context)?;

        // Graph is optional in N-Quads (default graph if omitted)
        let graph = if terms.len() == 4 {
            Some(self.parse_term(&terms[3], context)?)
        } else {
            None
        };

        Ok(StarQuad {
            subject,
            predicate,
            object,
            graph,
        })
    }

    /// Parse a triple pattern (subject predicate object)
    pub(crate) fn parse_triple_pattern(
        &self,
        pattern: &str,
        context: &mut ParseContext,
    ) -> Result<StarTriple> {
        let terms = self.tokenize_triple(pattern)?;

        if terms.len() != 3 {
            return Err(anyhow::anyhow!(
                "Triple must have exactly 3 terms, found {}",
                terms.len()
            ));
        }

        let subject = self.parse_term(&terms[0], context)?;
        let predicate = self.parse_term(&terms[1], context)?;
        let object = self.parse_term(&terms[2], context)?;

        let triple = StarTriple::new(subject, predicate, object);
        triple
            .validate()
            .map_err(|e| anyhow::anyhow!("Invalid triple: {}", e))?;

        Ok(triple)
    }

    /// Tokenize a triple into its three components, handling quoted triples
    pub(crate) fn tokenize_triple(&self, pattern: &str) -> Result<Vec<String>> {
        tokenizer::tokenize_triple(pattern)
    }

    /// Tokenize a quad pattern (similar to triple but allows 4 terms)
    pub(crate) fn tokenize_quad(&self, pattern: &str) -> Result<Vec<String>> {
        tokenizer::tokenize_quad(pattern)
    }

    /// Parse a single term (IRI, blank node, literal, or quoted triple)
    pub(crate) fn parse_term(
        &self,
        term_str: &str,
        context: &mut ParseContext,
    ) -> Result<StarTerm> {
        let term_str = term_str.trim();

        // Quoted triple: << ... >>
        if term_str.starts_with("<<") && term_str.ends_with(">>") {
            let inner = &term_str[2..term_str.len() - 2];
            let inner_triple = self.parse_triple_pattern(inner, context)?;
            return Ok(StarTerm::quoted_triple(inner_triple));
        }

        // IRI: <...> or prefixed name
        if term_str.starts_with('<') && term_str.ends_with('>') {
            let iri = &term_str[1..term_str.len() - 1];
            let resolved = context.resolve_relative(iri);
            return StarTerm::iri(&resolved).map_err(|e| anyhow::anyhow!("Invalid IRI: {}", e));
        }

        // Prefixed name
        if term_str.contains(':') && !term_str.starts_with('_') && !term_str.starts_with('"') {
            let resolved = context.resolve_prefix(term_str)?;
            return StarTerm::iri(&resolved).map_err(|e| anyhow::anyhow!("Invalid IRI: {}", e));
        }

        // Blank node: _:id
        if let Some(id) = term_str.strip_prefix("_:") {
            return StarTerm::blank_node(id)
                .map_err(|e| anyhow::anyhow!("Invalid blank node: {}", e));
        }

        // Literal: "value"@lang or "value"^^<datatype>
        if term_str.starts_with('"') {
            return self.parse_literal(term_str, context);
        }

        // Variable: ?name (for SPARQL-star)
        if let Some(name) = term_str.strip_prefix('?') {
            return StarTerm::variable(name)
                .map_err(|e| anyhow::anyhow!("Invalid variable: {}", e));
        }

        Err(anyhow::anyhow!("Unrecognized term format: {}", term_str))
    }

    /// Parse a literal term with optional language tag or datatype
    pub(crate) fn parse_literal(
        &self,
        literal_str: &str,
        context: &mut ParseContext,
    ) -> Result<StarTerm> {
        let mut chars = literal_str.chars().peekable();
        let mut value = String::new();
        let mut escape_next = false;

        // Skip opening quote
        if chars.next() != Some('"') {
            return Err(anyhow::anyhow!("Literal must start with quote"));
        }
        let mut in_string = true;

        // Parse value
        for ch in chars.by_ref() {
            if escape_next {
                value.push(ch);
                escape_next = false;
                continue;
            }

            match ch {
                '\\' => {
                    escape_next = true;
                }
                '"' => {
                    in_string = false;
                    break;
                }
                _ => {
                    value.push(ch);
                }
            }
        }

        if in_string {
            return Err(anyhow::anyhow!("Unterminated string literal"));
        }

        // Check for language tag or datatype
        let remaining: String = chars.collect();

        if let Some(lang) = remaining.strip_prefix('@') {
            Ok(StarTerm::literal_with_language(&value, lang)
                .map_err(|e| anyhow::anyhow!("Invalid literal: {}", e))?)
        } else if let Some(datatype_str) = remaining.strip_prefix("^^") {
            let datatype = if let Some(stripped) = datatype_str
                .strip_prefix('<')
                .and_then(|s| s.strip_suffix('>'))
            {
                stripped.to_string()
            } else {
                context.resolve_prefix(datatype_str)?
            };
            Ok(StarTerm::literal_with_datatype(&value, &datatype)
                .map_err(|e| anyhow::anyhow!("Invalid literal: {}", e))?)
        } else {
            Ok(StarTerm::literal(&value).map_err(|e| anyhow::anyhow!("Invalid literal: {}", e))?)
        }
    }
}