| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- //
- // parser.h
- // dice-roll
- //
- // Created by Sam Jaffe on 1/16/21.
- // Copyright © 2021 Sam Jaffe. All rights reserved.
- //
- #pragma once
- #include <iosfwd>
- #include "die.h"
- namespace dice {
- /*
- * A parser that translates a stream of text input into a dice object. The
- * string matches the following schema-rule:
- *
- * dice-string:
- * dice-expression
- * positive-integer '{' dice-expression '}'
- *
- * dice-expression:
- * die-expression
- * die-expression {'+'|'-'} dice-expression-rec
- *
- * dice-expression-rec:
- * {die-expression|modifier}
- * {die-expression|modifier} {'+'|'-'} dice-expression-rec
- *
- * modifier:
- * positive-integer
- *
- * die-expression:
- * positive-integer 'd' positive-integer
- * positive-integer 'D' positive-integer
- */
- class parser {
- private:
- std::istream & is_;
- dice dice_;
- public:
- parser(std::istream & is) : is_(is) {}
- dice parse();
- private:
- /**
- * Main dispatch function for parsing a dice roll.
- * @param s The current +/- sign attached to the parse sequence. s is ZERO
- * when parsing the first token, or after parsing a die. This means an
- * expression like '1d4+5+1d6+2d8' is evaluated as a sequence like so:
- * [1d4][+][5+][1d6][+][2d8]. This produces the following states of (SIGN,
- * input stream):
- * 1) ZERO, 1d4+5+1d6+2d8
- * 2) ZERO, +5+1d6+2d8
- * 3) PLUS, 5+1d6+2d8
- * 4) PLUS, 1d6+2d8
- * 5) ZERO, +2d8
- * 6) PLUS, 2d8
- */
- void parse_impl(sign s);
- /**
- * @sideeffect This function advances the input stream over a single numeric
- * token. This token represents the number of sides in the die roll.
- * This function appends a new die into {@see d.of}, representing (+/-)NdM,
- * where N is the input parameter 'value', and M is retrieved internally.
- * @param s The arithmatic sign attached to this roll, denoting whether this
- * die increases or decreases the total result of the roll. For example, the
- * 5E spell Bane imposes a -1d4 modifier on attack rolls, an attack roll might
- * go from '1d20+2+3' (1d20 + Proficiency + Ability) to '1d20+2+3-1d4'.
- * @param value The number of dice to be rolled.
- * Domain: value >= 0
- * @throw dice::unexpected_token if we somehow call parse_dN while the first
- * non-whitespace token after the 'd' char is not a number.
- */
- void parse_dN(sign s, int value);
- /**
- * @param s The arithmatic sign attached to this numeric constant. Because
- * value is non-negative, this token contains the +/- effect.
- * @param value The value associated with this modifier term.
- * Domain: value >= 0
- */
- void parse_const(sign s, int value);
- void parse_dc(char token);
- void parse_keep(char token);
- int read(int value, bool error_on_eof);
- int read() { return read(0, true); }
- };
- }
|