Evaluator.cc 28.7 KB
Newer Older
1
// -*- C++ -*-
2
// $Id: Evaluator.cc,v 1.4 2010/07/20 17:00:49 garren Exp $
3
4
// ---------------------------------------------------------------------------

5
#include "CLHEP/Evaluator/defs.h"
6
#include "CLHEP/Evaluator/Evaluator.h"
7

8
#include <iostream>
9
#include <sstream>
10
#include <cmath>	// for std::pow()
11
12
13
14
15
16
17
18
19
#include "stack.src"
#include "string.src"
#include "hash_map.src"
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>	// for strtod()

//---------------------------------------------------------------------------
Lynn Garren's avatar
Lynn Garren committed
20
21
22
// Fix non ISO C++ compliant cast from pointer to function
// to void*, which is a pointer to an object
typedef void (*voidfuncptr)();
23
24
25
26
struct Item {
  enum { UNKNOWN, VARIABLE, EXPRESSION, FUNCTION } what;
  double variable;
  string expression;
Lynn Garren's avatar
Lynn Garren committed
27
28
29
30
  // Fix non ISO C++ compliant cast from pointer to function
  // to void*, which is a pointer to an object
  //void   *function;
  voidfuncptr function;
31
32
33
34

  Item()         : what(UNKNOWN),   variable(0),expression(), function(0) {}
  Item(double x) : what(VARIABLE),  variable(x),expression(), function(0) {}
  Item(string x) : what(EXPRESSION),variable(0),expression(x),function(0) {}
Lynn Garren's avatar
Lynn Garren committed
35
  Item(voidfuncptr x) : what(FUNCTION),  variable(0),expression(), function(x) {}
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
};

typedef char * pchar;
typedef hash_map<string,Item> dic_type;

struct Struct {
  dic_type theDictionary;
  pchar    theExpression;
  pchar    thePosition;
  int      theStatus;
  double   theResult;
};

//---------------------------------------------------------------------------
#define EVAL HepTool::Evaluator

#define REMOVE_BLANKS \
for(pointer=name;;pointer++) if (!isspace(*pointer)) break; \
for(n=strlen(pointer);n>0;n--) if (!isspace(*(pointer+n-1))) break

#define SKIP_BLANKS                      \
for(;;pointer++) {                       \
  c = (pointer > end) ? '\0' : *pointer; \
  if (!isspace(c)) break;                \
}

#define EVAL_EXIT(STATUS,POSITION) endp = POSITION; return STATUS
#define MAX_N_PAR 5

static const char sss[MAX_N_PAR+2] = "012345";

enum { ENDL, LBRA, OR, AND, EQ, NE, GE, GT, LE, LT,
68
       PLUS, MINUS, UNARY_PLUS, UNARY_MINUS, MULT, DIV, POW, RBRA, VALUE };
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

static int engine(pchar, pchar, double &, pchar &, const dic_type &);

static int variable(const string & name, double & result,
		    const dic_type & dictionary)
/***********************************************************************
 *                                                                     *
 * Name: variable                                    Date:    03.10.00 *
 * Author: Evgeni Chernyaev                          Revised:          *
 *                                                                     *
 * Function: Finds value of the variable.                              * 
 *           This function is used by operand().                       *
 *                                                                     *
 * Parameters:                                                         *
 *   name   - name of the variable.                                    *
 *   result - value of the variable.                                   *
 *   dictionary - dictionary of available variables and functions.     *
 *                                                                     *
 ***********************************************************************/
{
  dic_type::const_iterator iter = dictionary.find(name);
  if (iter == dictionary.end())
    return EVAL::ERROR_UNKNOWN_VARIABLE;
  Item item = iter->second;
  switch (item.what) {
  case Item::VARIABLE:
    result = item.variable;
    return EVAL::OK;
  case Item::EXPRESSION: {
    pchar exp_begin = (char *)(item.expression.c_str());
    pchar exp_end   = exp_begin + strlen(exp_begin) - 1;
    if (engine(exp_begin, exp_end, result, exp_end, dictionary) == EVAL::OK)
      return EVAL::OK;
  }
  default:
    return EVAL::ERROR_CALCULATION_ERROR;
  }
}

108
109
110
111
112
113
114
115
116
117
118
119


#if defined __GNUC__ 
  #if __GNUC__ > 3 && __GNUC_MINOR__ > 6
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
  #endif
  #if __GNUC__ > 4 
    #pragma GCC diagnostic push
    #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
  #endif
#endif 
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
static int function(const string & name, stack<double> & par,
		    double & result, const dic_type & dictionary) 
/***********************************************************************
 *                                                                     *
 * Name: function                                    Date:    03.10.00 *
 * Author: Evgeni Chernyaev                          Revised:          *
 *                                                                     *
 * Function: Finds value of the function.                              * 
 *           This function is used by operand().                       *
 *                                                                     *
 * Parameters:                                                         *
 *   name   - name of the function.                                    *
 *   par    - stack of parameters.                                     *
 *   result - value of the function.                                   *
 *   dictionary - dictionary of available variables and functions.     *
 *                                                                     *
 ***********************************************************************/
{
  int npar = par.size();
  if (npar > MAX_N_PAR) return EVAL::ERROR_UNKNOWN_FUNCTION;

  dic_type::const_iterator iter = dictionary.find(sss[npar]+name);
  if (iter == dictionary.end()) return EVAL::ERROR_UNKNOWN_FUNCTION;
  Item item = iter->second;

Lynn Garren's avatar
Lynn Garren committed
145
  double pp[MAX_N_PAR] = {0.0};
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
  for(int i=0; i<npar; i++) { pp[i] = par.top(); par.pop(); }
  errno = 0;
  if (item.function == 0)       return EVAL::ERROR_CALCULATION_ERROR;
  switch (npar) {
  case 0:
    result = ((double (*)())item.function)();
    break;  
  case 1:
    result = ((double (*)(double))item.function)(pp[0]);
    break;  
  case 2:
    result = ((double (*)(double,double))item.function)(pp[1], pp[0]);
    break;  
  case 3:
    result = ((double (*)(double,double,double))item.function)
      (pp[2],pp[1],pp[0]);
    break;  
  case 4:
    result = ((double (*)(double,double,double,double))item.function)
      (pp[3],pp[2],pp[1],pp[0]);
    break;  
  case 5:
    result = ((double (*)(double,double,double,double,double))item.function)
      (pp[4],pp[3],pp[2],pp[1],pp[0]);
    break;  
  }
  return (errno == 0) ? EVAL::OK : EVAL::ERROR_CALCULATION_ERROR;
}
174
175
176
177
178
179
180
181
#if defined __GNUC__ 
  #if __GNUC__ > 3 && __GNUC_MINOR__ > 6
    #pragma GCC diagnostic pop
  #endif
  #if __GNUC__ > 4 
    #pragma GCC diagnostic pop
  #endif
#endif
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

static int operand(pchar begin, pchar end, double & result,
		   pchar & endp, const dic_type & dictionary) 
/***********************************************************************
 *                                                                     *
 * Name: operand                                     Date:    03.10.00 *
 * Author: Evgeni Chernyaev                          Revised:          *
 *                                                                     *
 * Function: Finds value of the operand. The operand can be either     * 
 *           a number or a variable or a function.                     *  
 *           This function is used by engine().                        * 
 *                                                                     *
 * Parameters:                                                         *
 *   begin  - pointer to the first character of the operand.           *
 *   end    - pointer to the last character of the character string.   *
 *   result - value of the operand.                                    *
 *   endp   - pointer to the character where the evaluation stoped.    *
 *   dictionary - dictionary of available variables and functions.     *
 *                                                                     *
 ***********************************************************************/
{
  pchar pointer = begin;
  int   EVAL_STATUS;
  char  c;

  //   G E T   N U M B E R

  if (!isalpha(*pointer)) {
    errno = 0;
    result = strtod(pointer, (char **)(&pointer));
    if (errno == 0) {
      EVAL_EXIT( EVAL::OK, --pointer );
    }else{
      EVAL_EXIT( EVAL::ERROR_CALCULATION_ERROR, begin );
    }
  }

  //   G E T   N A M E

  while(pointer <= end) {
    c = *pointer;
    if (c != '_' && !isalnum(c)) break;
    pointer++;
  }
  c = *pointer;
  *pointer = '\0';
  string name(begin);
  *pointer = c;

  //   G E T   V A R I A B L E

  result = 0.0;
  SKIP_BLANKS;
  if (c != '(') {
    EVAL_STATUS = variable(name, result, dictionary);
    EVAL_EXIT( EVAL_STATUS, (EVAL_STATUS == EVAL::OK) ? --pointer : begin);
  }

  //   G E T   F U N C T I O N

  stack<pchar>  pos;                // position stack 
  stack<double> par;                // parameter stack
  double        value;
  pchar         par_begin = pointer+1, par_end;

  for(;;pointer++) {
    c = (pointer > end) ? '\0' : *pointer;
    switch (c) {
    case '\0':  
      EVAL_EXIT( EVAL::ERROR_UNPAIRED_PARENTHESIS, pos.top() ); 
    case '(':
      pos.push(pointer); break;
    case ',':
      if (pos.size() == 1) {
	par_end = pointer-1;
	EVAL_STATUS = engine(par_begin, par_end, value, par_end, dictionary);
	if (EVAL_STATUS == EVAL::WARNING_BLANK_STRING)
	  { EVAL_EXIT( EVAL::ERROR_EMPTY_PARAMETER, --par_end ); }
	if (EVAL_STATUS != EVAL::OK)
	  { EVAL_EXIT( EVAL_STATUS, par_end ); }
	par.push(value);
	par_begin = pointer + 1;
      }
      break;
    case ')':
      if (pos.size() > 1) {
	pos.pop();
	break;
      }else{
	par_end = pointer-1;
	EVAL_STATUS = engine(par_begin, par_end, value, par_end, dictionary);
	switch (EVAL_STATUS) {
	case EVAL::OK:
	  par.push(value);
	  break;
	case EVAL::WARNING_BLANK_STRING:
	  if (par.size() != 0)
	    { EVAL_EXIT( EVAL::ERROR_EMPTY_PARAMETER, --par_end ); }
	  break;
	default:
	  EVAL_EXIT( EVAL_STATUS, par_end );
	}
	EVAL_STATUS = function(name, par, result, dictionary);
	EVAL_EXIT( EVAL_STATUS, (EVAL_STATUS == EVAL::OK) ? pointer : begin);
      }
    }
  }
}

/***********************************************************************
 *                                                                     *
 * Name: maker                                       Date:    28.09.00 *
 * Author: Evgeni Chernyaev                          Revised:          *
 *                                                                     *
 * Function: Executes basic arithmetic operations on values in the top *
 *           of the stack. Result is placed back into the stack.       *
 *           This function is used by engine().                        * 
 *                                                                     *
 * Parameters:                                                         *
 *   op  - code of the operation.                                      *
 *   val - stack of values.                                            *
 *                                                                     *
 ***********************************************************************/
static int maker(int op, stack<double> & val)
{
  if (val.size() < 2) return EVAL::ERROR_SYNTAX_ERROR;
  double val2 = val.top(); val.pop();
  double val1 = val.top();
  switch (op) {
  case OR:                                // operator ||
    val.top() = (val1 || val2) ? 1. : 0.;
    return EVAL::OK;
  case AND:                               // operator &&
    val.top() = (val1 && val2) ? 1. : 0.;
    return EVAL::OK;
  case EQ:                                // operator ==
    val.top() = (val1 == val2) ? 1. : 0.;
    return EVAL::OK;
  case NE:                                // operator !=
    val.top() = (val1 != val2) ? 1. : 0.;
    return EVAL::OK;
  case GE:                                // operator >=
    val.top() = (val1 >= val2) ? 1. : 0.;
    return EVAL::OK;
  case GT:                                // operator >
    val.top() = (val1 >  val2) ? 1. : 0.;
    return EVAL::OK;
  case LE:                                // operator <=
    val.top() = (val1 <= val2) ? 1. : 0.;
    return EVAL::OK;
  case LT:                                // operator <
    val.top() = (val1 <  val2) ? 1. : 0.;
    return EVAL::OK;
  case PLUS:                              // operator '+'
    val.top() = val1 + val2;
    return EVAL::OK;
  case MINUS:                             // operator '-'
    val.top() = val1 - val2;
    return EVAL::OK;
  case MULT:                              // operator '*'
    val.top() = val1 * val2;
    return EVAL::OK;
  case DIV:                               // operator '/'
    if (val2 == 0.0) return EVAL::ERROR_CALCULATION_ERROR;
    val.top() = val1 / val2;
    return EVAL::OK;
  case POW:                               // operator '^' (or '**')
    errno = 0;
350
    val.top() = std::pow(val1,val2);
351
    if (errno == 0) return EVAL::OK;
352
353
354
355
356
357
  case UNARY_PLUS:                              // unary operator '+'
    val.top() = val1 + val2;			// val1 is zero
    return EVAL::OK;
  case UNARY_MINUS:                             // unary operator '-'
    val.top() = val1 - val2;			// val1 is zero
    return EVAL::OK;
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
  default:
    return EVAL::ERROR_CALCULATION_ERROR;
  }
}

/***********************************************************************
 *                                                                     *
 * Name: engine                                      Date:    28.09.00 *
 * Author: Evgeni Chernyaev                          Revised:          *
 *                                                                     *
 * Function: Evaluates arithmetic expression.                          *
 *                                                                     *
 * Parameters:                                                         *
 *   begin  - pointer to the character string with expression.         *
 *   end    - pointer to the end of the character string (it is needed *
 *            for recursive call of engine(), when there is no '\0').  *
 *   result - result of the evaluation.                                *
 *   endp   - pointer to the character where the evaluation stoped.    *
 *   dictionary - dictionary of available variables and functions.     *
 *                                                                     *
 ***********************************************************************/
static int engine(pchar begin, pchar end, double & result,
		  pchar & endp, const dic_type & dictionary)
{
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
  enum SyntaxTableEntry {
    SyntaxError = 0,
    NumberVariableOrFunction = 1,
    UnaryPlusOrMinus = 2,
    AnyOperator = 3
  };
  static const int SyntaxTable[19][19] = {
    //E  (  || && == != >= >  <= <  +  -  u+ u- *  /  ^  )  V - current token
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // E - previous
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // (   token
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // ||
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // &&
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // ==
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // !=
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // >=
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // >
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // <=
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // <
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // +
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // -
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // unary +
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // unary -
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // *
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // /
    { 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 0, 0, 0, 0, 1 },   // ^
    { 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0 },   // )
    { 3, 0, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 0 }    // V = {.,N,C}
409
  };
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
  enum ActionTableEntry {
    UnbalancedParentheses = -1,
    ExpressionCompleted = 0,
    HigherPrecedenceOperator = 1,
    SamePrecedenceOperator = 2,
    CloseProcessedParenthesesOrExpression = 3,
    LowerPrecedenceOperator = 4
  };
  static const int ActionTable[17][18] = {
    //E  (  || && == != >= >  <= <  +  -  u+ u- *  /  ^  ) - current operator
    { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,-1 }, // E - top operator
    {-1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3 }, // (   in stack
    { 4, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4 }, // ||
    { 4, 1, 4, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4 }, // &&
    { 4, 1, 4, 4, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4 }, // ==
    { 4, 1, 4, 4, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4 }, // !=
    { 4, 1, 4, 4, 4, 4, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 4 }, // >=
    { 4, 1, 4, 4, 4, 4, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 4 }, // >
    { 4, 1, 4, 4, 4, 4, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 4 }, // <=
    { 4, 1, 4, 4, 4, 4, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 4 }, // <
    { 4, 1, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 1, 1, 1, 1, 1, 4 }, // +
    { 4, 1, 4, 4, 4, 4, 4, 4, 4, 4, 2, 2, 1, 1, 1, 1, 1, 4 }, // -
Lynn Garren's avatar
Lynn Garren committed
432
433
    { 4, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 4, 4, 1, 4 }, // unary +
    { 4, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 4, 4, 1, 4 }, // unary -
434
435
436
    { 4, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 2, 2, 1, 4 }, // *
    { 4, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 2, 2, 1, 4 }, // /
    { 4, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 4, 4, 4, 4 }  // ^
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
  };

  stack<int>    op;                      // operator stack
  stack<pchar>  pos;                     // position stack
  stack<double> val;                     // value stack
  double        value;
  pchar         pointer = begin;
  int           iWhat, iCur, iPrev = 0, iTop, EVAL_STATUS;
  char          c;

  op.push(0); pos.push(pointer);         // push EOL to the stack
  SKIP_BLANKS;
  if (c == '\0') { EVAL_EXIT( EVAL::WARNING_BLANK_STRING, begin ); }
  for(;;pointer++) {

    //   N E X T   T O K E N

    c = (pointer > end) ? '\0' : *pointer;
    if (isspace(c)) continue;            // skip space, tab etc.
    switch (c) {
    case '\0': iCur = ENDL; break;
    case '(':  iCur = LBRA; break;
    case '|':
      if (*(pointer+1) == '|') {
	pointer++; iCur = OR; break;
      }else{
        EVAL_EXIT( EVAL::ERROR_UNEXPECTED_SYMBOL, pointer );
      }
    case '&':
      if (*(pointer+1) == '&') {
	pointer++; iCur = AND; break;
      }else{
        EVAL_EXIT( EVAL::ERROR_UNEXPECTED_SYMBOL, pointer );
      }
    case '=':
      if (*(pointer+1) == '=') {
	pointer++; iCur = EQ; break;
      }else{
        EVAL_EXIT( EVAL::ERROR_UNEXPECTED_SYMBOL, pointer );
      }
    case '!':
      if (*(pointer+1) == '=') {
	pointer++; iCur = NE; break;
      }else{
        EVAL_EXIT( EVAL::ERROR_UNEXPECTED_SYMBOL, pointer );
      }
    case '>':
      if (*(pointer+1) == '=') { pointer++; iCur = GE; } else { iCur = GT; }
      break;
    case '<':
      if (*(pointer+1) == '=') { pointer++; iCur = LE; } else { iCur = LT; }
      break;
    case '+':  iCur = PLUS;  break;
    case '-':  iCur = MINUS; break;
    case '*':
      if (*(pointer+1) == '*') { pointer++; iCur = POW; }else{ iCur = MULT; }
      break;
    case '/':  iCur = DIV;  break;
    case '^':  iCur = POW;  break;
    case ')':  iCur = RBRA; break;
    default:
      if (c == '.' || isalnum(c)) {
        iCur = VALUE; break;
      }else{
        EVAL_EXIT( EVAL::ERROR_UNEXPECTED_SYMBOL, pointer );
      }
    }

    //   S Y N T A X   A N A L I S Y S

    iWhat = SyntaxTable[iPrev][iCur];
    iPrev = iCur;
    switch (iWhat) {
510
    case 0:                             // syntax error
511
512
513
514
515
516
517
518
      EVAL_EXIT( EVAL::ERROR_SYNTAX_ERROR, pointer );
    case 1:                             // operand: number, variable, function
      EVAL_STATUS = operand(pointer, end, value, pointer, dictionary);
      if (EVAL_STATUS != EVAL::OK) { EVAL_EXIT( EVAL_STATUS, pointer ); }
      val.push(value);
      continue;
    case 2:                             // unary + or unary -
      val.push(0.0);
519
520
521
522
      if (iCur == PLUS)  iCur = UNARY_PLUS;
      if (iCur == MINUS) iCur = UNARY_MINUS;
      // Note that for syntax purposes, ordinary + or - are fine.
      // Thus iPrev need not change when we encounter a unary minus or plus.
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
    case 3: default:                    // next operator
      break;
    }

    //   N E X T   O P E R A T O R

    for(;;) {
      if (op.size() == 0) { EVAL_EXIT( EVAL::ERROR_SYNTAX_ERROR, pointer ); }
      iTop = op.top();
      switch (ActionTable[iTop][iCur]) {
      case -1:                           // syntax error 
	if (op.size() > 1) pointer = pos.top();
	EVAL_EXIT( EVAL::ERROR_UNPAIRED_PARENTHESIS, pointer );
      case 0:                            // last operation (assignment)
        if (val.size() == 1) {
	  result = val.top();
	  EVAL_EXIT( EVAL::OK, pointer );
	}else{
	  EVAL_EXIT( EVAL::ERROR_SYNTAX_ERROR, pointer );
	}
      case 1:                           // push current operator in stack
	op.push(iCur); pos.push(pointer);
	break;
      case 2:                           // execute top operator
        EVAL_STATUS = maker(iTop, val); // put current operator in stack
        if (EVAL_STATUS != EVAL::OK) {
	  EVAL_EXIT( EVAL_STATUS, pos.top() );
	}
	op.top() = iCur; pos.top() = pointer;
	break;
      case 3:                           // delete '(' from stack
        op.pop(); pos.pop();
	break;
      case 4: default:                  // execute top operator and 
        EVAL_STATUS = maker(iTop, val); // delete it from stack
        if (EVAL_STATUS != EVAL::OK) {  // repete with the same iCur 
	  EVAL_EXIT( EVAL_STATUS, pos.top() );
	}
	op.pop(); pos.pop();
        continue;
      }
      break;
    }
  }
}

//---------------------------------------------------------------------------
static void setItem(const char * prefix, const char * name,
		    const Item & item, Struct * s) {

  if (name == 0 || *name == '\0') {
    s->theStatus = EVAL::ERROR_NOT_A_NAME;
    return;
  }

  //   R E M O V E   L E A D I N G   A N D   T R A I L I N G   S P A C E S

  const char * pointer; int n; REMOVE_BLANKS;

  //   C H E C K   N A M E 
 
  if (n == 0) {
    s->theStatus = EVAL::ERROR_NOT_A_NAME;
    return;
  }
  for(int i=0; i<n; i++) {
    char c = *(pointer+i);
    if (c != '_' && !isalnum(c)) {
      s->theStatus = EVAL::ERROR_NOT_A_NAME;
      return;
    }
  }

  //   A D D   I T E M   T O   T H E   D I C T I O N A R Y

  string item_name = prefix + string(pointer,n);
  dic_type::iterator iter = (s->theDictionary).find(item_name);
  if (iter != (s->theDictionary).end()) {
    iter->second = item;
    if (item_name == name) {
      s->theStatus = EVAL::WARNING_EXISTING_VARIABLE;
    }else{
      s->theStatus = EVAL::WARNING_EXISTING_FUNCTION;
    }
  }else{
    (s->theDictionary)[item_name] = item;
    s->theStatus = EVAL::OK;
  }
} 
		    
//---------------------------------------------------------------------------
namespace HepTool {

//---------------------------------------------------------------------------
Evaluator::Evaluator() {
  Struct * s = new Struct();
  p = (void *) s;
  s->theExpression = 0;
  s->thePosition   = 0;
  s->theStatus     = OK;
  s->theResult     = 0.0;
}

//---------------------------------------------------------------------------
Evaluator::~Evaluator() {
  delete (Struct *)(p);
}

//---------------------------------------------------------------------------
double Evaluator::evaluate(const char * expression) {
  Struct * s = (Struct *)(p);
  if (s->theExpression != 0) { delete[] s->theExpression; }
  s->theExpression = 0;
  s->thePosition   = 0;
  s->theStatus     = WARNING_BLANK_STRING;
  s->theResult     = 0.0;
  if (expression != 0) {
    s->theExpression = new char[strlen(expression)+1];
    strcpy(s->theExpression, expression);
    s->theStatus = engine(s->theExpression,
			  s->theExpression+strlen(expression)-1,
			  s->theResult,
			  s->thePosition,
			  s->theDictionary);
  }
  return s->theResult;
}

//---------------------------------------------------------------------------
int Evaluator::status() const {
  return ((Struct *)(p))->theStatus;
}

//---------------------------------------------------------------------------
int Evaluator::error_position() const {
  return ((Struct *)(p))->thePosition - ((Struct *)(p))->theExpression;
}

//---------------------------------------------------------------------------
void Evaluator::print_error() const {
663
664
665
666
667
668
669
670
671
672
  Struct * s = (Struct *) p;
  if(s->theStatus != OK) {
      std::cerr << error_name() << std::endl;
  }
  return;
}

//---------------------------------------------------------------------------
std::string Evaluator::error_name() const
{
673
  char prefix[] = "Evaluator : ";
674
  std::ostringstream errn;
675
676
677
  Struct * s = (Struct *) p;
  switch (s->theStatus) {
  case ERROR_NOT_A_NAME:
678
679
    errn << prefix << "invalid name";
    break;
680
  case ERROR_SYNTAX_ERROR:
681
682
    errn << prefix << "syntax error";
    break;
683
  case ERROR_UNPAIRED_PARENTHESIS:
684
685
    errn << prefix << "unpaired parenthesis";
    break;
686
  case ERROR_UNEXPECTED_SYMBOL:
687
688
    errn << prefix << "unexpected symbol";
    break;
689
  case ERROR_UNKNOWN_VARIABLE:
690
691
    errn << prefix << "unknown variable";
    break;
692
  case ERROR_UNKNOWN_FUNCTION:
693
694
    errn << prefix << "unknown function";
    break;
695
  case ERROR_EMPTY_PARAMETER: 
696
697
    errn << prefix << "empty parameter in function call";
    break;
698
  case ERROR_CALCULATION_ERROR:
699
700
    errn << prefix << "calculation error";
    break;
701
  default:
702
    errn << " ";
703
  }
704
  return errn.str();
705
706
707
708
709
710
711
712
713
714
}

//---------------------------------------------------------------------------
void Evaluator::setVariable(const char * name, double value)
{ setItem("", name, Item(value), (Struct *)p); }

void Evaluator::setVariable(const char * name, const char * expression)
{ setItem("", name, Item(expression), (Struct *)p); }

//---------------------------------------------------------------------------
Lynn Garren's avatar
Lynn Garren committed
715
716
// Fix non ISO C++ compliant cast from pointer to function
// to void*, which is a pointer to an object
717
718
void Evaluator::setFunction(const char * name,
			    double (*fun)())
Lynn Garren's avatar
Lynn Garren committed
719
{ setItem("0", name, Item(reinterpret_cast<voidfuncptr>(fun)), (Struct *)p); }
720
721
722

void Evaluator::setFunction(const char * name,
			    double (*fun)(double))
Lynn Garren's avatar
Lynn Garren committed
723
{ setItem("1", name, Item(reinterpret_cast<voidfuncptr>(fun)), (Struct *)p); }
724
725
726

void Evaluator::setFunction(const char * name,
			    double (*fun)(double,double))
Lynn Garren's avatar
Lynn Garren committed
727
{ setItem("2", name, Item(reinterpret_cast<voidfuncptr>(fun)), (Struct *)p); }
728
729
730

void Evaluator::setFunction(const char * name,
			    double (*fun)(double,double,double))
Lynn Garren's avatar
Lynn Garren committed
731
{ setItem("3", name, Item(reinterpret_cast<voidfuncptr>(fun)), (Struct *)p); }
732
733
734

void Evaluator::setFunction(const char * name,
			    double (*fun)(double,double,double,double))
Lynn Garren's avatar
Lynn Garren committed
735
{ setItem("4", name, Item(reinterpret_cast<voidfuncptr>(fun)), (Struct *)p); }
736
737
738

void Evaluator::setFunction(const char * name,
			    double (*fun)(double,double,double,double,double))
Lynn Garren's avatar
Lynn Garren committed
739
{ setItem("5", name, Item(reinterpret_cast<voidfuncptr>(fun)), (Struct *)p); }
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

//---------------------------------------------------------------------------
bool Evaluator::findVariable(const char * name) const {
  if (name == 0 || *name == '\0') return false;
  const char * pointer; int n; REMOVE_BLANKS;
  if (n == 0) return false;
  Struct * s = (Struct *)(p);
  return
    ((s->theDictionary).find(string(pointer,n)) == (s->theDictionary).end()) ?
    false : true;
}

//---------------------------------------------------------------------------
bool Evaluator::findFunction(const char * name, int npar) const {
  if (name == 0 || *name == '\0')    return false;
  if (npar < 0  || npar > MAX_N_PAR) return false;
  const char * pointer; int n; REMOVE_BLANKS;
  if (n == 0) return false;
  Struct * s = (Struct *)(p);
  return ((s->theDictionary).find(sss[npar]+string(pointer,n)) ==
	  (s->theDictionary).end()) ? false : true;
}

//---------------------------------------------------------------------------
void Evaluator::removeVariable(const char * name) {
  if (name == 0 || *name == '\0') return;
  const char * pointer; int n; REMOVE_BLANKS;
  if (n == 0) return;
  Struct * s = (Struct *)(p);
  (s->theDictionary).erase(string(pointer,n));
}

//---------------------------------------------------------------------------
void Evaluator::removeFunction(const char * name, int npar) {
  if (name == 0 || *name == '\0')    return;
  if (npar < 0  || npar > MAX_N_PAR) return;
  const char * pointer; int n; REMOVE_BLANKS;
  if (n == 0) return;
  Struct * s = (Struct *)(p);
  (s->theDictionary).erase(sss[npar]+string(pointer,n));
}

//---------------------------------------------------------------------------
void Evaluator::clear() {
  Struct * s = (Struct *) p;
  s->theDictionary.clear();
  s->theExpression = 0;
  s->thePosition   = 0;
  s->theStatus     = OK;
  s->theResult     = 0.0;
}

//---------------------------------------------------------------------------
} // namespace HepTool