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
mod filtermodifier;
mod interpreter;
mod options;
mod parser;
mod roll;

use crate::interpreter::Ast;
pub use crate::parser::*;
pub use crate::roll::*;
use core::fmt;
pub use rand_core;
use std::collections::HashMap;

pub struct RollResult {
    pub string_result: String,
    pub dice_total: crate::interpreter::Value,
}

impl fmt::Display for RollResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.string_result)
    }
}

const STAT_ROLL: &str = "4d6l";
pub fn roll_stats() -> String {
    let mut res = String::new();
    fn roll_stat() -> Roll {
        let mut rolls = Vec::new();
        Parser::new(STAT_ROLL)
            .parse()
            .unwrap()
            .interp(&mut rolls)
            .unwrap();
        rolls.remove(0).1
    }

    for _ in 0..6 {
        let roll = roll_stat();
        res.push_str(&format!("{:2}: {:?}\n", roll.total, roll.vals))
    }
    res
}

pub fn roll_inline(s: &str, advanced: bool) -> Result<RollResult, String> {
    let mut p = Parser::new(s);
    p.advanced = advanced;

    let ast = p.parse().map_err(|e| e.to_string())?;

    let copy = ast.clone();

    let mut rolls = Vec::new();
    let total = ast.interp(&mut rolls).unwrap();

    let mut map = HashMap::new();
    for (pos, roll) in rolls {
        map.insert(pos, roll);
    }

    let res = replace_rolls(copy, &map, |roll| format!("{:?}", roll.vals));
    let result: RollResult = RollResult {
        string_result: format!("{} = {} = {}", s, res, total),
        dice_total: total,
    };
    Ok(result)
}

fn replace_rolls(ast: Ast, lookup: &HashMap<u64, Roll>, func: fn(&Roll) -> String) -> Ast {
    return match ast {
        Ast::Add(l, r) => Ast::Add(
            Box::from(replace_rolls(*l, lookup, func)),
            Box::from(replace_rolls(*r, lookup, func)),
        ),
        Ast::Sub(l, r) => Ast::Sub(
            Box::from(replace_rolls(*l, lookup, func)),
            Box::from(replace_rolls(*r, lookup, func)),
        ),
        Ast::Mul(l, r) => Ast::Mul(
            Box::from(replace_rolls(*l, lookup, func)),
            Box::from(replace_rolls(*r, lookup, func)),
        ),
        Ast::Div(l, r) => Ast::Div(
            Box::from(replace_rolls(*l, lookup, func)),
            Box::from(replace_rolls(*r, lookup, func)),
        ),
        Ast::Mod(l, r) => Ast::Mod(
            Box::from(replace_rolls(*l, lookup, func)),
            Box::from(replace_rolls(*r, lookup, func)),
        ),
        Ast::IDiv(l, r) => Ast::IDiv(
            Box::from(replace_rolls(*l, lookup, func)),
            Box::from(replace_rolls(*r, lookup, func)),
        ),
        Ast::Power(l, r) => Ast::Power(
            Box::from(replace_rolls(*l, lookup, func)),
            Box::from(replace_rolls(*r, lookup, func)),
        ),
        Ast::Minus(l) => Ast::Minus(Box::from(replace_rolls(*l, lookup, func))),
        Ast::Dice(_, _, _, pos) => {
            // Safety: we exhaustively add all positions to this hashmap so it must contain everything
            // we look up.
            let roll = lookup.get(&pos).unwrap();
            Ast::Const(func(roll))
        }
        x @ Ast::Const(_) => x,
    };
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::parser::Parser;
    use bnf::Grammar;

    const GRAMMAR: &str = include_str!("../../grammar.bnf");

    fn generate_sentence(g: &Grammar) -> String {
        loop {
            let res = g.generate();
            match res {
                Ok(i) => break i,
                Err(bnf::Error::RecursionLimit(_)) => continue,
                _ => panic!("aaaaa"),
            }
        }
    }

    #[test]
    fn fuzz() {
        let grammar: Grammar = GRAMMAR.parse().unwrap();

        for _ in 0..500 {
            let sentence = generate_sentence(&grammar);
            if let Err(e) = Parser::new(&sentence).advanced().parse() {
                println!("failed with sentence \"{}\" and error: {:?}", sentence, e);
                break;
            }
        }
    }

    #[test]
    fn test_inplace() {
        println!("{}", roll_inline("4d8 + 2d8", false).unwrap());
    }
}