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
use logos::Logos;
use crate::lexer::LexIt;
use crate::error::ParseError;
use crate::step::Step;
use crate::step::Step::{Error, Fail, Success};


/// The base structure of the parser combinator that providers a set of methods to construct a gramma
///
/// To construct the parser it takes a token set from `Logos` typically as an Enum
///
/// ```
///  use logos::Logos;
///  use crate::parsit::parser::Parsit;
///  #[derive(Logos,PartialEq)]
///     pub enum TFQ {
///         #[token("true")]
///         True,
///         #[token("false")]
///         False,
///
///         #[token("?")]
///         Question,
///     }
///  let p:Parsit<TFQ> = Parsit::new("true?").unwrap();
/// ```
/// Note: The parser works only with string input
///
pub struct Parsit<'a, T> where T: Logos<'a, Source=str>, {
    lexer: LexIt<'a, T>,
}

impl<'a, Token> Parsit<'a, Token>
    where Token: Logos<'a, Source=str> + PartialEq,
{
    /// Creates a parser with aset of tokens from the source
    /// Raises an error if lexer raises an error
    pub fn new(src: &'a str) -> Result<Self, ParseError<'a>>
        where Token::Extras: Default
    {
        Ok(Parsit {
            lexer: LexIt::new(src)?,
        })
    }

    /// obtain a token from the parsing output according to the position number
    ///
    /// # Arguments
    /// * `pos` position number
    ///
    /// # Examples
    /// typically used in the token! macros:
    /// ```ignore
    ///  let p:Parsit<_> = Parsit::new(...)?;
    ///  token!(p.token(0) => ...)
    /// ```
    pub fn token(&self, pos: usize) -> Result<(&Token, usize), ParseError<'a>> {
        self.lexer.token(pos)
    }

    /// executes some rule one or more times shifting the cursor farther.
    /// The operator expects at least one occurance of the given function
    /// # Arguments
    /// * `pos` - starting postion to parse
    /// * `then` - parsing function
    ///
    /// # Examples
    /// ```
    ///  use logos::Logos;
    ///  use crate::parsit::parser::Parsit;
    ///  use crate::parsit::token;
    ///  use crate::parsit::step::Step;
    ///  #[derive(Logos,PartialEq)]
    ///     pub enum TFQ {
    ///         #[token("true")]
    ///         True,
    ///         #[token("false")]
    ///         False,
    ///
    ///         #[token("?")]
    ///         Question,
    ///     }
    ///  let parser:Parsit<TFQ> = Parsit::new("true?false").unwrap();
    ///  let parser_fn = |p|{ token!( parser.token(p) =>
    ///                   TFQ::True => Some(true),
    ///                   TFQ::False => Some(false),
    ///                   TFQ::Question => None
    ///             )};
    ///
    ///   if let Some(res) = parser.one_or_more(0, parser_fn).ok() {
    ///     assert_eq!(res, vec![Some(true), None, Some(false)]);
    ///   } else { assert!(false) };
    /// ```
    pub fn one_or_more<T, Then>(&self, pos: usize, then: Then) -> Step<'a, Vec<T>>
        where
            Then: FnOnce(usize) -> Step<'a, T> + Copy,
    {
        match self.zero_or_more(pos, then) {
            Success(vals, _) if vals.is_empty() => Fail(pos),
            other => other,
        }
    }
    /// executes some rule one or more times shifting the cursor farther.
    /// The operator expects zero or more occurances of the given function
    /// # Arguments
    /// * `pos` - starting postion to parse
    /// * `then` - parsing function
    ///
    /// # Examples
    /// ```
    ///  use logos::Logos;
    ///  use crate::parsit::parser::Parsit;
    ///  use crate::parsit::token;
    ///  use crate::parsit::step::Step;
    ///  #[derive(Logos,PartialEq)]
    ///     pub enum TFQ {
    ///         #[token("true")]
    ///         True,
    ///         #[token("false")]
    ///         False,
    ///
    ///         #[token("?")]
    ///         Question,
    ///     }
    ///  let parser:Parsit<TFQ> = Parsit::new("").unwrap();
    ///  let parser_fn = |p|{ token!( parser.token(p) =>
    ///                   TFQ::True => Some(true),
    ///                   TFQ::False => Some(false),
    ///                   TFQ::Question => None
    ///             )};
    ///
    ///   if let Some(res) = parser.zero_or_more(0, parser_fn).ok() {
    ///     assert_eq!(res, vec![]);
    ///   } else { assert!(false) };
    /// ```
    pub fn zero_or_more<T, Then>(&self, pos: usize, then: Then) -> Step<'a, Vec<T>>
        where
            Then: FnOnce(usize) -> Step<'a, T> + Copy,
    {
        match then(pos).then_multi_zip(then).merge() {
            Fail(_) => Success(vec![], pos),
            Error(ParseError::ReachedEOF(_)) => Success(vec![], pos),
            success => success,
        }
    }
    /// Validates if the parsing process reaches the end of the input.
    /// If so transforms the result to the error UnreachedEOF
    ///
    /// It can be used in the end of the parsing
    pub fn validate_eof<T>(&self, res: Step<'a, T>) -> Step<'a, T> {
        match res {
            Success(_, pos) if self.lexer.len() != pos => Error(ParseError::UnreachedEOF(pos)),
            other => other,
        }
    }
    /// Prints a position and env from the source text.
    /// It has a radius of 2 tokens so thus it prints
    /// -3-2-10+1+2+3
    pub fn env<T>(&self, step: &Step<'a, T>) -> String {
        match step {
            Success(_, p) => self.lexer.env(*p),
            Fail(p) => self.lexer.env(*p),
            Error(ParseError::ExternalError(_,p)) => self.lexer.env(*p),
            Error(ParseError::FailedOnValidation(_,p)) => self.lexer.env(*p),
            Error(ParseError::ReachedEOF(p)) => self.lexer.env(*p),
            Error(ParseError::UnreachedEOF(p)) => self.lexer.env(*p),
            Error(e) => format!("{:?}", e)
        }
    }
}

/// The token is used as a stub for the parsing operations when we need just a notion
/// that the token is parsed correctly but we don't need to process any values.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct EmptyToken {}

/// Helps to parse a token on the lexer level
///  - Typically, it takes a token from the parser(defined in the structure of Logos)
///  - The structure should implement `PartialEq`
///
/// # Examples
/// - create a pattern matching for the given tokens
/// ```
///     use logos::Logos;
///     use crate::parsit::parser::Parsit;
///     use crate::parsit::token;
///     use crate::parsit::step::Step;
///     use crate::parsit::parser::EmptyToken;
///     #[derive(Logos,PartialEq)]
///     pub enum TFQ {
///         #[token("true")]
///         True,
///         #[token("false")]
///         False,
///
///         #[token("?")]
///         Question,
///     }
///
///     let p:Parsit<TFQ> = Parsit::new("true?").unwrap();
///     // create a pattern matching for the given tokens
///      token!(
///         p.token(0) =>
///             TFQ::True => true,
///             TFQ::False => false
///      );
///     // create a matching for only one token without a result
///     // it is used oftenly with then().
///     // The EmptyToken will be return
///      token!(p.token(1) => TFQ::Question);
///
/// ```
///
#[macro_export]
macro_rules! token {
  ($obj:expr => $($matcher:pat $(if $pred:expr)* => $result:expr),*) => {
      match $obj {
            Ok((t,p)) => match t {
                $($matcher $(if $pred)* => Step::Success($result, p + 1)),*,
                _ => Step::Fail(p)
            }
            Err(e) => Step::Error(e)
        }

   };
  ($obj:expr => $($matcher:pat $(if $pred:expr)*),*) => {
      match $obj {
            Ok((t,p)) => match t {
                $($matcher $(if $pred)* => Step::Success(EmptyToken{}, p + 1)),*,
                _ => Step::Fail(p)
            }
            Err(e) => Step::Error(e)
        }

   }

}

/// Helps to parse a wrapper
/// ```ebnf
/// <rule> ::= '(' "value" ')'
/// ```
///
/// # Examples
/// ```
///     use logos::Logos;
///     use crate::parsit::parser::Parsit;
///     use crate::parsit::wrap;
///     use crate::parsit::token;
///     use crate::parsit::step::Step;
///     use crate::parsit::parser::EmptyToken;
///     #[derive(Logos,PartialEq)]
///     pub enum TFQ {
///         #[token("(")]
///         L,
///         #[token(")")]
///         R,
///
///         #[token("word")]
///         Word,
///         #[token("none")]
///         None,
///     }
///
///     let p:Parsit<TFQ> = Parsit::new("(word)").unwrap();
///     let left = |pos:usize|{token!(p.token(pos) => TFQ::L)};
///     let right = |pos:usize|{token!(p.token(pos) => TFQ::R)};
///     let word = |pos:usize|{token!(p.token(pos) => TFQ::Word)};
///     let pos = 0;
///     wrap!(pos => left ; word; right );
///
///     let p:Parsit<TFQ> = Parsit::new("()").unwrap();
///     let word = |pos:usize|{token!(p.token(pos) => TFQ::Word).or_none()};
///     wrap!(0 => left ; word ?; right );
///
///     let p:Parsit<TFQ> = Parsit::new("()").unwrap();
///     let word = |pos:usize|{token!(p.token(pos) => TFQ::Word => 1)};
///     wrap!(0 => left ; word or 0; right ).print();
/// ```
///
#[macro_export]
macro_rules! wrap {

  ($pos:literal => $left:ident; $internal:ident; $right:ident ) => {
      $left($pos).then($internal).then_zip($right).take_left()
   } ;
   ($pos:literal => $left:ident; $internal:ident ?; $right:ident ) => {
      $left($pos).then_or_none($internal).then_zip($right).take_left()
   };
   ($pos:literal => $left:ident; $internal:ident or $default:ident; $right:ident ) => {
      $left($pos).then_or_val($internal,$default).then_zip($right).take_left()
   };
    ($pos:literal => $left:ident; $internal:ident or $default:literal; $right:ident ) => {
      $left($pos).then_or_val($internal,$default).then_zip($right).take_left()
   };
   ($pos:ident => $left:ident; $internal:ident; $right:ident ) => {
      $left($pos).then($internal).then_zip($right).take_left()
   } ;
   ($pos:ident => $left:ident; $internal:ident ?; $right:ident ) => {
      $left($pos).then_or_none($internal).then_zip($right).take_left()
   };
   ($pos:ident => $left:ident; $internal:ident or $default:ident; $right:ident ) => {
      $left($pos).then_or_val($internal,$default).then_zip($right).take_left()
   };
    ($pos:ident => $left:ident; $internal:ident or $default:literal; $right:ident ) => {
      $left($pos).then_or_val($internal,$default).then_zip($right).take_left()
   }
}

/// Helps to parse a sequence
/// ```ebnf
/// <rule> ::= el {delim el}
/// ```
///
/// # Examples
/// ```
///     use logos::Logos;
///     use crate::parsit::parser::Parsit;
///     use crate::parsit::wrap;
///     use crate::parsit::seq;
///     use crate::parsit::token;
///     use crate::parsit::step::Step;
///     use crate::parsit::parser::EmptyToken;
///     #[derive(Logos,PartialEq)]
///     pub enum TFQ {
///         #[token("(")]
///         L,
///         #[token(")")]
///         R,
///         #[token(",")]
///         C,
///
///         #[token("word")]
///         Word,
///         #[token("none")]
///         None,
///     }
///
///     let p:Parsit<TFQ> = Parsit::new("word,word,word").unwrap();
///     let comma = |pos:usize|{token!(p.token(pos) => TFQ::C)};
///     let word = |pos:usize|{token!(p.token(pos) => TFQ::Word)};
///     let pos = 0;
///     seq!(pos => word, comma );
///     let p:Parsit<TFQ> = Parsit::new("word,word,word,").unwrap();
///     seq!(pos => word, comma ,);
/// ```
///
#[macro_export]
macro_rules! seq {
    ($pos:ident => $elem:ident, $sep:ident ) => {
      $elem($pos)
        .then_multi_zip(|p| $sep(p).then($elem))
        .merge()
   };
    ($pos:ident => $elem:ident,$sep:ident, ) => {
        $elem($pos)
        .then_multi_zip(|p| {$sep(p).then($elem)})
        .then_or_none_zip(|p| $sep(p).or_none())
        .take_left()
        .merge()
    };
}