fastobo/parser/
sequential.rs

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
use std::convert::TryFrom;
use std::fs::File;
use std::io::BufRead;
use std::io::BufReader;
use std::iter::Iterator;

use crate::ast::EntityFrame;
use crate::ast::Frame;
use crate::ast::HeaderClause;
use crate::ast::HeaderFrame;
use crate::ast::OboDoc;
use crate::error::Error;
use crate::error::SyntaxError;
use crate::syntax::Lexer;
use crate::syntax::Rule;

use super::Cache;
use super::FromPair;
use super::Parser;

/// An iterator reading entity frames contained in an OBO stream sequentially.
pub struct SequentialParser<B: BufRead> {
    stream: B,
    line: String,
    offset: usize,
    line_offset: usize,
    header: Option<Result<Frame, Error>>,
    cache: Cache,
}

impl<B: BufRead> AsRef<B> for SequentialParser<B> {
    fn as_ref(&self) -> &B {
        &self.stream
    }
}

impl<B: BufRead> AsRef<B> for Box<SequentialParser<B>> {
    fn as_ref(&self) -> &B {
        (**self).as_ref()
    }
}

impl<B: BufRead> AsMut<B> for SequentialParser<B> {
    fn as_mut(&mut self) -> &mut B {
        &mut self.stream
    }
}

impl<B: BufRead> AsMut<B> for Box<SequentialParser<B>> {
    fn as_mut(&mut self) -> &mut B {
        (**self).as_mut()
    }
}

impl<B: BufRead> From<B> for SequentialParser<B> {
    fn from(reader: B) -> Self {
        <Self as Parser<B>>::new(reader)
    }
}

impl<B: BufRead> From<B> for Box<SequentialParser<B>> {
    fn from(stream: B) -> Self {
        Box::new(SequentialParser::from(stream))
    }
}

impl<B: BufRead> Iterator for SequentialParser<B> {
    type Item = Result<Frame, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut l: &str;
        let mut frame_lines = String::new();
        let mut local_line_offset = 0;
        let mut local_offset = 0;

        if let Some(res) = self.header.take() {
            return Some(res);
        }

        while !self.line.is_empty() {
            // Store the line in the frame lines and clear the buffer.
            frame_lines.push_str(&self.line);
            self.line.clear();

            // Read the next line.
            if let Err(e) = self.stream.read_line(&mut self.line) {
                return Some(Err(Error::from(e)));
            }

            // Process the frame if we reached the next frame.
            l = self.line.trim_start();
            if l.starts_with('[') || self.line.is_empty() {
                let res = unsafe {
                    match Lexer::tokenize(Rule::EntitySingle, &frame_lines) {
                        Ok(mut pairs) => {
                            EntityFrame::from_pair_unchecked(pairs.next().unwrap(), &self.cache)
                                .map_err(Error::from)
                        }
                        Err(e) => Err(Error::from(
                            SyntaxError::from(e).with_offsets(self.line_offset, self.offset),
                        )),
                    }
                };

                // Update offsets
                self.line_offset += local_line_offset + 1;
                self.offset += local_offset + self.line.len();
                return Some(res.map(Frame::from));
            }

            // Update local offsets
            local_line_offset += 1;
            local_offset += self.line.len();
        }

        None
    }
}

impl<B: BufRead> Parser<B> for SequentialParser<B> {
    /// Create a new `SequentialParser` from the given stream.
    ///
    /// The constructor will parse the header frame right away, and return an
    /// error if it fails. The header can then be accessed using the `header`
    /// method.
    fn new(mut stream: B) -> Self {
        let cache = Cache::default();
        let mut line = String::new();
        let mut l: &str;
        let mut offset = 0;
        let mut line_offset = 0;
        let mut frame_clauses = Vec::new();

        let header = loop {
            // Read the next line
            line.clear();
            if let Err(e) = stream.read_line(&mut line) {
                break Some(Err(Error::from(e)));
            };
            l = line.trim_start();

            // Parse header as long as we didn't reach EOL or first frame.
            if !l.starts_with('[') && !l.is_empty() {
                unsafe {
                    // use `fastobo_syntax::Lexer` to tokenize the input
                    let p = match Lexer::tokenize(Rule::HeaderClause, &line) {
                        Ok(mut pairs) => pairs.next().unwrap(),
                        Err(e) => {
                            let err = SyntaxError::from(e).with_offsets(line_offset, offset);
                            break Some(Err(Error::from(err)));
                        }
                    };
                    // produce a header clause from the token stream
                    match HeaderClause::from_pair_unchecked(p, &cache) {
                        Ok(clause) => frame_clauses.push(clause),
                        Err(e) => {
                            let err = e.with_offsets(line_offset, offset);
                            break Some(Err(Error::from(err)));
                        }
                    }
                }
            }

            if l.starts_with('[') || line.is_empty() {
                // Bail out if we reached EOL or first frame.
                let frame = Frame::from(HeaderFrame::from(frame_clauses));
                break Some(Ok(frame));
            } else {
                // Update offsets
                line_offset += 1;
                offset += line.len();
            }
        };

        Self {
            stream,
            line,
            offset,
            line_offset,
            header,
            cache,
        }
    }

    /// Make the parser yield frames in the order they appear in the document.
    ///
    /// This has no effect on `SequentialParser` since the frames are always
    /// processed in the document order, but this method is provided for
    /// consistency of the [`FrameReader`](./type.FrameReader.html) type.
    fn ordered(&mut self, _ordered: bool) -> &mut Self {
        self
    }

    /// Consume the reader and extract the internal reader.
    fn into_inner(self) -> B {
        self.stream
    }
}

impl<B: BufRead> Parser<B> for Box<SequentialParser<B>> {
    fn new(stream: B) -> Self {
        Box::new(SequentialParser::new(stream))
    }

    fn ordered(&mut self, ordered: bool) -> &mut Self {
        (**self).ordered(ordered);
        self
    }

    fn into_inner(self) -> B {
        (*self).into_inner()
    }
}

impl<B: BufRead> TryFrom<SequentialParser<B>> for OboDoc {
    type Error = Error;
    fn try_from(mut parser: SequentialParser<B>) -> Result<Self, Self::Error> {
        OboDoc::try_from(&mut parser)
    }
}

impl<B: BufRead> TryFrom<&mut SequentialParser<B>> for OboDoc {
    type Error = Error;
    fn try_from(parser: &mut SequentialParser<B>) -> Result<Self, Self::Error> {
        // extract the header and create the doc
        let header = parser.next().unwrap()?.into_header().unwrap();

        // extract the remaining entities
        let entities = parser
            .map(|r| r.map(|f| f.into_entity().unwrap()))
            .collect::<Result<Vec<EntityFrame>, Error>>()?;

        // return the doc
        Ok(OboDoc::with_header(header).and_entities(entities))
    }
}

impl<B: BufRead> TryFrom<Box<SequentialParser<B>>> for OboDoc {
    type Error = Error;
    fn try_from(mut reader: Box<SequentialParser<B>>) -> Result<Self, Self::Error> {
        OboDoc::try_from(&mut (*reader))
    }
}

impl From<File> for SequentialParser<BufReader<File>> {
    fn from(f: File) -> Self {
        Self::new(BufReader::new(f))
    }
}

impl From<File> for Box<SequentialParser<BufReader<File>>> {
    fn from(f: File) -> Self {
        Box::new(SequentialParser::new(BufReader::new(f)))
    }
}