From 9640feb65b323da5f2e3274afec2d284c57ee53a Mon Sep 17 00:00:00 2001 From: Jeff Date: Mon, 15 Jul 2024 17:21:18 -0400 Subject: [PATCH] Add pretty errors example; Add validation in math --- dust-lang/examples/pretty_errors.rs | 29 ++++++++++++++++++++++++++++ dust-lang/src/abstract_tree/math.rs | 30 ++++++++++++++++------------- 2 files changed, 46 insertions(+), 13 deletions(-) create mode 100644 dust-lang/examples/pretty_errors.rs diff --git a/dust-lang/examples/pretty_errors.rs b/dust-lang/examples/pretty_errors.rs new file mode 100644 index 0000000..815cfd6 --- /dev/null +++ b/dust-lang/examples/pretty_errors.rs @@ -0,0 +1,29 @@ +// It's very easy to get nice-looking error messages from the Dust's top-level error type. + +use std::{io::stderr, sync::Arc}; + +use ariadne::sources; +use dust_lang::Interpreter; + +fn main() { + let interpreter = Interpreter::new(); + + // First, we'll run some bad code. + let error = interpreter + .run( + Arc::from("bad code"), + Arc::from( + " + x = 1 + 'a' + y: float = 'hello' + ", + ), + ) + .unwrap_err(); + + for report in error.build_reports() { + report + .write_for_stdout(sources(interpreter.sources()), stderr()) + .unwrap(); + } +} diff --git a/dust-lang/src/abstract_tree/math.rs b/dust-lang/src/abstract_tree/math.rs index 94b7e45..2955d2c 100644 --- a/dust-lang/src/abstract_tree/math.rs +++ b/dust-lang/src/abstract_tree/math.rs @@ -40,20 +40,24 @@ impl AbstractNode for Math { return Err(ValidationError::ExpectedValueStatement(right.position())); }; - if let Type::Integer | Type::Float | Type::String = left_type { - if let Type::Integer | Type::Float | Type::String = right_type { - Ok(()) - } else { - Err(ValidationError::ExpectedIntegerFloatOrString { - actual: right_type, - position: right.position(), - }) + match (&left_type, &right_type) { + (Type::Integer, Type::Integer) => Ok(()), + (Type::Float, Type::Float) => Ok(()), + (Type::String, Type::String) => Ok(()), + (Type::Integer, _) => { + Err(ValidationError::ExpectedIntegerOrFloat(right.position())) } - } else { - Err(ValidationError::ExpectedIntegerFloatOrString { - actual: left_type, - position: left.position(), - }) + (Type::Float, _) => { + Err(ValidationError::ExpectedIntegerOrFloat(right.position())) + } + (Type::String, _) => Err(ValidationError::ExpectedString { + actual: right_type, + position: right.position(), + }), + (_, _) => Err(ValidationError::ExpectedIntegerFloatOrString { + actual: right_type, + position: right.position(), + }), } } Math::Subtract(left, right)