From 228d10aeb31690e755fc3ed1b7a1eabc9c604b5b Mon Sep 17 00:00:00 2001 From: elkowar <5300871+elkowar@users.noreply.github.com> Date: Fri, 16 Jul 2021 19:46:23 +0200 Subject: [PATCH] small error handling improvement, allow adding strings --- examples/errors.rs | 2 -- src/error.rs | 6 ++++-- src/eval.rs | 13 ++++++++++--- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/examples/errors.rs b/examples/errors.rs index 0ecc8e3..5b36355 100644 --- a/examples/errors.rs +++ b/examples/errors.rs @@ -1,7 +1,5 @@ use std::collections::HashMap; -use simplexpr::dynval::DynVal; - fn main() { let mut files = codespan_reporting::files::SimpleFiles::new(); diff --git a/src/error.rs b/src/error.rs index b6a50c1..6e91360 100644 --- a/src/error.rs +++ b/src/error.rs @@ -6,9 +6,11 @@ pub type Result = std::result::Result; pub enum Error { #[error("Parse error: {source}")] ParseError { source: lalrpop_util::ParseError }, - #[error("Conversion error: {0}")] + + #[error("Type error: {0}")] ConversionError(#[from] dynval::ConversionError), - #[error("At: {0}: {1}")] + + #[error("{1}")] Spanned(Span, Box), #[error(transparent)] diff --git a/src/eval.rs b/src/eval.rs index 4ebd4cf..2fcb3ce 100644 --- a/src/eval.rs +++ b/src/eval.rs @@ -29,7 +29,7 @@ pub enum EvalError { #[error("Unable to index into value {0}")] CannotIndex(String), - #[error("At {0}: {1}")] + #[error("{1}")] Spanned(Span, Box), } @@ -49,6 +49,11 @@ impl EvalError { type VarName = String; +pub trait FunctionSource { + type Err; + fn run_fn(&self, name: &str, args: &Vec) -> Result; +} + impl SimplExpr { pub fn map_terminals_into(self, f: impl Fn(Self) -> Self) -> Self { use SimplExpr::*; @@ -124,8 +129,10 @@ impl SimplExpr { BinOp::NotEquals => DynVal::from(a != b), BinOp::And => DynVal::from(a.as_bool()? && b.as_bool()?), BinOp::Or => DynVal::from(a.as_bool()? || b.as_bool()?), - - BinOp::Plus => DynVal::from(a.as_f64()? + b.as_f64()?), + BinOp::Plus => match a.as_f64() { + Ok(num) => DynVal::from(num + b.as_f64()?), + Err(_) => DynVal::from(format!("{}{}", a.as_string()?, b.as_string()?)), + }, BinOp::Minus => DynVal::from(a.as_f64()? - b.as_f64()?), BinOp::Times => DynVal::from(a.as_f64()? * b.as_f64()?), BinOp::Div => DynVal::from(a.as_f64()? / b.as_f64()?),