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
#![crate_type = "rlib"]
#![crate_type = "dylib"]
extern crate regex;

pub use self::ParserResult::{Succ, Fail, Error};
use std::cmp::{min, Ordering};
use std::fmt;

pub use re::re;
pub use chainl::chainl;
pub use chainr::chainr;
pub use choice::choice;
pub use until::until;
pub use many::many;
pub use many1::many1;
pub use keyword::keyword;
pub use try::try;
pub use skip::skip;
pub use cond::cond;
pub use opt::opt;
pub use wrapper::wrap;
pub use split::split;
pub use many_until::many_until;

pub mod re;
pub mod chainl;
pub mod chainr;
pub mod choice;
pub mod until;
pub mod many;
pub mod many1;
pub mod keyword;
pub mod try;
pub mod skip;
pub mod cond;
pub mod opt;
pub mod wrapper;
pub mod split;
pub mod many_until;
mod macros;


pub struct CharSeq<'a> {
    pub pos: usize,
    pub text: String,
    pub place: String,
    hooks: Vec<&'a (ParserHook+'a)>,
    pub enable_hook: bool,
    pub trace: bool
}

#[derive(Clone)]
pub struct LocationInfo {
    pub col: usize,
    pub row: usize,
    pub pos: usize,
    pub place: String
}

impl Ord for LocationInfo {
    fn cmp(&self, other: &LocationInfo) -> Ordering {
        if self.row == other.row {
            self.col.cmp(&other.col)
        } else {
            self.row.cmp(&other.row)
        }
    }
}

impl PartialOrd for LocationInfo {
    fn partial_cmp(&self, other: &LocationInfo) -> Option<Ordering> {
        Some(self.pos.cmp(&other.pos))
    }
    fn lt(&self, other: &LocationInfo) -> bool {
        self.pos < other.pos
    }
    fn le(&self, other: &LocationInfo) -> bool {
        self.pos <= other.pos
    }
    fn gt(&self, other: &LocationInfo) -> bool {
        self.pos > other.pos
    }
    fn ge(&self, other: &LocationInfo) -> bool {
        self.pos >= other.pos
    }
}


impl PartialEq for LocationInfo {
    fn eq(&self, other: &LocationInfo) -> bool {
        self.pos == other.pos
    }
}

impl Eq for LocationInfo {
}

impl fmt::Display for LocationInfo {
    fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result {
        f.write_str(format!("Col: {}, Row: {} at {}", self.col, self.row, self.place).as_str())
    }
}

pub enum ParserResult<T> {
    Succ(T),
    Error(String, LocationInfo),
    Fail(String, LocationInfo),
}

impl<T> ParserResult<T> {
    pub fn map<S, F>(self, f: F) -> ParserResult<S> where F: Fn(T) -> S {
        match self {
            Succ(c) => Succ(f(c)),
            Fail(m, l) => Fail(m.clone(), l.clone()),
            Error(m, l) => Error(m.clone(), l.clone())
        }
    }

    pub fn and_then<S, F>(self, mut f: F) -> ParserResult<S> where F: FnMut(T) -> ParserResult<S> {
        match self {
            Succ(c) => f(c),
            Fail(m, l) => Fail(m.clone(), l.clone()),
            Error(m, l) => Error(m.clone(), l.clone())
        }
    }
}

impl<'a> CharSeq<'a> {
    pub fn view(&self) -> &str {
        return &self.text[self.pos..];
    }

    pub fn eof(&self) -> bool {
        return self.text.len() <= self.pos;
    }

    pub fn new(t: &str, l: &str) -> CharSeq<'a> {
        return CharSeq{pos: 0, text: t.to_string(), place: l.to_string(), hooks: Vec::new(), enable_hook: true, trace: false};
    }

    pub fn fail<T>(&self, msg: &str) -> ParserResult<T> {
        return Fail(msg.to_string(), self.get_location());
    }

    pub fn get_location(&self) -> LocationInfo {
        let mut col = 1;
        let mut row = 1;
        let max = self.pos;
        let mut i = 0;
        for c in self.text.chars() {
            if i >= max {
                break;
            }
            col += 1;
            if c == '\n' {
                row += 1;
                col = 1;
            }
            i+=1;
        }
        return LocationInfo{col: col, row:row, pos: self.pos, place: self.place.clone()};
    }

    pub fn current(&self) -> char {
        if self.eof() {
            return '\0';
        } else {
            return self.text.chars().nth(self.pos).unwrap();
        }
    }

    pub fn next(&mut self) {
        if !self.eof() {
            self.pos += 1;
        }
    }

    pub fn add_hook(&mut self, hook: &'a (ParserHook+'a)) {
        self.hooks.push(hook);
    }

    #[allow(unused_variables)]
    pub fn do_hook(&mut self) {
        if !self.enable_hook {
            return ();
        }
        self.enable_hook = false;
        for h in self.hooks.clone().iter() {
            h.hook(self);
        }
        self.enable_hook = true;
        return ();
    }

    pub fn accept<T>(&mut self, p: &Parser<T>) -> ParserResult<T> {
        if self.trace {
            println!("{}", self.get_location());
        }
        return p.parse(self);
    }
}


pub trait Parser<T> {
    fn parse(&self, cs: &mut CharSeq) -> ParserResult<T> {
        cs.do_hook();
        let r = self._parse(cs);
        cs.do_hook();
        return r;
    }

    fn _parse(&self, cs: &mut CharSeq) -> ParserResult<T>;
    
    #[allow(unused_variables)]
    fn lookahead(&self, cs: &mut CharSeq) -> bool {
        let p = cs.pos;
        let result = match self.parse(cs) {
            Succ(c) => true,
            Fail(m, l) => false,
            Error(m, l) => false
        };
        cs.pos = p;
        return result;
    }
}

pub trait ParserHook {
    fn hook(&self, cs: &mut CharSeq);
}

impl<'a> Parser<String> for &'a str {
    fn _parse(&self, cs: &mut CharSeq) -> ParserResult<String> {
        if cs.view()[..min(self.len(), cs.view().len())] == **self {
            cs.pos = cs.pos + self.len();
            return Succ(self.to_string().clone());
        } else {
            return cs.fail(*self);
        }
    }
}

#[derive(Clone)]
pub struct EOF;

impl Parser<()> for EOF {
    fn _parse(&self, cs: &mut CharSeq) -> ParserResult<()> {
        if cs.eof() {
            Succ(())
        } else {
            cs.fail("not eof")
        }
    }
}


#[cfg(test)]
#[allow(unused_variables)]
#[allow(unused_imports)]
mod tests {
    use super::{CharSeq, ParserResult, Parser, Succ, Fail, Error};
    #[test]
    fn test_s1() {
        let mut cs = CharSeq::new("abcabcdef", "<mem>");
        assert!(cs.pos == 0);
        match cs.accept(&"abc") {
            Succ(a) => assert!(a == "abc"),
            _ => assert!(false, "bug")
        }
        assert!(cs.pos == 3);
        assert!(cs.view() == "abcdef");

        match cs.accept(&"abc") {
            Succ(a) => assert!(a == "abc"),
            _ => assert!(false, "bug")
        }
        assert!(cs.pos == 6);
        assert!(cs.view() == "def");
        
        match cs.accept(&"abc") {
            Succ(a) => assert!(false, format!("unexcepted result: {}, pos:{}", a, cs.pos)),
            Fail(a, b) => (),
            Error(a, b) => assert!(false, "error")
        }
        assert!(cs.pos == 6);
     
        match cs.accept(&"def") {
            Succ(a) => assert!(a=="def"),
            _ => assert!(false, "bug")
        }
        assert!(cs.pos == 9);
        assert!(cs.eof());

        match cs.accept(&"def") {
            Succ(a) => assert!(false, format!("unexcepted result: {}, pos: {}", a , cs.pos)),
            Fail(a, b) => (),
            Error(a, b) => assert!(false, "error")
        }
        assert!(cs.pos == 9);
        assert!(cs.eof());
    }

    #[test]
    fn test_s2() {
        let mut cs = CharSeq::new("abcdefghi", "<mem>");
        let r = cs.accept(&"abc").and_then(
            |a| cs.accept(&"def").and_then(
                |b| cs.accept(&"ghi").map(
                    |c| {
                        assert!(a == "abc");
                        assert!(b == "def");
                        assert!(c == "ghi");
                    }
                )
            )
        );
    }

    #[test]
    fn test_s3() {
        let mut cs = CharSeq::new("a", "<mem>");
        match cs.accept(&"abc") {
            Succ(a) => assert!(false, format!("unexcepted result: {}, pos: {}", a , cs.pos)),
            Fail(a, b) => (),
            Error(a, b) => assert!(false, "error")
        }
    }
}