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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
//! # 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 rand::{thread_rng, Rng};
use std::convert::{TryFrom, TryInto};
use std::error::Error;
use std::fmt::Display;
use std::fmt::Formatter;
// use wasm_bindgen::prelude::*;
mod parse;
use parse::{wrap_dice, Die, Expr, ParseError, Sign, Term};
pub mod util;

pub(crate) type TResult = Result<i64, RollError>;

impl Display for Term {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        match self {
            Term::Die(x) => write!(f, "{}d{}", x.number, x.size),
            Term::Constant(x) => write!(f, "{}", x),
        }
    }
}

impl Display for Expr {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        // N
        // -N
        // NdN
        // -NdN
        let mut nstr = String::new();
        match self.sign {
            Sign::Positive => (),
            Sign::Negative => nstr.push_str("-"),
        }
        nstr.push_str(&format!("{}", self.term));
        write!(f, "{}", nstr)
    }
}

#[derive(Debug, Clone)]
pub struct ExpressionResult {
    /// Private field because `Expr`'s layout isn't final.
    pairs: Vec<(Expr, i64)>,
    total: i64,
}

impl ExpressionResult {
    pub fn total(&self) -> i64 {
        self.total
    }
}

impl Display for ExpressionResult {
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        let mut nstr = self.total.to_string();
        if self.pairs.len() > 1 {
            nstr.push_str(" = (");
            let mut iter = self.pairs.iter();
            // Keep unwrap local so I can see *why* it's safe.
            // It will be easier to remove later if I change
            // the above.
            let first = iter.next().unwrap();
            let form = |prior: Expr, val: i64| match prior.term {
                Term::Constant(_) => format!("{}", val),
                Term::Die(_) => format!("{} → {}", prior, val),
            };
            nstr.push_str(&form(first.0, first.1));
            for x in iter {
                nstr.push_str(&format!(", {}", form(x.0, x.1)));
            }
            nstr.push_str(")");
        }
        write!(f, "{}", nstr)
    }
}

/// Most general mice error type.
#[derive(Debug, Clone, Copy)]
pub enum RollError {
    /// This indicates the usage of a die with <= 0 sides
    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 From<ParseError> for RollError {
    fn from(e: ParseError) -> Self {
        match e {
            ParseError::InvalidExpression => RollError::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 {}
type EResult = Result<ExpressionResult, RollError>;

fn roll_die_with<R>(a: &Die, rng: &mut R) -> Result<i64, RollError>
where
    R: Rng,
{
    if a.size == 1 {
        Ok(a.number)
    } else if a.size < 1 {
        Err(RollError::InvalidDie)
    } else {
        let mut acc: i64 = 0;
        // Rng::gen_range has an exlusive upper bound
        for n in (0..a.number).map(|_| rng.gen_range(1, a.size + 1)) {
            acc = match acc.checked_add(n) {
                Some(x) => x,
                None => return Err(RollError::OverflowPositive),
            }
        }
        Ok(acc)
    }
}

fn eval_term_with<R>(a: &Expr, rng: &mut R) -> TResult
where
    R: Rng,
{
    let t = match a.term {
        Term::Die(x) => roll_die_with(&x, rng),
        Term::Constant(x) => Ok(x),
    };
    let p = match a.sign {
        Sign::Positive => match t {
            x => x,
        },
        Sign::Negative => match t {
            Ok(x) => Ok(x),
            Err(e) => match e {
                RollError::OverflowPositive => Err(RollError::OverflowNegative),
                x => Err(x),
            },
        },
    };
    match p {
        Ok(x) => match x.try_into() {
            Ok(x) => match a.sign {
                Sign::Positive => Ok(x),
                Sign::Negative => Ok(-x),
            },
            Err(_) => Err(RollError::OverflowPositive),
        },
        Err(x) => Err(x),
    }
}

/// Evaluate a dice expression!
/// This function takes the usual dice expression format,
/// and allows an arbitrary number of terms.
/// ```
/// # use mice::roll;
/// # use mice::RollError;
/// let dice_expression = "d20 + 5 - d2";
/// println!("{}", roll(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(input: &str) -> EResult {
    match wrap_dice(input) {
        Ok(x) => Ok(roll_expr_iter(x.into_iter())?),
        Err(x) => Err(RollError::from(x)),
    }
}

type ExprTuple = (i64, i64);

/// Get a `Vec` of tuples of the form:
/// (number of dice, number of faces)
///
/// Constant terms are expressed in the form: (value, 1)
///
/// There is no guarantee of the order of terms.
///
/// The only possible error here is `RollError::InvalidExpression`.
/// Other errors may be encountered in this function's complement:
/// `roll_tupls`.
pub fn tupl_vec(input: &str) -> Result<Vec<ExprTuple>, RollError> {
    let e = wrap_dice(input)?;
    Ok(e.into_iter().map(|x| x.into()).collect())
}

impl TryFrom<ExprTuple> for Expr {
    type Error = RollError;
    fn try_from(tup: ExprTuple) -> Result<Self, RollError> {
        let (mut n, s) = tup;
        let sign = if n < 0 {
            n = -n;
            Sign::Negative
        } else {
            Sign::Positive
        };
        Ok(Self {
            term: if s > 1 {
                Term::Die(Die::new(n, s)?)
            } else {
                Term::Constant(n)
            },
            sign,
        })
    }
}
impl From<Expr> for ExprTuple {
    fn from(e: Expr) -> ExprTuple {
        let t = match e.term {
            Term::Die(x) => (x.number, x.size),
            Term::Constant(x) => (x, 1),
        };
        match e.sign {
            Sign::Positive => t,
            Sign::Negative => (-t.0, t.1),
        }
    }
}

fn try_roll_expr_iter<I>(input: I) -> EResult
where
    I: Iterator<Item = Result<Expr, RollError>>,
{
    let mut rng = thread_rng();
    let mut pairs = Vec::new();
    let mut total: i64 = 0;
    for x in input {
        match x {
            Ok(x) => {
                let res = match eval_term_with(&x, &mut rng) {
                    Ok(x) => x,
                    Err(x) => return Err(x),
                };
                pairs.push((x, res));
                match total.checked_add(res) {
                    Some(x) => total = x,
                    None => {
                        return if res > 0 {
                            Err(RollError::OverflowPositive)
                        } else {
                            Err(RollError::OverflowNegative)
                        }
                    }
                }
            }
            Err(x) => return Err(x),
        }
    }
    Ok(ExpressionResult { pairs, total })
}

fn roll_expr_iter<I>(input: I) -> EResult
where
    I: Iterator<Item = Expr>,
{
    try_roll_expr_iter(input.map(Ok))
}

fn roll_tupl_iter<'a, I>(input: I) -> EResult
where
    I: Iterator<Item = &'a ExprTuple>,
{
    let terms = input.map(|x| Expr::try_from(*x));
    try_roll_expr_iter(terms)
}
/// Roll and sum a slice of tuples, in the form
/// provided by this function's complement: `tupl_vec`
pub fn roll_tupls(input: &[ExprTuple]) -> EResult {
    roll_tupl_iter(input.iter())
}

// /// JavaScript binding for `roll_dice`.
// #[wasm_bindgen]
// pub fn roll(input: &str) -> Result<i64, JsValue> {
//     match roll_dice(input) {
//         Ok(x) => Ok(x),
//         Err(x) => Err(JsValue::from_str(&format!("{}", x))),
//     }
// }

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

#[cfg(test)]
mod tests {
    use crate::{roll, Die};
    #[test]
    fn arithmetic() {
        assert_eq!(roll("5 + 3").unwrap().total, 8);
        assert_eq!(roll("5 - 3").unwrap().total, 2);
    }
    #[test]
    fn dice() {
        let mut good = true;
        match Die::new(0, 0) {
            Ok(_) => good = false,
            Err(_) => (),
        }
        if !good {
            panic!()
        }
    }
}