Add type check for type conversion; Add test
This commit is contained in:
parent
52493a0b73
commit
1f5dacad7d
@ -35,20 +35,28 @@ impl AbstractTree for As {
|
||||
}
|
||||
|
||||
fn validate(&self, _source: &str, context: &Context) -> Result<(), ValidationError> {
|
||||
let expected_type = self.expression.expected_type(context)?;
|
||||
let initial_type = self.expression.expected_type(context)?;
|
||||
|
||||
if let Type::List(item_type) = &self.r#type {
|
||||
match &expected_type {
|
||||
match &initial_type {
|
||||
Type::List(expected_item_type) => {
|
||||
if !item_type.accepts(&expected_item_type) {
|
||||
return Err(ValidationError::TypeCheck {
|
||||
expected: self.r#type.clone(),
|
||||
actual: expected_type.clone(),
|
||||
actual: initial_type.clone(),
|
||||
position: self.position,
|
||||
});
|
||||
}
|
||||
}
|
||||
Type::String => {}
|
||||
Type::String => {
|
||||
if let Type::String = item_type.as_ref() {
|
||||
} else {
|
||||
return Err(ValidationError::ConversionImpossible {
|
||||
initial_type,
|
||||
target_type: self.r#type.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Type::Any => todo!(),
|
||||
Type::Boolean => todo!(),
|
||||
Type::Collection => todo!(),
|
||||
|
@ -18,6 +18,12 @@ pub enum ValidationError {
|
||||
/// The 'assert' macro did not resolve successfully.
|
||||
AssertFailed { position: SourcePosition },
|
||||
|
||||
/// The attempted conversion is impossible.
|
||||
ConversionImpossible {
|
||||
initial_type: Type,
|
||||
target_type: Type,
|
||||
},
|
||||
|
||||
/// A built-in function was called with the wrong amount of arguments.
|
||||
ExpectedBuiltInFunctionArgumentAmount {
|
||||
function_name: String,
|
||||
|
13
tests/as.rs
13
tests/as.rs
@ -1,4 +1,4 @@
|
||||
use dust_lang::*;
|
||||
use dust_lang::{error::ValidationError, *};
|
||||
|
||||
#[test]
|
||||
fn string_as_list() {
|
||||
@ -14,3 +14,14 @@ fn string_as_list() {
|
||||
])))
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn string_as_list_conversion_error() {
|
||||
assert_eq!(
|
||||
interpret("'foobar' as [float]"),
|
||||
Err(Error::Validation(ValidationError::ConversionImpossible {
|
||||
initial_type: Type::String,
|
||||
target_type: Type::List(Box::new(Type::Float))
|
||||
}))
|
||||
)
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user