refactor: context errors

This commit is contained in:
electria 2026-07-16 00:25:49 -07:00
commit 9b59323306
Signed by: electria
SSH key fingerprint: SHA256:8LlB3ucPbBHqozqkhsNbaV5oG3SlzzqUj8FZDL6IPQs

View file

@ -4,18 +4,8 @@ use rug::{Float, float::ParseFloatError, ops::CompleteRound};
use crate::nodes::{Function, Node, Nodes, Operator, PREC};
#[derive(Clone, Debug, thiserror::Error)]
pub enum Error {
#[error("unrecognized function/constant: {0}")]
UnrecognizedName(String),
#[error("invalid operator: {0}")]
InvalidOperator(char),
#[error("failed to parse number '{0}': {1}")]
NumberParsing(String, ParseFloatError),
}
impl Node {
fn from_name(s: &str) -> Result<Self, Error> {
fn from_name(s: &str) -> Result<Self, String> {
Ok(match s {
"c" => Self::Number(Float::with_val(PREC, 299_792_458)),
"A" => Self::Number(Float::with_val(PREC, 6.02214076e23)),
@ -24,7 +14,7 @@ impl Node {
}
}
impl TryFrom<char> for Operator {
type Error = ();
type Error = char;
fn try_from(value: char) -> Result<Self, Self::Error> {
match value {
'+' => Ok(Self::Plus),
@ -32,12 +22,12 @@ impl TryFrom<char> for Operator {
'*' => Ok(Self::Mult),
'/' => Ok(Self::Div),
'^' => Ok(Self::Exp),
_ => Err(()),
_ => Err(value),
}
}
}
impl FromStr for Function {
type Err = Error;
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"sin" => Ok(Self::Sine),
@ -48,11 +38,20 @@ impl FromStr for Function {
"atan" => Ok(Self::ArcTangent),
"sec" => Ok(Self::Secant),
"csc" => Ok(Self::CoSecant),
_ => Err(Error::UnrecognizedName(s.to_owned())),
_ => Err(s.to_owned()),
}
}
}
#[derive(Clone, Debug, thiserror::Error)]
pub enum Error {
#[error("unrecognized function/constant: {0}")]
UnrecognizedName(String),
#[error("invalid operator: {0}")]
InvalidOperator(char),
#[error("failed to parse number '{0}': {1}")]
NumberParsing(String, ParseFloatError),
}
#[derive(Clone, Debug, Default, PartialEq)]
enum ParsingState {
#[default]
@ -98,7 +97,10 @@ impl FromStr for Nodes {
nodes.push(Node::Operator(Default::default()));
}
nodes.push(Node::from_name(&filtered_string[start_index..i])?);
nodes.push(
Node::from_name(&filtered_string[start_index..i])
.map_err(Error::UnrecognizedName)?,
);
state = ParsingState::Start;
}
@ -140,7 +142,7 @@ impl FromStr for Nodes {
state = ParsingState::ReadingNumber(i);
} else {
nodes.push(Node::Operator(
c.try_into().map_err(|()| Error::InvalidOperator(c))?,
c.try_into().map_err(Error::InvalidOperator)?,
));
}
}
@ -155,7 +157,10 @@ impl FromStr for Nodes {
if matches!(nodes.last(), Some(Node::ParenthesisEnd | Node::Number(_))) {
nodes.push(Node::Operator(Default::default()));
}
nodes.push(Node::from_name(&filtered_string[start_index..i])?);
nodes.push(
Node::from_name(&filtered_string[start_index..i])
.map_err(Error::UnrecognizedName)?,
);
}
ParsingState::ReadingNumber(start_index) => {
if matches!(nodes.last(), Some(Node::ParenthesisEnd)) {