1
0

Add pretty errors example; Add validation in math

This commit is contained in:
Jeff 2024-07-15 17:21:18 -04:00
parent d3f5585d07
commit 9640feb65b
2 changed files with 46 additions and 13 deletions

View File

@ -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();
}
}

View File

@ -40,20 +40,24 @@ impl AbstractNode for Math {
return Err(ValidationError::ExpectedValueStatement(right.position())); return Err(ValidationError::ExpectedValueStatement(right.position()));
}; };
if let Type::Integer | Type::Float | Type::String = left_type { match (&left_type, &right_type) {
if let Type::Integer | Type::Float | Type::String = right_type { (Type::Integer, Type::Integer) => Ok(()),
Ok(()) (Type::Float, Type::Float) => Ok(()),
} else { (Type::String, Type::String) => Ok(()),
Err(ValidationError::ExpectedIntegerFloatOrString { (Type::Integer, _) => {
Err(ValidationError::ExpectedIntegerOrFloat(right.position()))
}
(Type::Float, _) => {
Err(ValidationError::ExpectedIntegerOrFloat(right.position()))
}
(Type::String, _) => Err(ValidationError::ExpectedString {
actual: right_type, actual: right_type,
position: right.position(), position: right.position(),
}) }),
} (_, _) => Err(ValidationError::ExpectedIntegerFloatOrString {
} else { actual: right_type,
Err(ValidationError::ExpectedIntegerFloatOrString { position: right.position(),
actual: left_type, }),
position: left.position(),
})
} }
} }
Math::Subtract(left, right) Math::Subtract(left, right)