1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use std::fmt;
use std::rc::Rc;

use op::*;
use opers::*;
use parse::*;
use errors::*;
use context::*;
use num::*;
use answer::*;
use term::*;

/// The main Expression struct. Contains the string that was originally requested to be parsed, the
/// context the Expression was parsed with, and the Term the raw form was parsed as. For just the
/// parsed version of the expression, use the Term enum.
#[derive(Debug)]
pub struct Expression<N: Num> {
	/// The original string passed into this expression
	pub string: String,
	/// Context the expression was parsed with
	pub ctx: Context<N>,
	/// The term this string has been parsed as
	pub term: Term<N>,
}

impl<N: Num + 'static> Expression<N> {
	/// Parse a string into an expression
	pub fn parse(raw: &str) -> Result<Self, ParseError> {
		let ctx = Context::new();
		Self::parse_ctx(raw, ctx)
	}

	/// Parse a string into an expression with the given context
	pub fn parse_ctx(raw: &str, ctx: Context<N>) -> Result<Self, ParseError> {
		let raw = raw.trim();
		let term = Term::parse_ctx(raw, &ctx)?;

		Ok(Self {
			string: raw.to_string(),
			ctx,
			term,
		})
	}

	/// Evaluate the expression
	pub fn eval(&self) -> Calculation<N> {
		self.eval_ctx(&self.ctx)
	}

	/// Evaluate the expression with the given context
	pub fn eval_ctx(&self, ctx: &Context<N>) -> Calculation<N> {
		self.term.eval_ctx(ctx)
	}
}

impl<N: Num> fmt::Display for Expression<N> {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		f.write_str(&self.string)
	}
}