1
0

Improve error handling

This commit is contained in:
Jeff 2023-11-14 19:31:04 -05:00
parent ec1f059d16
commit 364fed810b
2 changed files with 25 additions and 7 deletions

View File

@ -21,7 +21,7 @@ pub enum Expression {
impl AbstractTree for Expression { impl AbstractTree for Expression {
fn from_syntax_node(source: &str, node: Node) -> Result<Self> { fn from_syntax_node(source: &str, node: Node) -> Result<Self> {
debug_assert_eq!("expression", node.kind()); Error::expect_syntax_node(source, "expression", node)?;
for index in 0..node.child_count() { for index in 0..node.child_count() {
let child = node.child(index).unwrap(); let child = node.child(index).unwrap();

View File

@ -3,9 +3,11 @@
//! To deal with errors from dependencies, either create a new error variant //! To deal with errors from dependencies, either create a new error variant
//! or use the ToolFailure variant if the error can only occur inside a tool. //! or use the ToolFailure variant if the error can only occur inside a tool.
use tree_sitter::Node;
use crate::{value::Value, Identifier}; use crate::{value::Value, Identifier};
use std::{fmt, io, time, string::FromUtf8Error, num::ParseFloatError, sync::PoisonError}; use std::{fmt, io, num::ParseFloatError, string::FromUtf8Error, sync::PoisonError, time};
pub type Result<T> = std::result::Result<T, Error>; pub type Result<T> = std::result::Result<T, Error>;
@ -128,6 +130,19 @@ pub enum Error {
} }
impl Error { impl Error {
pub fn expect_syntax_node(source: &str, expected: &'static str, actual: Node) -> Result<()> {
if expected == actual.kind() {
Ok(())
} else {
Err(Error::UnexpectedSyntaxNode {
expected,
actual: actual.kind(),
location: actual.start_position(),
relevant_source: source[actual.byte_range()].to_string(),
})
}
}
pub fn expect_tool_argument_amount( pub fn expect_tool_argument_amount(
tool_name: &'static str, tool_name: &'static str,
expected: usize, expected: usize,
@ -228,7 +243,7 @@ impl fmt::Display for Error {
} else { } else {
write!(f, " {actual}.") write!(f, " {actual}.")
} }
}, }
AssertFailed => write!( AssertFailed => write!(
f, f,
"Assertion failed. A false value was passed to \"assert\"." "Assertion failed. A false value was passed to \"assert\"."
@ -318,9 +333,12 @@ impl fmt::Display for Error {
relevant_source, relevant_source,
} => write!( } => write!(
f, f,
"Expected syntax node {expected}, but got {actual} at {location}. Code: {relevant_source} ", "Expected {expected}, but got {actual} at {location}. Code: {relevant_source} ",
),
WrongColumnAmount { expected, actual } => write!(
f,
"Wrong column amount. Expected {expected} but got {actual}."
), ),
WrongColumnAmount { expected, actual } => write!(f, "Wrong column amount. Expected {expected} but got {actual}."),
ToolFailure(message) => write!(f, "{message}"), ToolFailure(message) => write!(f, "{message}"),
CustomMessage(message) => write!(f, "{message}"), CustomMessage(message) => write!(f, "{message}"),
} }