Newer
Older
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
#include <valarray>
#include <sstream>
#include "ctokenizer.h"
using namespace std;
namespace pictcli_constraints
{
//
// handled by parseConstraint()
//
#define TEXT_TokenKeywordIf L"IF"
#define TEXT_TokenKeywordThen L"THEN"
#define TEXT_TokenKeywordElse L"ELSE"
//
// handled by getValueSet()
//
#define TEXT_TokenValueSetOpen L"{"
#define TEXT_TokenValueSetSeparator L","
#define TEXT_TokenValueSetClose L"}"
//
// handled by getParameterName()
//
// defined in cp.h as it's used by csolver.cpp
#define TEXT_TokenParameterNameOpen L"["
#define TEXT_TokenParameterNameClose L"]"
//
// handled by parseCondition() and getFunction()
//
#define TEXT_TokenParenthesisOpen L"("
#define TEXT_TokenParenthesisClose L")"
//
// handled by getFunction()
//
#define TEXT_FunctionIsNegativeParam L"ISNEGATIVE"
#define TEXT_FunctionIsPositiveParam L"ISPOSITIVE"
//
// handled by parseTerm()
//
#define TEXT_TokenQuotes L"\""
//
// handled by getRelation()
//
#define TEXT_TokenRelationEQ L"="
#define TEXT_TokenRelationNE L"<>"
#define TEXT_TokenRelationLT L"<"
#define TEXT_TokenRelationLE L"<="
#define TEXT_TokenRelationGT L">"
#define TEXT_TokenRelationGE L">="
#define TEXT_TokenRelationIN L"IN"
#define TEXT_TokenRelationLIKE L"LIKE"
//
// handled by getLogicalOper()
//
#define TEXT_TokenLogicalOperAND L"AND"
#define TEXT_TokenLogicalOperOR L"OR"
//
// not handled by any function because of grammar; used directly
//
#define TEXT_TokenLogicalOperNOT L"NOT"
//
// Special characters recognized within a string
//
#define TEXT_SpecialCharMarker L'\\'
//
// create an array of special characters, then populate valarray with it
//
const wchar_t SpecialCharacters[] = { TEXT_SpecialCharMarker, L'"', L']' };
//
//
//
void ConstraintsTokenizer::Tokenize()
{
_tokenLists.clear();
while( _currentPosition < _constraintsText.end() )
{
CTokenList tokenList;
parseConstraint( tokenList );
_tokenLists.push_back( tokenList );
skipWhiteChars();
}
}
//
//
//
void ConstraintsTokenizer::cleanUpTokenLists()
{
for( auto & tokenList : _tokenLists )
for( auto & token : tokenList )
delete( token );
}
//
// Parses a constraint:
//
// constraint ::= IF <clause> THEN <term>;
// IF <clause> THEN <term> ELSE <term>;
// <parameter_name> <relation> <parameter_name>;
//
void ConstraintsTokenizer::parseConstraint( IN OUT CTokenList& tokens )
{
skipWhiteChars();
// save position in case a new token is created
wstring::iterator position = _currentPosition;
// IF <clause> THEN <clause> ELSE <clause>
// <clause>
if ( isNextSubstring( wstring(TEXT_TokenKeywordIf)) )
{
CToken* tokenKeywordIf = new CToken( TokenType_KeywordIf, position );
tokens.push_back( tokenKeywordIf );
skipWhiteChars();
parseClause( tokens );
skipWhiteChars();
position = _currentPosition;
if ( isNextSubstring( charArrToStr( TEXT_TokenKeywordThen )))
{
CToken* tokenKeywordThen = new CToken( TokenType_KeywordThen, position );
tokens.push_back( tokenKeywordThen );
}
else
{
throw CSyntaxError( SyntaxErrType_NoKeywordThen, _currentPosition );
}
}
// evaluate the THEN part
parseClause( tokens );
// evaluate the ELSE part
skipWhiteChars();
position = _currentPosition;
if ( isNextSubstring( charArrToStr( TEXT_TokenKeywordElse )))
{
CToken* tokenKeywordElse = new CToken( TokenType_KeywordElse, position );
tokens.push_back( tokenKeywordElse );
parseClause( tokens );
}
// all forms of contraints should end with a termination marker
skipWhiteChars();
position = _currentPosition;
if ( ! isNextSubstring ( charArrToStr( TEXT_TokenConstraintEnd )))
{
throw CSyntaxError( SyntaxErrType_NoConstraintEnd, _currentPosition );
}
// some functions are like macros so do the expansions on the token list
doPostParseExpansions( tokens );
}
//
// Parses a clause:
//
// clause ::= <condition>
// <condition> <logical_operator> <clause>
//
void ConstraintsTokenizer::parseClause( IN OUT CTokenList& tokens )
{
skipWhiteChars();
parseCondition( tokens );
// getLogicalOper() may change the current position so preserve it for token creation
skipWhiteChars();
wstring::iterator position = _currentPosition;
LogicalOper logicalOper = getLogicalOper();
if ( LogicalOper_Unknown != logicalOper )
{
CToken* token = new CToken( logicalOper, position );
tokens.push_back( token );
skipWhiteChars();
parseClause( tokens );
}
}
//
// Parses a condition:
//
// condition ::= <term>
// (<clause>)
// NOT <clause>
//
void ConstraintsTokenizer::parseCondition( IN OUT CTokenList& tokens )
{
skipWhiteChars();
wstring::iterator position = _currentPosition;
// (<clause>)
if ( isNextSubstring( charArrToStr( TEXT_TokenParenthesisOpen )))
{
CToken* token = new CToken( TokenType_ParenthesisOpen, position );;
tokens.push_back( token );
skipWhiteChars();
parseClause( tokens );
skipWhiteChars();
position = _currentPosition;
if ( isNextSubstring( charArrToStr( TEXT_TokenParenthesisClose )))
{
token = new CToken( TokenType_ParenthesisClose, position );
tokens.push_back( token );
}
else
{
throw CSyntaxError( SyntaxErrType_NoEndParenthesis, _currentPosition );
}
}
// NOT <clause>
else if ( isNextSubstring( charArrToStr( TEXT_TokenLogicalOperNOT )))
{
CToken* token = new CToken( LogicalOper_NOT, position );
tokens.push_back( token );
skipWhiteChars();
parseClause( tokens );
}
// <term>
else
{
parseTerm( tokens );
}
}
//
// Parses a term:
//
// term ::= <parameter_name> <relation> <value>
// <parameter_name> LIKE <string>
// <parameter_name> IN {<value_set>}
// <parameter_name> <relation> <parameter_name>
// {functions on term level}
//
void ConstraintsTokenizer::parseTerm( IN OUT CTokenList& tokens )
{
skipWhiteChars();
wstring::iterator position = _currentPosition;
// check whether it's one of the functions
CFunction *function = getFunction();
if( NULL != function )
{
CToken* token;
try
{
token = new CToken( function, position );
}
catch( ... )
{
delete( function );
throw;
}
tokens.push_back( token );
}
// if not, parse anything that starts with para_name
else
{
wstring paramName = getParameterName();
CParameters::iterator found = _model.findParamByName( paramName );
CParameter* param = NULL;
if ( found != _model.Parameters.end() )
{
param = &*found;
}
skipWhiteChars();
Relation relation = getRelation();
skipWhiteChars();
CTerm* term = NULL;
switch( relation )
{
case Relation_IN:
case Relation_NOT_IN:
{
CValueSet* valueSet = new CValueSet;
if ( ! isNextSubstring( charArrToStr( TEXT_TokenValueSetOpen )))
{
throw CSyntaxError( SyntaxErrType_NoValueSetOpen, _currentPosition );
}
try
{
getValueSet( *valueSet );
}
catch( ... )
{
delete( valueSet );
throw;
}
skipWhiteChars();
if ( ! isNextSubstring( charArrToStr( TEXT_TokenValueSetClose )))
{
throw CSyntaxError( SyntaxErrType_NoValueSetClose, _currentPosition );
}
// raw text of a term
wstring rawText;
rawText.assign( position, _currentPosition );
try
{
term = new CTerm( param, relation, SyntaxTermDataType_ValueSet, valueSet, rawText );
}
catch( ... )
{
delete( valueSet );
throw;
}
break;
}
// At this point the relation LIKE is treated as an ordinary relation
// despite the fact it can only have a string as an argument on
// the right-side. It will be verified later during parsing.
default:
{
if ( isNextSubstring( charArrToStr( TEXT_TokenParameterNameOpen ), true ))
{
wstring paramName2 = getParameterName();
//
// look up parameters by their names and return references
//
CParameter *param2 = NULL;
found = _model.findParamByName( paramName2 );
if ( found != _model.Parameters.end() )
{
param2 = &*found;
}
wstring rawText;
rawText.assign( position, _currentPosition );
term = new CTerm( param, relation, SyntaxTermDataType_ParameterName, param2, rawText );
}
else
{
CValue* value = getValue();
// raw text of a term
wstring rawText;
rawText.assign( position, _currentPosition );
try
{
term = new CTerm( param, relation, SyntaxTermDataType_Value, value, rawText );
}
catch( ... )
{
delete( value );
throw;
}
}
break;
}
}
// now create token of type 'term'; this token has data
CToken* token;
try
{
token = new CToken( term, position );
}
catch( ... )
{
delete( term );
throw;
}
tokens.push_back( token );
}
}
//
// Parses a function
//
// <term> ::= IsNegative(<parameter_name>)
//
// Returns a CFunction object if in fact a function was parsed
// or NULL otherwise
//
CFunction *ConstraintsTokenizer::getFunction()
{
skipWhiteChars();
wstring::iterator position = _currentPosition;
FunctionType type = FunctionTypeUnknown;
if ( isNextSubstring( charArrToStr( TEXT_FunctionIsNegativeParam )))
{
type = FunctionTypeIsNegativeParam;
}
else if ( isNextSubstring( charArrToStr( TEXT_FunctionIsPositiveParam )))
{
type = FunctionTypeIsPositiveParam;
}
else
{
return NULL;
}
// opening bracket
if ( ! isNextSubstring( charArrToStr( TEXT_TokenParenthesisOpen )))
{
throw CSyntaxError( SyntaxErrType_FunctionNoParenthesisOpen, _currentPosition );
}
// get the parameter name
skipWhiteChars();
wstring paramName = getString( charArrToStr( TEXT_TokenParenthesisClose ));
CParameters::iterator found = _model.findParamByName( paramName );
CParameter* param = NULL;
if ( found != _model.Parameters.end() )
{
param = &*found;
}
if ( ! isNextSubstring( charArrToStr( TEXT_TokenParenthesisClose )))
{
throw CSyntaxError( SyntaxErrType_FunctionNoParenthesisClose, _currentPosition );
}
// now create a CFunction and return it
wstring rawText;
rawText.assign( position, _currentPosition );
CFunction* function = new CFunction( type, FunctionDataType_Parameter, param, paramName, rawText );
return( function );
}
//
// Returns a CValue.
//
// Note: allocates memory, caller is supposed to free it
//
CValue* ConstraintsTokenizer::getValue()
{
CValue* value;
// value is either string or number,
// a string always begins with quotes so check for it first
if ( isNextSubstring( charArrToStr( TEXT_TokenQuotes )))
{
wstring text;
text = getString( charArrToStr( TEXT_TokenQuotes ));
if (! isNextSubstring( charArrToStr( TEXT_TokenQuotes )))
{
throw CSyntaxError( SyntaxErrType_UnexpectedEndOfString, _currentPosition );
}
value = new CValue( text );
}
else
{
double number = getNumber();
value = new CValue( number );
}
return( value );
}
//
// Parses a valueset
//
// value_set ::= <value>
// <value>,<value_set>
//
void ConstraintsTokenizer::getValueSet( OUT CValueSet& valueSet )
{
skipWhiteChars();
CValue* value = getValue();
valueSet.push_back( *value );
delete( value );
skipWhiteChars();
if ( isNextSubstring( charArrToStr( TEXT_TokenValueSetSeparator )))
{
skipWhiteChars();
getValueSet( valueSet );
}
}
//
// Returns the next relation; order of comparisons is important
//
Relation ConstraintsTokenizer::getRelation()
{
if ( isNextSubstring( charArrToStr( TEXT_TokenRelationEQ ))) return ( Relation_EQ );
else if( isNextSubstring( charArrToStr( TEXT_TokenRelationNE ))) return ( Relation_NE );
else if( isNextSubstring( charArrToStr( TEXT_TokenRelationLE ))) return ( Relation_LE );
else if( isNextSubstring( charArrToStr( TEXT_TokenRelationGE ))) return ( Relation_GE );
else if( isNextSubstring( charArrToStr( TEXT_TokenRelationGT ))) return ( Relation_GT );
else if( isNextSubstring( charArrToStr( TEXT_TokenRelationLT ))) return ( Relation_LT );
else if( isNextSubstring( charArrToStr( TEXT_TokenRelationIN ))) return ( Relation_IN );
else if( isNextSubstring( charArrToStr( TEXT_TokenRelationLIKE ))) return ( Relation_LIKE );
else if( isNextSubstring( charArrToStr( TEXT_TokenLogicalOperNOT )))
{
skipWhiteChars();
if ( isNextSubstring( charArrToStr( TEXT_TokenRelationIN ))) return ( Relation_NOT_IN );
else if( isNextSubstring( charArrToStr( TEXT_TokenRelationLIKE ))) return ( Relation_NOT_LIKE );
else throw CSyntaxError( SyntaxErrType_UnknownRelation, _currentPosition );
}
else throw CSyntaxError( SyntaxErrType_UnknownRelation, _currentPosition );
assert( false );
return ( Relation_Unknown );
}
//
// Returns the next logical operator; doesn't handle NOT as it's parsed directly.
//
LogicalOper ConstraintsTokenizer::getLogicalOper()
{
if ( isNextSubstring( charArrToStr( TEXT_TokenLogicalOperAND ))) return ( LogicalOper_AND );
else if ( isNextSubstring( charArrToStr( TEXT_TokenLogicalOperOR ))) return ( LogicalOper_OR );
else return ( LogicalOper_Unknown );
}
//
// Parses parameter name
//
wstring ConstraintsTokenizer::getParameterName()
{
wstring name;
// look for opening marker
if ( ! ( isNextSubstring( charArrToStr( TEXT_TokenParameterNameOpen ))))
{
throw CSyntaxError( SyntaxErrType_NoParameterNameOpen, _currentPosition );
}
// retrive text
name = getString( charArrToStr( TEXT_TokenParameterNameClose ));
// look for closing marker
if ( ! isNextSubstring( charArrToStr( TEXT_TokenParameterNameClose )))
{
throw CSyntaxError( SyntaxErrType_NoParameterNameClose, _currentPosition );
}
return( name );
}
//
// Returns a number; reads from a string stream.
//
double ConstraintsTokenizer::getNumber()
{
// declare new stream from text we'd like to parse
// then try to get numeric value preserving old and new
// position within a stream to properly update cursor
wstring substring( _currentPosition, _constraintsText.end() );
wistringstream ist( substring );
unsigned int positionBefore = (unsigned int) ist.tellg();
double number;
ist>>number;
if (ist.rdstate() & ios::failbit)
{
throw CSyntaxError( SyntaxErrType_NotNumericValue, _currentPosition );
}
// success, update current cursor position
unsigned int difference = (unsigned int) ist.tellg() - positionBefore;
_currentPosition += difference;
return ( number );
}
//
// Reads next characters considering them part of string
// Terminator is the enclosing char, typically a "
//
wstring ConstraintsTokenizer::getString( IN const wstring& terminator )
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
{
wstring ret;
assert( 1 == terminator.size() );
wchar_t terminatingChar = terminator[ 0 ];
wchar_t readChar;
while( true )
{
// get next character, function throws error when there are no chars left
readChar = peekNextChar();
// string ends properly terminated
if ( terminatingChar == readChar )
{
movePosition( -1 );
break;
}
// handle special characters
else if ( TEXT_SpecialCharMarker == readChar )
{
wchar_t nextChar = peekNextChar();
bool found = false;
for( auto specialChar : SpecialCharacters )
{
if( nextChar == specialChar ) found = true;
}
if( !found ) throw CSyntaxError( SyntaxErrType_UnknownSpecialChar, _currentPosition );
// found a special character; append to resulting string in literal form
ret += nextChar;
}
// regular character: append to resulting string
else
{
ret += readChar;
}
}
return( ret );
}
//
// Skips all whitespace characters on and after current position.
//
void ConstraintsTokenizer::skipWhiteChars()
{
// probe next character; the function throws error when there are no chars left),
try
{
while ( true )
{
wchar_t nextChar = peekNextChar();
if ( ! ( iswspace ( nextChar ) // all white space characters
|| iswcntrl ( nextChar ))) // CRLF
{
movePosition( -1 );
break;
}
}
}
// there's nothing wrong with encountering the end of string here;
// other errors should be thrown to callers
catch ( CSyntaxError e )
{
if ( SyntaxErrType_UnexpectedEndOfString != e.Type )
{
throw e;
}
}
}
//
// Returns the next character updating the current position
// Throws when no more characters are left
//
wchar_t ConstraintsTokenizer::peekNextChar()
{
if ( _currentPosition >= _constraintsText.end() )
{
throw CSyntaxError( SyntaxErrType_UnexpectedEndOfString, _currentPosition );
}
return( *( _currentPosition++ ) );
}
//
// If texts match, returns True and also updates the current cursor position
// (unless explicitly requested not to)
//
bool ConstraintsTokenizer::isNextSubstring( IN const wstring& text, IN bool dontMoveCursor )
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
{
skipWhiteChars();
// Some STL implementations throw when text2 passed to 'equal' is shorter than text1.
// Checking for the sizes first should help.
bool textsMatch = false;
if( distance( _currentPosition, _constraintsText.end() ) >= (int) text.size() )
{
textsMatch = equal ( text.begin(), text.end(), _currentPosition,
[]( wchar_t c1, wchar_t c2 ) { return ( toupper( c1 ) == toupper( c2 ) ); }
);
}
if ( textsMatch && ! dontMoveCursor )
{
_currentPosition += text.length();
}
return ( textsMatch );
}
//
//
//
void ConstraintsTokenizer::movePosition( IN int count )
{
wstring::iterator newPosition = _currentPosition + count;
if ( newPosition < _constraintsText.begin() )
{
newPosition = _constraintsText.begin();
}
else if ( newPosition >= _constraintsText.end() )
{
newPosition = _constraintsText.end();
}
_currentPosition = newPosition;
}
//
// Expands "macros", there are two macros curently:
// IsNegative() == ( IsNegative(p1) or IsNegative(p2) or ... )
// IsPositive() == ( IsPositive(p1) and IsPositive(p2) and ... )
//
void ConstraintsTokenizer::doPostParseExpansions( IN OUT CTokenList& tokens )
{
CTokenList::iterator i_token = tokens.begin();
while( i_token != tokens.end() )
{
switch( (*i_token)->Type )
{
case TokenType_Function:
{
CFunction *function = (CFunction*) (*i_token)->Function;
if(( function->Type == FunctionTypeIsNegativeParam
|| function->Type == FunctionTypeIsPositiveParam )
&& function->DataText.empty() )
{
// deallocate the current token
// we don't have to deallocate Data because in this case it is always NULL
assert( function->Data == NULL );
// save positionInText and rawText and reuse it in all new tokens
wstring::iterator oldPosInText = (*i_token)->PositionInText;
FunctionType oldType = function->Type;
wstring oldRawText = function->RawText;
delete(*i_token);
i_token = tokens.erase( i_token );
// (
CToken* newToken = new CToken( TokenType_ParenthesisOpen, oldPosInText );
tokens.insert( i_token, newToken );
for( CParameters::iterator i_param = _model.Parameters.begin();
i_param != _model.Parameters.end();
++i_param )
{
if ( i_param->ResultParam ) continue;
if( i_param != _model.Parameters.begin() )
{
// logical operator OR or AND
newToken = new CToken( oldType == FunctionTypeIsNegativeParam ? LogicalOper_OR : LogicalOper_AND,
oldPosInText );
tokens.insert( i_token, newToken );
}
// IsNegative(param) / IsPositive(param)
CFunction* newFunction = new CFunction( oldType, FunctionDataType_Parameter,
&*i_param, i_param->Name, oldRawText );
newToken = new CToken( newFunction, oldPosInText );
tokens.insert( i_token, newToken );
}
// )
newToken = new CToken( TokenType_ParenthesisClose, oldPosInText );
tokens.insert( i_token, newToken );
}
else // it's not IsNegative() or IsPositive()
{
++i_token;
}
break;
}
default:
{
++i_token;
break;
}
}
}
}
}