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

use fastobo_derive_internal::FromStr;

use crate::ast::*;
use crate::error::CardinalityError;
use crate::error::SyntaxError;
use crate::parser::Cache;
use crate::parser::FromPair;
use crate::semantics::OboFrame;
use crate::semantics::Orderable;
use crate::syntax::pest::iterators::Pair;
use crate::syntax::Rule;

/// The header frame, containing metadata about an OBO document.
#[derive(Clone, Debug, Default, Eq, FromStr, Hash, PartialEq)]
pub struct HeaderFrame {
    clauses: Vec<HeaderClause>,
}

impl HeaderFrame {
    /// Create a new empty `HeaderFrame`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new `HeaderFrame` containing the provided clauses.
    pub fn with_clauses(clauses: Vec<HeaderClause>) -> Self {
        Self { clauses }
    }

    /// Create a new `HeaderFrame` containing only a single clause.
    pub fn from_clause(clause: HeaderClause) -> Self {
        Self::with_clauses(vec![clause])
    }

    /// Get the default namespace of the ontology, if any is declared.
    ///
    /// # 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.
    pub fn default_namespace(&self) -> Result<&NamespaceIdent, CardinalityError> {
        let mut namespace: Option<&NamespaceIdent> = None;
        for clause in &self.clauses {
            if let HeaderClause::DefaultNamespace(ns) = clause {
                match namespace {
                    Some(_) => return Err(CardinalityError::duplicate("default-namespace")),
                    None => namespace = Some(ns),
                }
            }
        }
        namespace.ok_or_else(|| CardinalityError::missing("default-namespace"))
    }

    /// Get the format version of the ontology, if any is declared.
    pub fn format_version(&self) -> Result<&UnquotedString, CardinalityError> {
        let mut version: Option<&UnquotedString> = None;
        for clause in &self.clauses {
            if let HeaderClause::FormatVersion(v) = clause {
                match version {
                    Some(_) => return Err(CardinalityError::duplicate("format-version")),
                    None => version = Some(v),
                }
            }
        }
        version.ok_or_else(|| CardinalityError::missing("format-version"))
    }

    /// Get the data version of the ontology, if any is declared.
    pub fn data_version(&self) -> Result<&UnquotedString, CardinalityError> {
        let mut version: Option<&UnquotedString> = None;
        for clause in &self.clauses {
            if let HeaderClause::DataVersion(v) = clause {
                match version {
                    Some(_) => return Err(CardinalityError::duplicate("data-version")),
                    None => version = Some(v),
                }
            }
        }
        version.ok_or_else(|| CardinalityError::missing("data-version"))
    }

    /// Merge several OWL axioms into a single clause.
    pub fn merge_owl_axioms(&mut self) {
        let mut merged = Vec::new();
        let clauses_new = Vec::with_capacity(self.clauses.len());
        for clause in std::mem::replace(&mut self.clauses, clauses_new) {
            if let HeaderClause::OwlAxioms(axioms) = clause {
                merged.push(axioms.into_string());
            } else {
                self.clauses.push(clause);
            }
        }

        if !merged.is_empty() {
            let s = UnquotedString::new(merged.join("\n"));
            self.clauses.push(HeaderClause::OwlAxioms(Box::new(s)));
        }
    }
}

impl AsMut<[HeaderClause]> for HeaderFrame {
    fn as_mut(&mut self) -> &mut [HeaderClause] {
        &mut self.clauses
    }
}

impl AsMut<Vec<HeaderClause>> for HeaderFrame {
    fn as_mut(&mut self) -> &mut Vec<HeaderClause> {
        &mut self.clauses
    }
}

impl AsRef<[HeaderClause]> for HeaderFrame {
    fn as_ref(&self) -> &[HeaderClause] {
        &self.clauses
    }
}

impl AsRef<Vec<HeaderClause>> for HeaderFrame {
    fn as_ref(&self) -> &Vec<HeaderClause> {
        &self.clauses
    }
}

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

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

impl Display for HeaderFrame {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        for clause in self.clauses.iter() {
            clause.fmt(f).and(f.write_char('\n'))?;
        }
        Ok(())
    }
}

impl From<HeaderFrame> for Vec<HeaderClause> {
    fn from(frame: HeaderFrame) -> Self {
        frame.clauses
    }
}

impl From<HeaderClause> for HeaderFrame {
    fn from(clause: HeaderClause) -> Self {
        Self::from_clause(clause)
    }
}

impl From<Vec<HeaderClause>> for HeaderFrame {
    fn from(clauses: Vec<HeaderClause>) -> Self {
        Self::with_clauses(clauses)
    }
}

impl FromIterator<HeaderClause> for HeaderFrame {
    fn from_iter<T>(iter: T) -> Self
    where
        T: IntoIterator<Item = HeaderClause>,
    {
        Self::with_clauses(iter.into_iter().collect())
    }
}

impl<'i> FromPair<'i> for HeaderFrame {
    const RULE: Rule = Rule::HeaderFrame;
    unsafe fn from_pair_unchecked(
        pair: Pair<'i, Rule>,
        cache: &Cache,
    ) -> Result<Self, SyntaxError> {
        let mut clauses = Vec::new();
        for inner in pair.into_inner() {
            clauses.push(HeaderClause::from_pair_unchecked(inner, cache)?)
        }
        Ok(HeaderFrame::with_clauses(clauses))
    }
}

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

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

impl<'a> IntoIterator for &'a mut HeaderFrame {
    type Item = &'a mut HeaderClause;
    type IntoIter = <&'a mut Vec<HeaderClause> as IntoIterator>::IntoIter;
    fn into_iter(self) -> Self::IntoIter {
        self.clauses.as_mut_slice().iter_mut()
    }
}

impl Orderable for HeaderFrame {
    fn sort(&mut self) {
        // NB: not `sort_unstable` to avoid shuffling owl-axioms
        self.clauses.sort();
    }
    fn is_sorted(&self) -> bool {
        for i in 1..self.clauses.len() {
            if self.clauses[i - 1] > self.clauses[i] {
                return false;
            }
        }
        true
    }
}

impl OboFrame for HeaderFrame {
    type Clause = HeaderClause;

    fn clauses_ref(&self) -> Vec<&Self::Clause> {
        self.clauses.iter().collect()
    }
}

#[cfg(test)]
mod tests {

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

    #[test]
    fn data_version() {
        let mut frame = HeaderFrame::new();
        self::assert_eq!(
            frame.data_version(),
            Err(CardinalityError::missing("data-version"))
        );

        let v = UnquotedString::from("1.4");
        frame.push(HeaderClause::DataVersion(Box::new(v.clone())));
        self::assert_eq!(frame.data_version(), Ok(&v));

        frame.push(HeaderClause::DataVersion(Box::new(v)));
        self::assert_eq!(
            frame.data_version(),
            Err(CardinalityError::duplicate("data-version"))
        );
    }

    #[test]
    fn default_namespace() {
        let mut frame = HeaderFrame::new();
        self::assert_eq!(
            frame.default_namespace(),
            Err(CardinalityError::missing("default-namespace"))
        );

        let ns = NamespaceIdent::from(UnprefixedIdent::new("TEST"));
        frame.push(HeaderClause::DefaultNamespace(Box::new(ns.clone())));
        self::assert_eq!(frame.default_namespace(), Ok(&ns));

        frame.push(HeaderClause::DefaultNamespace(Box::new(ns)));
        self::assert_eq!(
            frame.default_namespace(),
            Err(CardinalityError::duplicate("default-namespace"))
        );
    }

    #[test]
    fn format_version() {
        let mut frame = HeaderFrame::new();
        self::assert_eq!(
            frame.format_version(),
            Err(CardinalityError::missing("format-version"))
        );

        let v = UnquotedString::from("1.4");
        frame.push(HeaderClause::FormatVersion(Box::new(v.clone())));
        self::assert_eq!(frame.format_version(), Ok(&v));

        frame.push(HeaderClause::FormatVersion(Box::new(v)));
        self::assert_eq!(
            frame.format_version(),
            Err(CardinalityError::duplicate("format-version"))
        );
    }

    #[test]
    fn from_clause() {
        let clause = HeaderClause::FormatVersion(Box::new(UnquotedString::new("1.0")));

        let frame = HeaderFrame::from_clause(clause.clone());
        self::assert_eq!(frame.clauses, vec![clause.clone()]);
        self::assert_eq!(frame, HeaderFrame::from(clause));
    }

    #[test]
    fn from_str() {
        let actual = HeaderFrame::from_str(
            "format-version: 1.2
            data-version: releases/2019-03-17
            subsetdef: gocheck_do_not_annotate \"Term not to be used for direct annotation\"
            synonymtypedef: syngo_official_label \"label approved by the SynGO project\"
            synonymtypedef: systematic_synonym \"Systematic synonym\" EXACT
            default-namespace: gene_ontology
            remark: cvs version: $Revision: 38972$
            remark: Includes Ontology(OntologyID(OntologyIRI(<http://purl.obolibrary.org/obo/go/never_in_taxon.owl>))) [Axioms: 18 Logical Axioms: 0]
            ontology: go
            property_value: http://purl.org/dc/elements/1.1/license http://creativecommons.org/licenses/by/4.0/"
        ).unwrap();

        assert_eq!(
            actual.clauses[0],
            HeaderClause::FormatVersion(Box::new(UnquotedString::new("1.2"))),
        );

        assert_eq!(
            actual.clauses[1],
            HeaderClause::DataVersion(Box::new(UnquotedString::new("releases/2019-03-17"))),
        );

        assert_eq!(
            actual.clauses[2],
            HeaderClause::Subsetdef(
                Box::new(SubsetIdent::from(UnprefixedIdent::new(
                    "gocheck_do_not_annotate"
                ))),
                Box::new(QuotedString::new(
                    "Term not to be used for direct annotation"
                )),
            )
        );
    }

    #[test]
    fn new() {
        let frame = HeaderFrame::new();
        self::assert_eq!(frame.clauses, Vec::new());
    }

    #[test]
    fn is_sorted() {
        let frame = HeaderFrame::new();
        assert!(frame.is_sorted());

        let frame = HeaderFrame::with_clauses(vec![
            HeaderClause::FormatVersion(Box::new(UnquotedString::new("1.4"))),
            HeaderClause::DataVersion(Box::new(UnquotedString::new("v0.2.0"))),
            HeaderClause::SavedBy(Box::new(UnquotedString::new("Martin Larralde"))),
        ]);
        assert!(frame.is_sorted());

        let frame = HeaderFrame::with_clauses(vec![
            HeaderClause::FormatVersion(Box::new(UnquotedString::new("1.4"))),
            HeaderClause::SavedBy(Box::new(UnquotedString::new("Martin Larralde"))),
            HeaderClause::DataVersion(Box::new(UnquotedString::new("v0.2.0"))),
        ]);
        assert!(!frame.is_sorted());
    }

    #[test]
    fn sort() {
        let mut frame = HeaderFrame::with_clauses(vec![
            HeaderClause::SavedBy(Box::new(UnquotedString::new("Martin Larralde"))),
            HeaderClause::DataVersion(Box::new(UnquotedString::new("v0.2.0"))),
            HeaderClause::FormatVersion(Box::new(UnquotedString::new("1.4"))),
        ]);
        frame.sort();
        assert_eq!(
            frame,
            HeaderFrame::with_clauses(vec![
                HeaderClause::FormatVersion(Box::new(UnquotedString::new("1.4"))),
                HeaderClause::DataVersion(Box::new(UnquotedString::new("v0.2.0"))),
                HeaderClause::SavedBy(Box::new(UnquotedString::new("Martin Larralde"))),
            ])
        );
    }

    #[test]
    fn cardinality_check() {
        let frame = HeaderFrame::with_clauses(vec![
            HeaderClause::SavedBy(Box::new(UnquotedString::new("Martin Larralde"))),
            HeaderClause::DataVersion(Box::new(UnquotedString::new("v0.2.0"))),
            HeaderClause::FormatVersion(Box::new(UnquotedString::new("1.4"))),
        ]);
        assert!(frame.cardinality_check().is_ok());

        let frame2 = HeaderFrame::with_clauses(vec![
            HeaderClause::FormatVersion(Box::new(UnquotedString::new("1.4"))),
            HeaderClause::FormatVersion(Box::new(UnquotedString::new("1.5"))),
        ]);
        assert!(frame2.cardinality_check().is_err());
    }
}