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
//! Operator Symbols grouped by precedence

use nom::{
  IResult,
  branch::alt,
  bytes::complete::tag,
  character::complete::space0,
  combinator::map,
  sequence::delimited,
};
use crate::ast::{UnaryOperator, BinaryOperator};

pub fn unary(s: &str) -> IResult<&str, UnaryOperator> {
  delimited(
    space0,
    map(tag("-"), |_| UnaryOperator::Neg),
    space0,
  )(s)
}

pub fn power(s: &str) -> IResult<&str, BinaryOperator> {
  delimited(
    space0,
    map(tag("^"), |_| BinaryOperator::Pow),
    space0,
  )(s)
}

pub fn multiplicative(s: &str) -> IResult<&str, BinaryOperator> {
  delimited(
    space0,
    alt((
      map(tag("*"), |_| BinaryOperator::Mul),
      map(tag("/"), |_| BinaryOperator::Div),
      map(tag("%"), |_| BinaryOperator::Rem),
    )),
    space0,
  )(s)
}

pub fn additive(s: &str) -> IResult<&str, BinaryOperator> {
  delimited(
    space0,
    alt((
      map(tag("+"), |_| BinaryOperator::Add),
      map(tag("-"), |_| BinaryOperator::Sub),
    )),
    space0,
  )(s)
}

pub fn comparison(s: &str) -> IResult<&str, BinaryOperator> {
  delimited(
    space0,
    alt((
      map(tag("=="), |_| BinaryOperator::Eq),
      map(tag("!="), |_| BinaryOperator::Ne),
      map(tag("<="), |_| BinaryOperator::Le),
      map(tag(">="), |_| BinaryOperator::Ge),
      map(tag("<"), |_| BinaryOperator::Lt),
      map(tag(">"), |_| BinaryOperator::Gt),
    )),
    space0,
  )(s)
}