logo
  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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
// Copyright (c) 2021-2022  Brendan Molloy <brendan@bbqsrc.net>,
//                          Ilya Solovyiov <ilya.solovyiov@gmail.com>,
//                          Kai Ren <tyranron@gmail.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! [Cucumber Expressions][0] [AST] into [`Regex`] expansion.
//!
//! Follows original [production rules][1].
//!
//! [`Regex`]: regex::Regex
//! [0]: https://github.com/cucumber/cucumber-expressions#readme
//! [1]: https://git.io/J159T
//! [AST]: https://en.wikipedia.org/wiki/Abstract_syntax_tree

pub mod parameters;

use std::{fmt, iter, str, vec};

use derive_more::{Display, Error, From};
use either::Either;
use nom::{AsChar, InputIter};
use regex::Regex;

use crate::{
    parse, Alternation, Alternative, Expression, Optional, Parameter,
    SingleAlternation, SingleExpression, Spanned,
};

pub use self::parameters::{
    Provider as ParametersProvider, WithCustom as WithCustomParameters,
};

#[allow(clippy::multiple_inherent_impl)] // because of `into-regex` feature
impl<'s> Expression<Spanned<'s>> {
    /// Parses the given `input` as an [`Expression`], and immediately expands
    /// it into the appropriate [`Regex`].
    ///
    /// # Parameter types
    ///
    /// Text between curly braces references a *parameter type*.
    /// [Cucumber Expressions][0] come with the following
    /// [built-in parameter types][1]:
    ///
    /// | Parameter Type  | Description                                    |
    /// | --------------- | ---------------------------------------------- |
    /// | `{int}`         | Matches integers                               |
    /// | `{float}`       | Matches floats                                 |
    /// | `{word}`        | Matches words without whitespace               |
    /// | `{string}`      | Matches single-quoted or double-quoted strings |
    /// | `{}` anonymous  | Matches anything (`/.*/`)                      |
    ///
    /// To expand an [`Expression`] with custom parameter types in addition to
    /// the built-in ones, use [`Expression::regex_with_parameters()`].
    ///
    /// # Errors
    ///
    /// See [`Error`] for more details.
    ///
    /// [`Error`]: enum@Error
    /// [0]: https://github.com/cucumber/cucumber-expressions#readme
    /// [1]: https://github.com/cucumber/cucumber-expressions#parameter-types
    pub fn regex<Input: AsRef<str> + ?Sized>(
        input: &'s Input,
    ) -> Result<Regex, Error<Spanned<'s>>> {
        let re_str = Expression::parse(input)?
            .into_regex_char_iter()
            .collect::<Result<String, _>>()?;
        Regex::new(&re_str).map_err(Into::into)
    }

    /// Parses the given `input` as an [`Expression`], and immediately expands
    /// it into the appropriate [`Regex`], considering the custom defined
    /// `parameters` in addition to [default ones][1].
    ///
    /// # Errors
    ///
    /// See [`Error`] for more details.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use std::collections::HashMap;
    /// #
    /// # use cucumber_expressions::Expression;
    /// #
    /// let parameters = HashMap::from([("color", "[Rr]ed|[Gg]reen|[Bb]lue")]);
    /// let re = Expression::regex_with_parameters(
    ///     "{word} has {color} eyes",
    ///     &parameters,
    /// )
    /// .unwrap();
    ///
    /// assert_eq!(
    ///     re.as_str(),
    ///     "^([^\\s]+) has ([Rr]ed|[Gg]reen|[Bb]lue) eyes$",
    /// );
    /// ```
    ///
    /// [`Error`]: enum@Error
    /// [1]: https://github.com/cucumber/cucumber-expressions#parameter-types
    pub fn regex_with_parameters<Input, Parameters>(
        input: &'s Input,
        parameters: Parameters,
    ) -> Result<Regex, Error<Spanned<'s>>>
    where
        Input: AsRef<str> + ?Sized,
        Parameters: Clone + ParametersProvider<Spanned<'s>>,
        Parameters::Value: InputIter,
        <Parameters::Value as InputIter>::Item: AsChar,
    {
        let re_str = Expression::parse(input)?
            .with_parameters(parameters)
            .into_regex_char_iter()
            .collect::<Result<String, _>>()?;
        Regex::new(&re_str).map_err(Into::into)
    }

    /// Creates a parser, parsing [`Expression`]s and immediately expanding them
    /// into appropriate [`Regex`]es, considering the custom defined
    /// `parameters` in addition to [default ones][1].
    ///
    /// [1]: https://github.com/cucumber/cucumber-expressions#parameter-types
    pub fn with_parameters<P: ParametersProvider<Spanned<'s>>>(
        self,
        parameters: P,
    ) -> WithCustomParameters<Self, P> {
        WithCustomParameters {
            element: self,
            parameters,
        }
    }
}

/// Possible errors while parsing `Input` representing a
/// [Cucumber Expression][0] and expanding it into a [`Regex`].
///
/// [0]: https://github.com/cucumber/cucumber-expressions#readme
#[derive(Clone, Debug, Display, Error, From)]
pub enum Error<Input>
where
    Input: fmt::Display,
{
    /// Parsing error.
    #[display(fmt = "Parsing failed: {}", _0)]
    Parsing(parse::Error<Input>),

    /// Expansion error.
    #[display(fmt = "Failed to expand regex: {}", _0)]
    Expansion(ParameterError<Input>),

    /// [`Regex`] creation error.
    #[display(fmt = "Regex creation failed: {}", _0)]
    Regex(regex::Error),
}

/// Possible [`Parameter`] errors being used in an [`Expression`].
#[derive(Clone, Debug, Display, Error)]
pub enum ParameterError<Input>
where
    Input: fmt::Display,
{
    /// [`Parameter`] not found.
    #[display(fmt = "Parameter `{}` not found.", _0)]
    NotFound(Input),

    /// Failed to rename [`Regex`] capturing group.
    #[display(
        fmt = "Failed to rename capturing groups in regex `{}` of \
               parameter `{}`: {}",
        re,
        parameter,
        err
    )]
    RenameRegexGroup {
        /// [`Parameter`] name.
        parameter: Input,

        /// [`Regex`] of the [`Parameter`].
        re: String,

        /// [`Error`] of parsing the [`Regex`] with renamed capturing groups.
        ///
        /// [`Error`]: regex_syntax::Error
        err: regex_syntax::Error,
    },
}

/// Expansion of a [Cucumber Expressions][0] [AST] element into a [`Regex`] by
/// producing a [`char`]s [`Iterator`] following original [production rules][1].
///
/// [0]: https://github.com/cucumber/cucumber-expressions#readme
/// [1]: https://git.io/J159T
/// [AST]: https://en.wikipedia.org/wiki/Abstract_syntax_tree
pub trait IntoRegexCharIter<Input: fmt::Display> {
    /// Type of an [`Iterator`] performing the expansion.
    type Iter: Iterator<Item = Result<char, ParameterError<Input>>>;

    /// Consumes this [AST] element returning an [`Iterator`] over [`char`]s
    /// transformable into a [`Regex`].
    ///
    /// [AST]: https://github.com/cucumber/cucumber-expressions#readme
    fn into_regex_char_iter(self) -> Self::Iter;
}

impl<Input> IntoRegexCharIter<Input> for Expression<Input>
where
    Input: Clone + fmt::Display + InputIter,
    <Input as InputIter>::Item: AsChar,
{
    type Iter = ExpressionIter<Input>;

    fn into_regex_char_iter(self) -> Self::Iter {
        let into_regex_char_iter: fn(_) -> _ =
            IntoRegexCharIter::into_regex_char_iter;

        iter::once(Ok('^'))
            .chain(self.0.into_iter().flat_map(into_regex_char_iter))
            .chain(iter::once(Ok('$')))
    }
}

// TODO: Replace with TAIT, once stabilized:
//       https://github.com/rust-lang/rust/issues/63063
/// [`IntoRegexCharIter::Iter`] for an [`Expression`].
type ExpressionIter<Input> = iter::Chain<
    iter::Chain<
        iter::Once<Result<char, ParameterError<Input>>>,
        iter::FlatMap<
            vec::IntoIter<SingleExpression<Input>>,
            <SingleExpression<Input> as IntoRegexCharIter<Input>>::Iter,
            fn(
                SingleExpression<Input>,
            )
                -> <SingleExpression<Input> as IntoRegexCharIter<Input>>::Iter,
        >,
    >,
    iter::Once<Result<char, ParameterError<Input>>>,
>;

impl<Input> IntoRegexCharIter<Input> for SingleExpression<Input>
where
    Input: Clone + fmt::Display + InputIter,
    <Input as InputIter>::Item: AsChar,
{
    type Iter = SingleExpressionIter<Input>;

    fn into_regex_char_iter(self) -> Self::Iter {
        use Either::{Left, Right};

        let ok: fn(_) -> _ = Ok;
        let as_char: fn(_) -> _ = AsChar::as_char;

        match self {
            Self::Alternation(alt) => Left(alt.into_regex_char_iter()),
            Self::Optional(opt) => Right(Left(opt.into_regex_char_iter())),
            Self::Parameter(p) => Right(Right(Left(p.into_regex_char_iter()))),
            Self::Text(t) | Self::Whitespaces(t) => Right(Right(Right(
                EscapeForRegex::new(t.iter_elements().map(as_char)).map(ok),
            ))),
        }
    }
}

// TODO: Replace with TAIT, once stabilized:
//       https://github.com/rust-lang/rust/issues/63063
/// [`IntoRegexCharIter::Iter`] for a [`SingleExpression`].
type SingleExpressionIter<Input> = Either<
    <Alternation<Input> as IntoRegexCharIter<Input>>::Iter,
    Either<
        <Optional<Input> as IntoRegexCharIter<Input>>::Iter,
        Either<
            <Parameter<Input> as IntoRegexCharIter<Input>>::Iter,
            iter::Map<
                EscapeForRegex<
                    iter::Map<
                        <Input as InputIter>::IterElem,
                        fn(<Input as InputIter>::Item) -> char,
                    >,
                >,
                MapOkChar<Input>,
            >,
        >,
    >,
>;

impl<Input> IntoRegexCharIter<Input> for Alternation<Input>
where
    Input: fmt::Display + InputIter,
    <Input as InputIter>::Item: AsChar,
{
    type Iter = AlternationIter<Input>;

    fn into_regex_char_iter(self) -> Self::Iter {
        let ok: fn(_) -> _ = Ok;
        let single_alt: fn(SingleAlternation<Input>) -> _ = |alt| {
            let into_regex_char_iter: fn(_) -> _ =
                IntoRegexCharIter::into_regex_char_iter;

            alt.into_iter()
                .flat_map(into_regex_char_iter)
                .chain(iter::once(Ok('|')))
        };

        "(?:"
            .chars()
            .map(ok)
            .chain(SkipLast::new(self.0.into_iter().flat_map(single_alt)))
            .chain(iter::once(Ok(')')))
    }
}

// TODO: Replace with TAIT, once stabilized:
//       https://github.com/rust-lang/rust/issues/63063
/// [`IntoRegexCharIter::Iter`] for an [`Alternation`].
type AlternationIter<I> = iter::Chain<
    iter::Chain<
        iter::Map<str::Chars<'static>, MapOkChar<I>>,
        SkipLast<
            iter::FlatMap<
                vec::IntoIter<SingleAlternation<I>>,
                AlternationIterInner<I>,
                fn(SingleAlternation<I>) -> AlternationIterInner<I>,
            >,
        >,
    >,
    iter::Once<Result<char, ParameterError<I>>>,
>;

// TODO: Replace with TAIT, once stabilized:
//       https://github.com/rust-lang/rust/issues/63063
/// Inner type of an [`AlternationIter`].
type AlternationIterInner<I> = iter::Chain<
    iter::FlatMap<
        vec::IntoIter<Alternative<I>>,
        <Alternative<I> as IntoRegexCharIter<I>>::Iter,
        fn(Alternative<I>) -> <Alternative<I> as IntoRegexCharIter<I>>::Iter,
    >,
    iter::Once<Result<char, ParameterError<I>>>,
>;

impl<Input> IntoRegexCharIter<Input> for Alternative<Input>
where
    Input: fmt::Display + InputIter,
    <Input as InputIter>::Item: AsChar,
{
    type Iter = AlternativeIter<Input>;

    fn into_regex_char_iter(self) -> Self::Iter {
        use Either::{Left, Right};

        let as_char: fn(<Input as InputIter>::Item) -> char = AsChar::as_char;

        match self {
            Self::Optional(opt) => Left(opt.into_regex_char_iter()),
            Self::Text(text) => Right(
                EscapeForRegex::new(text.iter_elements().map(as_char)).map(Ok),
            ),
        }
    }
}

// TODO: Replace with TAIT, once stabilized:
//       https://github.com/rust-lang/rust/issues/63063
/// [`IntoRegexCharIter::Iter`] for an [`Alternative`].
type AlternativeIter<Input> = Either<
    <Optional<Input> as IntoRegexCharIter<Input>>::Iter,
    iter::Map<
        EscapeForRegex<
            iter::Map<
                <Input as InputIter>::IterElem,
                fn(<Input as InputIter>::Item) -> char,
            >,
        >,
        MapOkChar<Input>,
    >,
>;

impl<Input> IntoRegexCharIter<Input> for Optional<Input>
where
    Input: fmt::Display + InputIter,
    <Input as InputIter>::Item: AsChar,
{
    type Iter = OptionalIter<Input>;

    fn into_regex_char_iter(self) -> Self::Iter {
        let as_char: fn(<Input as InputIter>::Item) -> char = AsChar::as_char;

        "(?:"
            .chars()
            .chain(EscapeForRegex::new(self.0.iter_elements().map(as_char)))
            .chain(")?".chars())
            .map(Ok)
    }
}

// TODO: Replace with TAIT, once stabilized:
//       https://github.com/rust-lang/rust/issues/63063
/// [`IntoRegexCharIter::Iter`] for an [`Optional`].
type OptionalIter<Input> = iter::Map<
    iter::Chain<
        iter::Chain<
            str::Chars<'static>,
            EscapeForRegex<
                iter::Map<
                    <Input as InputIter>::IterElem,
                    fn(<Input as InputIter>::Item) -> char,
                >,
            >,
        >,
        str::Chars<'static>,
    >,
    MapOkChar<Input>,
>;

/// Function pointer describing [`Ok`].
type MapOkChar<Input> = fn(char) -> Result<char, ParameterError<Input>>;

impl<Input> IntoRegexCharIter<Input> for Parameter<Input>
where
    Input: Clone + fmt::Display + InputIter,
    <Input as InputIter>::Item: AsChar,
{
    type Iter = ParameterIter<Input>;

    fn into_regex_char_iter(self) -> Self::Iter {
        use Either::{Left, Right};

        let eq = |i: &Input, str: &str| {
            i.iter_elements().map(AsChar::as_char).eq(str.chars())
        };

        if eq(&self.input, "int") {
            Left(Left(r#"((?:-?\d+)|(?:\d+))"#.chars().map(Ok)))
        } else if eq(&self.input, "float") {
            // Regex in other implementations has lookaheads. As `regex` crate
            // doesn't support them, we use `f32`/`f64` grammar instead:
            // https://doc.rust-lang.org/stable/std/primitive.f64.html#grammar
            // Provided grammar is a superset of the original one:
            // - supports `e` as exponent in addition to `E`
            // - supports trailing comma: `1.`
            // - supports `inf` and `NaN`
            Left(Left(
                "([+-]?(?:inf\
                         |NaN\
                         |(?:\\d+|\\d+\\.\\d*|\\d*\\.\\d+)(?:[eE][+-]?\\d+)?\
                       ))"
                .chars()
                .map(Ok),
            ))
        } else if eq(&self.input, "word") {
            Left(Left(r#"([^\s]+)"#.chars().map(Ok)))
        } else if eq(&self.input, "string") {
            Left(Right(
                OwnedChars::new(format!(
                    "(?:\
                      \"(?P<__{id}_0>[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"\
                      |'(?P<__{id}_1>[^'\\\\]*(?:\\\\.[^'\\\\]*)*)'\
                    )",
                    id = self.id,
                ))
                .map(Ok),
            ))
        } else if eq(&self.input, "") {
            Left(Left(r#"(.*)"#.chars().map(Ok)))
        } else {
            Right(iter::once(Err(ParameterError::NotFound(self.input))))
        }
    }
}

// TODO: Replace with TAIT, once stabilized:
//       https://github.com/rust-lang/rust/issues/63063
/// [`IntoRegexCharIter::Iter`] for a [`Parameter`].
type ParameterIter<Input> = Either<
    Either<
        iter::Map<
            str::Chars<'static>,
            fn(char) -> Result<char, ParameterError<Input>>,
        >,
        iter::Map<OwnedChars, fn(char) -> Result<char, ParameterError<Input>>>,
    >,
    iter::Once<Result<char, ParameterError<Input>>>,
>;

/// [`Iterator`] for skipping a last [`Item`].
///
/// [`Item`]: Iterator::Item
pub struct SkipLast<Iter: Iterator> {
    /// Inner [`Iterator`] to skip the last [`Item`] from.
    ///
    /// [`Item`]: Iterator::Item
    iter: iter::Peekable<Iter>,
}

impl<Iter> Clone for SkipLast<Iter>
where
    Iter: Clone + Iterator,
    Iter::Item: Clone,
{
    fn clone(&self) -> Self {
        Self {
            iter: self.iter.clone(),
        }
    }
}

impl<Iter> fmt::Debug for SkipLast<Iter>
where
    Iter: fmt::Debug + Iterator,
    Iter::Item: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SkipLast")
            .field("iter", &self.iter)
            .finish()
    }
}

impl<Iter: Iterator> SkipLast<Iter> {
    /// Creates a new [`SkipLast`] [`Iterator`].
    pub fn new(iter: Iter) -> Self {
        Self {
            iter: iter.peekable(),
        }
    }
}

impl<Iter> Iterator for SkipLast<Iter>
where
    Iter: Iterator,
{
    type Item = Iter::Item;

    fn next(&mut self) -> Option<Self::Item> {
        let next = self.iter.next();
        (self.iter.peek().is_some()).then(|| next).flatten()
    }
}

// TODO: Make private, once TAIT stabilized:
//       https://github.com/rust-lang/rust/issues/63063
/// Like [`str::Chars`] [`Iterator`], but owns its [`String`].
#[derive(Clone, Debug)]
pub struct OwnedChars {
    /// Iterated [`String`].
    str: String,

    /// Current char number.
    cur: usize,
}

impl OwnedChars {
    /// Creates a new [`OwnedChars`] [`Iterator`].
    #[must_use]
    pub const fn new(str: String) -> Self {
        Self { str, cur: 0 }
    }
}

impl Iterator for OwnedChars {
    type Item = char;

    fn next(&mut self) -> Option<Self::Item> {
        let char = self.str.chars().nth(self.cur)?;
        self.cur += 1;
        Some(char)
    }
}

/// [`Iterator`] for escaping `^`, `$`, `[`, `]`, `(`, `)`, `{`, `}`, `.`, `|`,
/// `?`, `*`, `+` with `\`, and removing it for other [`char`]s.
///
/// # Example
///
/// ```rust
/// # use cucumber_expressions::expand::EscapeForRegex;
/// #
/// assert_eq!(
///     EscapeForRegex::new("\\\\text\\ (\\)\\".chars()).collect::<String>(),
///     "\\\\text \\(\\)",
/// );
/// ```
#[derive(Clone, Debug)]
pub struct EscapeForRegex<Iter: Iterator> {
    /// Inner [`Iterator`] for escaping.
    iter: iter::Peekable<Iter>,

    /// [`Item`] that was escaped.
    ///
    /// [`Item`]: Iterator::Item
    was_escaped: Option<Iter::Item>,
}

impl<Iter: Iterator> EscapeForRegex<Iter> {
    /// Creates a new [`EscapeForRegex`] [`Iterator`].
    pub fn new(iter: Iter) -> Self {
        Self {
            iter: iter.peekable(),
            was_escaped: None,
        }
    }
}

impl<Iter> Iterator for EscapeForRegex<Iter>
where
    Iter: Iterator<Item = char>,
{
    type Item = char;

    fn next(&mut self) -> Option<Self::Item> {
        let should_be_escaped = |c| "^$[]()\\{}.|?*+".contains(c);

        if self.was_escaped.is_some() {
            return self.was_escaped.take();
        }

        loop {
            return match self.iter.next() {
                Some('\\') => {
                    let c = *self.iter.peek()?;
                    if should_be_escaped(c) {
                        self.was_escaped = self.iter.next();
                        Some('\\')
                    } else {
                        continue;
                    }
                }
                Some(c) if should_be_escaped(c) => {
                    self.was_escaped = Some(c);
                    Some('\\')
                }
                Some(c) => Some(c),
                None => None,
            };
        }
    }
}

// All test examples from: <https://git.io/J159G>
// Naming of test cases is preserved.
#[cfg(test)]
mod spec {
    use super::{Error, Expression, ParameterError};

    #[test]
    fn alternation_with_optional() {
        // TODO: Use "{e}" syntax once MSRV bumps above 1.58.
        let expr = Expression::regex("a/b(c)")
            .unwrap_or_else(|e| panic!("failed: {}", e));

        assert_eq!(expr.as_str(), "^(?:a|b(?:c)?)$");
    }

    #[test]
    fn alternation() {
        // TODO: Use "{e}" syntax once MSRV bumps above 1.58.
        let expr = Expression::regex("a/b c/d/e")
            .unwrap_or_else(|e| panic!("failed: {}", e));

        assert_eq!(expr.as_str(), "^(?:a|b) (?:c|d|e)$");
        assert!(expr.is_match("a c"));
        assert!(expr.is_match("b e"));
        assert!(!expr.is_match("c e"));
        assert!(!expr.is_match("a"));
        assert!(!expr.is_match("a "));
    }

    #[test]
    fn empty() {
        // TODO: Use "{e}" syntax once MSRV bumps above 1.58.
        let expr =
            Expression::regex("").unwrap_or_else(|e| panic!("failed: {}", e));

        assert_eq!(expr.as_str(), "^$");
        assert!(expr.is_match(""));
        assert!(!expr.is_match("a"));
    }

    #[test]
    fn escape_regex_characters() {
        // TODO: Use "{e}" syntax once MSRV bumps above 1.58.
        let expr = Expression::regex(r"^$[]\()\{}\\.|?*+")
            .unwrap_or_else(|e| panic!("failed: {}", e));

        assert_eq!(expr.as_str(), r"^\^\$\[\]\(\)\{\}\\\.\|\?\*\+$");
        assert!(expr.is_match("^$[](){}\\.|?*+"));
    }

    #[test]
    fn optional() {
        // TODO: Use "{e}" syntax once MSRV bumps above 1.58.
        let expr = Expression::regex("(a)")
            .unwrap_or_else(|e| panic!("failed: {}", e));

        assert_eq!(expr.as_str(), "^(?:a)?$");
        assert!(expr.is_match(""));
        assert!(expr.is_match("a"));
        assert!(!expr.is_match("b"));
    }

    #[test]
    fn parameter_int() {
        // TODO: Use "{e}" syntax once MSRV bumps above 1.58.
        let expr = Expression::regex("{int}")
            .unwrap_or_else(|e| panic!("failed: {}", e));

        assert_eq!(expr.as_str(), "^((?:-?\\d+)|(?:\\d+))$");
        assert!(expr.is_match("123"));
        assert!(expr.is_match("-123"));
        assert!(!expr.is_match("+123"));
        assert!(!expr.is_match("123."));
    }

    #[test]
    fn parameter_float() {
        // TODO: Use "{e}" syntax once MSRV bumps above 1.58.
        let expr = Expression::regex("{float}")
            .unwrap_or_else(|e| panic!("failed: {}", e));

        assert_eq!(
            expr.as_str(),
            "^([+-]?(?:inf\
                      |NaN\
                      |(?:\\d+|\\d+\\.\\d*|\\d*\\.\\d+)(?:[eE][+-]?\\d+)?\
                    ))$",
        );
        assert!(expr.is_match("+1"));
        assert!(expr.is_match(".1"));
        assert!(expr.is_match("-.1"));
        assert!(expr.is_match("-1."));
        assert!(expr.is_match("-1.1E+1"));
        assert!(expr.is_match("-inf"));
        assert!(expr.is_match("NaN"));
    }

    #[test]
    fn parameter_word() {
        // TODO: Use "{e}" syntax once MSRV bumps above 1.58.
        let expr = Expression::regex("{word}")
            .unwrap_or_else(|e| panic!("failed: {}", e));

        assert_eq!(expr.as_str(), "^([^\\s]+)$");
        assert!(expr.is_match("test"));
        assert!(expr.is_match("\"test\""));
        assert!(!expr.is_match("with space"));
    }

    #[test]
    fn parameter_string() {
        // TODO: Use "{e}" syntax once MSRV bumps above 1.58.
        let expr = Expression::regex("{string}")
            .unwrap_or_else(|e| panic!("failed: {}", e));

        assert_eq!(
            expr.as_str(),
            "^(?:\
                \"(?P<__0_0>[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"\
                |'(?P<__0_1>[^'\\\\]*(?:\\\\.[^'\\\\]*)*)'\
             )$",
        );
        assert!(expr.is_match("\"\""));
        assert!(expr.is_match("''"));
        assert!(expr.is_match("'with \"'"));
        assert!(expr.is_match("\"with '\""));
        assert!(expr.is_match("\"with \\\" escaped\""));
        assert!(expr.is_match("'with \\' escaped'"));
        assert!(!expr.is_match("word"));
    }

    #[test]
    fn multiple_string_parameters() {
        // TODO: Use "{e}" syntax once MSRV bumps above 1.58.
        let expr = Expression::regex("{string} {string}")
            .unwrap_or_else(|e| panic!("failed: {}", e));

        assert_eq!(
            expr.as_str(),
            "^(?:\
                \"(?P<__0_0>[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"\
                |'(?P<__0_1>[^'\\\\]*(?:\\\\.[^'\\\\]*)*)'\
              ) (?:\
                \"(?P<__1_0>[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\"\
                |'(?P<__1_1>[^'\\\\]*(?:\\\\.[^'\\\\]*)*)'\
              )$",
        );
        assert!(expr.is_match("\"\" ''"));
        assert!(expr.is_match("'' \"\""));
        assert!(expr.is_match("'with \"' \"\""));
        assert!(expr.is_match("\"with '\" '\"'"));
        assert!(expr.is_match("\"with \\\" escaped\" 'with \\' escaped'"));
        assert!(expr.is_match("'with \\' escaped' \"with \\\" escaped\""));
    }

    #[test]
    fn parameter_all() {
        // TODO: Use "{e}" syntax once MSRV bumps above 1.58.
        let expr =
            Expression::regex("{}").unwrap_or_else(|e| panic!("failed: {}", e));

        assert_eq!(expr.as_str(), "^(.*)$");
        assert!(expr.is_match("anything matches"));
    }

    #[test]
    fn text() {
        // TODO: Use "{e}" syntax once MSRV bumps above 1.58.
        let expr =
            Expression::regex("a").unwrap_or_else(|e| panic!("failed: {}", e));

        assert_eq!(expr.as_str(), "^a$");
        assert!(expr.is_match("a"));
        assert!(!expr.is_match("b"));
        assert!(!expr.is_match("ab"));
    }

    #[test]
    fn unicode() {
        // TODO: Use "{e}" syntax once MSRV bumps above 1.58.
        let expr = Expression::regex("Привет, Мир(ы)!")
            .unwrap_or_else(|e| panic!("failed: {}", e));

        assert_eq!(expr.as_str(), "^Привет, Мир(?:ы)?!$");
        assert!(expr.is_match("Привет, Мир!"));
        assert!(expr.is_match("Привет, Миры!"));
        assert!(!expr.is_match("Hello world"));
    }

    #[test]
    fn unknown_parameter() {
        match Expression::regex("{custom}").unwrap_err() {
            Error::Expansion(ParameterError::NotFound(not_found)) => {
                assert_eq!(*not_found, "custom");
            }
            e @ (Error::Parsing(_) | Error::Regex(_) | Error::Expansion(_)) => {
                // TODO: Use "{e}" syntax once MSRV bumps above 1.58.
                panic!("wrong err: {}", e);
            }
        }
    }
}