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
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::fmt::Write;
use std::iter::IntoIterator;
use std::iter::FromIterator;
use std::ops::Deref;
use std::str::FromStr;

use pest::iterators::Pair;
use pest::error::Error as PestError;
use pest::error::InputLocation;

use crate::ast::*;
use crate::error::Error;
use crate::error::Result;
use crate::parser::FromPair;
use crate::parser::Rule;
use crate::share::Share;

/// A database cross-reference definition.
///
/// Cross-references can be used in `Def` or `Synonym` clauses of entity
/// frames to add sources for the provided definition or evidence to show the
/// actual existence of a synonym. They can also be found in `Xref` clauses
/// when the cross-reference is directly relevant to the annotated entity
/// (e.g. when exporting an ontology from a knowledge-base to add an hyperlink
/// to the original resource).
#[derive(Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
pub struct Xref {
    id: Ident,
    desc: Option<QuotedString>,
}

impl Xref {

    /// Create a new `Xref` from the given ID, without description.
    pub fn new<I>(id: I) -> Self
    where
        I: Into<Ident>,
    {
        Self::with_desc(id, None)
    }

    /// Create a new `Xref` with the given ID and optional description.
    pub fn with_desc<I, D>(id: I, desc: D) -> Self
    where
        I: Into<Ident>,
        D: Into<Option<QuotedString>>,
    {
        Self {
            id: id.into(),
            desc: desc.into(),
        }
    }

    /// Get a mutable reference to the identifier of the xref.
    pub fn id(&self) -> &Ident {
        &self.id
    }

    /// Get a reference to the identifier of the xref.
    pub fn id_mut(&mut self) -> &mut Ident {
        &mut self.id
    }

    /// Get a reference to the description of the xref, if any.
    pub fn description(&self) -> Option<&QuotedString> {
        match self.desc {
            Some(ref d) => Some(d),
            None => None,
        }
    }

    /// Get a mutable reference to the description of the xref, if any.
    pub fn description_mut(&mut self) -> Option<&mut QuotedString> {
        match self.desc {
            Some(ref mut d) => Some(d),
            None => None,
        }
    }
}

impl Display for Xref {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        self.id.fmt(f)?;
        match &self.desc {
            Some(desc) => f.write_char(' ').and(desc.fmt(f)),
            None => Ok(()),
        }
    }
}

impl<'i> FromPair<'i> for Xref {
    const RULE: Rule = Rule::Xref;
    unsafe fn from_pair_unchecked(pair: Pair<'i, Rule>) -> Result<Self> {
        let mut inner = pair.into_inner();
        let id = FromPair::from_pair_unchecked(inner.next().unwrap())?;
        let desc = match inner.next() {
            Some(pair) => Some(QuotedString::from_pair_unchecked(pair)?),
            None => None,
        };
        Ok(Xref { id, desc })
    }
}
impl_fromstr!(Xref);

impl Identified for Xref {
    fn as_id(&self) -> &Ident {
        &self.id
    }
    fn as_id_mut(&mut self) -> &mut Ident {
        &mut self.id
    }
}

/// A list of containing zero or more `Xref`s.
#[derive(Clone, Default, Debug, Hash, Eq, OpaqueTypedef, Ord, PartialOrd, PartialEq)]
#[opaque_typedef(allow_mut_ref)]
#[opaque_typedef(derive(
    AsRef(Inner, Self),
    AsMut(Inner, Self),
    Deref,
    DerefMut,
    Into(Inner),
    FromInner,
    PartialEq(Inner),
))]
pub struct XrefList {
    xrefs: Vec<Xref>,
}

impl XrefList {
    pub fn new(xrefs: Vec<Xref>) -> Self {
        Self { xrefs }
    }
}

impl AsRef<[Xref]> for XrefList {
    fn as_ref(&self) -> &[Xref] {
        &self.xrefs
    }
}

impl Display for XrefList {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        f.write_char('[')?;
        let mut xrefs = self.xrefs.iter().peekable();
        while let Some(xref) = xrefs.next() {
            // FIXME(@althonos): commas in id need escaping.
            xref.id().fmt(f)?;
            if let Some(ref desc) = xref.description() {
                f.write_char(' ').and(desc.fmt(f))?;
            }
            if xrefs.peek().is_some() {
                f.write_str(", ")?;
            }
        }
        f.write_char(']')
    }
}

impl FromIterator<Xref> for XrefList {
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = Xref>
    {
        Self::new(iter.into_iter().collect())
    }
}

impl<'i> FromPair<'i> for XrefList {
    const RULE: Rule = Rule::XrefList;
    unsafe fn from_pair_unchecked(pair: Pair<'i, Rule>) -> Result<Self> {
        let mut xrefs = Vec::new();
        for inner in pair.into_inner() {
            let xref = Xref::from_str(inner.as_str())
                .map_err(|e| e.with_span(inner.as_span()))?;
            xrefs.push(xref);
        }
        Ok(Self { xrefs })
    }
}
impl_fromstr!(XrefList);

impl IntoIterator for XrefList {
    type Item = Xref;
    type IntoIter = <Vec<Xref> as IntoIterator>::IntoIter;
    fn into_iter(self) -> Self::IntoIter {
        self.xrefs.into_iter()
    }
}

impl Orderable for XrefList {
    fn sort(&mut self) {
        self.xrefs.sort_unstable();
    }
    fn is_sorted(&self) -> bool {
        for i in 1..self.xrefs.len() {
            if self.xrefs[i-1] > self.xrefs[i] {
                return false;
            }
        }
        true
    }
}

#[cfg(test)]
mod tests {

    use pretty_assertions::assert_eq;
    use super::*;

    mod list {

        use super::*;

        #[test]
        fn from_str() {
            let actual = XrefList::from_str("[]").unwrap();
            let expected = XrefList::from(vec![]);
            self::assert_eq!(actual, expected);

            let actual = XrefList::from_str("[PSI:MS]").unwrap();
            let expected = XrefList::from(vec![Xref::new(PrefixedIdent::new("PSI", "MS"))]);
            self::assert_eq!(actual, expected);

            let actual = XrefList::from_str(
                "[PSI:MS, reactome:R-HSA-8983680 \"OAS1 produces oligoadenylates\"]",
            )
            .unwrap();
            let expected = XrefList::from(vec![
                Xref::new(PrefixedIdent::new("PSI", "MS")),
                Xref::with_desc(
                    PrefixedIdent::new("reactome", "R-HSA-8983680"),
                    QuotedString::new("OAS1 produces oligoadenylates"),
                ),
            ]);
            self::assert_eq!(actual, expected);
        }
    }
}