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
//! Implementation of IRIs as per
//! [\[RFC 3987\]](https://tools.ietf.org/html/rfc3987).
//!
//! This module is transparently reexported by its parent module.
//!

use super::{Iri, IRELATIVE_REF_REGEX, IRI_REGEX};
use crate::mown_str::MownStr;
use crate::ns::Namespace;
use crate::{Literal, MownTerm, Result, Term, TermData, TermError};
use std::fmt;

/// Resolve some kind of IRI with `self` as the base.
pub trait Resolve<S, T> {
    /// Resolve relative IRI(s) somewhat contained in `other` with `self` as
    /// the base IRI.
    fn resolve(&self, other: S) -> T;
}

/// Keeps track of the different components of an IRI reference.
///
/// NB: this type does not store the actual text of the IRI reference,
/// it borrows it from one (or possibly several) external `str`s.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct IriParsed<'a> {
    scheme: Option<&'a str>,
    authority: Option<&'a str>,
    /// NB: path complies with the following rules:
    /// - does not contain the separators ('/')
    /// - its first element is "" if the path starts with '/'
    /// - its last element is "" if the path ends with a '/'
    path: Vec<&'a str>,
    query: Option<&'a str>,
    fragment: Option<&'a str>,
}

impl<'a> IriParsed<'a> {
    /// Parse the given `str` as an IRI reference,
    /// and return its inner structure (or fail with a `TermError`).
    pub fn new(txt: &'a str) -> Result<IriParsed<'a>> {
        let mut pi = IriParsed::default();
        let path: Option<&str>;
        if let Some(cap) = IRI_REGEX.captures(txt) {
            pi.scheme = cap.get(1).map(|m| m.as_str());
            pi.authority = cap.get(2).map(|m| m.as_str());
            pi.query = cap.get(6).map(|m| m.as_str());
            pi.fragment = cap.get(7).map(|m| m.as_str());
            path = cap
                .get(3)
                .or_else(|| cap.get(4))
                .or_else(|| cap.get(5))
                .map(|m| m.as_str())
                .filter(|s| !s.is_empty());
        } else if let Some(cap) = IRELATIVE_REF_REGEX.captures(txt) {
            pi.authority = cap.get(1).map(|m| m.as_str());
            pi.query = cap.get(5).map(|m| m.as_str());
            pi.fragment = cap.get(6).map(|m| m.as_str());
            path = cap
                .get(2)
                .or_else(|| cap.get(3))
                .or_else(|| cap.get(4))
                .map(|m| m.as_str())
                .filter(|s| !s.is_empty());
        } else {
            return Err(TermError::InvalidIri(txt.to_owned()));
        }
        if let Some(path) = path {
            path.split('/').for_each(|i| pi.path.push(i))
        }
        Ok(pi)
    }

    /// Return `true` if this IRI reference is absolute.
    pub fn is_absolute(&self) -> bool {
        self.scheme.is_some()
    }

    /// Resolve `other` using this IRI reference as the base.
    ///
    /// NB: the resulting `IriParsed` may borrow parts from both parts.
    pub fn join(&self, other: &IriParsed<'a>) -> IriParsed<'a> {
        let (scheme, authority, query, fragment);
        let mut path;
        if other.scheme.is_some() {
            scheme = other.scheme;
            authority = other.authority;
            path = other.path.clone();
            query = other.query;
        } else {
            scheme = self.scheme;
            if other.authority.is_some() {
                authority = other.authority;
                path = other.path.clone();
                query = other.query;
            } else {
                authority = self.authority;
                if other.path.is_empty() {
                    path = self.path.clone();
                    query = other.query.or(self.query);
                } else {
                    if other.path[0] == "" {
                        path = other.path.clone();
                    } else {
                        path = self.merged_path(&other.path);
                    }
                    query = other.query;
                }
            }
        }
        remove_dot_segments(&mut path);
        fragment = other.fragment;
        IriParsed {
            scheme,
            authority,
            path,
            query,
            fragment,
        }
    }

    /// Appends the given path to `self`'s own path.
    fn merged_path(&self, path: &[&'a str]) -> Vec<&'a str> {
        if self.authority.is_some() && self.path.is_empty() {
            // resulting path must have a leading '/'
            std::iter::once("").chain(path.iter().cloned()).collect()
        } else {
            self.path
                .iter()
                .take(self.path.len() - 1)
                .cloned()
                .chain(path.iter().cloned())
                .collect()
        }
    }
}

impl<'a, 'b> Resolve<&'a str, Result<MownStr<'a>>> for IriParsed<'b> {
    /// Resolve an IRI given as `String`.
    ///
    /// Fails if `other` is not a valid IRI.
    fn resolve(&self, other: &'a str) -> Result<MownStr<'a>> {
        let other_parsed = IriParsed::new(other)?;
        if other_parsed.is_absolute() {
            Ok(other.into())
        } else {
            Ok(self.join(&other_parsed).to_string().into())
        }
    }
}

impl<'a> Resolve<&'a IriParsed<'a>, IriParsed<'a>> for IriParsed<'a> {
    /// Just a call to `IriParsed::join()`
    fn resolve(&self, other: &'a IriParsed<'a>) -> IriParsed<'a> {
        self.join(other)
    }
}

impl<'a, 'b> Resolve<Iri<&'a str>, Iri<MownStr<'a>>> for IriParsed<'b> {
    /// Resolve the given IRI.
    ///
    /// # Performance
    ///
    /// May allocate an intermediate IRI if `other` is suffixed.
    fn resolve(&self, other: Iri<&'a str>) -> Iri<MownStr<'a>> {
        if other.absolute {
            return other.map_into();
        }
        let mut buffer = String::new();
        let parsed = other.parse_components(&mut buffer);
        let joined = self.join(&parsed);
        Iri::new_unchecked(joined.to_string(), joined.is_absolute())
    }
}

impl<'a, 'b, TD> Resolve<&'a Iri<TD>, Iri<MownStr<'a>>> for IriParsed<'b>
where
    TD: TermData,
{
    /// Resolve the given IRI.
    ///
    /// # Performance
    ///
    /// May allocate an intermediate IRI if `other` is suffixed.
    fn resolve(&self, other: &'a Iri<TD>) -> Iri<MownStr<'a>> {
        self.resolve(other.as_ref_str())
    }
}

impl<'a, 'b, TD> Resolve<&'a Namespace<TD>, Namespace<MownStr<'a>>> for IriParsed<'b>
where
    TD: TermData,
{
    /// Resolve the IRI of the given `Namespace`.
    fn resolve(&self, other: &'a Namespace<TD>) -> Namespace<MownStr<'a>> {
        let iri = other.0.as_ref();
        let resolved: MownStr = self.resolve(iri).expect("Is valid as from Namespace");
        Namespace(resolved)
    }
}

impl<'a, 'b, TD> Resolve<&'a Literal<TD>, Literal<MownStr<'a>>> for IriParsed<'b>
where
    TD: TermData,
{
    /// Resolve the data type's IRI if it is relative.
    ///
    /// Note that this only affects datatyped literals;
    /// language-tagged literals are absolute by construction.
    ///
    /// # Performance
    ///
    /// May allocate an intermediate IRI if `other.dt()` is suffixed.
    fn resolve(&self, other: &'a Literal<TD>) -> Literal<MownStr<'a>> {
        if other.is_absolute() {
            other.clone_into()
        } else {
            Literal::new_dt(other.txt().as_ref(), self.resolve(other.dt()))
        }
    }
}

impl<'a, 'b, TD> Resolve<&'a Term<TD>, MownTerm<'a>> for IriParsed<'b>
where
    TD: TermData,
{
    /// Resolve IRIs and the IRIs of typed literals.
    ///
    /// # Performance
    ///
    /// May allocate an intermediate IRI if an IRI is suffixed.
    fn resolve(&self, other: &'a Term<TD>) -> MownTerm<'a> {
        match other {
            Term::Iri(iri) => Resolve::<_, Iri<MownStr>>::resolve(self, iri).into(),
            Term::Literal(lit) => Resolve::<_, Literal<MownStr>>::resolve(self, lit).into(),
            term => term.clone_into(),
        }
    }
}

impl fmt::Display for IriParsed<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        if let Some(scheme) = self.scheme {
            write!(f, "{}:", scheme)?;
        }
        if let Some(authority) = self.authority {
            write!(f, "//{}", authority)?;
        }
        if !self.path.is_empty() {
            write!(f, "{}", self.path[0])?;
            for p in &self.path[1..] {
                write!(f, "/{}", p)?;
            }
        }
        if let Some(query) = self.query {
            write!(f, "?{}", query)?;
        }
        if let Some(fragment) = self.fragment {
            write!(f, "#{}", fragment)?;
        }
        Ok(())
    }
}

fn remove_dot_segments(path: &mut Vec<&str>) {
    if path.is_empty() {
        return;
    }
    let mut i = 0;
    let last = path[path.len() - 1];
    if last == "." || last == ".." {
        path.push("");
    }
    while i < path.len() {
        if path[i] == "." {
            path.remove(i);
        } else if path[i] == ".." {
            if i != 0 && (i != 1 || path[0] != "") {
                path.remove(i - 1);
                i -= 1;
            }
            path.remove(i);
        } else {
            i += 1;
        }
    }
}

#[cfg(test)]
mod test {
    use super::super::test::{NEGATIVE_IRIS, POSITIVE_IRIS, RELATIVE_IRIS};
    use super::*;
    use crate::RefTerm;

    #[test]
    fn positive() {
        for (txt, parsed) in POSITIVE_IRIS {
            let rpi = IriParsed::new(txt);
            assert!(rpi.is_ok(), format!("<{}> → {:?}", txt, rpi));
            let pi = rpi.unwrap();
            assert_eq!(pi.is_absolute(), parsed.0);
            assert_eq!(pi.scheme, parsed.1);
            assert_eq!(pi.authority, parsed.2);
            assert_eq!(&pi.path[..], parsed.3);
            assert_eq!(pi.query, parsed.4);
            assert_eq!(pi.fragment, parsed.5);
            assert_eq!(&pi.to_string(), txt);
        }
    }

    #[test]
    fn negative() {
        for txt in NEGATIVE_IRIS {
            let rpi = IriParsed::new(txt);
            assert!(rpi.is_err(), format!("<{}> → {:?}", txt, rpi));
        }
    }

    #[test]
    fn relative() {
        let base = IriParsed::new("http://a/b/c/d;p?q").unwrap();
        for (rel, abs) in RELATIVE_IRIS {
            let rel = IriParsed::new(rel).unwrap();
            let got = base.join(&rel);
            assert_eq!(&got.to_string(), abs);
        }
    }

    #[test]
    fn resolve_str() {
        let base = IriParsed::new("http://a/b/c/d;p?q").unwrap();
        for (rel, abs) in RELATIVE_IRIS {
            let got = base.resolve(*rel).unwrap();
            assert_eq!(got, *abs);
        }
    }

    #[test]
    fn resolve_bad_str() {
        let base = IriParsed::new("http://a/b/c/d;p?q").unwrap();
        for txt in NEGATIVE_IRIS {
            assert!(base.resolve(*txt).is_err());
        }
    }

    #[test]
    fn resolve_iri_parsed() {
        let base = IriParsed::new("http://a/b/c/d;p?q").unwrap();
        for (rel, abs) in RELATIVE_IRIS {
            let rel = IriParsed::new(rel).unwrap();
            let got = base.resolve(&rel);
            assert_eq!(&got.to_string(), abs);
        }
    }

    #[test]
    fn resolve_namespace() {
        let base = IriParsed::new("http://a/b/c/d;p?q").unwrap();
        for (rel, abs) in RELATIVE_IRIS {
            let rel = Namespace::<&str>::new(*rel).unwrap();
            let got = base.resolve(&rel);
            assert_eq!(&got.as_ref(), abs);
        }
    }

    #[test]
    fn resolve_iri() {
        let base = IriParsed::new("http://a/b/c/d;p?q").unwrap();
        for (rel, abs) in RELATIVE_IRIS {
            let rel = Iri::<&str>::new(*rel).unwrap();
            let got = base.resolve(&rel);
            assert_eq!(&got.value(), abs);
        }
    }

    #[test]
    fn resolve_literal() {
        let base = IriParsed::new("http://a/b/c/d;p?q").unwrap();
        for (rel, abs) in RELATIVE_IRIS {
            let rel = Iri::<&str>::new(*rel).unwrap();
            let lit = Literal::<&str>::new_dt("hello", rel);
            let got = base.resolve(&lit);
            assert_eq!(&got.dt().value(), abs);
        }
    }

    #[test]
    fn resolve_iri_term() {
        let base = IriParsed::new("http://a/b/c/d;p?q").unwrap();
        for (rel, abs) in RELATIVE_IRIS {
            let rel = RefTerm::new_iri(*rel).unwrap();
            let got = base.resolve(&rel);
            assert_eq!(&got.value(), abs);
        }
    }
}