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
use core::{
    fmt,
    ops::{Bound, RangeBounds},
};

use crate::utils::default;

use super::{
    machine::{RepeatState, RepeatStyle, StackItem},
    traits::IntoMatchString,
    DebugPrecedence, Link, Links, MatchString, Matcher, StringPattern,
};

struct RepeatContinue {}

pub struct Repeat<'m, M> {
    min: u32,
    max: u32,
    style: RepeatStyle,
    inner: M,
    links: (Link<'m>, Link<'m>),
}

impl<M: IntoMatchString> IntoMatchString for Repeat<'_, M> {
    type Matcher<'m> = Repeat<'m, M::Matcher<'m>>
    where
        Self: 'm;

    fn into_match_string<'m>(self) -> Self::Matcher<'m>
    where
        Self: 'm,
    {
        let Self {
            min,
            max,
            style,
            inner,
            ..
        } = self;
        Self::Matcher {
            min,
            max,
            style,
            inner: inner.into_match_string(),
            links: default(),
        }
    }
}

impl<'m, M: MatchString<'m>> MatchString<'m> for Repeat<'m, M> {
    fn match_string(&'m self, cx: &mut super::StringMatcherContext<'m, '_>) -> Option<bool> {
        let (inner, outer) = if cx.is_reversed() {
            (self.inner.last(), self.prev_link())
        } else {
            (self.inner.first(), self.next_link())
        };

        cx.stack.push(
            outer
                .get()
                .map_or(StackItem::Accept, |m| StackItem::Matcher {
                    matcher: m.into(),
                }),
        );
        cx.push_matcher(inner);

        match self.style {
            RepeatStyle::Greedy | RepeatStyle::Lazy => {
                let mut state = cx.state();
                let RepeatState {
                    repeat_index: last_repeat,
                    depth: last_depth,
                    ..
                } = state.repeat;
                let greedy = self.style == RepeatStyle::Greedy;
                let repeat_index = cx.stack.len() as u16;
                cx.stack.push(StackItem::Repeat {
                    min: self.min,
                    max: self.max,
                    greedy,
                    last_repeat,
                    last_depth,
                });

                state.repeat = RepeatState {
                    repeat_index,
                    depth: 0,
                    greedy,
                    min: self.min,
                    max: self.max,
                };
                cx.set_state(state);
                cx.continue_repeat()
            }
            RepeatStyle::Simple => cx.continue_repeat_simple(self.min, self.max, 0),
        }
    }

    fn links(&'m self) -> super::Links<'m> {
        (&self.links).into()
    }

    fn initialize(&'m self) {
        if self.style != RepeatStyle::Simple {
            let Links(prev, next) = self.inner.links();
            let next_matcher = Matcher::from(&RepeatContinue {});
            prev.set(next_matcher);
            next.set(next_matcher);
        }
        self.inner.initialize()
    }

    fn fmt_matcher(&self, f: &mut fmt::Formatter, prec: DebugPrecedence) -> fmt::Result {
        prec.wrap_below(DebugPrecedence::Mul, f, |f| {
            self.inner.fmt_matcher(f, DebugPrecedence::Mul)?;
            f.write_str(" * ")?;
            match (self.min, self.max) {
                (min, max) if min == max => write!(f, "{min}")?,
                (0, u32::MAX) => f.write_str("..")?,
                (0, max) => write!(f, "..={max}")?,
                (min, u32::MAX) => write!(f, "{min}..")?,
                (min, max) => write!(f, "{min}..={max}")?,
            }
            Ok(())
        })
    }
}

impl<'m> MatchString<'m> for RepeatContinue {
    fn match_string(
        &'m self,
        cx: &mut super::machine::StringMatcherContext<'m, '_>,
    ) -> Option<bool> {
        cx.continue_repeat()
    }

    fn links(&'m self) -> Links<'m> {
        panic!()
    }
}

pub trait RepeatCount {
    fn bounds(&self) -> (Bound<&u32>, Bound<&u32>);
}

macro_rules! repeat_count_ranges {
    ($($Name:ty),* $(,)?) => {
        $(
            impl RepeatCount for $Name {
                fn bounds(&self) -> (Bound<&u32>, Bound<&u32>) {
                    (self.start_bound(), self.end_bound())
                }
            }
        )*
        impl_mul!($($Name,)*);
    };
}

macro_rules! impl_mul {
    ($($Name:ty),* $(,)?) => { $(
        impl<M> core::ops::Mul<$Name> for StringPattern<M> {
            type Output = StringPattern<Repeat<'static, M>>;

            fn mul(self, rhs: $Name) -> Self::Output {
                self.repeat(rhs)
            }
        }
        impl<M> core::ops::Mul<StringPattern<M>> for $Name {
            type Output = StringPattern<Repeat<'static, M>>;

            fn mul(self, rhs: StringPattern<M>) -> Self::Output {
                rhs * self
            }
        }
    )* };
}

repeat_count_ranges!(
    // core::ops::Range<u32>,
    core::ops::RangeInclusive<u32>,
    // core::ops::RangeTo<u32>,
    core::ops::RangeToInclusive<u32>,
    core::ops::RangeFrom<u32>,
    core::ops::RangeFull,
);

impl_mul!(u32);

impl RepeatCount for u32 {
    fn bounds(&self) -> (Bound<&u32>, Bound<&u32>) {
        (Bound::Included(self), Bound::Included(self))
    }
}

pub fn repeat<'m, M>(
    count: impl RepeatCount,
    inner: StringPattern<M>,
) -> StringPattern<Repeat<'m, M>> {
    inner.repeat(count)
}

impl<M> StringPattern<M> {
    pub fn repeat<'m>(self, count: impl RepeatCount) -> StringPattern<Repeat<'m, M>> {
        let (start, end) = count.bounds();
        let min = match start {
            Bound::Included(&x) => x,
            Bound::Excluded(&x) => x.saturating_add(1),
            Bound::Unbounded => 0,
        };
        let max = match end {
            Bound::Included(&x) => x,
            Bound::Excluded(&x) => x.saturating_sub(1),
            Bound::Unbounded => u32::MAX,
        };
        StringPattern::new(Repeat {
            min,
            max,
            style: default(),
            inner: self.inner,
            links: default(),
        })
    }

    pub fn optional<'m>(self) -> StringPattern<Repeat<'m, M>> {
        self.repeat(..=1)
    }
}

impl<'m, M> StringPattern<Repeat<'m, M>> {
    pub fn greedy(mut self) -> Self {
        self.inner.style = RepeatStyle::Greedy;
        self
    }
    pub fn lazy(mut self) -> Self {
        self.inner.style = RepeatStyle::Lazy;
        self
    }
    /// Repeats as many times as the repeated pattern matches and does not backtrack.
    pub fn simple(mut self) -> Self {
        self.inner.style = RepeatStyle::Simple;
        self
    }
}