Reorganise lex and parse under single read module

This commit is contained in:
cdo committed 2026-09-26 10:49:03 +01:00
1 parent df28276496
commit fb1a959bb7
4 files changed
+37 -28

No files matched your search

+3 -3
View File
@@ -2,8 +2,8 @@ pub mod token;
pub mod expression;
pub mod binding;
pub mod lex;
pub mod parse;
pub mod print;
pub mod read;
pub mod eval;
pub mod print;
pub mod repl;
+34
View File
@@ -0,0 +1,34 @@
mod lex;
mod parse;
use crate::expression::Expression;
use parse::parse;
impl std::str::FromStr for Expression {
type Err = parse::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
parse(lex::TokenSource::new(std::io::Cursor::new(s)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[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(parse::Error::InvalidSyntax)));
}
}
View File
File renamed without changes.
-25
View File
@@ -1,7 +1,6 @@
use crate::token::Token;
use crate::expression::Expression;
use crate::binding::{Binding, Power};
use crate::lex::TokenSource;
#[derive(Debug)]
pub enum Error {
@@ -18,14 +17,6 @@ impl std::fmt::Display for Error {
}
}
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>
where I: Iterator<Item = Result<Token, std::io::Error>>
{
@@ -502,20 +493,4 @@ mod tests {
let result = parse(tokens.into_iter().map(|t| Ok(t)));
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)));
}
}