Implement std::str::FromStr for Expression

This commit is contained in:
cdo committed 2026-09-26 09:44:10 +01:00
1 parent a9f737a1ad
commit 9c60e7a9cd
1 file changed
+25
+25
View File
@@ -1,6 +1,7 @@
use crate::token::Token; use crate::token::Token;
use crate::expression::Expression; use crate::expression::Expression;
use crate::binding::{Binding, Power}; use crate::binding::{Binding, Power};
use crate::lex::TokenSource;
#[derive(Debug)] #[derive(Debug)]
pub enum Error { pub enum Error {
@@ -8,6 +9,14 @@ pub enum Error {
InvalidSyntax, InvalidSyntax,
} }
impl std::str::FromStr for Expression {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
parse(TokenSource::new(std::io::Cursor::new(s)))
}
}
pub fn parse<I>(input: I) -> Result<Expression, Error> pub fn parse<I>(input: I) -> Result<Expression, Error>
where I: Iterator<Item = Result<Token, std::io::Error>> where I: Iterator<Item = Result<Token, std::io::Error>>
{ {
@@ -484,4 +493,20 @@ mod tests {
let result = parse(tokens.into_iter().map(|t| Ok(t))); let result = parse(tokens.into_iter().map(|t| Ok(t)));
std::assert_matches!(result, Err(Error::InvalidSyntax)); std::assert_matches!(result, Err(Error::InvalidSyntax));
} }
#[test]
fn expressions_can_be_read_from_string() {
let expr = "x - y".parse::<Expression>().unwrap();
assert_eq!(
expr,
Expression::difference(
Expression::Symbol('x'),
Expression::Symbol('y')));
}
#[test]
fn reading_string_with_invalid_syntax_yields_error() {
let result = "(x + 1".parse::<Expression>();
assert!(matches!(result, Err(Error::InvalidSyntax)));
}
} }