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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
use std::fmt::Display;
use std::write;
use crate::firstpass::{GetReqAttributes, RewriteToSynth};

use super::{Parse, LexerBridge, ParseResult, Tokens, SpannableNode, ResultPeek};
use super::atom::Atom;
use wagon_lexer::math::Math;

use wagon_macros::new_unspanned;

#[derive(PartialEq, Debug, Eq, Hash, Clone)]
#[new_unspanned]
/// A possible power equation, or just an [`Atom`].
///
/// # Grammar
/// <code>[Factor] -> [Atom] ("**" Factor)?;</code>
pub enum Factor {
	/// Just an [`Atom`].
	Primary(SpannableNode<Atom>),
	/// A power equation
	Power {
		/// The left-hand side.
		left: SpannableNode<Atom>,
		/// Whatever to evaluate to the power to.
		right: Box<SpannableNode<Factor>>
	}
}

impl Parse for Factor {

	fn parse(lexer: &mut LexerBridge) -> ParseResult<Self> {
		let left = SpannableNode::parse(lexer)?;
		if &Tokens::MathToken(Math::Pow) == lexer.peek_result()? {
			lexer.next();
			Ok(
				Self::Power {
					left, 
					right: Box::new(SpannableNode::parse(lexer)?)
				}
			)
		} else {
			Ok(Self::Primary(left))
		}
	}
}

impl GetReqAttributes for Factor {
    fn get_req_attributes(&self) -> crate::firstpass::ReqAttributes {
        match self {
            Self::Primary(p) => p.get_req_attributes(),
            Self::Power { left, right } => {
            	let mut req = left.get_req_attributes();
            	req.extend(right.get_req_attributes());
            	req
            },
        }
    }
}

impl RewriteToSynth for Factor {
    fn rewrite_to_synth(&mut self) -> crate::firstpass::ReqAttributes {
        match self {
            Self::Primary(p) => p.rewrite_to_synth(),
            Self::Power { left, right } => {
            	let mut req = left.rewrite_to_synth();
            	req.extend(right.rewrite_to_synth());
            	req
            },
        }
    }
}

impl Display for Factor {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Primary(p) => write!(f, "{p}"),
            Self::Power { left, right } => write!(f, "{left}^{right}"),
        }
    }
}