From 1f5dacad7d203eaa8697986861a8781b626f6a6f Mon Sep 17 00:00:00 2001 From: Jeff Date: Tue, 13 Feb 2024 10:49:49 -0500 Subject: [PATCH] Add type check for type conversion; Add test --- src/abstract_tree/as.rs | 16 ++++++++++++---- src/error/validation_error.rs | 6 ++++++ tests/as.rs | 13 ++++++++++++- 3 files changed, 30 insertions(+), 5 deletions(-) diff --git a/src/abstract_tree/as.rs b/src/abstract_tree/as.rs index 1a3aa04..444722c 100644 --- a/src/abstract_tree/as.rs +++ b/src/abstract_tree/as.rs @@ -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!(), diff --git a/src/error/validation_error.rs b/src/error/validation_error.rs index 1c5fe46..efea76a 100644 --- a/src/error/validation_error.rs +++ b/src/error/validation_error.rs @@ -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, diff --git a/tests/as.rs b/tests/as.rs index 083393c..2a3cc0d 100644 --- a/tests/as.rs +++ b/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)) + })) + ) +}