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
//! JMESPath errors.

use std::error::Error;
use std::fmt;

use crate::Context;

/// JMESPath error.
#[derive(Clone, Debug, PartialEq)]
pub struct JmespathError {
    /// Absolute character position.
    pub offset: usize,
    /// Line number of the coordinate.
    pub line: usize,
    /// Column of the line number.
    pub column: usize,
    /// Expression being evaluated.
    pub expression: String,
    /// Error reason information.
    pub reason: ErrorReason,
}

impl JmespathError {
    /// Create a new JMESPath Error.
    pub fn new(expr: &str, offset: usize, reason: ErrorReason) -> JmespathError {
        // Find each new line so we can create a formatted error message.
        let mut line: usize = 0;
        let mut column: usize = 0;
        for c in expr.chars().take(offset) {
            match c {
                '\n' => {
                    line += 1;
                    column = 0;
                }
                _ => column += 1,
            }
        }
        JmespathError {
            expression: expr.to_owned(),
            offset,
            line,
            column,
            reason,
        }
    }

    /// Create a new JMESPath Error from a Context struct.
    pub fn from_ctx(ctx: &Context<'_>, reason: ErrorReason) -> JmespathError {
        JmespathError::new(ctx.expression, ctx.offset, reason)
    }
}

impl Error for JmespathError {
    fn description(&self) -> &str {
        "error evaluating JMESPath expression"
    }
}

impl From<serde_json::Error> for JmespathError {
    fn from(err: serde_json::Error) -> Self {
        JmespathError::new(
            "",
            0,
            ErrorReason::Parse(format!("Serde parse error: {}", err)),
        )
    }
}

fn inject_carat(column: usize, buff: &mut String) {
    buff.push_str(&(0..column).map(|_| ' ').collect::<String>());
    buff.push_str(&"^\n");
}

impl fmt::Display for JmespathError {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        let mut error_location = String::new();
        let mut matched = false;
        let mut current_line = 0;
        for c in self.expression.chars() {
            error_location.push(c);
            if c == '\n' {
                current_line += 1;
                if current_line == self.line + 1 {
                    matched = true;
                    inject_carat(self.column, &mut error_location);
                }
            }
        }
        if !matched {
            error_location.push('\n');
            inject_carat(self.column, &mut error_location);
        }

        write!(
            fmt,
            "{} (line {}, column {})\n{}",
            self.reason, self.line, self.column, error_location
        )
    }
}

/// Error context to provide specific details about an error.
#[derive(Clone, Debug, PartialEq)]
pub enum ErrorReason {
    /// An error occurred while parsing an expression.
    Parse(String),
    /// An error occurred while evaluating an expression.
    Runtime(RuntimeError),
}

impl fmt::Display for ErrorReason {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        match *self {
            ErrorReason::Parse(ref e) => write!(fmt, "Parse error: {}", e),
            ErrorReason::Runtime(ref e) => write!(fmt, "Runtime error: {}", e),
        }
    }
}

/// Runtime JMESPath error
#[derive(Clone, Debug, PartialEq)]
pub enum RuntimeError {
    /// Encountered when a slice expression uses a step of 0
    InvalidSlice,
    /// Encountered when too many arguments are provided to a function.
    TooManyArguments {
        /// Expeced number of arguments.
        expected: usize,
        /// Provided number of arguments.
        actual: usize,
    },
    /// Encountered when too few arguments are provided to a function.
    NotEnoughArguments {
        /// Expeced number of arguments.
        expected: usize,
        /// Provided number of arguments.
        actual: usize,
    },
    /// Encountered when an unknown function is called.
    UnknownFunction(String),
    /// Encountered when a type of variable given to a function is invalid.
    InvalidType {
        /// Expected type.
        expected: String,
        /// Provided type.
        actual: String,
        /// Argument position when calling the function.
        position: usize,
    },
    /// Encountered when an expression reference returns an invalid type.
    InvalidReturnType {
        /// Expected return type.
        expected: String,
        /// Actual return type.
        actual: String,
        /// Argument position from which the expression reference was invoked.
        position: usize,
        /// Which invocation iteration of the expression reference failed.
        invocation: usize,
    },
}

impl fmt::Display for RuntimeError {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        use self::RuntimeError::*;
        match *self {
            UnknownFunction(ref function) => write!(fmt, "Call to undefined function {}", function),
            TooManyArguments {
                ref expected,
                ref actual,
            } => write!(
                fmt,
                "Too many arguments: expected {}, found {}",
                expected, actual
            ),
            NotEnoughArguments {
                ref expected,
                ref actual,
            } => write!(
                fmt,
                "Not enough arguments: expected {}, found {}",
                expected, actual
            ),
            InvalidType {
                ref expected,
                ref actual,
                ref position,
            } => write!(
                fmt,
                "Argument {} expects type {}, given {}",
                position, expected, actual
            ),
            InvalidSlice => write!(fmt, "Invalid slice"),
            InvalidReturnType {
                ref expected,
                ref actual,
                ref position,
                ref invocation,
            } => write!(
                fmt,
                "Argument {} must return {} but invocation {} returned {}",
                position, expected, invocation, actual
            ),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn coordinates_can_be_created_from_string_with_new_lines() {
        let expr = "foo\n..bar";
        let err = JmespathError::new(&expr, 5, ErrorReason::Parse("Test".to_owned()));
        assert_eq!(1, err.line);
        assert_eq!(1, err.column);
        assert_eq!(5, err.offset);
        assert_eq!(
            "Parse error: Test (line 1, column 1)\nfoo\n..bar\n ^\n",
            err.to_string()
        );
    }

    #[test]
    fn coordinates_can_be_created_from_string_with_new_lines_pointing_to_non_last() {
        let expr = "foo\n..bar\nbaz";
        let err = JmespathError::new(&expr, 5, ErrorReason::Parse("Test".to_owned()));
        assert_eq!(1, err.line);
        assert_eq!(1, err.column);
        assert_eq!(5, err.offset);
        assert_eq!(
            "Parse error: Test (line 1, column 1)\nfoo\n..bar\n ^\nbaz",
            err.to_string()
        );
    }

    #[test]
    fn coordinates_can_be_created_from_string_with_no_new_lines() {
        let expr = "foo..bar";
        let err = JmespathError::new(&expr, 4, ErrorReason::Parse("Test".to_owned()));
        assert_eq!(0, err.line);
        assert_eq!(4, err.column);
        assert_eq!(4, err.offset);
        assert_eq!(
            "Parse error: Test (line 0, column 4)\nfoo..bar\n    ^\n",
            err.to_string()
        );
    }

    #[test]
    fn reason_displays_parse_errors() {
        let reason = ErrorReason::Parse("bar".to_owned());
        assert_eq!("Parse error: bar", reason.to_string());
    }

    #[test]
    fn reason_displays_runtime_errors() {
        let reason = ErrorReason::Runtime(RuntimeError::UnknownFunction("a".to_owned()));
        assert_eq!(
            "Runtime error: Call to undefined function a",
            reason.to_string()
        );
    }

    #[test]
    fn displays_invalid_type_error() {
        let error = RuntimeError::InvalidType {
            expected: "string".to_owned(),
            actual: "boolean".to_owned(),
            position: 0,
        };
        assert_eq!(
            "Argument 0 expects type string, given boolean",
            error.to_string()
        );
    }

    #[test]
    fn displays_invalid_slice() {
        let error = RuntimeError::InvalidSlice;
        assert_eq!("Invalid slice", error.to_string());
    }

    #[test]
    fn displays_too_many_arguments_error() {
        let error = RuntimeError::TooManyArguments {
            expected: 1,
            actual: 2,
        };
        assert_eq!("Too many arguments: expected 1, found 2", error.to_string());
    }

    #[test]
    fn displays_not_enough_arguments_error() {
        let error = RuntimeError::NotEnoughArguments {
            expected: 2,
            actual: 1,
        };
        assert_eq!(
            "Not enough arguments: expected 2, found 1",
            error.to_string()
        );
    }

    #[test]
    fn displays_invalid_return_type_error() {
        let error = RuntimeError::InvalidReturnType {
            expected: "string".to_string(),
            actual: "boolean".to_string(),
            position: 0,
            invocation: 2,
        };
        assert_eq!(
            "Argument 0 must return string but invocation 2 returned boolean",
            error.to_string()
        );
    }
}