-
Notifications
You must be signed in to change notification settings - Fork 1
/
diceserv.cpp
3056 lines (2839 loc) · 94.1 KB
/
diceserv.cpp
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
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ----------------------------------------------------------------------------
* Name : diceserv.cpp
* Author : Naram Qashat (CyberBotX)
* Version : 3.0.4
* Date : (Last modified) August 26, 2017
* ----------------------------------------------------------------------------
* The following applies to the non-Anope-derived portions of the code
* (excluding the RNG):
The MIT License (MIT)
Copyright (c) 2004-2017 Naram Qashat
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
* (This basically covers the core functionality of DiceServ.)
*
* The following applies to the Anope-derived portions of the code:
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 1, or (at your option) any later
* version.
* ----------------------------------------------------------------------------
* Requires: Anope 2.0.x
* ----------------------------------------------------------------------------
* Description:
*
* A dice rolling pseudo-client, mainly useful for playing pen & paper RPGs,
* such as Dungeons and Dragons, over IRC.
* ----------------------------------------------------------------------------
* Configuration example can be found in diceserv.example.conf.
* ----------------------------------------------------------------------------
* Changelog:
*
* 3.0.4 - Replaced Agner Fog's SFMT+MOA RNG with a dSFMT RNG by the authors
* of the Mersenne Twister RNG, mainly due to concerns over the RNG
* not producing unbiased results.
* 3.0.3 - Fixed an issue with user access in a moderated channel.
* - Removed unused delimiter argument from my Join() function.
* - Fixed an issue with DiceServData's HasExtended() function so it
* would properly detect if we have extended results or not.
* - Changed logic on determining when to start attempting to get
* extended output.
* - Fixed some typos and comments.
* 3.0.2 - Fixed an issue with SET IGNORE's reloading.
* - Better handling on determining when to use extended output.
* - Replaced usage of OnPostCommand for adding to NickServ/ChanServ
* info, used OnNickInfo and OnChanInfo instead.
* - Better checks for numbers in Infix to Postfix conversion.
* - Prevent factorials of 13 or higher due to limit on 32-bit integers
* as well as execution time.
* - Prevent potential crashes if a fantasy command other than the D&D
* 3e Character one is used with no arguments.
* - Minor C++11 fixes.
* - Other minor code cleanups.
* 3.0.1 - Fixed issues with loading an old DiceServ database so it actually
* works (there was a typo in the configuration file plus a timer
* has to be used).
* - Made a specialization of stringify for double to correct issues
* with some numbers using scientific notation when they shouldn't
* have as well as bring the precision back up.
* - Fixed EARTHDAWN on *nix-based systems.
* - Fixed DND3ECHAR so it actually works.
* 3.0.0 - Massive rewrite, now only targets Anope 2.0.x and has been heavily
* modularized.
* - Added support for functions to have an arbitrary number of
* arguments, used by only the max and min function currently.
* - Better handling of when to switch from long-form extended output to
* short-form extended output to no extended output.
* - Made sure that the math functions that were added for use with
* Visual Studio are only compiled in for Visual Studio 2012 or
* earlier, as they were finally included with Visual Studio 2013.
* - Completely restructured how results are handled.
* - Removed dtoa function as Anope's stringify could be used to replace
* it (at the cost of lower output precision on floating-point
* values).
* - Replaced the Mersenne Twister RNG with a combination RNG of a
* SIMD-oriented Fast Mersenne Twister RNG and a Mother-of-all RNG.
* - Added atan2 math function.
* 2.0.3 - Fix some memory leaks that went unnoticed by me until recently.
* 2.0.2 - Fix a crash bug for the Anope 1.8.x versions and a lack of an error
* message for the Anope 1.9.x versions caused if there is nothing
* before or after the tilde.
* 2.0.1 - Minor fix of permission in DiceServ's SET command.
* - Minor edit of GECOS of DiceServ to use "Service" instead of
* "Server".
* - Added version for Anope 1.9.5.
* 2.0 - Replaced Coda's expression parser with a parser of my own that
* converts the expression from infix to postfix using the
* shunting-yard algorithm and then evaluates it.
* - Added support for DnD3e character creation rolls.
* - Removed Exalted dice rolls from the service, I'm not 100% sure they
* were ever being done right.
* - Used enums for the dice roll types and errors for easier usage.
* - Fixed overflow checks.
* - Allow for d% anywhere in an expression, suggested by Namegduf.
* - Split apart parsing the expression and evaluating it, suggested by
* Namegduf.
* - Better buffer overflow checking, and removed check for the
* expression being too long, the current parser can handle long
* expressions unlike the last parser (no offense to Coda).
* - Added support for the pen & paper RPG Earthdawn, suggested by
* DukePyrolator.
* - Added support for math functions. (such as sqrt, trunc, cos, etc.)
* - Added support for the math constants of e and pi.
* - Added a CALC command which is like ROLL but without rounding.
* - Added configuration options for DiceServ's pseudo-client name as
* well as giving a network-wide ability for channel operators to
* set DiceServ channel ignores.
* - Added functionality for a shorter extended output if showing the
* results of each individual roll would be too long to display.
* - Better way of determining when to display the extended output
* buffer.
* - Utilize the Mersenne Twister RNG (random number generator) instead
* of Anope's RNG, it's faster but uses up a bit more memory. As a
* result, Coda's algorithm used in the dice roller is not longer
* used.
* - Added support for dual-argument functions of max(), min, and rand().
* 1.0 - Initial version (was only part of an Epona 1.4.14 edit).
* - Contained expression parser and dice roller algorithms from Adam
* Higerd (Coda Highland).
*
* ----------------------------------------------------------------------------
*/
/* RequiredLibraries: m */
#include <algorithm>
#include <functional>
#include <cctype>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include "diceserv.h"
#ifdef _MSC_VER
# include <float.h>
#endif
#include <emmintrin.h>
static const int DICE_MAX_TIMES = 25;
static const unsigned DICE_MAX_DICE = 99999;
static const unsigned DICE_MAX_SIDES = 99999;
/** Determine if the double-precision floating point value is infinite or not.
* @param num The double-precision floating point value to check
* @return true if the value is infinite, false otherwise
*/
static inline bool is_infinite(double num)
{
#ifdef _MSC_VER
int fpc = _fpclass(num);
return fpc == _FPCLASS_NINF || fpc == _FPCLASS_PINF;
#else
return std::isinf(num);
#endif
}
/** Determine if the double-precision floating point value is NaN (Not a Number) or not.
* @param num The double-precision floating point value to check
* @return true if the value is NaN, false otherwise
*/
static inline bool is_notanumber(double num)
{
#ifdef _MSC_VER
int fpc = _fpclass(num);
return fpc == _FPCLASS_SNAN || fpc == _FPCLASS_QNAN;
#else
return std::isnan(num);
#endif
}
#if defined(_MSC_VER) && _MSC_VER < 1800
/** Calculate inverse hyperbolic cosine for Windows (only needed when compiling with Visual Studio 2012 or earlier).
* @param num The double-precision floating point value to calculate
* @return The inverse hyperbolic cosine of the value
*/
static inline double acosh(double num)
{
return std::log(num + std::sqrt(num - 1) * std::sqrt(num + 1));
}
/** Calculate inverse hyperbolic sine for Windows (only needed when compiling with Visual Studio 2012 or earlier).
* @param num The double-precision floating point value to calculate
* @return The inverse hyperbolic sine of the value
*/
static inline double asinh(double num)
{
return std::log(num + std::sqrt(num * num + 1));
}
/** Calculate inverse hyperbolic tangent for Windows (only needed when compiling with Visual Studio 2012 or earlier).
* @param num The double-precision floating point value to calculate
* @return The inverse hyperbolic tangent of the value
*/
static inline double atanh(double num)
{
return 0.5 * std::log((1 + num) / (1 - num));
}
/** Calculate cube root for Windows (only needed when compiling with Visual Studio 2012 or earlier).
* @param num The double-precision floating point value to calculate
* @return The cube root of the value
*/
static inline double cbrt(double num)
{
return std::pow(num, 1.0 / 3.0);
}
#endif
/** A double-precision SIMD-oriented Fast Mersenne Twister RNG.
*
* This class was copied from Mutsuo Saito and Makoto Matsumoto,
* obtained from http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/
* Modified by Naram Qashat to only include what was needed by DiceServ,
* as well as containing everything within the class.
*
* The following license applies to this class:
Copyright (c) 2007, 2008, 2009 Mutsuo Saito, Makoto Matsumoto
and Hiroshima University.
Copyright (c) 2011, 2002 Mutsuo Saito, Makoto Matsumoto, Hiroshima
University and The University of Tokyo.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of the Hiroshima University nor the names of
its contributors may be used to endorse or promote products
derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
class dSFMT216091
{
union w128_t
{
__m128i si;
uint64_t u[2];
uint32_t u32[4];
double d[2];
};
union X128I_T
{
uint64_t u[2];
__m128i i128;
};
static const int DSFMT_POS1 = 1890; // The pick up position of the array
static const int DSFMT_SL1 = 23; // The parameter of shift left as four 32-bit registers
// A bitmask, used in the recursion. These parameters are introduced to break symmetry of SIMD
static const uint64_t DSFMT_MSK1 = 0x000bf7df7fefcfffULL;
static const uint64_t DSFMT_MSK2 = 0x000e7ffffef737ffULL;
// These definitions are part of a 128-bit period certification vector
static const uint64_t DSFMT_FIX1 = 0xd7f95a04764c27d7ULL;
static const uint64_t DSFMT_FIX2 = 0x6a483861810bebc2ULL;
static const uint64_t DSFMT_PCV1 = 0x3af0a8f3d5600000ULL;
static const uint64_t DSFMT_PCV2 = 0x0000000000000001ULL;
static const uint64_t DSFMT_LOW_MASK = 0x000FFFFFFFFFFFFFULL;
static const uint64_t DSFMT_HIGH_CONST = 0x3FF0000000000000ULL;
static const int DSFMT_SR = 12;
static const int SSE2_SHUFF = 0x1b;
static const int DSFMT_MEXP = 216091; // Mersenne Exponent. The period of the sequence is a multiple of 2^DSFMT_MEXP - 1.
static const int DSFMT_N = (DSFMT_MEXP - 128) / 104 + 1; // DSFMT generator has an internal state array of 128-bit integers, and N is its size
static const int DSFMT_N64 = DSFMT_N * 2; // N64 is the size of internal state array when regarded as an array of 64-bit integers
static const X128I_T sse2_param_mask;
w128_t status[DSFMT_N + 1]; // The 128-bit internal state array
int idx;
/** Represents the recursion formula.
* @param r output 128-bit
* @param a a 128-bit part of the internal state array
* @param b a 128-bit part of the internal state array
* @param u a 128-bit part of the internal state array (I/O)
*/
static void do_recursion(w128_t &r, const w128_t &a, const w128_t &b, w128_t &u)
{
__m128i x = a.si;
__m128i z = _mm_slli_epi64(x, DSFMT_SL1);
__m128i y = _mm_shuffle_epi32(u.si, SSE2_SHUFF);
z = _mm_xor_si128(z, b.si);
y = _mm_xor_si128(y, z);
__m128i v = _mm_srli_epi64(y, DSFMT_SR);
__m128i w = _mm_and_si128(y, sse2_param_mask.i128);
v = _mm_xor_si128(v, x);
v = _mm_xor_si128(v, w);
r.si = v;
u.si = y;
}
/** Fills the internal state array with double precision floating point pseudorandom numbers of the IEEE 754 format.
*/
void gen_rand_all()
{
w128_t lung = this->status[DSFMT_N];
do_recursion(this->status[0], this->status[0], this->status[DSFMT_POS1], lung);
int i;
for (i = 1; i < DSFMT_N - DSFMT_POS1; ++i)
do_recursion(this->status[i], this->status[i], this->status[i + DSFMT_POS1], lung);
for (; i < DSFMT_N; ++i)
do_recursion(this->status[i], this->status[i], this->status[i + DSFMT_POS1 - DSFMT_N], lung);
this->status[DSFMT_N] = lung;
}
/** Initializes the internal state array with a 32-bit integer seed.
* @param seed a 32-bit integer used as the seed.
*/
void init_gen_rand(uint32_t seed)
{
uint32_t *psfmt = &this->status[0].u32[0];
psfmt[0] = seed;
for (int i = 1; i < (DSFMT_N + 1) * 4; ++i)
psfmt[i] = 1812433253UL * (psfmt[i - 1] ^ (psfmt[i - 1] >> 30)) + i;
this->initial_mask();
this->period_certification();
this->idx = DSFMT_N64;
}
/** Initializes the internal state array to fit the IEEE 754 format.
*/
void initial_mask()
{
uint64_t *psfmt = &this->status[0].u[0];
for (int i = 0; i < DSFMT_N * 2; ++i)
psfmt[i] = (psfmt[i] & DSFMT_LOW_MASK) | DSFMT_HIGH_CONST;
}
/** Certificate the period of 2^DSFMT_MEXP - 1.
*/
void period_certification()
{
static const uint64_t pcv[] = { DSFMT_PCV1, DSFMT_PCV2 };
uint64_t tmp[] = { this->status[DSFMT_N].u[0] ^ DSFMT_FIX1, this->status[DSFMT_N].u[1] ^ DSFMT_FIX2 };
uint64_t inner = tmp[0] & pcv[0];
inner ^= tmp[1] & pcv[1];
int i;
for (i = 32; i > 0; i >>= 1)
inner ^= inner >> i;
inner &= 1;
// check OK
if (inner == 1)
return;
// check NG, and modification
if ((DSFMT_PCV2 & 1) == 1)
this->status[DSFMT_N].u[1] ^= 1;
else
{
for (i = 1; i >= 0; --i)
{
uint64_t work = 1;
for (int j = 0; j < 64; ++j)
{
if (work & pcv[i])
{
this->status[DSFMT_N].u[i] ^= work;
return;
}
work <<= 1;
}
}
}
}
/** Generates and returns double precision pseudorandom number which distributes uniformly in the range [1, 2).
* @return double precision floating point pseudorandom number
*
* This is the primitive and faster than generating numbers in other ranges.
*/
double genrand_close1_open2()
{
double *psfmt64 = &this->status[0].d[0];
if (this->idx >= DSFMT_N64)
{
this->gen_rand_all();
this->idx = 0;
}
return psfmt64[this->idx++];
}
/** Generates and returns double precision pseudorandom number which distributes uniformly in the range [0, 1).
* @return double precision floating point pseudorandom number
*/
double genrand_close_open()
{
return this->genrand_close1_open2() - 1.0;
}
public:
dSFMT216091(uint32_t seed)
{
this->init_gen_rand(seed);
}
/** Generate a random integer within the given range.
* @param min The minimum value of the range
* @param max The maximum value of the range
* @return An integer in the interval min <= x <= max
*
* This function was not part of the original dSFMT implementation and was added by Naram Qashat.
*/
int Random(int min, int max)
{
return static_cast<int>(std::floor(this->genrand_close_open() * (max - min + 1)) + min);
}
};
const dSFMT216091::X128I_T dSFMT216091::sse2_param_mask = { { DSFMT_MSK1, DSFMT_MSK2 } };
static dSFMT216091 sfmtRNG(static_cast<uint32_t>(std::time(NULL)));
/** Determine if the given character is a number.
* @param chr Character to check
* @return true if the character is a number, false otherwise
*/
static inline bool is_number(char chr)
{
return (chr >= '0' && chr <= '9') || chr == '.';
}
/** Determine if the given string is a number.
* @param str String to check
* @return true if the string is a number, false otherwise
*/
static inline bool is_number_str(const Anope::string &str)
{
Anope::string::const_iterator begin = str.begin(), end = str.end();
return std::find_if(begin, end, std::not1(std::ptr_fun(is_number))) == end && std::count(begin, end, '.') < 2;
}
/** Determine if the given character is a multiplication or division operator.
* @param chr Character to check
* @return true if the character is a multiplication or division operator, false otherwise
*/
static inline bool is_muldiv(char chr)
{
return chr == '%' || chr == '/' || chr == '*';
}
/** Determine if the given character is an addition or subtraction operator.
* @param chr Character to check
* @return true if the character is an addition or subtraction operator, false otherwise
*/
static inline bool is_plusmin(char chr)
{
return chr == '+' || chr == '-';
}
/** Determine if the given character is an operator of any sort, except for parentheses.
* @param chr Character to check
* @return true if the character is a non-parenthesis operator, false otherwise
*/
static inline bool is_op_noparen(char chr)
{
return is_plusmin(chr) || is_muldiv(chr) || chr == '^' || chr == 'd';
}
/** Determine if the given character is an operator of any sort.
* @param chr Character to check
* @return true if the character is an operator, false otherwise
*/
static inline bool is_operator(char chr)
{
return chr == '(' || chr == ')' || is_op_noparen(chr);
}
/** Determine if the substring portion of the given string is a function.
* @param str String to check
* @param pos Starting position of the substring to check, defaults to 0
* @return 0 if the string isn't a function, or a number corresponding to the length of the function name
*/
static inline unsigned is_function(const Anope::string &str, unsigned pos = 0)
{
// We only need a 5 character substring as that's the largest substring we will be looking at
Anope::string func = str.substr(pos, 5);
// acosh, asinh, atan2, atanh, floor, log10, round, trunc
Anope::string func_5 = func.substr(0, 5);
if (func_5.equals_ci("acosh") || func_5.equals_ci("asinh") || func_5.equals_ci("atan2") || func_5.equals_ci("atanh") || func_5.equals_ci("floor") ||
func_5.equals_ci("log10") || func_5.equals_ci("round") || func_5.equals_ci("trunc"))
return 5;
// acos, asin, atan, cbrt, ceil, cosh, rand, sinh, sqrt, tanh
Anope::string func_4 = func.substr(0, 4);
if (func_4.equals_ci("acos") || func_4.equals_ci("asin") || func_4.equals_ci("atan") || func_4.equals_ci("cbrt") || func_4.equals_ci("ceil") ||
func_4.equals_ci("cosh") || func_4.equals_ci("rand") || func_4.equals_ci("sinh") || func_4.equals_ci("sqrt") || func_4.equals_ci("tanh"))
return 4;
// abs, cos, deg, exp, fac, log, max, min, rad, sin, tan
Anope::string func_3 = func.substr(0, 3);
if (func_3.equals_ci("abs") || func_3.equals_ci("cos") || func_3.equals_ci("deg") || func_3.equals_ci("exp") || func_3.equals_ci("fac") ||
func_3.equals_ci("log") || func_3.equals_ci("max") || func_3.equals_ci("min") || func_3.equals_ci("rad") || func_3.equals_ci("sin") ||
func_3.equals_ci("tan"))
return 3;
// None of the above
return 0;
}
/** Determine the number of arguments that the given function needs.
* @param str Function string to check
* @return Returns 1 except for the min and max functions which return -2 (to say they require AT LEAST 2 arguments), and the atan2 and rand functions which return 2
*/
static inline int function_argument_count(const Anope::string &str)
{
Anope::string func_3 = str.substr(0, 3);
if (func_3.equals_ci("max") || func_3.equals_ci("min"))
return -2;
if (str.equals_ci("atan2") || str.equals_ci("rand"))
return 2;
return 1;
}
/** Determine if the substring portion of the given string is a constant (currently only e and pi).
* @param str String to check
* @param pos Starting position of the substring to check, defaults to 0
* @return 0 if the string isn't a constant, or a number corresponding to the length of the constant's name
*/
static inline unsigned is_constant(const Anope::string &str, unsigned pos = 0)
{
// We only need a 2 character substring as that's the largest substring we will be looking at
Anope::string constant = str.substr(pos, 2);
// pi
if (constant.substr(0, 2).equals_ci("pi"))
return 2;
// e
if (constant.substr(0, 1).equals_ci("e"))
return 1;
// None of the above
return 0;
}
/** Determine if the given operator has a higher precedence than the operator on the top of the stack during infix to postfix conversion.
* @param adding The operator we are adding to the stack, or an empty string if nothing is being added and we just want to remove
* @param topstack The operator that was at the top of the operator stack
* @return 0 if the given operator has the same or lower precedence (and won't cause a pop), 1 if the operator has higher precedence (and will cause a pop)
*
* In addition to the above in regards to the return value, there are other situations. If the top of the stack is an open parenthesis,
* or is empty, a 0 will be returned to stop the stack from popping anything else. If nothing is being added to the stack and the previous
* situation hasn't occurred, a 1 will be returned to signify to continue popping the stack until the previous situation occurs. If the operator
* being added is a function, we return 0 to signify we aren't popping. If the top of the stack is a function, we return 1 to signify we are
* popping. A -1 is only returned if an invalid operator is given, hopefully that will never happen.
*/
static inline int would_pop(const Anope::string &adding, const Anope::string &topstack)
{
if (adding.empty())
return topstack.empty() || topstack == "(" ? 0 : 1;
if (is_function(adding))
return 0;
if (topstack.empty() || topstack == "(")
return 0;
if (is_function(topstack))
return 1;
if (topstack == adding && adding != "^")
return 1;
switch (adding[0])
{
case 'd':
return 0;
case '^':
return topstack.equals_ci("d") ? 1 : 0;
case '%':
case '/':
case '*':
return topstack == "^" || topstack.equals_ci("d") || is_muldiv(topstack[0]) ? 1 : 0;
case '+':
case '-':
return is_op_noparen(topstack[0]) ? 1 : 0;
}
return -1;
}
/** Calculate a die roll for the given number of sides for a set number of times.
* @param num Number of times to throw the die
* @param sides Number of sides on the die
* @return The results of the dice in a special structure
*/
DiceResult Dice(int num, unsigned sides)
{
DiceResult result = DiceResult(num, sides);
for (int i = 0; i < num; ++i)
// Get a random number between 1 and the number of sides
result.AddResult(sfmtRNG.Random(1, sides));
return result;
}
/** Round a value to the given number of decimals, originally needed for Windows but also used for other OSes as well due to undefined references.
* @param val The value to round
* @param decimals The number of digits after the decimal point, defaults to 0
* @return The rounded value
*
* NOTE: Function is a slightly modified form of the code from this page:
* http://social.msdn.microsoft.com/forums/en-US/vclanguage/thread/a7d4bf31-6c32-4b25-bc76-21b29f5287a1/
*/
static double my_round(double val, unsigned decimals = 0)
{
if (!val) // val must be different from zero to avoid division by zero!
return 0;
double sign = std::abs(val) / val; // we obtain the sign to calculate positive always
double tempval = std::abs(val * std::pow(10.0, static_cast<double>(decimals))); // shift decimal places
unsigned tempint = static_cast<unsigned>(tempval);
double decimalpart = tempval - tempint; // obtain just the decimal part
if (decimalpart >= 0.5)
tempval = std::ceil(tempval); // next integer number if greater or equal to 0.5
else
tempval = std::floor(tempval); // otherwise stay in the current integer part
return (tempval * std::pow(10.0, -static_cast<int>(decimals))) * sign; // shift again to the normal decimal places
}
/** Structure to store the infix notation string as well as the positions each character is compared to the original input */
struct Infix
{
Anope::string str;
std::vector<unsigned> positions;
Infix(const Anope::string &newStr, std::vector<unsigned> newPositions)
{
this->str = newStr;
this->positions = newPositions;
}
Infix(const Anope::string &newStr, unsigned newPositions[], unsigned num)
{
this->str = newStr;
this->positions = std::vector<unsigned>(newPositions, newPositions + sizeof(unsigned) * num);
}
};
/** Fix an infix notation equation.
* @param infix The original infix notation equation
* @return A fixed infix notation equation
*
* This will convert a single % to 1d100, place a 1 in front of any d's that have no numbers before them, change all %'s after a d into 100,
* add *'s for implicit multiplication, and convert unary -'s to _ for easier parsing later.
*/
static Infix FixInfix(const Anope::string &infix)
{
if (infix == "%")
{
unsigned tmp[] = { 0, 0, 0, 0, 0 };
return Infix("1d100", tmp, 5);
}
bool prev_was_func = false, prev_was_const = false;
Anope::string newinfix;
std::vector<unsigned> positions;
unsigned len = infix.length();
for (unsigned x = 0; x < len; ++x)
{
// Check for a function, and skip it if it exists
unsigned func = is_function(infix, x);
if (func)
{
if (x && is_number(infix[x - 1]))
{
newinfix += '*';
positions.push_back(x);
}
newinfix += infix.substr(x, func);
for (unsigned y = 0; y < func; ++y)
positions.push_back(x + y);
x += func - 1;
prev_was_func = true;
continue;
}
// Check for a constant, and skip it if it exists
unsigned constant = is_constant(infix, x);
if (constant)
{
if (x && is_number(infix[x - 1]))
{
newinfix += '*';
positions.push_back(x);
}
newinfix += infix.substr(x, constant);
for (unsigned y = 0; y < constant; ++y)
positions.push_back(x + y);
if (x + constant < len && (is_number(infix[x + constant]) || is_constant(infix, x + constant) || is_function(infix, x + constant)))
{
newinfix += '*';
positions.push_back(x + constant);
}
x += constant - 1;
prev_was_const = true;
continue;
}
char curr = static_cast<char>(std::tolower(infix[x]));
if (curr == 'd')
{
positions.push_back(x);
if (!x)
{
newinfix += "1d";
positions.push_back(x);
}
else
{
if (!is_number(infix[x - 1]) && infix[x - 1] != ')' && !prev_was_const)
{
newinfix += '1';
positions.push_back(x);
}
newinfix += 'd';
}
if (x != len - 1 && infix[x + 1] == '%')
{
newinfix += "100";
++x;
positions.push_back(x);
positions.push_back(x);
}
}
else if (curr == '(')
{
if (x && !prev_was_func && (is_number(infix[x - 1]) || prev_was_const))
{
newinfix += '*';
positions.push_back(x);
}
newinfix += '(';
positions.push_back(x);
}
else if (curr == ')')
{
newinfix += ')';
positions.push_back(x);
if (x != len - 1 && (is_number(infix[x + 1]) || infix[x + 1] == '(' || is_constant(infix, x + 1)))
{
newinfix += '*';
positions.push_back(x);
}
}
else if (curr == '-')
{
positions.push_back(x);
if (x != len - 1 && (!x ? 1 : is_op_noparen(static_cast<char>(std::tolower(infix[x - 1]))) || infix[x - 1] == '(' || infix[x - 1] == ','))
{
if (infix[x + 1] == '(' || is_function(infix, x + 1))
{
newinfix += "0-";
positions.push_back(x);
}
else if (is_number(infix[x + 1]) || is_constant(infix, x + 1))
newinfix += '_';
else
newinfix += '-';
}
else
newinfix += '-';
}
else
{
newinfix += curr;
positions.push_back(x);
}
prev_was_func = prev_was_const = false;
}
positions.push_back(len);
return Infix(newinfix, positions);
}
/** Validate an infix notation equation.
* @param infix The infix notation equation to validate
* @return false for an invalid equation, true for a valid one
*
* The validation is as follows:
* - All functions must have an open parenthesis after them.
* - A comma must be prefixed by a number or close parenthesis and must be suffixed by a number, open parenthesis, _ for unary minus, constant, or function.
* - All non-parenthesis operators must be prefixed by a number or close parenthesis and suffixed by a number, open parenthesis, _ for unary minus, constant, or function.
* - All open parentheses must be prefixed by an operator, open parenthesis, or comma and suffixed by a number, an open parenthesis, _ for unary minus, constant, or function.
* - All close parentheses must be prefixed by a number or close parenthesis and suffixed by an operator, close parenthesis, or comma.
*/
static bool CheckInfix(DiceServData &data, const Infix &infix)
{
bool prev_was_func = false, prev_was_const = false;
for (unsigned x = 0, len = infix.str.length(); x < len; ++x)
{
unsigned position = infix.positions[x];
// Check for a function, and skip it if it exists
unsigned func = is_function(infix.str, x);
if (func)
{
if ((x + func < len && infix.str[x + func] != '(') || x + func >= len)
{
data.errPos = infix.positions[x + func >= len ? len : x + func];
data.errCode = DICE_ERROR_PARSE;
data.errStr = "No open parenthesis found after function.";
return false;
}
x += func - 1;
prev_was_func = true;
continue;
}
// Check for a constant, and skip it if it exists
unsigned constant = is_constant(infix.str, x);
if (constant)
{
x += constant - 1;
prev_was_const = true;
continue;
}
if (infix.str[x] == ',')
{
if (!x ? 1 : !is_number(infix.str[x - 1]) && infix.str[x - 1] != ')' && !prev_was_const)
{
data.errPos = position;
data.errCode = DICE_ERROR_PARSE;
data.errStr = "No number or close parenthesis before comma.";
return false;
}
if (x == len - 1 ? 1 : !is_number(infix.str[x + 1]) && infix.str[x + 1] != '(' && infix.str[x + 1] != '_' && !is_constant(infix.str, x + 1) &&
!is_function(infix.str, x + 1))
{
data.errPos = position;
data.errCode = DICE_ERROR_PARSE;
data.errStr = "No number or open parenthesis after comma.";
return false;
}
}
else if (is_op_noparen(infix.str[x]))
{
if (!x ? 1 : !is_number(infix.str[x - 1]) && infix.str[x - 1] != ')' && !prev_was_const)
{
data.errPos = position;
data.errCode = DICE_ERROR_PARSE;
data.errStr = "No number or close parenthesis before operator.";
return false;
}
if (x == len - 1 ? 1 : !is_number(infix.str[x + 1]) && infix.str[x + 1] != '(' && infix.str[x + 1] != '_' && !is_constant(infix.str, x + 1) &&
!is_function(infix.str, x + 1))
{
data.errPos = position;
data.errCode = DICE_ERROR_PARSE;
data.errStr = "No number or open parenthesis after operator.";
return false;
}
}
else if (infix.str[x] == '(')
{
if (x && !is_op_noparen(infix.str[x - 1]) && infix.str[x - 1] != '(' && infix.str[x - 1] != ',' && !prev_was_func)
{
data.errPos = position;
data.errCode = DICE_ERROR_PARSE;
data.errStr = "No operator or open parenthesis found before current open\nparenthesis.";
return false;
}
if (x != len - 1 && !is_number(infix.str[x + 1]) && infix.str[x + 1] != '(' && infix.str[x + 1] != '_' && !is_constant(infix.str, x + 1) &&
!is_function(infix.str, x + 1))
{
data.errPos = position;
data.errCode = DICE_ERROR_PARSE;
data.errStr = "No number after current open parenthesis.";
return false;
}
}
else if (infix.str[x] == ')')
{
if (x && !is_number(infix.str[x - 1]) && infix.str[x - 1] != ')' && !prev_was_const)
{
data.errPos = position;
data.errCode = DICE_ERROR_PARSE;
data.errStr = "No number found before current close parenthesis.";
return false;
}
if (x != len - 1 && !is_op_noparen(infix.str[x + 1]) && infix.str[x + 1] != ')' && infix.str[x + 1] != ',')
{
data.errPos = position;
data.errCode = DICE_ERROR_PARSE;
data.errStr = "No operator or close parenthesis found after current close\nparenthesis.";
return false;
}
}
else if (!is_number(infix.str[x]) && !is_muldiv(infix.str[x]) && !is_plusmin(infix.str[x]) && !is_operator(infix.str[x]) && infix.str[x] != '_')
{
data.errPos = position;
data.errCode = DICE_ERROR_PARSE;
data.errStr = "An invalid character was encountered.";
return false;
}
prev_was_func = prev_was_const = false;
}
return true;
}
/** Tokenize an infix notation equation by adding spaces between operators.
* @param infix The original infix notation equation to tokenize
* @return A new infix notation equation with spaces between operators
*/
static Infix TokenizeInfix(const Infix &infix)
{
Anope::string newinfix;
std::vector<unsigned> positions;
for (unsigned x = 0, len = infix.str.length(); x < len; ++x)
{
unsigned position = infix.positions[x], func = is_function(infix.str, x), constant = is_constant(infix.str, x);
char curr = infix.str[x];
if (func)
{
if (x && !newinfix.empty() && newinfix[newinfix.length() - 1] != ' ')
{
newinfix += ' ';
positions.push_back(position);
}
newinfix += infix.str.substr(x, func);
for (unsigned y = 0; y < func; ++y)
positions.push_back(infix.positions[x + y]);
if (x != len - 1)
{
newinfix += ' ';
positions.push_back(infix.positions[x + func]);
}
x += func - 1;
}
else if (constant)
{
if (x && !newinfix.empty() && newinfix[newinfix.length() - 1] != ' ' && newinfix[newinfix.length() - 1] != '_')
{
newinfix += ' ';
positions.push_back(position);
}
newinfix += infix.str.substr(x, constant);
for (unsigned y = 0; y < constant; ++y)
positions.push_back(infix.positions[x + y]);
if (x != len - 1)
{
newinfix += ' ';
positions.push_back(infix.positions[x + constant]);
}
x += constant - 1;
}
else if (curr == ',')
{
if (x && !newinfix.empty() && newinfix[newinfix.length() - 1] != ' ')
{
newinfix += ' ';
positions.push_back(position);
}
newinfix += ',';
positions.push_back(position);
if (x != len - 1)
{
newinfix += ' ';
positions.push_back(position);
}
}
else if (is_operator(curr))
{
if (x && !newinfix.empty() && newinfix[newinfix.length() - 1] != ' ')
{
newinfix += ' ';
positions.push_back(position);
}
newinfix += curr;
positions.push_back(position);
if (x != len - 1)
{
newinfix += ' ';
positions.push_back(position);
}
}
else
{
newinfix += curr;
positions.push_back(position);