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
//! The macros primarily exist to make creating zero size parsers easier.
//! Without putting them in macros "&'static str" and "chars" can act as parsers,
//! but they have a size, and when combined they can become bigger.
//! If however all the parsers you combine have zero size, then the final resulting parser
//! will also be zero size and therefor much easier to construct
//!

/// Makes zero sized parsers based on the expression given and potentially the return type given.

/// ```rust
/// use gobble::*;
/// parser!{
///     (Cat->String),
///     "cat".plus(),
/// }
/// assert_eq!(Cat.parse_s("ctar"),Ok("cta".to_string()));
/// ```
#[macro_export]
macro_rules! parser {
    ($id:ident,$x:expr) => {
        parser!(($id->&'static str) $x);
    };
    ($($doc:literal $(,)?)? ($id:ident -> $ot:ty) $(,)? $x:expr $(,)?) => {
        parser!($($doc)? ($id->$ot) $x, Expected::Str(stringify!($id)));
    };
    ($id:ident,$x:expr,$exp:expr) => {
        parser!(($id->&'static str) $x, $exp);
    };
    ($($doc:literal $(,)?)? ($id:ident -> $ot:ty) $(,)? $x:expr,$exp:expr $(,)?) => {
        $(#[doc=$doc])?
        #[derive(Copy, Clone)]
        pub struct $id;
        impl Parser for $id {
            type Out = $ot;
            ///Parse run the main parser
            fn parse<'a>(&self, it: &LCChars<'a>) -> ParseRes<'a, Self::Out> {
                let name_e = it.err_p(self);
                match (&$x).parse(it){
                    Ok(v)=> Ok(v),
                    Err(e)=> match (e.index,name_e.index) {
                        (Some(ei),Some(ii)) if (ii == ei) => it.err_rp(self),
                        _=>Err(e.join(name_e)),
                    }
                }
            }
            ///The expected return type
            fn expected(&self) -> Expected {
                $exp
            }
        }
    };
}

#[macro_export]
macro_rules! parser_as {
    (($ot:ty),(($id:ident->$res:expr) $(,)? $main:expr,$exp:expr $(,)?) ) => {
        parser! {($id->$ot) ,$main.map(|_|$res),$exp}
    };
    (($ot:ty),(($id:ident->$res:expr) $(,)? $main:expr $(,)?) ) => {
        parser! {($id->$ot) ,$main.map(|_|$res)}
    };
    (($ot:ty),($id:ident, $main:expr)) => {
        parser! { ($id->$ot) $main}
    };
}

#[macro_export]
macro_rules! as_id {
    ((($id:ident->$_x:expr) $($_t:tt)*) ) => {
        $id
    };
    (($id:ident $($_t:tt)*) ) => {
        $id
    };
}

/// ```rust
///
/// use gobble::*;
/// mod scoper{
///     // had to make a new scope for the doc test but it shouldn't be needed
///     // from outer crates
///     use gobble::*;
///     //declare the enum
///     #[derive(Clone, PartialEq, Debug)]
///     pub enum Oper {
///         Add,
///         Sub,
///         Div,
///         Mul,
///         Var(String),
///     }
///     
///     enum_parser! { (OPER,oper,Oper) =>
///         ((ADD->Oper::Add) '+'),
///         ((SUB->Oper::Sub) '-'),
///         ((DIV->Oper::Div) '/'),
///         ((MUL->Oper::Mul) '*'),
///         (VAR , Alpha.plus().map(|s|Oper::Var(s))),
///     }
/// }
/// use scoper::*;
///
/// let v = star(scoper::OPER).parse_s("-cat").unwrap();
/// assert_eq!( v, vec![ Oper::Sub, Oper::Var("cat".to_string()) ]);
///
/// let v2 = star(or!(oper::ADD, oper::SUB)).parse_s("-+-hello").unwrap();
/// assert_eq!(v2, vec![Oper::Sub, Oper::Add, Oper::Sub]);
///
///
/// ```
#[macro_export]
macro_rules! enum_parser{
    ( ($name:ident,$mod:ident,$ot:ty)=>$($mbit:tt),* $(,)?) =>{
        pub mod $mod{
            use $crate::*;
            use super::*;
            $( parser_as!{($ot),$mbit})*
            parser!{ ($name->$ot) ( or!{ $(as_id!{$mbit}),*} )}
        }
        pub use $mod::$name;
    }
}

#[macro_export]
macro_rules! char_bool {
    ($id:ident,$x:expr) => {
        char_bool!($id, $x, Expected::CharIn(stringify!($id)));
    };
    ($id:ident,$x:expr,$s:literal) => {
        char_bool!($id, $x, Expected::CharIn($s));
    };
    ($id:ident,$x:expr,$exp:expr) => {
        #[derive(Copy, Clone)]
        pub struct $id;
        impl CharBool for $id {
            fn char_bool(&self, c: char) -> bool {
                (&$x).char_bool(c)
            }
            fn expected(&self) -> Expected {
                $exp
            }
        }
    };
}

#[macro_export]
macro_rules! char_bools {
    ( $( ($id:ident,$x:expr) ),*) => {$(char_bool!($id,$x);)*};
}

/// a macro replacement for numbered or statements.
/// ```rust
/// use gobble::*;
/// assert_eq!(or!("cat","dog","car",).parse_s("catdogman "),Ok("cat"));
/// ```
#[macro_export]
macro_rules! or{
    ($s:expr,$($x:expr),* $(,)?) => { $s$(.or($x))*;};
}

#[macro_export]
macro_rules! or_ig{
    ($s:expr,$($x:expr),* $(,)?) => { $s.ig()$(.or($x.ig()))*;};
}

#[cfg(test)]
mod test {

    fn size_of<T: Sized>(_t: &T) -> usize {
        std::mem::size_of::<T>()
    }

    use crate::*;
    parser!(DOG, "dog");
    parser!(CAR, "car");
    parser!(CAT, "cat");

    parser!((GROW->Vec<&'static str>) star(or(CAT, DOG)));

    #[test]
    pub fn parser_makes_parser() {
        assert_eq!(DOG.parse_s("dog   "), Ok("dog"));
        assert_eq!(CAT.parse_s("cat    "), Ok("cat"));
        assert_eq!(
            GROW.parse_s("catdogcatcatno"),
            Ok(vec!["cat", "dog", "cat", "cat"])
        );
    }

    char_bool!(HOT, "hot");
    char_bool!(MNUM, |c| c >= '0' && c <= '9');

    #[test]
    pub fn charbool_macro_makes_parser() {
        use Expected::*;
        let p = (HOT, MNUM);
        assert_eq!(std::mem::size_of::<(HOT, MNUM)>(), 0);
        assert_eq!(p.plus().parse_s("09h3f"), Ok("09h3".to_string()));
        assert_eq!(p.expected(), OneOf(vec![CharIn("HOT"), CharIn("MNUM")]));
        assert_eq!(size_of(&p), 0);
    }
    #[derive(Clone, PartialEq, Debug)]
    pub enum Oper {
        Add,
        Sub,
        Div,
        Mul,
        Var(String),
    }

    enum_parser! { (OPER,oper,Oper) =>
        ((ADD->Oper::Add) '+'),
        ((SUB->Oper::Sub) '-'),
        ((DIV->Oper::Div) '/'),
        ((MUL->Oper::Mul) '*'),
        (VAR , Alpha.plus().map(|s|Oper::Var(s))),
    }

    #[test]
    fn test_enum_group_make_parser() {
        let v = star(OPER).parse_s("-cat").unwrap();
        assert_eq!(v, vec![Oper::Sub, Oper::Var("cat".to_string())]);

        let v2 = star(or!(oper::ADD, oper::SUB)).parse_s("-+-hello").unwrap();
        assert_eq!(v2, vec![Oper::Sub, Oper::Add, Oper::Sub]);
    }
}