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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
//! Module containing error definitions for the evaluation process.

use crate::any::Dynamic;
use crate::error::ParseError;
use crate::parser::INT;
use crate::token::Position;

use crate::stdlib::{
    boxed::Box,
    error::Error,
    fmt,
    string::{String, ToString},
};

#[cfg(not(feature = "no_std"))]
use crate::stdlib::path::PathBuf;

/// Evaluation result.
///
/// All wrapped `Position` values represent the location in the script where the error occurs.
///
/// Currently, `EvalAltResult` is neither `Send` nor `Sync`. Turn on the `sync` feature to make it `Send + Sync`.
#[derive(Debug)]
pub enum EvalAltResult {
    /// Syntax error.
    ErrorParsing(Box<ParseError>),

    /// Error reading from a script file. Wrapped value is the path of the script file.
    ///
    /// Never appears under the `no_std` feature.
    #[cfg(not(feature = "no_std"))]
    ErrorReadingScriptFile(PathBuf, Position, std::io::Error),

    /// Call to an unknown function. Wrapped value is the name of the function.
    ErrorFunctionNotFound(String, Position),
    /// An error has occurred inside a called function.
    /// Wrapped values re the name of the function and the interior error.
    ErrorInFunctionCall(String, Box<EvalAltResult>, Position),
    /// Function call has incorrect number of arguments.
    /// Wrapped values are the name of the function, the number of parameters required
    /// and the actual number of arguments passed.
    ErrorFunctionArgsMismatch(String, usize, usize, Position),
    /// Non-boolean operand encountered for boolean operator. Wrapped value is the operator.
    ErrorBooleanArgMismatch(String, Position),
    /// Non-character value encountered where a character is required.
    ErrorCharMismatch(Position),
    /// Array access out-of-bounds.
    /// Wrapped values are the current number of elements in the array and the index number.
    ErrorArrayBounds(usize, INT, Position),
    /// String indexing out-of-bounds.
    /// Wrapped values are the current number of characters in the string and the index number.
    ErrorStringBounds(usize, INT, Position),
    /// Trying to index into a type that is not an array, an object map, or a string, and has no indexer function defined.
    ErrorIndexingType(String, Position),
    /// Trying to index into an array or string with an index that is not `i64`.
    ErrorNumericIndexExpr(Position),
    /// Trying to index into a map with an index that is not `String`.
    ErrorStringIndexExpr(Position),
    /// Trying to import with an expression that is not `String`.
    ErrorImportExpr(Position),
    /// Invalid arguments for `in` operator.
    ErrorInExpr(Position),
    /// The guard expression in an `if` or `while` statement does not return a boolean value.
    ErrorLogicGuard(Position),
    /// The `for` statement encounters a type that is not an iterator.
    ErrorFor(Position),
    /// Usage of an unknown variable. Wrapped value is the name of the variable.
    ErrorVariableNotFound(String, Position),
    /// Usage of an unknown module. Wrapped value is the name of the module.
    ErrorModuleNotFound(String, Position),
    /// Assignment to an inappropriate LHS (left-hand-side) expression.
    ErrorAssignmentToUnknownLHS(Position),
    /// Assignment to a constant variable.
    ErrorAssignmentToConstant(String, Position),
    /// Returned type is not the same as the required output type.
    /// Wrapped value is the type of the actual result.
    ErrorMismatchOutputType(String, Position),
    /// Inappropriate member access.
    ErrorDotExpr(String, Position),
    /// Arithmetic error encountered. Wrapped value is the error message.
    ErrorArithmetic(String, Position),
    /// Number of operations over maximum limit.
    ErrorTooManyOperations(Position),
    /// Modules over maximum limit.
    ErrorTooManyModules(Position),
    /// Call stack over maximum limit.
    ErrorStackOverflow(Position),
    /// The script is prematurely terminated.
    ErrorTerminated(Position),
    /// Run-time error encountered. Wrapped value is the error message.
    ErrorRuntime(String, Position),

    /// Breaking out of loops - not an error if within a loop.
    /// The wrapped value, if true, means breaking clean out of the loop (i.e. a `break` statement).
    /// The wrapped value, if false, means breaking the current context (i.e. a `continue` statement).
    ErrorLoopBreak(bool, Position),
    /// Not an error: Value returned from a script via the `return` keyword.
    /// Wrapped value is the result value.
    Return(Dynamic, Position),
}

impl EvalAltResult {
    pub(crate) fn desc(&self) -> &str {
        match self {
            #[cfg(not(feature = "no_std"))]
            Self::ErrorReadingScriptFile(_, _, _) => "Cannot read from script file",

            Self::ErrorParsing(p) => p.desc(),
            Self::ErrorInFunctionCall(_, _, _) => "Error in called function",
            Self::ErrorFunctionNotFound(_, _) => "Function not found",
            Self::ErrorFunctionArgsMismatch(_, _, _, _) => {
                "Function call with wrong number of arguments"
            }
            Self::ErrorBooleanArgMismatch(_, _) => "Boolean operator expects boolean operands",
            Self::ErrorCharMismatch(_) => "Character expected",
            Self::ErrorNumericIndexExpr(_) => {
                "Indexing into an array or string expects an integer index"
            }
            Self::ErrorStringIndexExpr(_) => "Indexing into an object map expects a string index",
            Self::ErrorIndexingType(_, _) => {
                "Indexing can only be performed on an array, an object map, a string, or a type with an indexer function defined"
            }
            Self::ErrorImportExpr(_) => "Importing a module expects a string path",
            Self::ErrorArrayBounds(_, index, _) if *index < 0 => {
                "Array access expects non-negative index"
            }
            Self::ErrorArrayBounds(0, _, _) => "Empty array has nothing to access",
            Self::ErrorArrayBounds(_, _, _) => "Array index out of bounds",
            Self::ErrorStringBounds(_, index, _) if *index < 0 => {
                "Indexing a string expects a non-negative index"
            }
            Self::ErrorStringBounds(0, _, _) => "Empty string has nothing to index",
            Self::ErrorStringBounds(_, _, _) => "String index out of bounds",
            Self::ErrorLogicGuard(_) => "Boolean value expected",
            Self::ErrorFor(_) => "For loop expects an array, object map, or range",
            Self::ErrorVariableNotFound(_, _) => "Variable not found",
            Self::ErrorModuleNotFound(_, _) => "module not found",
            Self::ErrorAssignmentToUnknownLHS(_) => {
                "Assignment to an unsupported left-hand side expression"
            }
            Self::ErrorAssignmentToConstant(_, _) => "Assignment to a constant variable",
            Self::ErrorMismatchOutputType(_, _) => "Output type is incorrect",
            Self::ErrorInExpr(_) => "Malformed 'in' expression",
            Self::ErrorDotExpr(_, _) => "Malformed dot expression",
            Self::ErrorArithmetic(_, _) => "Arithmetic error",
            Self::ErrorTooManyOperations(_) => "Too many operations",
            Self::ErrorTooManyModules(_) => "Too many modules imported",
            Self::ErrorStackOverflow(_) => "Stack overflow",
            Self::ErrorTerminated(_) => "Script terminated.",
            Self::ErrorRuntime(_, _) => "Runtime error",
            Self::ErrorLoopBreak(true, _) => "Break statement not inside a loop",
            Self::ErrorLoopBreak(false, _) => "Continue statement not inside a loop",
            Self::Return(_, _) => "[Not Error] Function returns value",
        }
    }
}

impl Error for EvalAltResult {}

impl fmt::Display for EvalAltResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let desc = self.desc();

        match self {
            #[cfg(not(feature = "no_std"))]
            Self::ErrorReadingScriptFile(path, pos, err) if pos.is_none() => {
                write!(f, "{} '{}': {}", desc, path.display(), err)
            }
            #[cfg(not(feature = "no_std"))]
            Self::ErrorReadingScriptFile(path, pos, err) => {
                write!(f, "{} '{}': {} ({})", desc, path.display(), err, pos)
            }

            Self::ErrorParsing(p) => write!(f, "Syntax error: {}", p),

            Self::ErrorInFunctionCall(s, err, pos) => {
                write!(f, "Error in call to function '{}' ({}): {}", s, pos, err)
            }

            Self::ErrorFunctionNotFound(s, pos)
            | Self::ErrorVariableNotFound(s, pos)
            | Self::ErrorModuleNotFound(s, pos) => write!(f, "{}: '{}' ({})", desc, s, pos),

            Self::ErrorDotExpr(s, pos) if !s.is_empty() => write!(f, "{} {} ({})", desc, s, pos),

            Self::ErrorIndexingType(_, pos)
            | Self::ErrorNumericIndexExpr(pos)
            | Self::ErrorStringIndexExpr(pos)
            | Self::ErrorImportExpr(pos)
            | Self::ErrorLogicGuard(pos)
            | Self::ErrorFor(pos)
            | Self::ErrorAssignmentToUnknownLHS(pos)
            | Self::ErrorInExpr(pos)
            | Self::ErrorDotExpr(_, pos)
            | Self::ErrorTooManyOperations(pos)
            | Self::ErrorTooManyModules(pos)
            | Self::ErrorStackOverflow(pos)
            | Self::ErrorTerminated(pos) => write!(f, "{} ({})", desc, pos),

            Self::ErrorRuntime(s, pos) => {
                write!(f, "{} ({})", if s.is_empty() { desc } else { s }, pos)
            }

            Self::ErrorAssignmentToConstant(s, pos) => write!(f, "{}: '{}' ({})", desc, s, pos),
            Self::ErrorMismatchOutputType(s, pos) => write!(f, "{}: {} ({})", desc, s, pos),
            Self::ErrorArithmetic(s, pos) => write!(f, "{} ({})", s, pos),

            Self::ErrorLoopBreak(_, pos) => write!(f, "{} ({})", desc, pos),
            Self::Return(_, pos) => write!(f, "{} ({})", desc, pos),

            Self::ErrorFunctionArgsMismatch(fn_name, 0, n, pos) => write!(
                f,
                "Function '{}' expects no argument but {} found ({})",
                fn_name, n, pos
            ),
            Self::ErrorFunctionArgsMismatch(fn_name, 1, n, pos) => write!(
                f,
                "Function '{}' expects one argument but {} found ({})",
                fn_name, n, pos
            ),
            Self::ErrorFunctionArgsMismatch(fn_name, need, n, pos) => write!(
                f,
                "Function '{}' expects {} argument(s) but {} found ({})",
                fn_name, need, n, pos
            ),
            Self::ErrorBooleanArgMismatch(op, pos) => {
                write!(f, "{} operator expects boolean operands ({})", op, pos)
            }
            Self::ErrorCharMismatch(pos) => {
                write!(f, "string indexing expects a character value ({})", pos)
            }
            Self::ErrorArrayBounds(_, index, pos) if *index < 0 => {
                write!(f, "{}: {} < 0 ({})", desc, index, pos)
            }
            Self::ErrorArrayBounds(0, _, pos) => write!(f, "{} ({})", desc, pos),
            Self::ErrorArrayBounds(1, index, pos) => write!(
                f,
                "Array index {} is out of bounds: only one element in the array ({})",
                index, pos
            ),
            Self::ErrorArrayBounds(max, index, pos) => write!(
                f,
                "Array index {} is out of bounds: only {} elements in the array ({})",
                index, max, pos
            ),
            Self::ErrorStringBounds(_, index, pos) if *index < 0 => {
                write!(f, "{}: {} < 0 ({})", desc, index, pos)
            }
            Self::ErrorStringBounds(0, _, pos) => write!(f, "{} ({})", desc, pos),
            Self::ErrorStringBounds(1, index, pos) => write!(
                f,
                "String index {} is out of bounds: only one character in the string ({})",
                index, pos
            ),
            Self::ErrorStringBounds(max, index, pos) => write!(
                f,
                "String index {} is out of bounds: only {} characters in the string ({})",
                index, max, pos
            ),
        }
    }
}

impl From<ParseError> for Box<EvalAltResult> {
    fn from(err: ParseError) -> Self {
        Box::new(EvalAltResult::ErrorParsing(Box::new(err)))
    }
}
impl From<Box<ParseError>> for Box<EvalAltResult> {
    fn from(err: Box<ParseError>) -> Self {
        Box::new(EvalAltResult::ErrorParsing(err))
    }
}

impl<T: AsRef<str>> From<T> for Box<EvalAltResult> {
    fn from(err: T) -> Self {
        Box::new(EvalAltResult::ErrorRuntime(
            err.as_ref().to_string(),
            Position::none(),
        ))
    }
}

impl EvalAltResult {
    /// Get the `Position` of this error.
    pub fn position(&self) -> Position {
        match self {
            #[cfg(not(feature = "no_std"))]
            Self::ErrorReadingScriptFile(_, pos, _) => *pos,

            Self::ErrorParsing(err) => err.position(),

            Self::ErrorFunctionNotFound(_, pos)
            | Self::ErrorInFunctionCall(_, _, pos)
            | Self::ErrorFunctionArgsMismatch(_, _, _, pos)
            | Self::ErrorBooleanArgMismatch(_, pos)
            | Self::ErrorCharMismatch(pos)
            | Self::ErrorArrayBounds(_, _, pos)
            | Self::ErrorStringBounds(_, _, pos)
            | Self::ErrorIndexingType(_, pos)
            | Self::ErrorNumericIndexExpr(pos)
            | Self::ErrorStringIndexExpr(pos)
            | Self::ErrorImportExpr(pos)
            | Self::ErrorLogicGuard(pos)
            | Self::ErrorFor(pos)
            | Self::ErrorVariableNotFound(_, pos)
            | Self::ErrorModuleNotFound(_, pos)
            | Self::ErrorAssignmentToUnknownLHS(pos)
            | Self::ErrorAssignmentToConstant(_, pos)
            | Self::ErrorMismatchOutputType(_, pos)
            | Self::ErrorInExpr(pos)
            | Self::ErrorDotExpr(_, pos)
            | Self::ErrorArithmetic(_, pos)
            | Self::ErrorTooManyOperations(pos)
            | Self::ErrorTooManyModules(pos)
            | Self::ErrorStackOverflow(pos)
            | Self::ErrorTerminated(pos)
            | Self::ErrorRuntime(_, pos)
            | Self::ErrorLoopBreak(_, pos)
            | Self::Return(_, pos) => *pos,
        }
    }

    /// Override the `Position` of this error.
    pub fn set_position(&mut self, new_position: Position) {
        match self {
            #[cfg(not(feature = "no_std"))]
            Self::ErrorReadingScriptFile(_, pos, _) => *pos = new_position,

            Self::ErrorParsing(err) => err.1 = new_position,

            Self::ErrorFunctionNotFound(_, pos)
            | Self::ErrorInFunctionCall(_, _, pos)
            | Self::ErrorFunctionArgsMismatch(_, _, _, pos)
            | Self::ErrorBooleanArgMismatch(_, pos)
            | Self::ErrorCharMismatch(pos)
            | Self::ErrorArrayBounds(_, _, pos)
            | Self::ErrorStringBounds(_, _, pos)
            | Self::ErrorIndexingType(_, pos)
            | Self::ErrorNumericIndexExpr(pos)
            | Self::ErrorStringIndexExpr(pos)
            | Self::ErrorImportExpr(pos)
            | Self::ErrorLogicGuard(pos)
            | Self::ErrorFor(pos)
            | Self::ErrorVariableNotFound(_, pos)
            | Self::ErrorModuleNotFound(_, pos)
            | Self::ErrorAssignmentToUnknownLHS(pos)
            | Self::ErrorAssignmentToConstant(_, pos)
            | Self::ErrorMismatchOutputType(_, pos)
            | Self::ErrorInExpr(pos)
            | Self::ErrorDotExpr(_, pos)
            | Self::ErrorArithmetic(_, pos)
            | Self::ErrorTooManyOperations(pos)
            | Self::ErrorTooManyModules(pos)
            | Self::ErrorStackOverflow(pos)
            | Self::ErrorTerminated(pos)
            | Self::ErrorRuntime(_, pos)
            | Self::ErrorLoopBreak(_, pos)
            | Self::Return(_, pos) => *pos = new_position,
        }
    }

    /// Consume the current `EvalAltResult` and return a new one
    /// with the specified `Position`.
    pub(crate) fn new_position(mut self: Box<Self>, new_position: Position) -> Box<Self> {
        self.set_position(new_position);
        self
    }
}