-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfparser.cpp
3800 lines (3403 loc) · 123 KB
/
fparser.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
/***************************************************************************\
|* Function Parser for C++ v4.5.2 *|
|*-------------------------------------------------------------------------*|
|* Copyright: Juha Nieminen, Joel Yliluoma *|
|* *|
|* This library is distributed under the terms of the *|
|* GNU Lesser General Public License version 3. *|
|* (See lgpl.txt and gpl.txt for the license text.) *|
\***************************************************************************/
#include "fpconfig.hh"
#include "fparser.hh"
#include <set>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <cassert>
#include <limits>
#include "extrasrc/fptypes.hh"
#include "extrasrc/fpaux.hh"
using namespace FUNCTIONPARSERTYPES;
#ifdef FP_USE_THREAD_SAFE_EVAL_WITH_ALLOCA
#ifndef FP_USE_THREAD_SAFE_EVAL
#define FP_USE_THREAD_SAFE_EVAL
#endif
#endif
#ifdef __GNUC__
# define likely(x) __builtin_expect(!!(x), 1)
# define unlikely(x) __builtin_expect(!!(x), 0)
#else
# define likely(x) (x)
# define unlikely(x) (x)
#endif
//=========================================================================
// Opcode analysis functions
//=========================================================================
// These functions are used by the Parse() bytecode optimizer (mostly from
// code in fp_opcode_add.inc).
bool FUNCTIONPARSERTYPES::IsLogicalOpcode(unsigned op)
{
switch(op)
{
case cAnd: case cAbsAnd:
case cOr: case cAbsOr:
case cNot: case cAbsNot:
case cNotNot: case cAbsNotNot:
case cEqual: case cNEqual:
case cLess: case cLessOrEq:
case cGreater: case cGreaterOrEq:
return true;
default: break;
}
return false;
}
bool FUNCTIONPARSERTYPES::IsComparisonOpcode(unsigned op)
{
switch(op)
{
case cEqual: case cNEqual:
case cLess: case cLessOrEq:
case cGreater: case cGreaterOrEq:
return true;
default: break;
}
return false;
}
unsigned FUNCTIONPARSERTYPES::OppositeComparisonOpcode(unsigned op)
{
switch(op)
{
case cLess: return cGreater;
case cGreater: return cLess;
case cLessOrEq: return cGreaterOrEq;
case cGreaterOrEq: return cLessOrEq;
}
return op;
}
bool FUNCTIONPARSERTYPES::IsNeverNegativeValueOpcode(unsigned op)
{
switch(op)
{
case cAnd: case cAbsAnd:
case cOr: case cAbsOr:
case cNot: case cAbsNot:
case cNotNot: case cAbsNotNot:
case cEqual: case cNEqual:
case cLess: case cLessOrEq:
case cGreater: case cGreaterOrEq:
case cSqrt: case cRSqrt: case cSqr:
case cHypot:
case cAbs:
case cAcos: case cCosh:
return true;
default: break;
}
return false;
}
bool FUNCTIONPARSERTYPES::IsAlwaysIntegerOpcode(unsigned op)
{
switch(op)
{
case cAnd: case cAbsAnd:
case cOr: case cAbsOr:
case cNot: case cAbsNot:
case cNotNot: case cAbsNotNot:
case cEqual: case cNEqual:
case cLess: case cLessOrEq:
case cGreater: case cGreaterOrEq:
case cInt: case cFloor: case cCeil: case cTrunc:
return true;
default: break;
}
return false;
}
bool FUNCTIONPARSERTYPES::IsUnaryOpcode(unsigned op)
{
switch(op)
{
case cInv: case cNeg:
case cNot: case cAbsNot:
case cNotNot: case cAbsNotNot:
case cSqr: case cRSqrt:
case cDeg: case cRad:
return true;
}
return (op < FUNC_AMOUNT && Functions[op].params == 1);
}
bool FUNCTIONPARSERTYPES::IsBinaryOpcode(unsigned op)
{
switch(op)
{
case cAdd: case cSub: case cRSub:
case cMul: case cDiv: case cRDiv:
case cMod:
case cEqual: case cNEqual: case cLess:
case cLessOrEq: case cGreater: case cGreaterOrEq:
case cAnd: case cAbsAnd:
case cOr: case cAbsOr:
return true;
}
return (op < FUNC_AMOUNT && Functions[op].params == 2);
}
bool FUNCTIONPARSERTYPES::IsVarOpcode(unsigned op)
{
// See comment in declaration of FP_ParamGuardMask
return int(op) >= VarBegin;
}
bool FUNCTIONPARSERTYPES::IsCommutativeOrParamSwappableBinaryOpcode(unsigned op)
{
switch(op)
{
case cAdd:
case cMul:
case cEqual: case cNEqual:
case cAnd: case cAbsAnd:
case cOr: case cAbsOr:
case cMin: case cMax: case cHypot:
return true;
case cDiv: case cSub: case cRDiv: case cRSub:
return true;
case cLess: case cGreater:
case cLessOrEq: case cGreaterOrEq: return true;
}
return false;
}
unsigned FUNCTIONPARSERTYPES::GetParamSwappedBinaryOpcode(unsigned op)
{
switch(op)
{
case cAdd:
case cMul:
case cEqual: case cNEqual:
case cAnd: case cAbsAnd:
case cOr: case cAbsOr:
case cMin: case cMax: case cHypot:
return op;
case cDiv: return cRDiv;
case cSub: return cRSub;
case cRDiv: return cDiv;
case cRSub: return cSub;
case cLess: return cGreater;
case cGreater: return cLess;
case cLessOrEq: return cGreaterOrEq;
case cGreaterOrEq: return cLessOrEq;
}
return op; // Error
}
template<bool ComplexType>
bool FUNCTIONPARSERTYPES::HasInvalidRangesOpcode(unsigned op)
{
// Returns true, if the given opcode has a range of
// input values that gives an error.
if(ComplexType)
{
// COMPLEX:
switch(op)
{
case cAtan: // allowed range: x != +-1i
case cAtanh: // allowed range: x != +-1
//case cCot: // allowed range: tan(x) != 0
//case cCsc: // allowed range: sin(x) != 0
case cLog: // allowed range: x != 0
case cLog2: // allowed range: x != 0
case cLog10: // allowed range: x != 0
#ifdef FP_SUPPORT_OPTIMIZER
case cLog2by:// allowed range: x != 0
#endif
//case cPow: // allowed when: x != 0 or y != 0
//case cSec: // allowed range: cos(x) != 0
//case cTan: // allowed range: cos(x) != 0 --> x != +-(pi/2)
//case cTanh: // allowed range: log(x) != -1 --> x != +-(pi/2)i
case cRSqrt: // allowed range: x != 0
//case cDiv: // allowed range: y != 0
//case cRDiv: // allowed range: x != 0
//case cInv: // allowed range: x != 0
return true;
}
}
else
{
// REAL:
switch(op)
{
case cAcos: // allowed range: |x| <= 1
case cAsin: // allowed range: |x| <= 1
case cAcosh: // allowed range: x >= 1
case cAtanh: // allowed range: |x| < 1
//case cCot: // allowed range: tan(x) != 0
//case cCsc: // allowed range: sin(x) != 0
case cLog: // allowed range: x > 0
case cLog2: // allowed range: x > 0
case cLog10: // allowed range: x > 0
#ifdef FP_SUPPORT_OPTIMIZER
case cLog2by:// allowed range: x > 0
#endif
//case cPow: // allowed when: x > 0 or (x = 0 and y != 0) or (x<0)
// Technically, when (x<0 and y is not integer),
// it is not allowed, but we allow it anyway
// in order to make nontrivial roots work.
//case cSec: // allowed range: cos(x) != 0
case cSqrt: // allowed range: x >= 0
case cRSqrt: // allowed range: x > 0
//case cTan: // allowed range: cos(x) != 0 --> x != +-(pi/2)
//case cDiv: // allowed range: y != 0
//case cRDiv: // allowed range: x != 0
//case cInv: // allowed range: x != 0
return true;
}
}
return false;
}
template bool FUNCTIONPARSERTYPES::HasInvalidRangesOpcode<false>(unsigned op);
template bool FUNCTIONPARSERTYPES::HasInvalidRangesOpcode<true>(unsigned op);
#if(0) // Implementation moved to fpaux.hh due to linker problems
//=========================================================================
// Mathematical template functions
//=========================================================================
/* fp_pow() is a wrapper for std::pow()
* that produces an identical value for
* exp(1) ^ 2.0 (0x4000000000000000)
* as exp(2.0) (0x4000000000000000)
* - std::pow() on x86_64
* produces 2.0 (0x3FFFFFFFFFFFFFFF) instead!
* See comments below for other special traits.
*/
namespace
{
template<typename ValueT>
inline ValueT fp_pow_with_exp_log(const ValueT& x, const ValueT& y)
{
// Exponentiation using exp(log(x)*y).
// See http://en.wikipedia.org/wiki/Exponentiation#Real_powers
// Requirements: x > 0.
return fp_exp(fp_log(x) * y);
}
template<typename ValueT>
inline ValueT fp_powi(ValueT x, unsigned long y)
{
// Fast binary exponentiation algorithm
// See http://en.wikipedia.org/wiki/Exponentiation_by_squaring
// Requirements: y is non-negative integer.
ValueT result(1);
while(y != 0)
{
if(y & 1) { result *= x; y -= 1; }
else { x *= x; y /= 2; }
}
return result;
}
}
template<typename ValueT>
ValueT FUNCTIONPARSERTYPES::fp_pow(const ValueT& x, const ValueT& y)
{
if(x == ValueT(1)) return ValueT(1);
// y is now zero or positive
if(isLongInteger(y))
{
// Use fast binary exponentiation algorithm
if(y >= ValueT(0))
return fp_powi(x, makeLongInteger(y));
else
return ValueT(1) / fp_powi(x, -makeLongInteger(y));
}
if(y >= ValueT(0))
{
// y is now positive. Calculate using exp(log(x)*y).
if(x > ValueT(0)) return fp_pow_with_exp_log(x, y);
if(x == ValueT(0)) return ValueT(0);
// At this point, y > 0.0 and x is known to be < 0.0,
// because positive and zero cases are already handled.
if(!isInteger(y*ValueT(16)))
return -fp_pow_with_exp_log(-x, y);
// ^This is not technically correct, but it allows
// functions such as cbrt(x^5), that is, x^(5/3),
// to be evaluated when x is negative.
// It is too complicated (and slow) to test whether y
// is a formed from a ratio of an integer to an odd integer.
// (And due to floating point inaccuracy, pointless too.)
// For example, x^1.30769230769... is
// actually x^(17/13), i.e. (x^17) ^ (1/13).
// (-5)^(17/13) gives us now -8.204227562330453.
// To see whether the result is right, we can test the given
// root: (-8.204227562330453)^13 gives us the value of (-5)^17,
// which proves that the expression was correct.
//
// The y*16 check prevents e.g. (-4)^(3/2) from being calculated,
// as it would confuse functioninfo when pow() returns no error
// but sqrt() does when the formula is converted into sqrt(x)*x.
//
// The errors in this approach are:
// (-2)^sqrt(2) should produce NaN
// or actually sqrt(2)I + 2^sqrt(2),
// produces -(2^sqrt(2)) instead.
// (Impact: Neglible)
// Thus, at worst, we're changing a NaN (or complex)
// result into a negative real number result.
}
else
{
// y is negative. Utilize the x^y = 1/(x^-y) identity.
if(x > ValueT(0)) return fp_pow_with_exp_log(ValueT(1) / x, -y);
if(x < ValueT(0))
{
if(!isInteger(y*ValueT(-16)))
return -fp_pow_with_exp_log(ValueT(-1) / x, -y);
// ^ See comment above.
}
// Remaining case: 0.0 ^ negative number
}
// This is reached when:
// x=0, and y<0
// x<0, and y*16 is either positive or negative integer
// It is used for producing error values and as a safe fallback.
return fp_pow_base(x, y);
}
#endif
//=========================================================================
// Elementary (atom) parsing functions
//=========================================================================
namespace
{
const unsigned FP_ParamGuardMask = 1U << (sizeof(unsigned) * 8u - 1u);
// ^ This mask is used to prevent cFetch/other opcode's parameters
// from being confused into opcodes or variable indices within the
// bytecode optimizer. Because the way it is tested in bytecoderules.dat
// for speed reasons, it must also be the sign-bit of the "int" datatype.
// Perhaps an "assert(IsVarOpcode(X | FP_ParamGuardMask) == false)"
// might be justified to put somewhere in the code, just in case?
/* Reads an UTF8-encoded sequence which forms a valid identifier name from
the given input string and returns its length. If bit 31 is set, the
return value also contains the internal function opcode (defined in
fptypes.hh) that matches the name.
*/
unsigned readIdentifierCommon(const char* input)
{
/* Assuming unsigned = 32 bits:
76543210 76543210 76543210 76543210
Return value if built-in function:
1PPPPPPP PPPPPPPP LLLLLLLL LLLLLLLL
P = function opcode (15 bits)
L = function name length (16 bits)
Return value if not built-in function:
0LLLLLLL LLLLLLLL LLLLLLLL LLLLLLLL
L = identifier length (31 bits)
If unsigned has more than 32 bits, the other
higher order bits are to be assumed zero.
*/
#include "extrasrc/fp_identifier_parser.inc"
return 0;
}
template<typename Value_t>
inline unsigned readIdentifier(const char* input)
{
const unsigned value = readIdentifierCommon(input);
if( (value & 0x80000000U) != 0) // Function?
{
// Verify that the function actually exists for this datatype
if(IsIntType<Value_t>::result
&& !Functions[(value >> 16) & 0x7FFF].okForInt())
{
// If it does not exist, return it as an identifier instead
return value & 0xFFFFu;
}
if(!IsComplexType<Value_t>::result
&& Functions[(value >> 16) & 0x7FFF].complexOnly())
{
// If it does not exist, return it as an identifier instead
return value & 0xFFFFu;
}
}
return value;
}
// Returns true if the entire string is a valid identifier
template<typename Value_t>
bool containsOnlyValidIdentifierChars(const std::string& name)
{
if(name.empty()) return false;
return readIdentifier<Value_t>(name.c_str()) == (unsigned) name.size();
}
// -----------------------------------------------------------------------
// Wrappers for strto... functions
// -----------------------------------------------------------------------
template<typename Value_t>
inline Value_t fp_parseLiteral(const char* str, char** endptr)
{
return std::strtod(str, endptr);
}
#if defined(FP_USE_STRTOLD) || defined(FP_SUPPORT_CPLUSPLUS11_MATH_FUNCS)
template<>
inline long double fp_parseLiteral<long double>(const char* str,
char** endptr)
{
using namespace std; // Just in case strtold() is not inside std::
return strtold(str, endptr);
}
#endif
#ifdef FP_SUPPORT_LONG_INT_TYPE
template<>
inline long fp_parseLiteral<long>(const char* str, char** endptr)
{
return std::strtol(str, endptr, 10);
}
#endif
#ifdef FP_SUPPORT_COMPLEX_NUMBERS
template<typename T>
inline std::complex<T> fp_parseComplexLiteral(const char* str,
char** endptr)
{
T result = fp_parseLiteral<T> (str,endptr);
const char* end = *endptr;
if( (*end == 'i' || *end == 'I')
&& !std::isalnum(end[1]) )
{
++*endptr;
return std::complex<T> (T(), result);
}
return std::complex<T> (result, T());
}
#endif
#ifdef FP_SUPPORT_COMPLEX_DOUBLE_TYPE
template<>
inline std::complex<double> fp_parseLiteral<std::complex<double> >
(const char* str, char** endptr)
{
return fp_parseComplexLiteral<double> (str,endptr);
}
#endif
#ifdef FP_SUPPORT_COMPLEX_FLOAT_TYPE
template<>
inline std::complex<float> fp_parseLiteral<std::complex<float> >
(const char* str, char** endptr)
{
return fp_parseComplexLiteral<float> (str,endptr);
}
#endif
#ifdef FP_SUPPORT_COMPLEX_LONG_DOUBLE_TYPE
template<>
inline std::complex<long double> fp_parseLiteral<std::complex<long double> >
(const char* str, char** endptr)
{
return fp_parseComplexLiteral<long double> (str,endptr);
}
#endif
// -----------------------------------------------------------------------
// Hexadecimal floating point literal parsing
// -----------------------------------------------------------------------
inline int testXdigit(unsigned c)
{
if((c-'0') < 10u) return c&15; // 0..9
if(((c|0x20)-'a') < 6u) return 9+(c&15); // A..F or a..f
return -1; // Not a hex digit
}
template<typename elem_t, unsigned n_limbs, unsigned limb_bits>
inline void addXdigit(elem_t* buffer, unsigned nibble)
{
for(unsigned p=0; p<n_limbs; ++p)
{
unsigned carry = unsigned( buffer[p] >> (elem_t)(limb_bits-4) );
buffer[p] = (buffer[p] << 4) | nibble;
nibble = carry;
}
}
template<typename Value_t>
Value_t parseHexLiteral(const char* str, char** endptr)
{
const unsigned bits_per_char = 8;
const int MantissaBits =
std::numeric_limits<Value_t>::radix == 2
? std::numeric_limits<Value_t>::digits
: (((sizeof(Value_t) * bits_per_char) &~ 3) - 4);
typedef unsigned long elem_t;
const int ExtraMantissaBits = 4 + ((MantissaBits+3)&~3); // Store one digit more for correct rounding
const unsigned limb_bits = sizeof(elem_t) * bits_per_char;
const unsigned n_limbs = (ExtraMantissaBits + limb_bits-1) / limb_bits;
elem_t mantissa_buffer[n_limbs] = { 0 };
int n_mantissa_bits = 0; // Track the number of bits
int exponent = 0; // The exponent that will be used to multiply the mantissa
// Read integer portion
while(true)
{
int xdigit = testXdigit(*str);
if(xdigit < 0) break;
addXdigit<elem_t,n_limbs,limb_bits> (mantissa_buffer, xdigit);
++str;
n_mantissa_bits += 4;
if(n_mantissa_bits >= ExtraMantissaBits)
{
// Exhausted the precision. Parse the rest (until exponent)
// normally but ignore the actual digits.
for(; testXdigit(*str) >= 0; ++str)
exponent += 4;
// Read but ignore decimals
if(*str == '.')
for(++str; testXdigit(*str) >= 0; ++str)
{}
goto read_exponent;
}
}
// Read decimals
if(*str == '.')
for(++str; ; )
{
int xdigit = testXdigit(*str);
if(xdigit < 0) break;
addXdigit<elem_t,n_limbs,limb_bits> (mantissa_buffer, xdigit);
++str;
exponent -= 4;
n_mantissa_bits += 4;
if(n_mantissa_bits >= ExtraMantissaBits)
{
// Exhausted the precision. Skip the rest
// of the decimals, until the exponent.
while(testXdigit(*str) >= 0)
++str;
break;
}
}
// Read exponent
read_exponent:
if(*str == 'p' || *str == 'P')
{
const char* str2 = str+1;
long p_exponent = strtol(str2, const_cast<char**> (&str2), 10);
if(str2 != str+1 && p_exponent == (long)(int)p_exponent)
{
exponent += (int)p_exponent;
str = str2;
}
}
if(endptr) *endptr = const_cast<char*> (str);
Value_t result = std::ldexp(Value_t(mantissa_buffer[0]), exponent);
for(unsigned p=1; p<n_limbs; ++p)
{
exponent += limb_bits;
result += ldexp(Value_t(mantissa_buffer[p]), exponent);
}
return result;
}
#ifdef FP_SUPPORT_LONG_INT_TYPE
template<>
long parseHexLiteral<long>(const char* str, char** endptr)
{
return std::strtol(str, endptr, 16);
}
#endif
#ifdef FP_SUPPORT_COMPLEX_DOUBLE_TYPE
template<>
std::complex<double>
parseHexLiteral<std::complex<double> >(const char* str, char** endptr)
{
return parseHexLiteral<double> (str, endptr);
}
#endif
#ifdef FP_SUPPORT_COMPLEX_FLOAT_TYPE
template<>
std::complex<float>
parseHexLiteral<std::complex<float> >(const char* str, char** endptr)
{
return parseHexLiteral<float> (str, endptr);
}
#endif
#ifdef FP_SUPPORT_COMPLEX_LONG_DOUBLE_TYPE
template<>
std::complex<long double>
parseHexLiteral<std::complex<long double> >(const char* str, char** endptr)
{
return parseHexLiteral<long double> (str, endptr);
}
#endif
}
//=========================================================================
// Utility functions
//=========================================================================
namespace
{
// -----------------------------------------------------------------------
// Add a new identifier to the specified identifier map
// -----------------------------------------------------------------------
// Return value will be false if the name already existed
template<typename Value_t>
bool addNewNameData(NamePtrsMap<Value_t>& namePtrs,
std::pair<NamePtr, NameData<Value_t> >& newName,
bool isVar)
{
typename NamePtrsMap<Value_t>::iterator nameIter =
namePtrs.lower_bound(newName.first);
if(nameIter != namePtrs.end() && newName.first == nameIter->first)
{
// redefining a var is not allowed.
if(isVar) return false;
// redefining other tokens is allowed, if the type stays the same.
if(nameIter->second.type != newName.second.type)
return false;
// update the data
nameIter->second = newName.second;
return true;
}
if(!isVar)
{
// Allocate a copy of the name (pointer stored in the map key)
// However, for VARIABLEs, the pointer points to VariableString,
// which is managed separately. Thusly, only done when !IsVar.
char* namebuf = new char[newName.first.nameLength];
memcpy(namebuf, newName.first.name, newName.first.nameLength);
newName.first.name = namebuf;
}
namePtrs.insert(nameIter, newName);
return true;
}
}
//=========================================================================
// Data struct implementation
//=========================================================================
template<typename Value_t>
FunctionParserBase<Value_t>::Data::Data():
mReferenceCounter(1),
mDelimiterChar(0),
mParseErrorType(NO_FUNCTION_PARSED_YET),
mEvalErrorType(0),
mUseDegreeConversion(false),
mErrorLocation(0),
mVariablesAmount(0),
mStackSize(0)
{}
template<typename Value_t>
FunctionParserBase<Value_t>::Data::Data(const Data& rhs):
mReferenceCounter(0),
mDelimiterChar(rhs.mDelimiterChar),
mParseErrorType(rhs.mParseErrorType),
mEvalErrorType(rhs.mEvalErrorType),
mUseDegreeConversion(rhs.mUseDegreeConversion),
mErrorLocation(rhs.mErrorLocation),
mVariablesAmount(rhs.mVariablesAmount),
mVariablesString(rhs.mVariablesString),
mNamePtrs(),
mFuncPtrs(rhs.mFuncPtrs),
mFuncParsers(rhs.mFuncParsers),
mByteCode(rhs.mByteCode),
mImmed(rhs.mImmed),
#ifndef FP_USE_THREAD_SAFE_EVAL
mStack(rhs.mStackSize),
#endif
mStackSize(rhs.mStackSize)
{
for(typename NamePtrsMap<Value_t>::const_iterator i = rhs.mNamePtrs.begin();
i != rhs.mNamePtrs.end();
++i)
{
if(i->second.type == NameData<Value_t>::VARIABLE)
{
const std::size_t variableStringOffset =
i->first.name - rhs.mVariablesString.c_str();
std::pair<NamePtr, NameData<Value_t> > tmp
(NamePtr(&mVariablesString[variableStringOffset],
i->first.nameLength),
i->second);
mNamePtrs.insert(mNamePtrs.end(), tmp);
}
else
{
std::pair<NamePtr, NameData<Value_t> > tmp
(NamePtr(new char[i->first.nameLength], i->first.nameLength),
i->second );
memcpy(const_cast<char*>(tmp.first.name), i->first.name,
tmp.first.nameLength);
mNamePtrs.insert(mNamePtrs.end(), tmp);
}
}
}
template<typename Value_t>
FunctionParserBase<Value_t>::Data::~Data()
{
for(typename NamePtrsMap<Value_t>::iterator i = mNamePtrs.begin();
i != mNamePtrs.end();
++i)
{
if(i->second.type != NameData<Value_t>::VARIABLE)
delete[] i->first.name;
}
}
template<typename Value_t>
void FunctionParserBase<Value_t>::incFuncWrapperRefCount
(FunctionWrapper* wrapper)
{
++wrapper->mReferenceCount;
}
template<typename Value_t>
unsigned FunctionParserBase<Value_t>::decFuncWrapperRefCount
(FunctionWrapper* wrapper)
{
return --wrapper->mReferenceCount;
}
template<typename Value_t>
FunctionParserBase<Value_t>::Data::FuncWrapperPtrData::FuncWrapperPtrData():
mRawFuncPtr(0), mFuncWrapperPtr(0), mParams(0)
{}
template<typename Value_t>
FunctionParserBase<Value_t>::Data::FuncWrapperPtrData::~FuncWrapperPtrData()
{
if(mFuncWrapperPtr &&
FunctionParserBase::decFuncWrapperRefCount(mFuncWrapperPtr) == 0)
delete mFuncWrapperPtr;
}
template<typename Value_t>
FunctionParserBase<Value_t>::Data::FuncWrapperPtrData::FuncWrapperPtrData
(const FuncWrapperPtrData& rhs):
mRawFuncPtr(rhs.mRawFuncPtr),
mFuncWrapperPtr(rhs.mFuncWrapperPtr),
mParams(rhs.mParams)
{
if(mFuncWrapperPtr)
FunctionParserBase::incFuncWrapperRefCount(mFuncWrapperPtr);
}
template<typename Value_t>
typename FunctionParserBase<Value_t>::Data::FuncWrapperPtrData&
FunctionParserBase<Value_t>::Data::FuncWrapperPtrData::operator=
(const FuncWrapperPtrData& rhs)
{
if(&rhs != this)
{
if(mFuncWrapperPtr &&
FunctionParserBase::decFuncWrapperRefCount(mFuncWrapperPtr) == 0)
delete mFuncWrapperPtr;
mRawFuncPtr = rhs.mRawFuncPtr;
mFuncWrapperPtr = rhs.mFuncWrapperPtr;
mParams = rhs.mParams;
if(mFuncWrapperPtr)
FunctionParserBase::incFuncWrapperRefCount(mFuncWrapperPtr);
}
return *this;
}
//=========================================================================
// FunctionParser constructors, destructor and assignment
//=========================================================================
template<typename Value_t>
FunctionParserBase<Value_t>::FunctionParserBase():
mData(new Data),
mStackPtr(0)
{
}
template<typename Value_t>
FunctionParserBase<Value_t>::~FunctionParserBase()
{
if(--(mData->mReferenceCounter) == 0)
delete mData;
}
template<typename Value_t>
FunctionParserBase<Value_t>::FunctionParserBase(const FunctionParserBase& cpy):
mData(cpy.mData),
mStackPtr(0)
{
++(mData->mReferenceCounter);
}
template<typename Value_t>
FunctionParserBase<Value_t>&
FunctionParserBase<Value_t>::operator=(const FunctionParserBase& cpy)
{
if(mData != cpy.mData)
{
if(--(mData->mReferenceCounter) == 0) delete mData;
mData = cpy.mData;
++(mData->mReferenceCounter);
}
return *this;
}
template<typename Value_t>
typename FunctionParserBase<Value_t>::Data*
FunctionParserBase<Value_t>::getParserData()
{
return mData;
}
template<typename Value_t>
void FunctionParserBase<Value_t>::setDelimiterChar(char c)
{
mData->mDelimiterChar = c;
}
//---------------------------------------------------------------------------
// Copy-on-write method
//---------------------------------------------------------------------------
template<typename Value_t>
void FunctionParserBase<Value_t>::CopyOnWrite()
{
if(mData->mReferenceCounter > 1)
{
Data* oldData = mData;
mData = new Data(*oldData);
--(oldData->mReferenceCounter);
mData->mReferenceCounter = 1;
}
}
template<typename Value_t>
void FunctionParserBase<Value_t>::ForceDeepCopy()
{
CopyOnWrite();
}
//=========================================================================
// Epsilon
//=========================================================================
template<typename Value_t>
Value_t FunctionParserBase<Value_t>::epsilon()
{
return Epsilon<Value_t>::value;
}
template<typename Value_t>
void FunctionParserBase<Value_t>::setEpsilon(Value_t value)
{
Epsilon<Value_t>::value = value;
}
//=========================================================================
// User-defined identifier addition functions
//=========================================================================
template<typename Value_t>
bool FunctionParserBase<Value_t>::AddConstant(const std::string& name,
Value_t value)
{
if(!containsOnlyValidIdentifierChars<Value_t>(name)) return false;
CopyOnWrite();
std::pair<NamePtr, NameData<Value_t> > newName
(NamePtr(name.data(), unsigned(name.size())),
NameData<Value_t>(NameData<Value_t>::CONSTANT, value));
return addNewNameData(mData->mNamePtrs, newName, false);
}
template<typename Value_t>
bool FunctionParserBase<Value_t>::AddUnit(const std::string& name,
Value_t value)
{
if(!containsOnlyValidIdentifierChars<Value_t>(name)) return false;
CopyOnWrite();
std::pair<NamePtr, NameData<Value_t> > newName
(NamePtr(name.data(), unsigned(name.size())),
NameData<Value_t>(NameData<Value_t>::UNIT, value));
return addNewNameData(mData->mNamePtrs, newName, false);
}
template<typename Value_t>
bool FunctionParserBase<Value_t>::AddFunction
(const std::string& name, FunctionPtr ptr, unsigned paramsAmount)
{
if(!containsOnlyValidIdentifierChars<Value_t>(name)) return false;
CopyOnWrite();
std::pair<NamePtr, NameData<Value_t> > newName
(NamePtr(name.data(), unsigned(name.size())),
NameData<Value_t>(NameData<Value_t>::FUNC_PTR,
unsigned(mData->mFuncPtrs.size())));
const bool success = addNewNameData(mData->mNamePtrs, newName, false);
if(success)
{
mData->mFuncPtrs.push_back(typename Data::FuncWrapperPtrData());
mData->mFuncPtrs.back().mRawFuncPtr = ptr;
mData->mFuncPtrs.back().mParams = paramsAmount;
}
return success;
}
template<typename Value_t>
bool FunctionParserBase<Value_t>::addFunctionWrapperPtr
(const std::string& name, FunctionWrapper* wrapper, unsigned paramsAmount)
{
if(!AddFunction(name, FunctionPtr(0), paramsAmount)) return false;
mData->mFuncPtrs.back().mFuncWrapperPtr = wrapper;
return true;
}
template<typename Value_t>
typename FunctionParserBase<Value_t>::FunctionWrapper*
FunctionParserBase<Value_t>::GetFunctionWrapper(const std::string& name)
{
CopyOnWrite();
NamePtr namePtr(name.data(), unsigned(name.size()));
typename NamePtrsMap<Value_t>::iterator nameIter =