redesign parse function to take a dice as parameter

Otherwise we couldn't fetch any error message or code if the dice
object is never visible to the user.
This commit is contained in:
2018-02-21 10:19:24 +01:00
parent 82431e7814
commit 6a0abd810f
4 changed files with 27 additions and 23 deletions

View File

@@ -44,7 +44,7 @@ struct dice_
char *error;
};
static dice_t dice_new(void)
dice_t dice_new(void)
{
dice_t tmp = calloc(1, sizeof(struct dice_));
@@ -101,16 +101,14 @@ dice_t dice_simple(uint32_t amount, uint32_t sides)
return tmp;
}
dice_t dice_parse(char const *s)
bool dice_parse(dice_t d, char const *s)
{
void *scanner = NULL;
dice_t d = NULL;
void *buffer = NULL;
int ret = 0;
d = dice_new();
if (d == NULL) {
return NULL;
if (d == NULL || s == NULL) {
return false;
}
yylex_init_extra(d, &scanner);
@@ -123,11 +121,10 @@ dice_t dice_parse(char const *s)
yylex_destroy(scanner);
if (ret) {
dice_free(d);
return NULL;
return false;
}
return d;
return true;
}
bool dice_set(dice_t d, dice_option_t opt, ...)

View File

@@ -44,9 +44,10 @@ typedef enum {
void dice_result_free(dice_result_t *r);
void dice_result_freev(dice_result_t *r, size_t len);
dice_t dice_new(void);
void dice_free(dice_t t);
dice_t dice_simple(uint32_t amount, uint32_t sides);
dice_t dice_parse(char const *s);
bool dice_parse(dice_t d, char const *s);
bool dice_set(dice_t d, dice_option_t opt, ...);
bool dice_get(dice_t d, dice_option_t opt, ...);

View File

@@ -279,13 +279,15 @@ void next_token(state *s) {
if (isdigit(s->next[0]) || s->next[0] == '.' || s->next[0] == 'd') {
/* first try reading a dice expression, if that fails, we go
back to trying a number instead */
dice_t d = dice_parse(s->next);
if (d != NULL) {
dice_t d = dice_new();
if (dice_parse(d, s->next)) {
int consumed = dice_consumed(d);
s->type = TOK_DICE;
s->dice = d;
s->next += consumed;
} else if (d == NULL) {
} else {
dice_free(d);
/* Try reading a number. */
s->value = strtod(s->next, (char**)&s->next);
s->type = TOK_NUMBER;