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
#![allow(missing_docs, missing_copy_implementations, missing_debug_implementations)]

// Recursion implementation modified from `toml`: https://github.com/toml-rs/toml/blob/a02cbf46cab4a8683e641efdba648a31498f7342/crates/toml_edit/src/parser/mod.rs#L99

use core::fmt;
use winnow::{error::ContextError, Parser};

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum CustomError {
    RecursionLimitExceeded,
}

impl fmt::Display for CustomError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::RecursionLimitExceeded => f.write_str("recursion limit exceeded"),
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for CustomError {}

pub type Input<'a> = winnow::Stateful<&'a str, RecursionCheck>;

pub fn new_input(input: &str) -> Input<'_> {
    winnow::Stateful { input, state: Default::default() }
}

pub fn check_recursion<'a, O>(
    mut parser: impl Parser<Input<'a>, O, ContextError>,
) -> impl Parser<Input<'a>, O, ContextError> {
    move |input: &mut Input<'a>| {
        input.state.enter().map_err(|_err| {
            // TODO: Very weird bug with features: https://github.com/alloy-rs/core/issues/717
            // use winnow::error::FromExternalError;
            // let err = winnow::error::ContextError::from_external_error(
            //     input,
            //     winnow::error::ErrorKind::Eof,
            //     _err,
            // );
            let err = winnow::error::ContextError::new();
            winnow::error::ErrMode::Cut(err)
        })?;
        let result = parser.parse_next(input);
        input.state.exit();
        result
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RecursionCheck {
    current: usize,
}

const LIMIT: usize = 80;

impl RecursionCheck {
    #[cfg(any())]
    fn check_depth(_depth: usize) -> Result<(), CustomError> {
        if LIMIT <= _depth {
            return Err(CustomError::RecursionLimitExceeded);
        }

        Ok(())
    }

    fn enter(&mut self) -> Result<(), CustomError> {
        self.current += 1;
        if LIMIT <= self.current {
            return Err(CustomError::RecursionLimitExceeded);
        }
        Ok(())
    }

    fn exit(&mut self) {
        self.current -= 1;
    }
}