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
use crate::input::ParserContext;
use std::error;
use std::fmt::Display;

/// The error type returned [when parsers fail](crate::Res).
///
/// This is a tree-like structure where nodes represent specific parsers or combinators that
/// failed.
///
/// Here is an example:
/// ```
/// use parser_compose::Parser;
///
/// let msg = "ABCD";
///
/// let parser = "B".or("C").or("A");
///
/// let result = parser.accumulate(4).try_parse(msg.into());
///
/// assert!(result.is_err());
///
/// println!("{}", result.err().unwrap());
/// // stdout:
/// // expected 4 match(es). matched 3 time(s)
/// //    both branches failed:
/// //       both branches failed:
/// //          expected 'B' at position 3
/// //          expected 'C' at position 3
/// //       expected 'A' at position 3
/// ```
///
/// In this case, the parser failed because it could not match "A", "B," or "C" at
/// position 3 in the input.
///
/// You can augment the information in this tree by adding custom errors using
/// [`err()`](crate::Parser::err) or labelling a parser using [`label()`](crate::Parser::label).
/// Both methods insert additional nodes into the tree.
///
/// ```
/// use parser_compose::Parser;
///
/// let msg = "A";
///
/// let parser = "B".or("C").label("failed to parse C or B");
///
/// let result = parser.try_parse(msg.into());
///
/// assert!(result.is_err());
/// println!("{}", result.err().unwrap());
///
/// // stdout:
/// // [failed to parse C or B]
/// //    both branches failed:
/// //       expected 'B' at position 0
/// //       expected 'C' at position 0
/// ```
#[derive(Debug)]
pub enum ErrorTree {
    Or {
        pos: usize,
        left: Box<ErrorTree>,
        right: Box<ErrorTree>,
    },
    Predicate {
        pos: usize,
    },
    Fold {
        pos: usize,
        child: Box<ErrorTree>,
        matched: usize,
        lower_bound: usize,
        upper_bound: Option<usize>,
    },
    Peeked {
        pos: usize,
        child: Box<ErrorTree>,
    },
    NotPeeked {
        pos: usize,
    },
    AndThen {
        pos: usize,
        callback_error: Box<dyn error::Error>,
    },
    Sequence {
        pos: usize,
        position_in_sequence: usize,
        child: Box<ErrorTree>,
    },
    Label {
        pos: usize,
        label: &'static str,
        child: Box<ErrorTree>,
    },
    Mismatch {
        expected: String,
        pos: usize,
    },
    Custom {
        pos: usize,
        child: Box<ErrorTree>,
        err: Box<dyn error::Error>,
    },
}
impl ErrorTree {
    fn pretty_print_recursive(&self, indent: usize) -> String {
        let prefix = "   ".repeat(indent);
        let text = match self {
            ErrorTree::Or { left, right, .. } => {
                // An `Or` parser failed if both branches failed.
                format!(
                    "both branches failed:\n{}\n{}",
                    left.pretty_print_recursive(indent + 1),
                    right.pretty_print_recursive(indent + 1)
                )
            }
            ErrorTree::Predicate { .. } => {
                // A Predicate parser
                "predicate evaluated to false".to_string()
            }
            ErrorTree::Fold {
                child,
                lower_bound,
                upper_bound,
                matched,
                ..
            } => {
                if let Some(upper) = upper_bound {
                    if upper == lower_bound {
                        format!(
                            "expected {} match(es). matched {} time(s)\n{}",
                            upper,
                            matched,
                            child.pretty_print_recursive(indent + 1)
                        )
                    } else {
                        format!(
                            "expected at least {} and at most {} match(es). matched {} time(s):\n{}",
                            lower_bound,
                            upper,
                            matched,
                            child.pretty_print_recursive(indent + 1)
                        )
                    }
                } else {
                    format!(
                        "expected at least {} match(es). matched {} time(s)\n{}",
                        lower_bound,
                        matched,
                        child.pretty_print_recursive(indent + 1)
                    )
                }
            }
            ErrorTree::Peeked { child, .. } => {
                format!(
                    "lookahead failed\n{}",
                    child.pretty_print_recursive(indent + 1)
                )
            }
            ErrorTree::NotPeeked { pos } => {
                format!("negative lookahead failed at position: {}", pos)
            }
            ErrorTree::AndThen { callback_error, .. } => {
                format!("[err: {}]", callback_error)
            }
            ErrorTree::Sequence {
                position_in_sequence,
                child,
                ..
            } => {
                format!(
                    "sequence failed at member [{}]\n{}",
                    position_in_sequence,
                    child.pretty_print_recursive(indent + 1)
                )
            }
            ErrorTree::Label { label, child, .. } => {
                format!("[{}]\n{}", label, child.pretty_print_recursive(indent + 1))
            }
            ErrorTree::Mismatch { expected, pos } => {
                format!("expected '{}' at position {}", expected, pos)
            }
            ErrorTree::Custom { child, err, .. } => {
                format!(
                    "[err: {}]\n{}",
                    err,
                    child.pretty_print_recursive(indent + 1)
                )
            }
        };

        format!("{}{}", prefix, text)
    }
}

impl Display for ErrorTree {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.pretty_print_recursive(0))
    }
}

/// The return value of this crate's parsers
pub type Res<In, Out> = Result<(Out, ParserContext<In>), ErrorTree>;