-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathroll.c
682 lines (525 loc) · 14.8 KB
/
roll.c
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
/* Copyright (c) 2005-2023 Matteo Corti
* This file is part of roll
*
* You may distribute this file under the terms the GNU General Public
* License. See the file COPYING for more information.
*/
/*!
* \file roll.c
* \author Matteo Corti
* \brief The main application file
*/
#include "roll.h"
#include "parser.h"
int yyparse(void);
int sum_flag = FALSE; /**< command line argument: sum series */
static int test = 0; /**< command line argument: test run (no random results) */
static int verbose_flag = FALSE; /**< command line argument: verbose output */
static int version_flag = FALSE; /**< command line argument: version */
extern int positive_flag; /**< command line argument: allow only positive results */
/** Not defined in the automatically generated header files */
#ifndef YY_TYPEDEF_YY_BUFFER_STATE
#define YY_TYPEDEF_YY_BUFFER_STATE
typedef struct yy_buffer_state *YY_BUFFER_STATE;
#endif
YY_BUFFER_STATE yy_scan_string ( const char *yy_str );
#ifdef DEBUG
int debug_flag = 0; /**< command line argument: debug output */
#endif
#ifdef DEBUG
void debug( char * message ) {
if ( debug_flag > 0 ) {
printf("[DBG] %s\n", message);
}
}
#endif
/*!
* \brief Prints the program's usage
*/
void usage() {
printf("\nusage: %s [OPTION] expression\n\n", PACKAGE_NAME);
printf("Options\n");
printf(" -p, --positive allow only positive results\n");
printf(" -h, --help show this help screen\n");
printf(" -s, --sum-series show the sum of roll series\n");
printf(" -t, --test the result of the dice is always 3 (for testing purposes)\n");
printf(" -v, --verbose increase verbosity\n");
printf(" --version prints the program version and exits\n");
#ifdef DEBUG
printf(" -d, --debug debugging output\n");
#endif
printf("\nPlease see the %s(1) man page for full documentation\n\n", PACKAGE_NAME);
}
/*!
* \brief Prints the specified error message and exits with a failure status
* \param[message] error message
*/
void error(char * message) {
fprintf(stderr, "\nError: %s\n", message);
exit(EXIT_FAILURE);
}
/*!
* \brief Wrapper for roll(int dice) translates special dices (e.g., d%)
* \param[sides] Sides of the dice
*/
int roll_dice(int sides) {
int result = 0;
if ( sides == HUNDRED ) {
/* d100 -> d10*10+d10 */
int d10 = roll(10);
if (verbose_flag) {
printf("d10 -> %i\n", d10);
}
d10 = d10 % 10;
int d1 = roll(10);
if (verbose_flag) {
printf("d10 -> %i\n", d1);
}
if (d1 == 0 && d10 == 0) {
result = 100;
} else if (d10 == 0) {
result = d1;
} else {
result = d10*10 + d1;
}
} else if ( sides == FUDGE_DICE ) {
result = roll(3) - 2;
if (verbose_flag) {
switch (result) {
case -1:
printf("dF -> -\n");
break;
case 0:
printf("dF -> o\n");
break;
case 1:
printf("dF -> +\n");
break;
}
}
} else {
result = roll(sides);
if (verbose_flag) {
printf("d%i -> %i\n", sides, result);
}
}
return result;
}
/*!
* \brief Rolls an n-sided dice
* \param[dice] Number of sides of the rolled dice
* \return Result of the dice roll
*/
int roll(int dice) {
/*
* In: W. H. Press et al,Numerical Recipes in C: The Art of
* Scientific Computing. New York, Cambridge University Press,
* 1992, 2nd ed., p. 277
*
* "If you want to generate a random integer between 1
* and 10, you should always do it by using high-order
* bits, as in
*
* j=1+(int) (10.0*rand()/(RAND_MAX+1.0));
*/
int res;
if ( ! test ) {
#if defined HAVE_SRANDOMDEV || defined HAVE_SRANDOM
res = 1+(int)(((double)dice)*random()/(RAND_MAX+1.0));
#else
res = 1+(int)(((double)dice)*rand()/(RAND_MAX+1.0));
#endif
} else {
res = test;
}
return res;
}
#ifdef HAVE_SRANDOM
/*!
* \brief Try to initialize random from /dev/urandom, otherwise fallback on srandom(time(0))
*/
static void urandom_init() {
FILE* urandom = fopen("/dev/urandom", "rb");
if (urandom) {
unsigned int seed = 0;
fread(&seed, sizeof(seed), 1, urandom);
fclose(urandom);
srandom(seed ^ time(NULL));
}
else
srandom(time(NULL));
}
#endif
/*!
* \brief Main program
* \param[argc] Number of command line arguments
* \param[argv] Array of strings with the command line arguments
* \return Exit status
*/
int main(int argc, char **argv) {
char expression[EXPRESSION_SIZE];
int expression_size;
#ifdef DEBUG
debug("[DBG] Debug mode enabled");
#endif
#ifdef HAVE_SRANDOMDEV
srandomdev();
#elif defined HAVE_SRANDOM
urandom_init();
#else
srand(time(NULL));
#endif
while (TRUE) {
static struct option long_options[] = {
{"sum-series", no_argument, NULL, 's'},
{"positive", no_argument, NULL, 'p'},
{"test", no_argument, NULL, 't'},
{"verbose", no_argument, NULL, 'v'},
{"version", no_argument, &version_flag, TRUE},
{"help", no_argument, NULL, 'h'},
#ifdef DEBUG
{"debug", no_argument, NULL, 'd'},
#endif
{NULL, 0, NULL, 0}
};
/* getopt_long stores the option index here. */
int option_index = 0;
int c;
#ifdef DEBUG
c = getopt_long (argc, argv, "hvsptd",
long_options, &option_index);
#else
c = getopt_long (argc, argv, "hvspt",
long_options, &option_index);
#endif
/* Detect the end of the options. */
if (c == -1)
break;
switch (c) {
case 'v':
verbose_flag = TRUE;
break;
case 's':
sum_flag = TRUE;
break;
case 'p':
positive_flag = TRUE;
break;
case 'h':
usage();
exit(0);
case 't':
test = 3; /* value to be used as a fix result of a dice roll */
break;
case '?':
usage();
/* getopt_long already printed an error message. */
exit(EXIT_SUCCESS);
#ifdef DEBUG
case 'd':
debug_flag++;
break;
#endif
case 0:
break;
default:
abort ();
}
}
if (version_flag) {
printf("%s %s\n", PACKAGE_NAME, PACKAGE_VERSION);
exit(EXIT_SUCCESS);
}
argc -= optind;
argv += optind;
/* build string to parse */
expression[0] = '\0';
expression_size = 0;
while(argc>0) {
expression_size += strlen(*argv);
if (expression_size >= EXPRESSION_SIZE) {
error("Expression too long!\n");
}
strncat(expression, *argv, EXPRESSION_SIZE-1);
argc--;
argv++;
}
if (expression_size > 0) {
#ifdef DEBUG
debug(expression);
#endif
yy_scan_string(expression);
#ifdef DEBUG
debug("expression scanned");
#endif
yyparse();
#ifdef DEBUG
debug("expression parsed\n");
#endif
} else {
error("No expression provided!\nPlease use the \"-h\" option.\n");
exit(EXIT_FAILURE);
}
return 0;
}
/*!
* \brief Allocates a new IR node
* \return Newly allocated node
*/
struct ir_node * allocate_node ( void ) {
struct ir_node * node = malloc(sizeof(struct ir_node));
if (node == NULL) {
error("Out of memory\n");
exit(EXIT_FAILURE);
}
/* initialize default values */
node->left = NULL;
node->right = NULL;
node->next = NULL;
node->op = 0;
node->value = 0;
return node;
}
/*!
* \brief Allocates a new NUMBER node
* \param[number] Number value
* \return A NUMBER node
*/
struct ir_node * new_number ( int number ) {
struct ir_node * node = allocate_node();
node->op = OP_NUMBER;
node->value = number;
return node;
}
/*!
* \brief Comparison function for qsort
* \param[p1] First integer
* \param[p2] Second integer
* \return 1 if p1 > p2, -1 if p1 < p2 and 0 if p1 and p2 are equal
*/
int compare(const void * p1, const void * p2) {
const int i1 = *((const int *)p1);
const int i2 = *((const int *)p2);
if (i1 > i2) {
return 1;
} else if (i1 < i2) {
return -1;
} else {
return 0;
}
}
/*!
* \brief Allocates a new OP node
* \param[op] Operation
* \param[left] Left operand
* \param[right] Right operand
* \return An OP node
*/
struct ir_node * new_op ( unsigned short int op, struct ir_node * left, struct ir_node * right) {
struct ir_node * node = allocate_node();
node->op = op;
node->value = 0;
node->left = left;
node->right = right;
return node;
}
/*!
* \brief Allocates a new DICE node
* \param[sides] A node representing the number of dice sides
* \return A DICE node
*/
struct ir_node * new_dice ( struct ir_node * sides) {
struct ir_node * node = allocate_node();
node->op = OP_DICE;
node->value = 0;
node->right = sides;
return node;
}
int checked_sum( int op1, int op2 ) {
if ( (op2 > 0 && op1 > INT_MAX - op2) ||
(op2 < 0 && op1 < INT_MIN - op2)) {
error("Overflow");
}
return op1+op2;
}
int checked_multiplication( int op1, int op2 ) {
int result = op1 * op2;
if (op1 != 0 && result / op1 != op2 ) {
error("Overflow");
}
return result;
}
/*!
* \brief Roll dices and compute expressions
* \param[node] The root of the expression tree to compute
* \param[print] Set to true to print the result of the expression
* \return The expression value
*/
int roll_expression ( struct ir_node * node, int print ) {
int high;
int i;
int limit;
int low;
int repetitions;
int return_value = 0;
int sides;
int tmp;
int * results;
struct ir_node * cur;
cur = node;
while (cur != NULL) {
int sum = 0;
switch (cur->op) {
case OP_NUMBER:
sum = cur->value;
break;
case OP_REP:
for (i = 0; i < roll_expression(cur->left, FALSE); i++) {
sum = checked_sum( sum, roll_expression(cur->right, FALSE) );
}
break;
case OP_DICE:
sum = roll_dice( roll_expression(cur->right, FALSE) );
break;
case OP_PLUS:
sum = checked_sum( roll_expression( cur->left, FALSE ),
roll_expression( cur->right, FALSE ) );
break;
case OP_MINUS:
sum = checked_sum( roll_expression( cur->left, FALSE ),
-roll_expression( cur->right, FALSE ) );
break;
case OP_TIMES:
sum = checked_multiplication( roll_expression( cur->left, FALSE ),
roll_expression( cur->right, FALSE ) );
break;
case OP_DIV:
sum = (int)
ceil( (float)roll_expression( cur->left, FALSE ) /
roll_expression( cur->right, FALSE ) );
break;
case OP_HIGH:
sides = roll_expression(cur->right->right->right, FALSE);
repetitions = roll_expression(cur->right->left, FALSE);
high = roll_expression(cur->left, FALSE);
/* array to store the results to sort */
if (!(results = malloc(sizeof(int)*repetitions))) {
error("Out of memory");
}
for(i=0; i<repetitions; i++) {
results[i] = roll_dice(sides);
}
qsort(results, repetitions, sizeof(int), &compare);
for(i=(repetitions-high); i<repetitions; i++) {
sum = checked_sum( sum, results[i] );
}
free(results);
break;
case OP_LOW:
sides = roll_expression(cur->right->right->right, FALSE);
repetitions = roll_expression(cur->right->left, FALSE);
low = roll_expression(cur->left, FALSE);
if (cur->right->left != NULL) {
repetitions = roll_expression(cur->right->left, FALSE);
}
/* array to store the results to sort */
if (!(results = malloc(sizeof(int)*repetitions))) {
error("Out of memory");
}
for(i=0; i<repetitions; i++) {
results[i] = roll_dice(sides);
}
qsort(results, repetitions, sizeof(int), &compare);
for(i=0; i<low; i++) {
sum = checked_sum( sum, results[i] );
}
free(results);
break;
case OP_GT:
limit = roll_expression(cur->right, FALSE);
tmp = roll_expression(cur->left, FALSE);
while (tmp <= limit) {
tmp = roll_expression(cur->left, FALSE);
}
sum = checked_sum( sum, tmp );
break;
case OP_GE:
limit = roll_expression(cur->right, FALSE);
tmp = roll_expression(cur->left, FALSE);
while (tmp < limit) {
tmp = roll_expression(cur->left, FALSE);
}
sum = checked_sum( sum, tmp );
break;
case OP_LT:
limit = roll_expression(cur->right, FALSE);
tmp = roll_expression(cur->left, FALSE);
while (tmp >= limit) {
tmp = roll_expression(cur->left, FALSE);
}
sum = checked_sum( sum, tmp );
break;
case OP_LE:
limit = roll_expression(cur->right, FALSE);
tmp = roll_expression(cur->left, FALSE);
while (tmp > limit) {
tmp = roll_expression(cur->left, FALSE);
}
sum = checked_sum( sum, tmp );
break;
case OP_NE:
limit = roll_expression(cur->right, FALSE);
tmp = roll_expression(cur->left, FALSE);
while (tmp == limit) {
tmp = roll_expression(cur->left, FALSE);
}
sum = checked_sum( sum, tmp );
break;
default :
fprintf(stderr, "Implementation error: unknown IR node with code %i\n", cur->op);
exit(EXIT_FAILURE);
}
return_value = checked_sum( return_value, sum);
if (print == TRUE) {
printf("%i\n", sum);
}
cur = cur->next;
}
return return_value;
}
#ifdef DEBUG
void print_node( struct ir_node * node) {
switch (node->op) {
case OP_NUMBER: printf("number (%i)", node->value); break;
case OP_DICE: printf("dice"); break;
case OP_PLUS: printf("+"); break;
case OP_MINUS: printf("-"); break;
case OP_TIMES: printf("*"); break;
case OP_DIV: printf("/"); break;
case OP_HIGH: printf("high"); break;
case OP_LOW: printf("low"); break;
case OP_GT: printf(">"); break;
case OP_GE: printf(">="); break;
case OP_LT: printf("<"); break;
case OP_LE: printf("<="); break;
case OP_NE: printf("!="); break;
case OP_REP: printf("rep"); break;
default : printf("unknown node"); break;
}
}
void print_tree( char * prefix, struct ir_node * node, int indent) {
int i;
printf("[%s] ", prefix);
for (i = 0; i < indent; i++) {
printf(" ");
}
print_node(node);
printf("\n");
if (node->left != NULL) {
print_tree(prefix, node->left, indent+1);
}
if (node->right != NULL) {
print_tree(prefix, node->right, indent+1);
}
}
#endif