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
//! Implemtations of [`Parse`] and [`Peek`] for types in
//! the rust standard library
use crate::{eyre, Buffer, Context, Parse};
use std::mem::MaybeUninit;

/// Result is `None` if parsing `P` fails, otherwise, result is `Some(p)`
impl<P: Parse<T>, T> Parse<T> for Option<P> {
    fn parse(input: &mut impl Buffer<T>) -> eyre::Result<Self> {
        let mut cursor = input.cursor();
        match P::parse(&mut cursor) {
            Ok(p) => {
                cursor.fast_forward_parent();
                Ok(Some(p))
            }
            Err(_) => Ok(None),
        }
    }

    fn peek(input: &mut impl Buffer<T>) -> bool {
        let mut cursor = input.cursor();

        if P::peek(&mut cursor) {
            cursor.fast_forward_parent()
        }

        // Option should always return true for peek
        true
    }
}

/// Repeatedly attempts to parse `P`, Result is all successful attempts
impl<P: Parse<T>, T> Parse<T> for Vec<P> {
    fn parse(input: &mut impl Buffer<T>) -> eyre::Result<Self> {
        let mut output = Self::new();
        loop {
            let mut cursor = input.cursor();
            match P::parse(&mut cursor) {
                Ok(p) => output.push(p),
                Err(_) => break,
            }
            cursor.fast_forward_parent();
        }

        Ok(output)
    }

    fn peek(input: &mut impl Buffer<T>) -> bool {
        loop {
            let mut cursor = input.cursor();
            if !P::peek(&mut cursor) {
                break;
            }
            cursor.fast_forward_parent()
        }
        true
    }
}

/// Vec1 is similar to [`Vec`] but implements [`Parse`] such that it will error if it fails to parse at least once
#[derive(Debug, Clone, PartialEq)]
pub struct Vec1<P>(Vec<P>);

impl<P> AsRef<Vec<P>> for Vec1<P> {
    fn as_ref(&self) -> &Vec<P> {
        &self.0
    }
}

impl<P> AsMut<Vec<P>> for Vec1<P> {
    fn as_mut(&mut self) -> &mut Vec<P> {
        &mut self.0
    }
}

impl<P> From<Vec1<P>> for Vec<P> {
    fn from(v: Vec1<P>) -> Self {
        v.0
    }
}

/// Repeatedly attempt to parse `P`, Result is all successful attempts
/// Must parse `P` at least once
impl<P: Parse<T>, T> Parse<T> for Vec1<P> {
    fn parse(input: &mut impl Buffer<T>) -> eyre::Result<Self> {
        let mut output = vec![P::parse(input)?];
        loop {
            let mut cursor = input.cursor();
            match P::parse(&mut cursor) {
                Ok(p) => output.push(p),
                Err(_) => break,
            }
            cursor.fast_forward_parent();
        }

        Ok(Self(output))
    }

    fn peek(input: &mut impl Buffer<T>) -> bool {
        if !P::peek(input) {
            return false;
        }

        loop {
            let mut cursor = input.cursor();
            if !P::peek(&mut cursor) {
                break;
            }
            cursor.fast_forward_parent()
        }

        true
    }
}

/// Parse `P` `N` times into `[P; N]`, fails if any step fails
///
/// ```
/// use nommy::{parse_terminated, text::Tag};
/// let _: [Tag<".">; 3] = parse_terminated("...".chars()).unwrap();
/// ```
impl<P: Parse<T>, T, const N: usize> Parse<T> for [P; N] {
    fn parse(input: &mut impl Buffer<T>) -> eyre::Result<Self> {
        // safety: we only return the new data if no errors occured,
        // and if no errors occured, then we definitely filled all N spaces
        // therefore the array was initialised.
        unsafe {
            let mut output = MaybeUninit::uninit_array();
            for (i, output) in output.iter_mut().enumerate() {
                *output.as_mut_ptr() =
                    P::parse(input).wrap_err_with(|| format!("could not parse element {}", i))?;
            }

            Ok(MaybeUninit::array_assume_init(output))
        }
    }

    fn peek(input: &mut impl Buffer<T>) -> bool {
        for _ in 0..N {
            if !P::peek(input) {
                return false;
            }
        }

        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{parse, text::Tag, IntoBuf};

    #[test]
    fn option() {
        let res: Option<Tag<".">> = parse(".".chars()).unwrap();
        assert!(res.is_some());
    }

    #[test]
    fn option_none() {
        let res: Option<Tag<".">> = parse("".chars()).unwrap();
        assert!(res.is_none());
    }

    #[test]
    fn sequence() {
        let res: Vec<Tag<".">> = parse("...".chars()).unwrap();
        assert_eq!(res.len(), 3);
    }

    #[test]
    fn sequence_peek() {
        let mut input = "...-".chars().into_buf();
        let mut cursor = input.cursor();
        assert!(Vec::<Tag<".">>::peek(&mut cursor));
        assert_eq!(cursor.next(), Some('-'));
    }

    #[test]
    fn sequence2_peek() {
        let mut input = "-...-".chars().into_buf();
        let mut cursor = input.cursor();

        assert!(Tag::<"-">::peek(&mut cursor));
        assert!(Vec::<Tag<".">>::peek(&mut cursor));
        assert_eq!(cursor.next(), Some('-'));
    }

    #[test]
    fn count() {
        let _: [Tag<".">; 3] = parse("...".chars()).unwrap();
    }

    #[test]
    fn sequence_none() {
        let res: Vec<Tag<".">> = parse("-".chars()).unwrap();
        assert!(res.is_empty())
    }

    #[test]
    fn sequence_at_least_one() {
        let res: Vec1<Tag<".">> = parse("...".chars()).unwrap();
        assert_eq!(res.as_ref().len(), 3);
    }

    #[test]
    fn sequence_at_least_one_but_none() {
        let res: Result<Vec1<Tag<".">>, _> = parse("-".chars());
        assert_eq!(
            format!("{}", res.unwrap_err()),
            "failed to parse tag \".\", found \"-\""
        );
    }
}