-
Notifications
You must be signed in to change notification settings - Fork 0
/
muParserBase.cpp
1778 lines (1524 loc) · 64.3 KB
/
muParserBase.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
/*
__________
_____ __ __\______ \_____ _______ ______ ____ _______
/ \ | | \| ___/\__ \ \_ __ \/ ___/_/ __ \\_ __ \
| Y Y \| | /| | / __ \_| | \/\___ \ \ ___/ | | \/
|__|_| /|____/ |____| (____ /|__| /____ > \___ >|__|
\/ \/ \/ \/
Copyright (C) 2011 Ingo Berg
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.
*/
#include "muParserBase.h"
#include "muParserTemplateMagic.h"
//--- Standard includes ------------------------------------------------------------------------
#include <cassert>
#include <algorithm>
#include <cmath>
#include <memory>
#include <vector>
#include <deque>
#include <sstream>
#include <locale>
#ifdef MUP_USE_OPENMP
#include <omp.h>
#endif
using namespace std;
/** \file
\brief This file contains the basic implementation of the muparser engine.
*/
namespace mu
{
std::locale ParserBase::s_locale = std::locale(std::locale::classic(), new change_dec_sep<char_type>('.'));
bool ParserBase::g_DbgDumpCmdCode = false;
bool ParserBase::g_DbgDumpStack = false;
//------------------------------------------------------------------------------
/** \brief Identifiers for built in binary operators.
When defining custom binary operators with #AddOprt(...) make sure not to choose
names conflicting with these definitions.
*/
const char_type* ParserBase::c_DefaultOprt[] =
{
_T("<="), _T(">="), _T("!="),
_T("=="), _T("<"), _T(">"),
_T("+"), _T("-"), _T("*"),
_T("/"), _T("^"), _T("&&"),
_T("||"), _T("="), _T("("),
_T(")"), _T("?"), _T(":"), 0
};
//------------------------------------------------------------------------------
/** \brief Constructor.
\param a_szFormula the formula to interpret.
\throw ParserException if a_szFormula is null.
*/
ParserBase::ParserBase()
:m_pParseFormula(&ParserBase::ParseString)
,m_vRPN()
,m_vStringBuf()
,m_pTokenReader()
,m_FunDef()
,m_PostOprtDef()
,m_InfixOprtDef()
,m_OprtDef()
,m_ConstDef()
,m_StrVarDef()
,m_VarDef()
,m_bBuiltInOp(true)
,m_sNameChars()
,m_sOprtChars()
,m_sInfixOprtChars()
,m_nIfElseCounter(0)
,m_vStackBuffer()
,m_nFinalResultIdx(0)
{
InitTokenReader();
}
//---------------------------------------------------------------------------
/** \brief Copy constructor.
The parser can be safely copy constructed but the bytecode is reset during
copy construction.
*/
ParserBase::ParserBase(const ParserBase &a_Parser)
:m_pParseFormula(&ParserBase::ParseString)
,m_vRPN()
,m_vStringBuf()
,m_pTokenReader()
,m_FunDef()
,m_PostOprtDef()
,m_InfixOprtDef()
,m_OprtDef()
,m_ConstDef()
,m_StrVarDef()
,m_VarDef()
,m_bBuiltInOp(true)
,m_sNameChars()
,m_sOprtChars()
,m_sInfixOprtChars()
,m_nIfElseCounter(0)
{
m_pTokenReader.reset(new token_reader_type(this));
Assign(a_Parser);
}
//---------------------------------------------------------------------------
ParserBase::~ParserBase()
{}
//---------------------------------------------------------------------------
/** \brief Assignment operator.
Implemented by calling Assign(a_Parser). Self assignment is suppressed.
\param a_Parser Object to copy to this.
\return *this
\throw nothrow
*/
ParserBase& ParserBase::operator=(const ParserBase &a_Parser)
{
Assign(a_Parser);
return *this;
}
//---------------------------------------------------------------------------
/** \brief Copy state of a parser object to this.
Clears Variables and Functions of this parser.
Copies the states of all internal variables.
Resets parse function to string parse mode.
\param a_Parser the source object.
*/
void ParserBase::Assign(const ParserBase &a_Parser)
{
if (&a_Parser==this)
return;
// Don't copy bytecode instead cause the parser to create new bytecode
// by resetting the parse function.
ReInit();
m_ConstDef = a_Parser.m_ConstDef; // Copy user define constants
m_VarDef = a_Parser.m_VarDef; // Copy user defined variables
m_bBuiltInOp = a_Parser.m_bBuiltInOp;
m_vStringBuf = a_Parser.m_vStringBuf;
m_vStackBuffer = a_Parser.m_vStackBuffer;
m_nFinalResultIdx = a_Parser.m_nFinalResultIdx;
m_StrVarDef = a_Parser.m_StrVarDef;
m_vStringVarBuf = a_Parser.m_vStringVarBuf;
m_nIfElseCounter = a_Parser.m_nIfElseCounter;
m_pTokenReader.reset(a_Parser.m_pTokenReader->Clone(this));
// Copy function and operator callbacks
m_FunDef = a_Parser.m_FunDef; // Copy function definitions
m_PostOprtDef = a_Parser.m_PostOprtDef; // post value unary operators
m_InfixOprtDef = a_Parser.m_InfixOprtDef; // unary operators for infix notation
m_OprtDef = a_Parser.m_OprtDef; // binary operators
m_sNameChars = a_Parser.m_sNameChars;
m_sOprtChars = a_Parser.m_sOprtChars;
m_sInfixOprtChars = a_Parser.m_sInfixOprtChars;
}
//---------------------------------------------------------------------------
/** \brief Set the decimal separator.
\param cDecSep Decimal separator as a character value.
\sa SetThousandsSep
By default muparser uses the "C" locale. The decimal separator of this
locale is overwritten by the one provided here.
*/
void ParserBase::SetDecSep(char_type cDecSep)
{
char_type cThousandsSep = std::use_facet< change_dec_sep<char_type> >(s_locale).thousands_sep();
s_locale = std::locale(std::locale("C"), new change_dec_sep<char_type>(cDecSep, cThousandsSep));
}
//---------------------------------------------------------------------------
/** \brief Sets the thousands operator.
\param cThousandsSep The thousands separator as a character
\sa SetDecSep
By default muparser uses the "C" locale. The thousands separator of this
locale is overwritten by the one provided here.
*/
void ParserBase::SetThousandsSep(char_type cThousandsSep)
{
char_type cDecSep = std::use_facet< change_dec_sep<char_type> >(s_locale).decimal_point();
s_locale = std::locale(std::locale("C"), new change_dec_sep<char_type>(cDecSep, cThousandsSep));
}
//---------------------------------------------------------------------------
/** \brief Resets the locale.
The default locale used "." as decimal separator, no thousands separator and
"," as function argument separator.
*/
void ParserBase::ResetLocale()
{
s_locale = std::locale(std::locale("C"), new change_dec_sep<char_type>('.'));
SetArgSep(',');
}
//---------------------------------------------------------------------------
/** \brief Initialize the token reader.
Create new token reader object and submit pointers to function, operator,
constant and variable definitions.
\post m_pTokenReader.get()!=0
\throw nothrow
*/
void ParserBase::InitTokenReader()
{
m_pTokenReader.reset(new token_reader_type(this));
}
//---------------------------------------------------------------------------
/** \brief Reset parser to string parsing mode and clear internal buffers.
Clear bytecode, reset the token reader.
\throw nothrow
*/
void ParserBase::ReInit() const
{
m_pParseFormula = &ParserBase::ParseString;
m_vStringBuf.clear();
m_vRPN.clear();
m_pTokenReader->ReInit();
m_nIfElseCounter = 0;
}
//---------------------------------------------------------------------------
void ParserBase::OnDetectVar(string_type * /*pExpr*/, int & /*nStart*/, int & /*nEnd*/)
{}
//---------------------------------------------------------------------------
/** \brief Returns the version of muparser.
\param eInfo A flag indicating whether the full version info should be
returned or not.
Format is as follows: "MAJOR.MINOR (COMPILER_FLAGS)" The COMPILER_FLAGS
are returned only if eInfo==pviFULL.
*/
string_type ParserBase::GetVersion(EParserVersionInfo eInfo) const
{
stringstream_type ss;
ss << MUP_VERSION;
if (eInfo==pviFULL)
{
ss << _T(" (") << MUP_VERSION_DATE;
ss << std::dec << _T("; ") << sizeof(void*)*8 << _T("BIT");
#ifdef _DEBUG
ss << _T("; DEBUG");
#else
ss << _T("; RELEASE");
#endif
#ifdef _UNICODE
ss << _T("; UNICODE");
#else
#ifdef _MBCS
ss << _T("; MBCS");
#else
ss << _T("; ASCII");
#endif
#endif
#ifdef MUP_USE_OPENMP
ss << _T("; OPENMP");
//#else
// ss << _T("; NO_OPENMP");
#endif
#if defined(MUP_MATH_EXCEPTIONS)
ss << _T("; MATHEXC");
//#else
// ss << _T("; NO_MATHEXC");
#endif
ss << _T(")");
}
return ss.str();
}
//---------------------------------------------------------------------------
/** \brief Add a value parsing function.
When parsing an expression muParser tries to detect values in the expression
string using different valident callbacks. Thus it's possible to parse
for hex values, binary values and floating point values.
*/
void ParserBase::AddValIdent(identfun_type a_pCallback)
{
m_pTokenReader->AddValIdent(a_pCallback);
}
//---------------------------------------------------------------------------
/** \brief Set a function that can create variable pointer for unknown expression variables.
\param a_pFactory A pointer to the variable factory.
\param pUserData A user defined context pointer.
*/
void ParserBase::SetVarFactory(facfun_type a_pFactory, void *pUserData)
{
m_pTokenReader->SetVarCreator(a_pFactory, pUserData);
}
//---------------------------------------------------------------------------
/** \brief Add a function or operator callback to the parser. */
void ParserBase::AddCallback( const string_type &a_strName,
const ParserCallback &a_Callback,
funmap_type &a_Storage,
const char_type *a_szCharSet )
{
if (a_Callback.GetAddr()==0)
Error(ecINVALID_FUN_PTR);
const funmap_type *pFunMap = &a_Storage;
// Check for conflicting operator or function names
if ( pFunMap!=&m_FunDef && m_FunDef.find(a_strName)!=m_FunDef.end() )
Error(ecNAME_CONFLICT, -1, a_strName);
if ( pFunMap!=&m_PostOprtDef && m_PostOprtDef.find(a_strName)!=m_PostOprtDef.end() )
Error(ecNAME_CONFLICT, -1, a_strName);
if ( pFunMap!=&m_InfixOprtDef && pFunMap!=&m_OprtDef && m_InfixOprtDef.find(a_strName)!=m_InfixOprtDef.end() )
Error(ecNAME_CONFLICT, -1, a_strName);
if ( pFunMap!=&m_InfixOprtDef && pFunMap!=&m_OprtDef && m_OprtDef.find(a_strName)!=m_OprtDef.end() )
Error(ecNAME_CONFLICT, -1, a_strName);
CheckOprt(a_strName, a_Callback, a_szCharSet);
a_Storage[a_strName] = a_Callback;
ReInit();
}
//---------------------------------------------------------------------------
/** \brief Check if a name contains invalid characters.
\throw ParserException if the name contains invalid characters.
*/
void ParserBase::CheckOprt(const string_type &a_sName,
const ParserCallback &a_Callback,
const string_type &a_szCharSet) const
{
if ( !a_sName.length() ||
(a_sName.find_first_not_of(a_szCharSet)!=string_type::npos) ||
(a_sName[0]>='0' && a_sName[0]<='9'))
{
switch(a_Callback.GetCode())
{
case cmOPRT_POSTFIX: Error(ecINVALID_POSTFIX_IDENT, -1, a_sName);
case cmOPRT_INFIX: Error(ecINVALID_INFIX_IDENT, -1, a_sName);
default: Error(ecINVALID_NAME, -1, a_sName);
}
}
}
//---------------------------------------------------------------------------
/** \brief Check if a name contains invalid characters.
\throw ParserException if the name contains invalid characters.
*/
void ParserBase::CheckName(const string_type &a_sName,
const string_type &a_szCharSet) const
{
if ( !a_sName.length() ||
(a_sName.find_first_not_of(a_szCharSet)!=string_type::npos) ||
(a_sName[0]>='0' && a_sName[0]<='9'))
{
Error(ecINVALID_NAME);
}
}
//---------------------------------------------------------------------------
/** \brief Set the formula.
\param a_strFormula Formula as string_type
\throw ParserException in case of syntax errors.
Triggers first time calculation thus the creation of the bytecode and
scanning of used variables.
*/
void ParserBase::SetExpr(const string_type &a_sExpr)
{
// Check locale compatibility
std::locale loc;
if (m_pTokenReader->GetArgSep()==std::use_facet<numpunct<char_type> >(loc).decimal_point())
Error(ecLOCALE);
// <ibg> 20060222: Bugfix for Borland-Kylix:
// adding a space to the expression will keep Borlands KYLIX from going wild
// when calling tellg on a stringstream created from the expression after
// reading a value at the end of an expression. (mu::Parser::IsVal function)
// (tellg returns -1 otherwise causing the parser to ignore the value)
string_type sBuf(a_sExpr + _T(" ") );
m_pTokenReader->SetFormula(sBuf);
ReInit();
}
//---------------------------------------------------------------------------
/** \brief Get the default symbols used for the built in operators.
\sa c_DefaultOprt
*/
const char_type** ParserBase::GetOprtDef() const
{
return (const char_type **)(&c_DefaultOprt[0]);
}
//---------------------------------------------------------------------------
/** \brief Define the set of valid characters to be used in names of
functions, variables, constants.
*/
void ParserBase::DefineNameChars(const char_type *a_szCharset)
{
m_sNameChars = a_szCharset;
}
//---------------------------------------------------------------------------
/** \brief Define the set of valid characters to be used in names of
binary operators and postfix operators.
*/
void ParserBase::DefineOprtChars(const char_type *a_szCharset)
{
m_sOprtChars = a_szCharset;
}
//---------------------------------------------------------------------------
/** \brief Define the set of valid characters to be used in names of
infix operators.
*/
void ParserBase::DefineInfixOprtChars(const char_type *a_szCharset)
{
m_sInfixOprtChars = a_szCharset;
}
//---------------------------------------------------------------------------
/** \brief Virtual function that defines the characters allowed in name identifiers.
\sa #ValidOprtChars, #ValidPrefixOprtChars
*/
const char_type* ParserBase::ValidNameChars() const
{
assert(m_sNameChars.size());
return m_sNameChars.c_str();
}
//---------------------------------------------------------------------------
/** \brief Virtual function that defines the characters allowed in operator definitions.
\sa #ValidNameChars, #ValidPrefixOprtChars
*/
const char_type* ParserBase::ValidOprtChars() const
{
assert(m_sOprtChars.size());
return m_sOprtChars.c_str();
}
//---------------------------------------------------------------------------
/** \brief Virtual function that defines the characters allowed in infix operator definitions.
\sa #ValidNameChars, #ValidOprtChars
*/
const char_type* ParserBase::ValidInfixOprtChars() const
{
assert(m_sInfixOprtChars.size());
return m_sInfixOprtChars.c_str();
}
//---------------------------------------------------------------------------
/** \brief Add a user defined operator.
\post Will reset the Parser to string parsing mode.
*/
void ParserBase::DefinePostfixOprt(const string_type &a_sName,
fun_type1 a_pFun,
bool a_bAllowOpt)
{
AddCallback(a_sName,
ParserCallback(a_pFun, a_bAllowOpt, prPOSTFIX, cmOPRT_POSTFIX),
m_PostOprtDef,
ValidOprtChars() );
}
//---------------------------------------------------------------------------
/** \brief Initialize user defined functions.
Calls the virtual functions InitFun(), InitConst() and InitOprt().
*/
void ParserBase::Init()
{
InitCharSets();
InitFun();
InitConst();
InitOprt();
}
//---------------------------------------------------------------------------
/** \brief Add a user defined operator.
\post Will reset the Parser to string parsing mode.
\param [in] a_sName operator Identifier
\param [in] a_pFun Operator callback function
\param [in] a_iPrec Operator Precedence (default=prSIGN)
\param [in] a_bAllowOpt True if operator is volatile (default=false)
\sa EPrec
*/
void ParserBase::DefineInfixOprt(const string_type &a_sName,
fun_type1 a_pFun,
int a_iPrec,
bool a_bAllowOpt)
{
AddCallback(a_sName,
ParserCallback(a_pFun, a_bAllowOpt, a_iPrec, cmOPRT_INFIX),
m_InfixOprtDef,
ValidInfixOprtChars() );
}
//---------------------------------------------------------------------------
/** \brief Define a binary operator.
\param [in] a_sName The identifier of the operator.
\param [in] a_pFun Pointer to the callback function.
\param [in] a_iPrec Precedence of the operator.
\param [in] a_eAssociativity The associativity of the operator.
\param [in] a_bAllowOpt If this is true the operator may be optimized away.
Adds a new Binary operator the the parser instance.
*/
void ParserBase::DefineOprt( const string_type &a_sName,
fun_type2 a_pFun,
unsigned a_iPrec,
EOprtAssociativity a_eAssociativity,
bool a_bAllowOpt )
{
// Check for conflicts with built in operator names
for (int i=0; m_bBuiltInOp && i<cmENDIF; ++i)
if (a_sName == string_type(c_DefaultOprt[i]))
Error(ecBUILTIN_OVERLOAD, -1, a_sName);
AddCallback(a_sName,
ParserCallback(a_pFun, a_bAllowOpt, a_iPrec, a_eAssociativity),
m_OprtDef,
ValidOprtChars() );
}
//---------------------------------------------------------------------------
/** \brief Define a new string constant.
\param [in] a_strName The name of the constant.
\param [in] a_strVal the value of the constant.
*/
void ParserBase::DefineStrConst(const string_type &a_strName, const string_type &a_strVal)
{
// Test if a constant with that names already exists
if (m_StrVarDef.find(a_strName)!=m_StrVarDef.end())
Error(ecNAME_CONFLICT);
CheckName(a_strName, ValidNameChars());
m_vStringVarBuf.push_back(a_strVal); // Store variable string in internal buffer
m_StrVarDef[a_strName] = m_vStringVarBuf.size()-1; // bind buffer index to variable name
ReInit();
}
//---------------------------------------------------------------------------
/** \brief Add a user defined variable.
\param [in] a_sName the variable name
\param [in] a_pVar A pointer to the variable value.
\post Will reset the Parser to string parsing mode.
\throw ParserException in case the name contains invalid signs or a_pVar is NULL.
*/
void ParserBase::DefineVar(const string_type &a_sName, value_type *a_pVar)
{
if (a_pVar==0)
Error(ecINVALID_VAR_PTR);
// Test if a constant with that names already exists
if (m_ConstDef.find(a_sName)!=m_ConstDef.end())
Error(ecNAME_CONFLICT);
CheckName(a_sName, ValidNameChars());
m_VarDef[a_sName] = a_pVar;
ReInit();
}
//---------------------------------------------------------------------------
/** \brief Add a user defined constant.
\param [in] a_sName The name of the constant.
\param [in] a_fVal the value of the constant.
\post Will reset the Parser to string parsing mode.
\throw ParserException in case the name contains invalid signs.
*/
void ParserBase::DefineConst(const string_type &a_sName, value_type a_fVal)
{
CheckName(a_sName, ValidNameChars());
m_ConstDef[a_sName] = a_fVal;
ReInit();
}
//---------------------------------------------------------------------------
/** \brief Get operator priority.
\throw ParserException if a_Oprt is no operator code
*/
int ParserBase::GetOprtPrecedence(const token_type &a_Tok) const
{
switch (a_Tok.GetCode())
{
// built in operators
case cmEND: return -5;
case cmARG_SEP: return -4;
case cmASSIGN: return -1;
case cmELSE:
case cmIF: return 0;
case cmLAND: return prLAND;
case cmLOR: return prLOR;
case cmLT:
case cmGT:
case cmLE:
case cmGE:
case cmNEQ:
case cmEQ: return prCMP;
case cmADD:
case cmSUB: return prADD_SUB;
case cmMUL:
case cmDIV: return prMUL_DIV;
case cmPOW: return prPOW;
// user defined binary operators
case cmOPRT_INFIX:
case cmOPRT_BIN: return a_Tok.GetPri();
default: Error(ecINTERNAL_ERROR, 5);
return 999;
}
}
//---------------------------------------------------------------------------
/** \brief Get operator priority.
\throw ParserException if a_Oprt is no operator code
*/
EOprtAssociativity ParserBase::GetOprtAssociativity(const token_type &a_Tok) const
{
switch (a_Tok.GetCode())
{
case cmASSIGN:
case cmLAND:
case cmLOR:
case cmLT:
case cmGT:
case cmLE:
case cmGE:
case cmNEQ:
case cmEQ:
case cmADD:
case cmSUB:
case cmMUL:
case cmDIV: return oaLEFT;
case cmPOW: return oaRIGHT;
case cmOPRT_BIN: return a_Tok.GetAssociativity();
default: return oaNONE;
}
}
//---------------------------------------------------------------------------
/** \brief Return a map containing the used variables only. */
const varmap_type& ParserBase::GetUsedVar() const
{
try
{
m_pTokenReader->IgnoreUndefVar(true);
CreateRPN(); // try to create bytecode, but don't use it for any further calculations since it
// may contain references to nonexisting variables.
m_pParseFormula = &ParserBase::ParseString;
m_pTokenReader->IgnoreUndefVar(false);
}
catch(exception_type & /*e*/)
{
// Make sure to stay in string parse mode, dont call ReInit()
// because it deletes the array with the used variables
m_pParseFormula = &ParserBase::ParseString;
m_pTokenReader->IgnoreUndefVar(false);
throw;
}
return m_pTokenReader->GetUsedVar();
}
//---------------------------------------------------------------------------
/** \brief Return a map containing the used variables only. */
const varmap_type& ParserBase::GetVar() const
{
return m_VarDef;
}
//---------------------------------------------------------------------------
/** \brief Return a map containing all parser constants. */
const valmap_type& ParserBase::GetConst() const
{
return m_ConstDef;
}
//---------------------------------------------------------------------------
/** \brief Return prototypes of all parser functions.
\return #m_FunDef
\sa FunProt
\throw nothrow
The return type is a map of the public type #funmap_type containing the prototype
definitions for all numerical parser functions. String functions are not part of
this map. The Prototype definition is encapsulated in objects of the class FunProt
one per parser function each associated with function names via a map construct.
*/
const funmap_type& ParserBase::GetFunDef() const
{
return m_FunDef;
}
//---------------------------------------------------------------------------
/** \brief Retrieve the formula. */
const string_type& ParserBase::GetExpr() const
{
return m_pTokenReader->GetExpr();
}
//---------------------------------------------------------------------------
/** \brief Execute a function that takes a single string argument.
\param a_FunTok Function token.
\throw exception_type If the function token is not a string function
*/
ParserBase::token_type ParserBase::ApplyStrFunc(const token_type &a_FunTok,
const std::vector<token_type> &a_vArg) const
{
if (a_vArg.back().GetCode()!=cmSTRING)
Error(ecSTRING_EXPECTED, m_pTokenReader->GetPos(), a_FunTok.GetAsString());
token_type valTok;
generic_fun_type pFunc = a_FunTok.GetFuncAddr();
assert(pFunc);
try
{
// Check function arguments; write dummy value into valtok to represent the result
switch(a_FunTok.GetArgCount())
{
case 0: valTok.SetVal(1); a_vArg[0].GetAsString(); break;
case 1: valTok.SetVal(1); a_vArg[1].GetAsString(); a_vArg[0].GetVal(); break;
case 2: valTok.SetVal(1); a_vArg[2].GetAsString(); a_vArg[1].GetVal(); a_vArg[0].GetVal(); break;
default: Error(ecINTERNAL_ERROR);
}
}
catch(ParserError& )
{
Error(ecVAL_EXPECTED, m_pTokenReader->GetPos(), a_FunTok.GetAsString());
}
// string functions won't be optimized
m_vRPN.AddStrFun(pFunc, a_FunTok.GetArgCount(), a_vArg.back().GetIdx());
// Push dummy value representing the function result to the stack
return valTok;
}
//---------------------------------------------------------------------------
/** \brief Apply a function token.
\param iArgCount Number of Arguments actually gathered used only for multiarg functions.
\post The result is pushed to the value stack
\post The function token is removed from the stack
\throw exception_type if Argument count does not match function requirements.
*/
void ParserBase::ApplyFunc( ParserStack<token_type> &a_stOpt,
ParserStack<token_type> &a_stVal,
int a_iArgCount) const
{
assert(m_pTokenReader.get());
// Operator stack empty or does not contain tokens with callback functions
if (a_stOpt.empty() || a_stOpt.top().GetFuncAddr()==0 )
return;
token_type funTok = a_stOpt.pop();
assert(funTok.GetFuncAddr());
// Binary operators must rely on their internal operator number
// since counting of operators relies on commas for function arguments
// binary operators do not have commas in their expression
int iArgCount = (funTok.GetCode()==cmOPRT_BIN) ? funTok.GetArgCount() : a_iArgCount;
// determine how many parameters the function needs. To remember iArgCount includes the
// string parameter whilst GetArgCount() counts only numeric parameters.
int iArgRequired = funTok.GetArgCount() + ((funTok.GetType()==tpSTR) ? 1 : 0);
// Thats the number of numerical parameters
int iArgNumerical = iArgCount - ((funTok.GetType()==tpSTR) ? 1 : 0);
if (funTok.GetCode()==cmFUNC_STR && iArgCount-iArgNumerical>1)
Error(ecINTERNAL_ERROR);
if (funTok.GetArgCount()>=0 && iArgCount>iArgRequired)
Error(ecTOO_MANY_PARAMS, m_pTokenReader->GetPos()-1, funTok.GetAsString());
if (funTok.GetCode()!=cmOPRT_BIN && iArgCount<iArgRequired )
Error(ecTOO_FEW_PARAMS, m_pTokenReader->GetPos()-1, funTok.GetAsString());
if (funTok.GetCode()==cmFUNC_STR && iArgCount>iArgRequired )
Error(ecTOO_MANY_PARAMS, m_pTokenReader->GetPos()-1, funTok.GetAsString());
// Collect the numeric function arguments from the value stack and store them
// in a vector
std::vector<token_type> stArg;
for (int i=0; i<iArgNumerical; ++i)
{
stArg.push_back( a_stVal.pop() );
if ( stArg.back().GetType()==tpSTR && funTok.GetType()!=tpSTR )
Error(ecVAL_EXPECTED, m_pTokenReader->GetPos(), funTok.GetAsString());
}
switch(funTok.GetCode())
{
case cmFUNC_STR:
stArg.push_back(a_stVal.pop());
if ( stArg.back().GetType()==tpSTR && funTok.GetType()!=tpSTR )
Error(ecVAL_EXPECTED, m_pTokenReader->GetPos(), funTok.GetAsString());
ApplyStrFunc(funTok, stArg);
break;
case cmFUNC_BULK:
m_vRPN.AddBulkFun(funTok.GetFuncAddr(), (int)stArg.size());
break;
case cmOPRT_BIN:
case cmOPRT_POSTFIX:
case cmOPRT_INFIX:
case cmFUNC:
if (funTok.GetArgCount()==-1 && iArgCount==0)
Error(ecTOO_FEW_PARAMS, m_pTokenReader->GetPos(), funTok.GetAsString());
m_vRPN.AddFun(funTok.GetFuncAddr(), (funTok.GetArgCount()==-1) ? -iArgNumerical : iArgNumerical);
break;
}
// Push dummy value representing the function result to the stack
token_type token;
token.SetVal(1);
a_stVal.push(token);
}
//---------------------------------------------------------------------------
void ParserBase::ApplyIfElse(ParserStack<token_type> &a_stOpt,
ParserStack<token_type> &a_stVal) const
{
// Check if there is an if Else clause to be calculated
while (a_stOpt.size() && a_stOpt.top().GetCode()==cmELSE)
{
token_type opElse = a_stOpt.pop();
MUP_ASSERT(a_stOpt.size()>0);
// Take the value associated with the else branch from the value stack
token_type vVal2 = a_stVal.pop();
MUP_ASSERT(a_stOpt.size()>0);
MUP_ASSERT(a_stVal.size()>=2);
// it then else is a ternary operator Pop all three values from the value s
// tack and just return the right value
token_type vVal1 = a_stVal.pop();
token_type vExpr = a_stVal.pop();
a_stVal.push( (vExpr.GetVal()!=0) ? vVal1 : vVal2);
token_type opIf = a_stOpt.pop();
MUP_ASSERT(opElse.GetCode()==cmELSE);
MUP_ASSERT(opIf.GetCode()==cmIF);
m_vRPN.AddIfElse(cmENDIF);
} // while pending if-else-clause found
}
//---------------------------------------------------------------------------
/** \brief Performs the necessary steps to write code for
the execution of binary operators into the bytecode.
*/
void ParserBase::ApplyBinOprt(ParserStack<token_type> &a_stOpt,
ParserStack<token_type> &a_stVal) const
{
// is it a user defined binary operator?
if (a_stOpt.top().GetCode()==cmOPRT_BIN)
{
ApplyFunc(a_stOpt, a_stVal, 2);
}
else
{
MUP_ASSERT(a_stVal.size()>=2);
token_type valTok1 = a_stVal.pop(),
valTok2 = a_stVal.pop(),
optTok = a_stOpt.pop(),
resTok;
if ( valTok1.GetType()!=valTok2.GetType() ||
(valTok1.GetType()==tpSTR && valTok2.GetType()==tpSTR) )
Error(ecOPRT_TYPE_CONFLICT, m_pTokenReader->GetPos(), optTok.GetAsString());
if (optTok.GetCode()==cmASSIGN)
{
if (valTok2.GetCode()!=cmVAR)
Error(ecUNEXPECTED_OPERATOR, -1, _T("="));
m_vRPN.AddAssignOp(valTok2.GetVar());
}
else
m_vRPN.AddOp(optTok.GetCode());
resTok.SetVal(1);
a_stVal.push(resTok);
}
}
//---------------------------------------------------------------------------
/** \brief Apply a binary operator.
\param a_stOpt The operator stack
\param a_stVal The value stack
*/
void ParserBase::ApplyRemainingOprt(ParserStack<token_type> &stOpt,
ParserStack<token_type> &stVal) const
{
while (stOpt.size() &&
stOpt.top().GetCode() != cmBO &&
stOpt.top().GetCode() != cmIF)
{
token_type tok = stOpt.top();
switch (tok.GetCode())
{
case cmOPRT_INFIX:
case cmOPRT_BIN:
case cmLE:
case cmGE:
case cmNEQ:
case cmEQ:
case cmLT:
case cmGT:
case cmADD:
case cmSUB:
case cmMUL:
case cmDIV:
case cmPOW:
case cmLAND:
case cmLOR:
case cmASSIGN:
if (stOpt.top().GetCode()==cmOPRT_INFIX)
ApplyFunc(stOpt, stVal, 1);
else
ApplyBinOprt(stOpt, stVal);
break;
case cmELSE:
ApplyIfElse(stOpt, stVal);
break;
default:
Error(ecINTERNAL_ERROR);
}
}
}
//---------------------------------------------------------------------------
/** \brief Parse the command code.
\sa ParseString(...)
Command code contains precalculated stack positions of the values and the
associated operators. The Stack is filled beginning from index one the
value at index zero is not used at all.
*/
value_type ParserBase::ParseCmdCode() const
{
return ParseCmdCodeBulk(0, 0);
}
//---------------------------------------------------------------------------