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
use std::fmt::{self, Display};
use std::error::Error as StdError;
use quoted_string::error::CoreError;


#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum ExpectedChar {
    Char(char),
    CharClass(&'static str),
}

impl Display for ExpectedChar {
    fn fmt(&self, fter: &mut fmt::Formatter) -> fmt::Result {
        use self::ExpectedChar::*;
        match *self {
            Char(ch) => write!(fter, "{:?}", ch),
            CharClass(chc) => write!(fter, "{:?}", chc)
        }
    }
}


#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub enum ErrorKind {

    QuotedParamValue {
        pos: usize,
        cause: CoreError
    },

    UnquotedParamValue {
        pos: usize,
        cause: CoreError
    },

    UnexpectedChar {
        pos: usize,
        expected: ExpectedChar
    },

    UnexpectedEof,

    IllegalCrNlSeq {
        pos: usize
    }
}

impl ErrorKind {

    pub fn with_input(self, input: &str) -> ParserErrorRef {
        ParserErrorRef::new(input, self)
    }

    fn description(&self) -> &str {
        use self::ErrorKind::*;
        match *self {
            QuotedParamValue {..} => "parsing quoted parameter value failed",
            UnquotedParamValue {..} => "parsing unquoted parameter value failed",
            UnexpectedChar { .. } => "parsing hit an unexpected character",
            UnexpectedEof { .. } => "parsing unexpectedly hit eof",
            IllegalCrNlSeq { .. } => r#"parsing found a illegal "\r\n "/"\r\n\t" seqence"#
        }
    }

    fn cause(&self) -> Option<&StdError> {
        use self::ErrorKind::*;
        match self {
            &QuotedParamValue { ref cause, ..} => Some(cause as &StdError),
            &UnquotedParamValue { ref cause, ..} => Some(cause as &StdError),
            _ => None
        }
    }

    fn display(&self, input: &str, fter: &mut fmt::Formatter) -> fmt::Result {
        use self::ErrorKind::*;
        match *self {
            QuotedParamValue { pos, cause } => {
                write!(
                    fter,
                    "parsing quoted parameter failed on: {:?} at byte {:?} because of {:?} ({})",
                    input, pos, cause, cause
                )
            },
            UnquotedParamValue { pos, cause } => {
                write!(
                    fter,
                    "parsing unquoted parameter failed on: {:?} at byte {:?} because of {:?} ({})",
                    input, pos, cause, cause
                )
            },
            UnexpectedChar {  pos, expected } => {
                write!(
                    fter,
                    "hit unexpected char {:?} while parsing {:?} at {} expected {}",
                    one_char_str(input, pos), input, pos, expected
                )
            },
            UnexpectedEof => {
                write!(fter, "hit eof unexpectedly in {:?}", input)
            },

            IllegalCrNlSeq { pos } => {
                write!(fter, "hit invalid \"\\r\\n \"/\"\\r\\n\\t\" seq in {:?} at {}", input, pos)
            }
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ParserErrorRef<'a> {
    input: &'a str,
    kind: ErrorKind
}

impl<'a> ParserErrorRef<'a> {

    pub fn new(input: &'a str, kind: ErrorKind) -> Self {
        ParserErrorRef { input, kind }
    }

    pub fn input(&self) -> &'a str {
        self.input
    }

    pub fn kind(&self) -> ErrorKind {
        self.kind
    }

    pub fn to_owned(&self) -> Error {
        Error::new(self.input, self.kind)
    }
}

impl<'a> Display for ParserErrorRef<'a> {
    fn fmt(&self, fter: &mut fmt::Formatter) -> fmt::Result {
        self.kind.display(self.input, fter)
    }
}


impl<'a> StdError for ParserErrorRef<'a> {

    fn description(&self) -> &str {
        self.kind.description()
    }

    fn cause(&self) -> Option<&StdError> {
        self.kind.cause()
    }
}

impl<'a> From<ParserErrorRef<'a>> for Error {
    fn from(pref: ParserErrorRef<'a>) -> Self {
        pref.to_owned()
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Error {
    input: String,
    kind: ErrorKind
}

impl Error {

    pub fn new<I: Into<String>>(input: I, kind: ErrorKind) -> Self {
        Error { input: input.into(), kind }
    }

    pub fn input(&self) -> &str {
        self.input.as_ref()
    }

    pub fn kind(&self) -> ErrorKind {
        self.kind
    }

    //Deref, Borrow, AsRef can not be implemented unless rust has
    // AssociatedTypeConstructors, at last wrt. lifetimes
    pub fn as_ref(&self) -> ParserErrorRef {
        ParserErrorRef {
            input: self.input.as_ref(),
            kind: self.kind
        }
    }
}

impl Display for Error {
    fn fmt(&self, fter: &mut fmt::Formatter) -> fmt::Result {
        self.kind.display(self.input.as_ref(), fter)
    }
}

impl StdError for Error {
    fn description(&self) -> &str {
        self.kind.description()
    }

    fn cause(&self) -> Option<&StdError> {
        self.kind.cause()
    }
}


fn one_char_str(inp: &str, offset: usize) -> &str {
    inp.get(offset..)
        .map(|tail: &str| {
            let first_char_len = tail.chars().next().map(|ch| ch.len_utf8()).unwrap_or(0);
            //INDEX_SAFE: if there is no char it's 0, ..0 is always valid if there is a char
            // indexing the substring only containing the existing first char is also valid
            &tail[..first_char_len]
        })
        .unwrap_or("<[BUG] invalid str index in error>")
}