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

use pest::iterators::Pair;

use crate::ast::*;
use crate::error::Result;
use crate::parser::FromPair;
use crate::parser::Rule;

/// A term frame, describing a class.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct TermFrame {
    id: Line<ClassIdent>,
    clauses: Vec<Line<TermClause>>,
}

impl TermFrame {
    /// Create a new term frame with the given ID but without any clause.
    ///
    /// # Example
    /// ```rust
    /// # extern crate fastobo;
    /// # use std::str::FromStr;
    /// # use fastobo::ast::*;
    /// let id = ClassIdent::from(PrefixedIdent::new("MS", "1000031"));
    /// let frame = TermFrame::new(id);
    /// assert_eq!(frame.to_string(), "[Term]\nid: MS:1000031\n");
    /// ```
    pub fn new<I>(id: I) -> Self
    where
        I: Into<Line<ClassIdent>>,
    {
        Self::with_clauses(id, Vec::new())
    }

    /// Create a new term frame with the provided ID and clauses.
    pub fn with_clauses<I>(id: I, clauses: Vec<Line<TermClause>>) -> Self
    where
        I: Into<Line<ClassIdent>>,
    {
        Self {
            id: id.into(),
            clauses,
        }
    }

    /// Get a reference to the identifier of the `TermFrame`.
    pub fn id(&self) -> &Line<ClassIdent> {
        &self.id
    }

    /// Get a mutable reference to the identifier of the `TermFrame`.
    pub fn id_mut(&mut self) -> &mut Line<ClassIdent> {
        &mut self.id
    }

    /// Get the `TermClause`s of the `TermFrame`.
    pub fn clauses(&self) -> &Vec<Line<TermClause>> {
        &self.clauses
    }

    /// Get a mutable reference to the `TermClause`s of the `TermFrame`.
    pub fn clauses_mut(&mut self) -> &mut Vec<Line<TermClause>> {
        &mut self.clauses
    }

    /// Check if the class has a *genus-differentia* definition.
    ///
    /// *Genus-differentia* definition is a method of intensional definition
    /// which uses an existing definition (the *genus*) and portions of the
    /// new definition not provided by the *genera* (the *differentia*).
    ///
    /// A frame has such a definition if it contains some `intersection_of`
    /// clauses, but only one in the form `intersection_of: <ClassIdent>`.
    ///
    /// # See also
    /// - [Genus differentia definition](https://en.wikiversity.org/wiki/Dominant_group/Genus_differentia_definition)
    ///   on [Wikiversity](https://en.wikiversity.org/).
    pub fn is_genus_differentia(&self) -> bool {
        let mut has_differentia = false;
        let mut genus_count = 0;

        for clause in &self.clauses {
            if let TermClause::IntersectionOf(r, _) = clause.as_ref() {
                match r {
                    Some(_) => has_differentia = true,
                    None => genus_count += 1,
                }
            }
        }

        genus_count == 1 && has_differentia
    }

}

impl AsRef<Vec<Line<TermClause>>> for TermFrame {
    fn as_ref(&self) -> &Vec<Line<TermClause>> {
        &self.clauses
    }
}

impl AsRef<[Line<TermClause>]> for TermFrame {
    fn as_ref(&self) -> &[Line<TermClause>] {
        &self.clauses
    }
}

impl Deref for TermFrame {
    type Target = Vec<Line<TermClause>>;
    fn deref(&self) -> &Self::Target {
        &self.clauses
    }
}

impl DerefMut for TermFrame {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.clauses
    }
}

impl Display for TermFrame {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        f.write_str("[Term]\nid: ").and(self.id.fmt(f))?;
        self.clauses.iter().try_for_each(|clause| clause.fmt(f))
    }
}

impl Identified for TermFrame {
    /// Get a reference to the identifier of the term.
    fn as_id(&self) -> &Ident {
        self.id.as_inner().as_ref()
    }

    /// Get a mutable reference to the identifier of the term.
    fn as_id_mut(&mut self) -> &mut Ident {
        self.id.as_mut().as_mut()
    }
}

/// Create a new term frame with the frame ID given as a `Line`.
impl From<Line<ClassIdent>> for TermFrame {
    fn from(line: Line<ClassIdent>) -> Self {
        Self::new(line)
    }
}

/// Create a new term frame with the frame ID given as a `ClassIdent`.
impl From<ClassIdent> for TermFrame {
    fn from(id: ClassIdent) -> Self {
        Self::new(id)
    }
}

impl<'i> FromPair<'i> for TermFrame {
    const RULE: Rule = Rule::TermFrame;
    unsafe fn from_pair_unchecked(pair: Pair<'i, Rule>) -> Result<Self> {

        use crate::parser::QuickFind;
        let n = pair.as_str().quickcount(b'\n');

        let mut inner = pair.into_inner();
        let clsid = ClassIdent::from_pair_unchecked(inner.next().unwrap())?;
        let id = Eol::from_pair_unchecked(inner.next().unwrap())?.and_inner(clsid);

        let mut clauses = Vec::with_capacity(n-1);

        for pair in inner {
            clauses.push(Line::<TermClause>::from_pair_unchecked(pair)?);
        }

        Ok(TermFrame { id, clauses })
    }
}
impl_fromstr!(TermFrame);

impl IntoIterator for TermFrame {
    type Item = Line<TermClause>;
    type IntoIter = <Vec<Line<TermClause>> as IntoIterator>::IntoIter;
    fn into_iter(self) -> Self::IntoIter {
        self.clauses.into_iter()
    }
}

impl<'a> IntoIterator for &'a TermFrame {
    type Item = &'a Line<TermClause>;
    type IntoIter = <&'a Vec<Line<TermClause>> as IntoIterator>::IntoIter;
    fn into_iter(self) -> Self::IntoIter {
        self.clauses.as_slice().iter()
    }
}

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

#[cfg(test)]
mod tests {

    use std::str::FromStr;
    use pretty_assertions::assert_eq;
    use super::*;

    #[test]
    fn is_genus_differentia() {

        // Genus w/ 1 differentia
        let term = TermFrame::from_str(
            "[Term]
            id: TEST:01
            intersection_of: TEST:02
            intersection_of: part_of TEST:03\n"
        ).unwrap();
        assert!(term.is_genus_differentia());

        // Genus w/ 1+ differentia
        let term = TermFrame::from_str(
            "[Term]
            id: TEST:01
            intersection_of: TEST:02
            intersection_of: part_of TEST:03
            intersection_of: has_part TEST:04\n"
        ).unwrap();
        assert!(term.is_genus_differentia());

        // Genus w/o differentia (cardinality error)
        let term = TermFrame::from_str(
            "[Term]
            id: TEST:01
            intersection_of: TEST:02\n"
        ).unwrap();
        assert!(!term.is_genus_differentia());

        // Differentia w/o genus (cardinality error)
        let term = TermFrame::from_str(
            "[Term]
            id: TEST:01
            intersection_of: part_of TEST:03\n"
        ).unwrap();
        assert!(!term.is_genus_differentia());

        // No intersection_of clause
        let term = TermFrame::from_str("[Term]\nid: TEST:01\n").unwrap();
        assert!(!term.is_genus_differentia());
    }

    #[test]
    fn from_str() {
        let actual = TermFrame::from_str(
            "[Term]
            id: MS:1000008
            name: ionization type
            def: \"The method by which gas phase ions are generated from the sample.\" [PSI:MS]
            relationship: part_of MS:1000458 ! source\n",
        )
        .unwrap();
        self::assert_eq!(
            actual.id.as_ref(),
            &ClassIdent::from(Ident::from(PrefixedIdent::new("MS", "1000008")))
        );

        assert!(TermFrame::from_str(
            "[Term]
            id: PO:0000067
            name: proteoid root
            namespace: plant_anatomy
            xref: PO_GIT:588
            is_a: PO:0009005 ! root
            created_by: austinmeier
            creation_date: 2015-08-11T15:05:12Z\n",
        ).is_ok());
    }
}