jsonata/
errors.rs

1use std::{char, error, fmt};
2
3pub type Result<T> = std::result::Result<T, Error>;
4
5#[derive(Debug, PartialEq)]
6pub enum Error {
7    // Compile time errors
8    S0101UnterminatedStringLiteral(usize),
9    S0102LexedNumberOutOfRange(usize, String),
10    S0103UnsupportedEscape(usize, char),
11    S0104InvalidUnicodeEscape(usize),
12    S0105UnterminatedQuoteProp(usize),
13    S0106UnterminatedComment(usize),
14    S0201SyntaxError(usize, String),
15    S0202UnexpectedToken(usize, String, String),
16    S0204UnknownOperator(usize, String),
17    S0203ExpectedTokenBeforeEnd(usize, String),
18    S0208InvalidFunctionParam(usize, String),
19    S0209InvalidPredicate(usize),
20    S0210MultipleGroupBy(usize),
21    S0211InvalidUnary(usize, String),
22    S0212ExpectedVarLeft(usize),
23    S0213InvalidStep(usize, String),
24    S0214ExpectedVarRight(usize, String),
25
26    // Runtime errors
27    D1001NumberOfOutRange(f64),
28    D1002NegatingNonNumeric(usize, String),
29    D1009MultipleKeys(usize, String),
30    D2014RangeOutOfBounds(usize, isize),
31    D3001StringNotFinite(usize),
32    D3030NonNumericCast(usize, String),
33    D3060SqrtNegative(usize, String),
34    D3061PowUnrepresentable(usize, String, String),
35    D3141Assert(String),
36    D3137Error(String),
37
38    // Type errors
39    T0410ArgumentNotValid(usize, usize, String),
40    T0412ArgumentMustBeArrayOfType(usize, usize, String, String),
41    T1003NonStringKey(usize, String),
42    T1005InvokedNonFunctionSuggest(usize, String),
43    T1006InvokedNonFunction(usize),
44    T2001LeftSideNotNumber(usize, String),
45    T2002RightSideNotNumber(usize, String),
46    T2003LeftSideNotInteger(usize),
47    T2004RightSideNotInteger(usize),
48    T2009BinaryOpMismatch(usize, String, String, String),
49    T2010BinaryOpTypes(usize, String),
50    
51    // Expression timebox/depth errors
52    U1001StackOverflow,
53    U1001Timeout
54}
55
56impl error::Error for Error {}
57
58impl Error {
59    /**
60     * Error codes
61     *
62     * Sxxxx    - Static errors (compile time)
63     * Txxxx    - Type errors
64     * Dxxxx    - Dynamic errors (evaluate time)
65     *  01xx    - tokenizer
66     *  02xx    - parser
67     *  03xx    - regex parser
68     *  04xx    - function signature parser/evaluator
69     *  10xx    - evaluator
70     *  20xx    - operators
71     *  3xxx    - functions (blocks of 10 for each function)
72     */
73    pub fn code(&self) -> &str {
74        match *self {
75            // Compile time errors
76            Error::S0101UnterminatedStringLiteral(..) => "S0101",
77            Error::S0102LexedNumberOutOfRange(..) => "S0102",
78            Error::S0103UnsupportedEscape(..) => "S0103",
79            Error::S0104InvalidUnicodeEscape(..) => "S0104",
80            Error::S0105UnterminatedQuoteProp(..) => "S0105",
81            Error::S0106UnterminatedComment(..) => "S0106",
82            Error::S0201SyntaxError(..) => "S0201",
83            Error::S0202UnexpectedToken(..) => "S0202",
84            Error::S0203ExpectedTokenBeforeEnd(..) => "S0203",
85            Error::S0204UnknownOperator(..) => "S0204",
86            Error::S0208InvalidFunctionParam(..) => "S0208",
87            Error::S0209InvalidPredicate(..) => "S0209",
88            Error::S0210MultipleGroupBy(..) => "S0210",
89            Error::S0211InvalidUnary(..) => "S0211",
90            Error::S0212ExpectedVarLeft(..) => "S0212",
91            Error::S0213InvalidStep(..) => "S0213",
92            Error::S0214ExpectedVarRight(..) => "S0214",
93
94            // Runtime errors
95            Error::D1001NumberOfOutRange(..) => "D1001",
96            Error::D1002NegatingNonNumeric(..) => "D1002",
97            Error::D1009MultipleKeys(..) => "D1009",
98            Error::D2014RangeOutOfBounds(..) => "D2014",
99            Error::D3001StringNotFinite(..) => "D3001",
100            Error::D3030NonNumericCast(..) => "D3030",
101            Error::D3060SqrtNegative(..) => "D3060",
102            Error::D3061PowUnrepresentable(..) => "D3061",
103            Error::D3141Assert(..) => "D3141",
104            Error::D3137Error(..) => "D3137",
105
106            // Type errors
107            Error::T0410ArgumentNotValid(..) => "T0410",
108            Error::T0412ArgumentMustBeArrayOfType(..) => "T0412",
109            Error::T1003NonStringKey(..) => "T1003",
110            Error::T1005InvokedNonFunctionSuggest(..) => "T1005",
111            Error::T1006InvokedNonFunction(..) => "T1006",
112            Error::T2001LeftSideNotNumber(..) => "T2001",
113            Error::T2002RightSideNotNumber(..) => "T2002",
114            Error::T2003LeftSideNotInteger(..) => "T2003",
115            Error::T2004RightSideNotInteger(..) => "T2004",
116            Error::T2009BinaryOpMismatch(..) => "T2009",
117            Error::T2010BinaryOpTypes(..) => "T2010",
118            
119            // Expression timebox/depth errors
120            Error::U1001StackOverflow => "U1001",
121            Error::U1001Timeout => "U1001"
122        }
123    }
124}  
125
126impl fmt::Display for Error {
127    #[allow(clippy::many_single_char_names)]
128    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
129        use Error::*;
130
131        write!(f, "{} @ ", self.code())?;
132
133        match *self {
134            // Compile time errors
135            S0101UnterminatedStringLiteral(ref p) =>
136                write!(f, "{}: String literal must be terminated by a matching quote", p),
137            S0102LexedNumberOutOfRange(ref p, ref n) =>
138                write!(f, "{}: Number out of range: {}", p, n),
139            S0103UnsupportedEscape(ref p, ref c) =>
140                write!(f, "{}: Unsupported escape sequence: \\{}", p, c),
141            S0104InvalidUnicodeEscape(ref p) =>
142                write!(f, "{}: The escape sequence \\u must be followed by 4 hex digits", p),
143            S0105UnterminatedQuoteProp(ref p) =>
144                write!(f, "{}: Quoted property name must be terminated with a backquote (`)", p),
145            S0106UnterminatedComment(ref p) =>
146                write!(f, "{}: Comment has no closing tag", p),
147            S0201SyntaxError(ref p, ref t) =>
148                write!(f, "{}: Syntax error `{}`", p, t),
149            S0202UnexpectedToken(ref p, ref e, ref a) =>
150                write!(f, "{}: Expected `{}`, got `{}`", p, e, a),
151            S0203ExpectedTokenBeforeEnd(ref p, ref t) =>
152                write!(f, "{}: Expected `{}` before end of expression", p, t),
153            S0204UnknownOperator(ref p, ref t) =>
154                write!(f, "{}: Unknown operator: `{}`", p, t),
155            S0208InvalidFunctionParam(ref p, ref k) =>
156                write!(f, "{}: Parameter `{}` of function definition must be a variable name (start with $)", p, k),
157            S0209InvalidPredicate(ref p) =>
158                write!(f, "{}: A predicate cannot follow a grouping expression in a step", p),
159            S0210MultipleGroupBy(ref p) =>
160                write!(f, "{}: Each step can only have one grouping expression", p),
161            S0211InvalidUnary(ref p, ref k) =>
162                write!(f, "{}: The symbol `{}` cannot be used as a unary operator", p, k),
163            S0212ExpectedVarLeft(ref p) =>
164                write!(f, "{}: The left side of `:=` must be a variable name (start with $)", p),
165            S0213InvalidStep(ref p, ref k) =>
166                write!(f, "{}: The literal value `{}` cannot be used as a step within a path expression", p, k),
167            S0214ExpectedVarRight(ref p, ref k) =>
168                write!(f, "{}: The right side of `{}` must be a variable name (start with $)", p, k),
169            
170            // Runtime errors
171            D1001NumberOfOutRange(ref n) =>
172                write!(f, "Number out of range: {}", n),
173            D1002NegatingNonNumeric(ref p, ref v) =>
174                write!(f, "{}: Cannot negate a non-numeric value `{}`", p, v),
175            D1009MultipleKeys(ref p, ref k) =>
176                write!(f, "{}: Multiple key definitions evaluate to same key: {}", p, k),
177            D2014RangeOutOfBounds(ref p, ref s) =>
178                write!(f, "{}: The size of the sequence allocated by the range operator (..) must not exceed 1e7.  Attempted to allocate {}", p, s),
179            D3001StringNotFinite(ref p) => 
180                write!(f, "{}: Attempting to invoke string function on Infinity or NaN", p),
181            D3030NonNumericCast(ref p, ref n) =>
182                write!(f, "{}: Unable to cast value to a number: {}", p, n),
183            D3060SqrtNegative(ref p, ref n) =>
184                write!(f, "{}: The sqrt function cannot be applied to a negative number: {}", p, n),
185            D3061PowUnrepresentable(ref p, ref b, ref e) =>
186                write!(f, "{}: The power function has resulted in a value that cannot be represented as a JSON number: base={}, exponent={}", p, b, e),
187            D3141Assert(ref m) =>
188                write!(f, "{}", m),
189            D3137Error(ref m) =>
190                write!(f, "{}", m),
191            
192            // Type errors
193            T0410ArgumentNotValid(ref p, ref i, ref t) =>
194                write!(f, "{}: Argument {} of function {} does not match function signature", p, i, t),
195            T0412ArgumentMustBeArrayOfType(ref p, ref i, ref t, ref ty) =>
196                write!(f, "{}: Argument {} of function {} must be an array of {}", p, i, t, ty),
197            T1003NonStringKey(ref p, ref v) =>
198                write!( f, "{}: Key in object structure must evaluate to a string; got: {}", p, v),
199            T1005InvokedNonFunctionSuggest(ref p, ref t) =>
200                write!(f, "{}: Attempted to invoke a non-function. Did you mean ${}?", p, t),
201            T1006InvokedNonFunction(ref p) =>
202                write!(f, "{}: Attempted to invoke a non-function", p),
203            T2001LeftSideNotNumber(ref p, ref o) =>
204                write!( f, "{}: The left side of the `{}` operator must evaluate to a number", p, o),
205            T2002RightSideNotNumber(ref p, ref o) =>
206                write!( f, "{}: The right side of the `{}` operator must evaluate to a number", p, o),
207            T2003LeftSideNotInteger(ref p) =>
208                write!(f, "{}: The left side of the range operator (..) must evaluate to an integer", p),
209            T2004RightSideNotInteger(ref p) =>
210                write!(f, "{}: The right side of the range operator (..) must evaluate to an integer", p),
211            T2009BinaryOpMismatch(ref p,ref l ,ref r ,ref o ) =>
212                write!(f, "{}: The values {} and {} either side of operator {} must be of the same data type", p, l, r, o),
213            T2010BinaryOpTypes(ref p, ref o) =>
214                write!(f, "{}: The expressions either side of operator `{}` must evaluate to numeric or string values", p, o),
215    
216            // Expression timebox/depth errors
217            U1001StackOverflow => 
218                write!(f, "Stack overflow error: Check for non-terminating recursive function.  Consider rewriting as tail-recursive."),
219            U1001Timeout => 
220                write!(f, "Expression evaluation timeout: Check for infinite loop")
221        }
222    }
223}
224
225// "S0205": "Unexpected token: {{token}}",
226// "S0206": "Unknown expression type: {{token}}",
227// "S0207": "Unexpected end of expression",
228// "S0215": "A context variable binding must precede any predicates on a step",
229// "S0216": "A context variable binding must precede the 'order-by' clause on a step",
230// "S0217": "The object representing the 'parent' cannot be derived from this expression",
231
232// "S0301": "Empty regular expressions are not allowed",
233// "S0302": "No terminating / in regular expression",
234// "S0402": "Choice groups containing parameterized types are not supported",
235// "S0401": "Type parameters can only be applied to functions and arrays",
236// "S0500": "Attempted to evaluate an expression containing syntax error(s)",
237// "T0411": "Context value is not a compatible type with argument {{index}} of function {{token}}",
238// "D1004": "Regular expression matches zero length string",
239// "T1007": "Attempted to partially apply a non-function. Did you mean ${{{token}}}?",
240// "T1008": "Attempted to partially apply a non-function",
241// // "T1010": "The matcher function argument passed to function {{token}} does not return the correct object structure",
242// "D2005": "The left side of := must be a variable name (start with $)",  // defunct - replaced by S0212 parser error
243// "T2006": "The right side of the function application operator ~> must be a function",
244// "T2007": "Type mismatch when comparing values {{value}} and {{value2}} in order-by clause",
245// "T2008": "The expressions within an order-by clause must evaluate to numeric or string values",
246// "T2011": "The insert/update clause of the transform expression must evaluate to an object: {{value}}",
247// "T2012": "The delete clause of the transform expression must evaluate to a string or array of strings: {{value}}",
248// "T2013": "The transform expression clones the input object using the $clone() function.  This has been overridden in the current scope by a non-function.",
249// define_error!(
250//     D2014,
251//     "The size of the sequence allocated by the range operator (..) must not exceed 1e7.  Attempted to allocate {}",
252//     value
253// );
254// "D3010": "Second argument of replace function cannot be an empty string",
255// "D3011": "Fourth argument of replace function must evaluate to a positive number",
256// "D3012": "Attempted to replace a matched string with a non-string value",
257// "D3020": "Third argument of split function must evaluate to a positive number",
258// "D3040": "Third argument of match function must evaluate to a positive number",
259// "D3050": "The second argument of reduce function must be a function with at least two arguments",
260// "D3070": "The single argument form of the sort function can only be applied to an array of strings or an array of numbers.  Use the second argument to specify a comparison function",
261// "D3080": "The picture string must only contain a maximum of two sub-pictures",
262// "D3081": "The sub-picture must not contain more than one instance of the 'decimal-separator' character",
263// "D3082": "The sub-picture must not contain more than one instance of the 'percent' character",
264// "D3083": "The sub-picture must not contain more than one instance of the 'per-mille' character",
265// "D3084": "The sub-picture must not contain both a 'percent' and a 'per-mille' character",
266// "D3085": "The mantissa part of a sub-picture must contain at least one character that is either an 'optional digit character' or a member of the 'decimal digit family'",
267// "D3086": "The sub-picture must not contain a passive character that is preceded by an active character and that is followed by another active character",
268// "D3087": "The sub-picture must not contain a 'grouping-separator' character that appears adjacent to a 'decimal-separator' character",
269// "D3088": "The sub-picture must not contain a 'grouping-separator' at the end of the integer part",
270// "D3089": "The sub-picture must not contain two adjacent instances of the 'grouping-separator' character",
271// "D3090": "The integer part of the sub-picture must not contain a member of the 'decimal digit family' that is followed by an instance of the 'optional digit character'",
272// "D3091": "The fractional part of the sub-picture must not contain an instance of the 'optional digit character' that is followed by a member of the 'decimal digit family'",
273// "D3092": "A sub-picture that contains a 'percent' or 'per-mille' character must not contain a character treated as an 'exponent-separator'",
274// "D3093": "The exponent part of the sub-picture must comprise only of one or more characters that are members of the 'decimal digit family'",
275// "D3100": "The radix of the formatBase function must be between 2 and 36.  It was given {{value}}",
276// "D3110": "The argument of the toMillis function must be an ISO 8601 formatted timestamp. Given {{value}}",
277// "D3120": "Syntax error in expression passed to function eval: {{value}}",
278// "D3121": "Dynamic error evaluating the expression passed to function eval: {{value}}",
279// "D3130": "Formatting or parsing an integer as a sequence starting with {{value}} is not supported by this implementation",
280// "D3131": "In a decimal digit pattern, all digits must be from the same decimal group",
281// "D3132": "Unknown component specifier {{value}} in date/time picture string",
282// "D3133": "The 'name' modifier can only be applied to months and days in the date/time picture string, not {{value}}",
283// "D3134": "The timezone integer format specifier cannot have more than four digits",
284// "D3135": "No matching closing bracket ']' in date/time picture string",
285// "D3136": "The date/time picture string is missing specifiers required to parse the timestamp",
286// "D3138": "The $single() function expected exactly 1 matching result.  Instead it matched more.",
287// "D3139": "The $single() function expected exactly 1 matching result.  Instead it matched 0.",
288// "D3140": "Malformed URL passed to ${{{functionName}}}(): {{value}}",