mexprp/
expr.rs

1use std::fmt;
2
3
4
5use crate::opers::*;
6
7use crate::errors::*;
8use crate::context::*;
9use crate::num::*;
10
11use crate::term::*;
12
13/// The main Expression struct. Contains the string that was originally requested to be parsed, the
14/// context the Expression was parsed with, and the Term the raw form was parsed as. For just the
15/// parsed version of the expression, use the Term enum.
16#[derive(Debug, Clone)]
17pub struct Expression<N: Num> {
18	/// The original string passed into this expression
19	pub string: String,
20	/// Context the expression was parsed with
21	pub ctx: Context<N>,
22	/// The term this string has been parsed as
23	pub term: Term<N>,
24}
25
26impl<N: Num + 'static> Expression<N> {
27	/// Parse a string into an expression
28	pub fn parse(raw: &str) -> Result<Self, ParseError> {
29		let ctx = Context::new();
30		Self::parse_ctx(raw, ctx)
31	}
32
33	/// Parse a string into an expression with the given context
34	pub fn parse_ctx(raw: &str, ctx: Context<N>) -> Result<Self, ParseError> {
35		let raw = raw.trim();
36		let term = Term::parse_ctx(raw, &ctx)?;
37
38		Ok(Self {
39			string: raw.to_string(),
40			ctx,
41			term,
42		})
43	}
44
45	/// Evaluate the expression
46	pub fn eval(&self) -> Calculation<N> {
47		self.eval_ctx(&self.ctx)
48	}
49
50	/// Evaluate the expression with the given context
51	pub fn eval_ctx(&self, ctx: &Context<N>) -> Calculation<N> {
52		self.term.eval_ctx(ctx)
53	}
54}
55
56impl<N: Num> fmt::Display for Expression<N> {
57	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
58		f.write_str(&self.string)
59	}
60}