Skip to content

Commit 228d10a

Browse files
committed
small error handling improvement, allow adding strings
1 parent 752a842 commit 228d10a

File tree

3 files changed

+14
-7
lines changed

3 files changed

+14
-7
lines changed

examples/errors.rs

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
use std::collections::HashMap;
22

3-
use simplexpr::dynval::DynVal;
4-
53
fn main() {
64
let mut files = codespan_reporting::files::SimpleFiles::new();
75

src/error.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@ pub type Result<T> = std::result::Result<T, Error>;
66
pub enum Error {
77
#[error("Parse error: {source}")]
88
ParseError { source: lalrpop_util::ParseError<usize, lexer::Token, lexer::LexicalError> },
9-
#[error("Conversion error: {0}")]
9+
10+
#[error("Type error: {0}")]
1011
ConversionError(#[from] dynval::ConversionError),
11-
#[error("At: {0}: {1}")]
12+
13+
#[error("{1}")]
1214
Spanned(Span, Box<dyn std::error::Error>),
1315

1416
#[error(transparent)]

src/eval.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ pub enum EvalError {
2929
#[error("Unable to index into value {0}")]
3030
CannotIndex(String),
3131

32-
#[error("At {0}: {1}")]
32+
#[error("{1}")]
3333
Spanned(Span, Box<EvalError>),
3434
}
3535

@@ -49,6 +49,11 @@ impl EvalError {
4949

5050
type VarName = String;
5151

52+
pub trait FunctionSource {
53+
type Err;
54+
fn run_fn(&self, name: &str, args: &Vec<DynVal>) -> Result<DynVal, Self::Err>;
55+
}
56+
5257
impl SimplExpr {
5358
pub fn map_terminals_into(self, f: impl Fn(Self) -> Self) -> Self {
5459
use SimplExpr::*;
@@ -124,8 +129,10 @@ impl SimplExpr {
124129
BinOp::NotEquals => DynVal::from(a != b),
125130
BinOp::And => DynVal::from(a.as_bool()? && b.as_bool()?),
126131
BinOp::Or => DynVal::from(a.as_bool()? || b.as_bool()?),
127-
128-
BinOp::Plus => DynVal::from(a.as_f64()? + b.as_f64()?),
132+
BinOp::Plus => match a.as_f64() {
133+
Ok(num) => DynVal::from(num + b.as_f64()?),
134+
Err(_) => DynVal::from(format!("{}{}", a.as_string()?, b.as_string()?)),
135+
},
129136
BinOp::Minus => DynVal::from(a.as_f64()? - b.as_f64()?),
130137
BinOp::Times => DynVal::from(a.as_f64()? * b.as_f64()?),
131138
BinOp::Div => DynVal::from(a.as_f64()? / b.as_f64()?),

0 commit comments

Comments
 (0)