Replace TypeError with more detailed errors

Implements #9
This commit is contained in:
Sebastian Schmidt 2019-03-20 11:42:17 +02:00
parent 38c4c35a0b
commit 1ae674a693
2 changed files with 43 additions and 10 deletions

View File

@ -13,30 +13,42 @@ use token::PartialToken;
pub enum Error {
/// An operator was called with a wrong amount of arguments.
WrongOperatorArgumentAmount {
/// Expected amount of arguments.
/// The expected amount of arguments.
expected: usize,
/// Actual amount of arguments.
/// The actual amount of arguments.
actual: usize,
},
/// A function was called with a wrong amount of arguments.
WrongFunctionArgumentAmount {
/// Expected amount of arguments.
/// The expected amount of arguments.
expected: usize,
/// Actual amount of arguments.
/// The actual amount of arguments.
actual: usize,
},
/// An integer value was expected.
ExpectedInt {
/// The actual value.
actual: Value,
},
/// A float value was expected.
ExpectedFloat {
/// The actual value.
actual: Value,
},
/// A numeric value was expected.
/// Numeric values are the variants `Value::Int` and `Value::Float`.
ExpectedNumber {
/// Actual value.
/// The actual value.
actual: Value,
},
/// A boolean value was expected.
ExpectedBoolean {
/// Actual value.
/// The actual value.
actual: Value,
},
@ -60,8 +72,14 @@ pub enum Error {
/// A `FunctionIdentifier` operation did not find its value in the configuration.
FunctionIdentifierNotFound(String),
/// A value has the wrong type. Only use this if there is no other error that describes the expected and provided types in more detail.
TypeError,
/// A value has the wrong type.
/// Only use this if there is no other error that describes the expected and provided types in more detail.
TypeError {
/// The expected types.
expected: Vec<Value>,
/// The actual value.
actual: Value,
},
/// An opening brace without a matching closing brace was found.
UnmatchedLBrace,
@ -89,6 +107,21 @@ impl Error {
Error::WrongFunctionArgumentAmount { actual, expected }
}
/// Constructs `Error::TypeError{actual, expected}`.
pub fn type_error(actual: Value, expected: Vec<Value>) -> Self {
Error::TypeError {actual, expected}
}
/// Constructs `Error::ExpectedInt(actual)`.
pub fn expected_int(actual: Value) -> Self {
Error::ExpectedInt { actual }
}
/// Constructs `Error::ExpectedFloat(actual)`.
pub fn expected_float(actual: Value) -> Self {
Error::ExpectedFloat { actual }
}
/// Constructs `Error::ExpectedNumber(actual)`.
pub fn expected_number(actual: Value) -> Self {
Error::ExpectedNumber { actual }

View File

@ -42,7 +42,7 @@ impl Value {
pub fn as_int(&self) -> Result<IntType, Error> {
match self {
Value::Int(i) => Ok(*i),
_ => Err(Error::TypeError),
value => Err(Error::expected_int(value.clone())),
}
}
@ -51,7 +51,7 @@ impl Value {
match self {
Value::Float(f) => Ok(*f),
Value::Int(i) => Ok(*i as FloatType),
_ => Err(Error::TypeError),
value => Err(Error::expected_number(value.clone())),
}
}
}