oxrdf 0.1.2

A library providing basic data structures related to RDF
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
use crate::vocab::xsd;
use crate::{
    BlankNode, BlankNodeIdParseError, IriParseError, LanguageTagParseError, Literal, NamedNode,
    Term, Variable, VariableNameParseError,
};
#[cfg(feature = "rdf-star")]
use crate::{Subject, Triple};
use std::char;
use std::error::Error;
use std::fmt;
use std::str::{Chars, FromStr};

/// This limit is set in order to avoid stack overflow error when parsing nested triples due to too many recursive calls.
/// The actual limit value is a wet finger compromise between not failing to parse valid files and avoiding to trigger stack overflow errors.
const MAX_NUMBER_OF_NESTED_TRIPLES: usize = 128;

impl FromStr for NamedNode {
    type Err = TermParseError;

    /// Parses a named node from its NTriples and Turtle serialization
    ///
    /// ```
    /// use oxrdf::NamedNode;
    /// use std::str::FromStr;
    ///
    /// assert_eq!(NamedNode::from_str("<http://example.com>").unwrap(), NamedNode::new("http://example.com").unwrap())
    /// ```
    fn from_str(s: &str) -> Result<Self, TermParseError> {
        let (term, left) = read_named_node(s)?;
        if !left.is_empty() {
            return Err(TermParseError::msg(
                "Named node serialization should end with a >",
            ));
        }
        Ok(term)
    }
}

impl FromStr for BlankNode {
    type Err = TermParseError;

    /// Parses a blank node from its NTriples and Turtle serialization
    ///
    /// ```
    /// use oxrdf::BlankNode;
    /// use std::str::FromStr;
    ///
    /// assert_eq!(BlankNode::from_str("_:ex").unwrap(), BlankNode::new("ex").unwrap())
    /// ```
    fn from_str(s: &str) -> Result<Self, TermParseError> {
        let (term, left) = read_blank_node(s)?;
        if !left.is_empty() {
            return Err(TermParseError::msg(
                "Blank node serialization should not contain whitespaces",
            ));
        }
        Ok(term)
    }
}

impl FromStr for Literal {
    type Err = TermParseError;

    /// Parses a literal from its NTriples or Turtle serialization
    ///
    /// ```
    /// use oxrdf::{Literal, NamedNode, vocab::xsd};
    /// use std::str::FromStr;
    ///
    /// assert_eq!(Literal::from_str("\"ex\\n\"").unwrap(), Literal::new_simple_literal("ex\n"));
    /// assert_eq!(Literal::from_str("\"ex\"@en").unwrap(), Literal::new_language_tagged_literal("ex", "en").unwrap());
    /// assert_eq!(Literal::from_str("\"2020\"^^<http://www.w3.org/2001/XMLSchema#gYear>").unwrap(), Literal::new_typed_literal("2020", NamedNode::new("http://www.w3.org/2001/XMLSchema#gYear").unwrap()));
    /// assert_eq!(Literal::from_str("true").unwrap(), Literal::new_typed_literal("true", xsd::BOOLEAN));
    /// assert_eq!(Literal::from_str("+122").unwrap(), Literal::new_typed_literal("+122", xsd::INTEGER));
    /// assert_eq!(Literal::from_str("-122.23").unwrap(), Literal::new_typed_literal("-122.23", xsd::DECIMAL));
    /// assert_eq!(Literal::from_str("-122e+1").unwrap(), Literal::new_typed_literal("-122e+1", xsd::DOUBLE));
    /// ```
    fn from_str(s: &str) -> Result<Self, TermParseError> {
        let (term, left) = read_literal(s)?;
        if !left.is_empty() {
            return Err(TermParseError::msg("Invalid literal serialization"));
        }
        Ok(term)
    }
}

impl FromStr for Term {
    type Err = TermParseError;

    /// Parses a term from its NTriples or Turtle serialization
    ///
    /// ```
    /// use oxrdf::*;
    /// use std::str::FromStr;
    ///
    /// assert_eq!(Term::from_str("\"ex\"").unwrap(), Literal::new_simple_literal("ex").into());
    /// assert_eq!(Term::from_str("<< _:s <http://example.com/p> \"o\" >>").unwrap(), Triple::new(
    ///     BlankNode::new("s").unwrap(),
    ///     NamedNode::new("http://example.com/p").unwrap(),
    ///     Literal::new_simple_literal("o")
    /// ).into());
    /// ```
    fn from_str(s: &str) -> Result<Self, TermParseError> {
        let (term, left) = read_term(s, 0)?;
        if !left.is_empty() {
            return Err(TermParseError::msg("Invalid term serialization"));
        }
        Ok(term)
    }
}

impl FromStr for Variable {
    type Err = TermParseError;

    /// Parses a variable from its SPARQL serialization
    ///
    /// ```
    /// use oxrdf::Variable;
    /// use std::str::FromStr;
    ///
    /// assert_eq!(Variable::from_str("$foo").unwrap(), Variable::new("foo").unwrap())
    /// ```
    fn from_str(s: &str) -> Result<Self, TermParseError> {
        if !s.starts_with('?') && !s.starts_with('$') {
            return Err(TermParseError::msg(
                "Variable serialization should start with ? or $",
            ));
        }
        Self::new(&s[1..]).map_err(|error| TermParseError {
            kind: TermParseErrorKind::Variable {
                value: s.to_owned(),
                error,
            },
        })
    }
}

fn read_named_node(s: &str) -> Result<(NamedNode, &str), TermParseError> {
    let s = s.trim();
    if let Some(remain) = s.strip_prefix('<') {
        let end = remain
            .find('>')
            .ok_or_else(|| TermParseError::msg("Named node serialization should end with a >"))?;
        let (value, remain) = remain.split_at(end);
        let remain = &remain[1..];
        let term = NamedNode::new(value).map_err(|error| TermParseError {
            kind: TermParseErrorKind::Iri {
                value: value.to_owned(),
                error,
            },
        })?;
        Ok((term, remain))
    } else {
        Err(TermParseError::msg(
            "Named node serialization should start with a <",
        ))
    }
}

fn read_blank_node(s: &str) -> Result<(BlankNode, &str), TermParseError> {
    let s = s.trim();
    if let Some(remain) = s.strip_prefix("_:") {
        let end = remain
            .find(|v: char| v.is_whitespace() || matches!(v, '<' | '_' | '?' | '$' | '"' | '\''))
            .unwrap_or(remain.len());
        let (value, remain) = remain.split_at(end);
        let term = BlankNode::new(value).map_err(|error| TermParseError {
            kind: TermParseErrorKind::BlankNode {
                value: value.to_owned(),
                error,
            },
        })?;
        Ok((term, remain))
    } else {
        Err(TermParseError::msg(
            "Blank node serialization should start with '_:'",
        ))
    }
}

fn read_literal(s: &str) -> Result<(Literal, &str), TermParseError> {
    let s = s.trim();
    if let Some(s) = s.strip_prefix('"') {
        let mut value = String::with_capacity(s.len());
        let mut chars = s.chars();
        while let Some(c) = chars.next() {
            match c {
                '"' => {
                    let remain = chars.as_str();
                    return if let Some(remain) = remain.strip_prefix('@') {
                        let end = remain
                            .find(|v| !matches!(v, 'a'..='z' | 'A'..='Z' | '-'))
                            .unwrap_or(remain.len());
                        let (language, remain) = remain.split_at(end);
                        Ok((
                            Literal::new_language_tagged_literal(value, language).map_err(
                                |error| TermParseError {
                                    kind: TermParseErrorKind::LanguageTag {
                                        value: language.to_owned(),
                                        error,
                                    },
                                },
                            )?,
                            remain,
                        ))
                    } else if let Some(remain) = remain.strip_prefix("^^") {
                        let (datatype, remain) = read_named_node(remain)?;
                        Ok((Literal::new_typed_literal(value, datatype), remain))
                    } else {
                        Ok((Literal::new_simple_literal(value), remain))
                    };
                }
                '\\' => {
                    if let Some(c) = chars.next() {
                        value.push(match c {
                            't' => '\t',
                            'b' => '\u{8}',
                            'n' => '\n',
                            'r' => '\r',
                            'f' => '\u{C}',
                            '"' => '"',
                            '\'' => '\'',
                            '\\' => '\\',
                            'u' => read_hexa_char(&mut chars, 4)?,
                            'U' => read_hexa_char(&mut chars, 8)?,
                            _ => return Err(TermParseError::msg("Unexpected escaped char")),
                        })
                    } else {
                        return Err(TermParseError::msg("Unexpected literal end"));
                    }
                }
                c => value.push(c),
            }
        }
        Err(TermParseError::msg("Unexpected literal end"))
    } else if let Some(remain) = s.strip_prefix("true") {
        Ok((Literal::new_typed_literal("true", xsd::BOOLEAN), remain))
    } else if let Some(remain) = s.strip_prefix("false") {
        Ok((Literal::new_typed_literal("false", xsd::BOOLEAN), remain))
    } else {
        let input = s.as_bytes();
        if input.is_empty() {
            return Err(TermParseError::msg("Empty term serialization"));
        }

        let mut cursor = match input.first() {
            Some(b'+' | b'-') => 1,
            _ => 0,
        };
        let mut with_dot = false;

        let mut count_before: usize = 0;
        while cursor < input.len() && b'0' <= input[cursor] && input[cursor] <= b'9' {
            count_before += 1;
            cursor += 1;
        }

        let mut count_after: usize = 0;
        if cursor < input.len() && input[cursor] == b'.' {
            with_dot = true;
            cursor += 1;
            while cursor < input.len() && b'0' <= input[cursor] && input[cursor] <= b'9' {
                count_after += 1;
                cursor += 1;
            }
        }

        if cursor < input.len() && (input[cursor] == b'e' || input[cursor] == b'E') {
            cursor += 1;
            cursor += match input.get(cursor) {
                Some(b'+' | b'-') => 1,
                _ => 0,
            };
            let mut count_exponent = 0;
            while cursor < input.len() && b'0' <= input[cursor] && input[cursor] <= b'9' {
                count_exponent += 1;
                cursor += 1;
            }
            if count_exponent > 0 {
                Ok((Literal::new_typed_literal(s, xsd::DOUBLE), &s[cursor..]))
            } else {
                Err(TermParseError::msg(
                    "Double serialization with an invalid exponent",
                ))
            }
        } else if with_dot {
            if count_after > 0 {
                Ok((Literal::new_typed_literal(s, xsd::DECIMAL), &s[cursor..]))
            } else {
                Err(TermParseError::msg(
                    "Decimal serialization without floating part",
                ))
            }
        } else if count_before > 0 {
            Ok((Literal::new_typed_literal(s, xsd::INTEGER), &s[cursor..]))
        } else {
            Err(TermParseError::msg("Empty integer serialization"))
        }
    }
}

fn read_term(s: &str, number_of_recursive_calls: usize) -> Result<(Term, &str), TermParseError> {
    if number_of_recursive_calls == MAX_NUMBER_OF_NESTED_TRIPLES {
        return Err(TermParseError::msg(
            "Too many nested triples. The parser fails here to avoid a stack overflow.",
        ));
    }
    let s = s.trim();
    #[allow(unused_variables)]
    if let Some(remain) = s.strip_prefix("<<") {
        #[cfg(feature = "rdf-star")]
        {
            let (subject, remain) = read_term(remain, number_of_recursive_calls + 1)?;
            let (predicate, remain) = read_named_node(remain)?;
            let (object, remain) = read_term(remain, number_of_recursive_calls + 1)?;
            let remain = remain.trim_start();
            if let Some(remain) = remain.strip_prefix(">>") {
                Ok((
                    Triple {
                        subject: match subject {
                            Term::NamedNode(s) => s.into(),
                            Term::BlankNode(s) => s.into(),
                            Term::Literal(_) => {
                                return Err(TermParseError::msg(
                                    "Literals are not allowed in subject position",
                                ))
                            }
                            Term::Triple(s) => Subject::Triple(s),
                        },
                        predicate,
                        object,
                    }
                    .into(),
                    remain,
                ))
            } else {
                Err(TermParseError::msg(
                    "Nested triple serialization should be enclosed between << and >>",
                ))
            }
        }
        #[cfg(not(feature = "rdf-star"))]
        {
            Err(TermParseError::msg("RDF-star is not supported"))
        }
    } else if s.starts_with('<') {
        let (term, remain) = read_named_node(s)?;
        Ok((term.into(), remain))
    } else if s.starts_with('_') {
        let (term, remain) = read_blank_node(s)?;
        Ok((term.into(), remain))
    } else {
        let (term, remain) = read_literal(s)?;
        Ok((term.into(), remain))
    }
}

fn read_hexa_char(input: &mut Chars<'_>, len: usize) -> Result<char, TermParseError> {
    let mut value = 0;
    for _ in 0..len {
        if let Some(c) = input.next() {
            value = value * 16
                + match c {
                    '0'..='9' => u32::from(c) - u32::from('0'),
                    'a'..='f' => u32::from(c) - u32::from('a') + 10,
                    'A'..='F' => u32::from(c) - u32::from('A') + 10,
                    _ => {
                        return Err(TermParseError::msg(
                            "Unexpected character in a unicode escape",
                        ))
                    }
                }
        } else {
            return Err(TermParseError::msg("Unexpected literal string end"));
        }
    }
    char::from_u32(value).ok_or_else(|| TermParseError::msg("Invalid encoded unicode code point"))
}

/// An error raised during term serialization parsing using the [`FromStr`] trait.
#[derive(Debug)]
pub struct TermParseError {
    kind: TermParseErrorKind,
}

#[derive(Debug)]
enum TermParseErrorKind {
    Iri {
        error: IriParseError,
        value: String,
    },
    BlankNode {
        error: BlankNodeIdParseError,
        value: String,
    },
    LanguageTag {
        error: LanguageTagParseError,
        value: String,
    },
    Variable {
        error: VariableNameParseError,
        value: String,
    },
    Msg {
        msg: &'static str,
    },
}

impl fmt::Display for TermParseError {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            TermParseErrorKind::Iri { error, value } => {
                write!(f, "Error while parsing the named node '{value}': {error}")
            }
            TermParseErrorKind::BlankNode { error, value } => {
                write!(f, "Error while parsing the blank node '{value}': {error}")
            }
            TermParseErrorKind::LanguageTag { error, value } => {
                write!(f, "Error while parsing the language tag '{value}': {error}")
            }
            TermParseErrorKind::Variable { error, value } => {
                write!(f, "Error while parsing the variable '{value}': {error}")
            }
            TermParseErrorKind::Msg { msg } => f.write_str(msg),
        }
    }
}

impl Error for TermParseError {}

impl TermParseError {
    pub(crate) fn msg(msg: &'static str) -> Self {
        Self {
            kind: TermParseErrorKind::Msg { msg },
        }
    }
}