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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
use std::convert::TryFrom;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
use std::fmt::Write;
use std::str::FromStr;

use pest::iterators::Pair;
use url::Url;

use crate::ast::*;
use crate::error::CardinalityError;
use crate::error::Error;
use crate::error::SyntaxError;
use crate::parser::FrameReader;
use crate::parser::FromPair;
use crate::parser::Rule;
use crate::semantics::Identified;
use crate::semantics::Orderable;
use crate::share::Cow;
use crate::share::Redeem;
use crate::share::Share;

/// A complete OBO document in format version 1.4.
#[derive(Clone, Default, Debug, Hash, Eq, PartialEq)]
pub struct OboDoc {
    header: HeaderFrame,
    entities: Vec<EntityFrame>,
}

/// Constructors and builder methods.
///
/// # Parser
/// Use `from_file` to parse a file on the local filesystem, or `from_stream`
/// to parse a `BufRead` implementor (`BufRead` is needed instead of `Read` as
/// the parser is line-based):
/// ```rust
/// # extern crate fastobo;
/// # use std::io::BufReader;
/// # use std::fs::File;
/// # use fastobo::ast::*;
/// let doc1 = fastobo::from_file("tests/data/ms.obo").unwrap();
///
/// // This is equivalent to (but with the file path set in eventual errors):
/// let mut r = BufReader::new(File::open("tests/data/ms.obo").unwrap());
/// let doc2 = fastobo::from_reader(&mut r).unwrap();
///
/// assert_eq!(doc1, doc2);
/// ```
///
/// # Builder Pattern
/// The builder pattern makes it easy to create an `OboDoc` from an interator
/// of `EntityFrame`, in order to add an `HeaderFrame` after all the entities
/// where collected:
/// ```rust
/// # extern crate fastobo;
/// # use fastobo::ast::*;
/// use std::iter::FromIterator;
///
/// let entities = vec![TermFrame::new(ClassIdent::from(PrefixedIdent::new("TEST", "001")))];
/// let doc = OboDoc::from_iter(entities.into_iter())
///     .and_header(HeaderFrame::from(HeaderClause::FormatVersion("1.4".into())));
/// ```
impl OboDoc {
    /// Create a new empty OBO document.
    pub fn new() -> Self {
        Default::default()
    }

    /// Create a new OBO document with the provided frame.
    pub fn with_header(header: HeaderFrame) -> Self {
        Self {
            header,
            entities: Default::default(),
        }
    }

    /// Use the provided frame as the header of the OBO document.
    pub fn and_header(mut self, header: HeaderFrame) -> Self {
        self.header = header;
        self
    }

    /// Create a new OBO document with the provided entity frames.
    pub fn with_entities(entities: Vec<EntityFrame>) -> Self {
        Self {
            header: Default::default(),
            entities,
        }
    }

    /// Use the provided entity frames as the content of the OBO document.
    pub fn and_entities(mut self, entities: Vec<EntityFrame>) -> Self {
        self.entities = entities;
        self
    }
}

/// Shared and mutable getters.
impl OboDoc {
    /// Get a reference to the header of the OBO document.
    pub fn header(&self) -> &HeaderFrame {
        &self.header
    }

    /// Get a mutable reference to the header of the OBO document.
    pub fn header_mut(&mut self) -> &mut HeaderFrame {
        &mut self.header
    }

    /// Get a reference to the entities of the OBO document.
    pub fn entities(&self) -> &Vec<EntityFrame> {
        &self.entities
    }

    /// Get a reference to the entities of the OBO document.
    pub fn entities_mut(&mut self) -> &mut Vec<EntityFrame> {
        &mut self.entities
    }

    /// Check whether or not the document is empty.
    ///
    /// An empty document has no header clauses and no entity frames.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.header().is_empty() && self.entities().is_empty()
    }
}

/// Additional methods for `OboDoc` that can be used to edit the syntax tree.
///
/// The OBO 1.4 semantics are used to process header macros or to add the
/// default OBO namespace to all the frames of the document.
impl OboDoc {
    /// Assign the ontology default namespace to all frames without one.
    ///
    /// This function will not check the cardinality of `namespace` clauses in
    /// entity frames: it will only add a single `namespace` clause to all
    /// frames that have none.
    ///
    /// # Errors
    /// - `CardinalityError::MissingClause`: if the header frame does not
    ///   contain any default namespace definition.
    /// - `CardinalityError::DuplicateClauses` if the header frame does
    ///   contain more than one default namespace definition.
    ///
    /// # Example
    /// ```rust
    /// # extern crate fastobo;
    /// # use pretty_assertions::assert_eq;
    /// # use std::str::FromStr;
    /// # use std::string::ToString;
    /// # use fastobo::ast::*;
    /// let mut doc = OboDoc::from_str(
    /// "default-namespace: TST
    ///
    /// [Term]
    /// id: TST:01
    ///
    /// [Term]
    /// id: PATO:0000001
    /// namespace: quality
    /// ").unwrap();
    ///
    /// doc.assign_namespaces().unwrap();
    ///
    /// assert_eq!(doc.to_string(),
    /// "default-namespace: TST
    ///
    /// [Term]
    /// id: TST:01
    /// namespace: TST
    ///
    /// [Term]
    /// id: PATO:0000001
    /// namespace: quality
    /// ");
    ///
    pub fn assign_namespaces(&mut self) -> Result<(), CardinalityError> {
        macro_rules! expand {
            ($frame:ident, $clause:ident, $ns:ident, $outer:lifetime) => ({
                for clause in $frame.iter() {
                    if let $clause::Namespace(_) = clause.as_ref() {
                        continue $outer
                    }
                }
                $frame.push(Line::from($clause::Namespace($ns.clone())));
            });
        }

        use self::EntityFrame::*;

        // Force borrowck to split borrows: we shoudl be able to borrow
        // the header AND the entities at the same time.
        let ns = self.header.default_namespace()?;
        'outer: for entity in &mut self.entities {
            match entity {
                Term(x) => expand!(x, TermClause, ns, 'outer),
                Typedef(x) => expand!(x, TypedefClause, ns, 'outer),
                Instance(x) => expand!(x, InstanceClause, ns, 'outer),
            }
        }

        Ok(())
    }

    /// Process macros in the header frame, adding clauses to relevant entities.
    ///
    /// Header macros are used to expand an ontology by overloading the
    /// actual semantics of  `xref` clauses contained in several entity frames.
    /// In case the translated clauses are already present in the document,
    /// they *won't* be added a second time.
    ///
    /// The following implicit macros will be processed even if they are not
    /// part of the document:
    /// - `treat-xrefs-as-equivalent: RO`
    /// - `treat-xrefs-as-equivalent: BFO`
    ///
    /// # Note
    /// After processing the document, neither the original frame `xrefs`
    /// nor the `treat-xrefs` header clauses will be removed from the AST.
    ///
    /// # See also
    /// - [Header Macro Translation](http://owlcollab.github.io/oboformat/doc/obo-syntax.html#4.4.2)
    ///   section of the syntax and semantics guide.
    pub fn treat_xrefs(&mut self) {
        use self::HeaderClause::*;

        // Force borrowck to split borrows: we should be able to mutably
        // borrow the header AND the entities at the same time.
        let entities = &mut self.entities;

        // Apply implicit macros for `BFO` and `RO`
        crate::semantics::as_equivalent(entities, &IdentPrefix::new("BFO"));
        crate::semantics::as_equivalent(entities, &IdentPrefix::new("RO"));

        // Apply all `treat-xrefs` macros to the document.
        for clause in &self.header {
            match clause {
                TreatXrefsAsEquivalent(prefix) => {
                    crate::semantics::as_equivalent(entities, &prefix)
                }
                TreatXrefsAsIsA(prefix) => crate::semantics::as_is_a(entities, &prefix),
                TreatXrefsAsHasSubclass(prefix) => {
                    crate::semantics::as_has_subclass(entities, &prefix)
                }
                TreatXrefsAsGenusDifferentia(prefix, rel, cls) => {
                    crate::semantics::as_genus_differentia(entities, &prefix, &rel, &cls)
                }
                TreatXrefsAsReverseGenusDifferentia(prefix, rel, cls) => {
                    crate::semantics::as_reverse_genus_differentia(entities, &prefix, &rel, &cls)
                }
                TreatXrefsAsRelationship(prefix, rel) => {
                    crate::semantics::as_relationship(entities, &prefix, &rel)
                }
                _ => (),
            }
        }
    }

    /// Check if the OBO document is fully labeled.
    ///
    /// An OBO ontology is fully labeled if every frame has exactly one `name`
    /// clause. This is equivalent to the definition in the [OBO specification]
    /// if we suppose an invalid OBO document is never *fully labeled*.
    ///
    /// [OBO specification]: http://owlcollab.github.io/oboformat/doc/obo-syntax.html#6.1.5
    pub fn is_fully_labeled(&self) -> bool {
        self.entities.iter().all(|frame| match frame {
            EntityFrame::Term(f) => f.name().is_ok(),
            EntityFrame::Typedef(f) => f.name().is_ok(),
            EntityFrame::Instance(f) => f.name().is_ok(),
        })
    }
}

impl AsRef<[EntityFrame]> for OboDoc {
    fn as_ref(&self) -> &[EntityFrame] {
        self.entities.as_slice()
    }
}

impl AsRef<Vec<EntityFrame>> for OboDoc {
    fn as_ref(&self) -> &Vec<EntityFrame> {
        &self.entities
    }
}

impl AsMut<Vec<EntityFrame>> for OboDoc {
    fn as_mut(&mut self) -> &mut Vec<EntityFrame> {
        &mut self.entities
    }
}

impl Display for OboDoc {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        self.header.fmt(f)?;
        if !self.header.is_empty() && !self.entities.is_empty() {
            f.write_char('\n')?;
        }

        let mut entities = self.entities.iter().peekable();
        while let Some(entity) = entities.next() {
            entity.fmt(f)?;
            if entities.peek().is_some() {
                f.write_char('\n')?;
            }
        }
        Ok(())
    }
}

impl<E> FromIterator<E> for OboDoc
where
    E: Into<EntityFrame>,
{
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = E>,
    {
        Self::with_entities(iter.into_iter().map(Into::into).collect())
    }
}

impl Orderable for OboDoc {
    /// Sort the document in the right serialization order.
    fn sort(&mut self) {
        self.header.sort_unstable();
        // FIXME(@althonos): should probably not require cloning here.
        self.entities.sort_unstable_by_key(|e| e.as_id().clone());
        for entity in &mut self.entities {
            entity.sort()
        }
    }

    /// Check if the document is sorted in the right serialization order.
    fn is_sorted(&self) -> bool {
        // Check entities are sorted on their identifier.
        for i in 1..self.entities.len() {
            if self.entities[i - 1].as_id() > self.entities[i].as_id() {
                return false;
            }
        }

        // Check every entity is sorted.
        for entity in &self.entities {
            if !entity.is_sorted() {
                return false;
            }
        }

        // Check the header is sorted.
        self.header.is_sorted()
    }
}

impl<'i> FromPair<'i> for OboDoc {
    const RULE: Rule = Rule::OboDoc;
    unsafe fn from_pair_unchecked(pair: Pair<'i, Rule>) -> Result<Self, SyntaxError> {
        let mut inner = pair.into_inner();

        let mut entities = Vec::new();
        let header = HeaderFrame::from_pair_unchecked(inner.next().unwrap())?;

        let mut pair = inner.next().unwrap();
        while pair.as_rule() != Rule::EOI {
            entities.push(EntityFrame::from_pair_unchecked(pair)?);
            pair = inner.next().unwrap();
        }
        Ok(OboDoc { header, entities })
    }
}
impl_fromstr!(OboDoc);

#[cfg(test)]
mod tests {

    use super::*;
    use pretty_assertions::assert_eq;
    use std::iter::FromIterator;
    use textwrap::dedent;

    #[test]
    fn from_str() {
        // Empty file should give empty `OboDoc`.
        let doc = OboDoc::from_str("").unwrap();
        self::assert_eq!(doc, Default::default());

        // Empty lines should be ignored.
        let doc = OboDoc::from_str("\n\n").unwrap();
        self::assert_eq!(doc, Default::default());

        // A simple file should parse.
        let doc = OboDoc::from_str(&dedent(
            "
            format-version: 1.2

            [Term]
            id: TEST:001
        ",
        ))
        .unwrap();

        let header = HeaderFrame::from_iter(vec![HeaderClause::FormatVersion(
            UnquotedString::new("1.2"),
        )]);
        let term = TermFrame::new(ClassIdent::from(PrefixedIdent::new("TEST", "001")));
        self::assert_eq!(doc, OboDoc::from_iter(Some(term)).and_header(header));
    }

    #[test]
    fn to_string() {
        // Empty `OboDoc` should give empty string.
        let doc = OboDoc::default();
        self::assert_eq!(doc.to_string(), "");

        // `OboDoc` with only header frame should not add newline separator.
        let doc = OboDoc::with_header(HeaderFrame::from(vec![
            HeaderClause::FormatVersion(UnquotedString::new("1.2")),
            HeaderClause::Remark(UnquotedString::new("this is a test")),
        ]));
        self::assert_eq!(
            doc.to_string(),
            dedent(
                "
            format-version: 1.2
            remark: this is a test
            "
            )
            .trim_start_matches('\n')
        );
    }

    #[test]
    fn is_fully_labeled() {
        let doc = OboDoc::from_str("[Term]\nid: TEST:001\n").unwrap();
        assert!(!doc.is_fully_labeled());

        let doc = OboDoc::from_str("[Term]\nid: TEST:001\nname: test item\n").unwrap();
        assert!(doc.is_fully_labeled());

        let doc = OboDoc::from_str(&dedent(
            "
            [Term]
            id: TEST:001
            name: test item

            [Term]
            id: TEST:002
            name: test item two
        ",
        ))
        .unwrap();
        assert!(doc.is_fully_labeled());

        let doc = OboDoc::from_str(&dedent(
            "
            [Term]
            id: TEST:001
            name: test item

            [Term]
            id: TEST:002
        ",
        ))
        .unwrap();
        assert!(!doc.is_fully_labeled());

        let doc = OboDoc::from_str(&dedent(
            "
            [Term]
            id: TEST:001

            [Term]
            id: TEST:002
            name: test item two
        ",
        ))
        .unwrap();
        assert!(!doc.is_fully_labeled());
    }
}