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
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
//! # mice, messing with dice
//! The heading obviates the need for a body.
//!
//! This crate is written primarily for my own
//! usage, and will likely obtain extensions related
//! to games that I play.
#![forbid(unsafe_code)]
use nom::{
    branch::alt,
    bytes::complete::{tag, take_while1},
    combinator::opt,
    multi::many0,
    sequence::tuple,
    IResult,
};
use rand::{thread_rng, Rng};
use std::error::Error;
use std::fmt::Display;
use std::fmt::Formatter;

#[derive(Debug)]
pub enum RollError {
    /// This indicates the usage of a d0
    InvalidDie,
    /// The sum of terms is greater than what an `i64` can hold
    OverflowPositive,
    /// The sum of terms is lower than what an `i64` can hold
    OverflowNegative,
    /// The expression evaluated isn't a valid dice expression
    InvalidExpression,
}
impl Display for RollError {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        match self {
            RollError::InvalidDie => write!(f, "Invalid die"),
            RollError::OverflowPositive => write!(f, "sum is too high for `i64`"),
            RollError::OverflowNegative => write!(f, "sum is too low for `i64`"),
            RollError::InvalidExpression => {
                write!(f, "you've specified an invalid dice expression.")
            }
        }
    }
}

impl Error for RollError {}

#[derive(Debug)]
struct Die {
    number: u64,
    size: u64,
}
impl Die {
    #[allow(dead_code)]
    fn new(number: u64, size: u64) -> Result<Die, RollError> {
        // u64 type constraint means
        // we don't need to check if number < 0
        // Forbid d0. d1 is weird, but it
        // has a correct interpretation.
        if size < 1 {
            Err(RollError::InvalidDie)
        } else {
            Ok(Die { number, size })
        }
    }
}

#[derive(Debug)]
enum Term {
    Die(Die),
    Constant(u64),
}

#[derive(Debug)]
enum Sign {
    Positive,
    Negative,
}

#[derive(Debug)]
struct Expr {
    term: Term,
    sign: Sign,
}

#[derive(Debug)]
struct Expression {
    exprs: Vec<Expr>,
}

fn eval_dice(a: Expression) -> Result<i64, RollError> {
    let mut rng = thread_rng();
    let mut sum: i64 = 0;
    for expr in a.exprs {
        let total = match expr.term {
            Term::Die(x) => {
                if x.size == 1 {
                    x.number as i64 // This is correct.
                } else if x.size < 1 {
                    return Err(RollError::InvalidDie);
                } else {
                    (0..x.number)
                        .map(|_| rng.gen_range(1u64, x.size))
                        .fold(0, |a, x| a + x as i64)
                }
            }
            Term::Constant(x) => x as i64,
        };
        match expr.sign {
            Sign::Positive => {
                sum = match sum.checked_add(total) {
                    Some(x) => x,
                    None => return Err(RollError::OverflowPositive),
                }
            }
            Sign::Negative => {
                sum = match sum.checked_sub(total) {
                    Some(x) => x,
                    None => return Err(RollError::OverflowNegative),
                }
            }
        }
    }
    Ok(sum)
}

fn is_dec_digit(c: char) -> bool {
    c.is_digit(10)
}
fn integer(input: &str) -> IResult<&str, u64> {
    let (input, int) = take_while1(is_dec_digit)(input)?;
    // Pretend to be a 63 bit unsigned integer.
    let i = match int.parse::<i64>() {
        // The only error possible here is
        // integer overflow.
        // This should emit a nom Failure
        Err(_) => {
            return Err(nom::Err::<(&str, nom::error::ErrorKind)>::Failure((
                input,
                nom::error::ErrorKind::TooLarge,
            )))
        }
        Ok(x) => x as u64,
    };
    Ok((input, i))
}

fn die(input: &str) -> IResult<&str, Term> {
    // number of dice : [integer]
    // separator      : "d"
    // size of dice   : integer
    let (input, d) = tuple((opt(integer), tag("d"), integer))(input)?;
    Ok((
        input,
        Term::Die(Die {
            number: match d.0 {
                Some(x) => x,
                None => 1,
            },
            size: d.2,
        }),
    ))
}

fn addition(input: &str) -> IResult<&str, Sign> {
    let (input, _) = tag("+")(input)?;
    Ok((input, Sign::Positive))
}
fn subtraction(input: &str) -> IResult<&str, Sign> {
    let (input, _) = tag("-")(input)?;
    Ok((input, Sign::Negative))
}

fn operator(input: &str) -> IResult<&str, Sign> {
    alt((addition, subtraction))(input)
}

fn whitespace(input: &str) -> IResult<&str, &str> {
    alt((tag(" "), tag("\t")))(input)
}

fn separator(input: &str) -> IResult<&str, Sign> {
    let (input, t) = tuple((many0(whitespace), operator, many0(whitespace)))(input)?;
    Ok((input, t.1))
}

fn constant(input: &str) -> IResult<&str, Term> {
    let i = integer(input)?;
    Ok((i.0, Term::Constant(i.1)))
}

fn term(input: &str) -> IResult<&str, Term> {
    alt((die, constant))(input)
}

fn dice(input: &str) -> IResult<&str, Expression> {
    // [(+/-)] die ((+/-) die)*
    let (input, s) = tuple((opt(separator), term, many0(tuple((separator, term)))))(input)?;
    let mut expression = Expression {
        exprs: vec![Expr {
            term: s.1,
            sign: match s.0 {
                Some(x) => x,
                None => Sign::Positive,
            },
        }],
    };
    for t in s.2 {
        expression.exprs.push(Expr {
            term: t.1,
            sign: t.0,
        });
    }
    Ok((input, expression))
}

// This is the one and only output of the library.
/// Evaluate a dice expression!
/// This function takes the usual dice expression format,
/// and allows an arbitrary number of terms.
/// ```
/// # use mice::roll_dice;
/// # use mice::RollError;
/// let dice_expression = "d20 + 5 - d2";
/// println!("{}", roll_dice(dice_expression)?);
/// # Ok::<(), RollError>(())
/// ```
///
/// An `Err` is returned in the following cases:
///   - A d0 is used
///   - The sum of all terms is too high
///   - The sum of all terms is too low
///   - Nonsense input
pub fn roll_dice(input: &str) -> Result<i64, RollError> {
    let (input, e) = match dice(input.trim()) {
        Ok(x) => x,
        Err(_) => return Err(RollError::InvalidExpression),
    };
    // Prevent weirdness like "10dlol" => 10
    if !input.is_empty() {
        Err(RollError::InvalidExpression)
    } else {
        eval_dice(e)
    }
}

// N
// dN1   (+/-) N2
// N1dN2 (+/-) N3
// N1dN2 (+/-) N3dN4 (+/-) [...] (+/-) NN