aboutsummaryrefslogtreecommitdiff
path: root/src/Expression.c
blob: 315691c0987c6e58ddc67021942e3133e30c686f (plain)
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
 /*@@
   @file      Expression.c
   @date      Tue Sep 19 13:25:39 2000
   @author    Tom Goodale
   @desc 
   Expression evaluator.
   @enddesc
   @version $Header$
 @@*/

#ifndef TEST_HTTP_EVALUATE
#include "cctk.h"
#endif

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "Expression.h"

static const char *rcsid = "$Header$";

CCTK_FILEVERSION(CactusConnect_HTTPD_Expression_c)

/********************************************************************
 *********************     Local Data Types   ***********************
 ********************************************************************/

typedef struct PToken
{
  struct PToken *last;
  struct PToken *next;
  char *token;
} pToken;

/********************************************************************
 ********************* Local Routine Prototypes *********************
 ********************************************************************/

static pToken *Tokenise(const char *expression);
static char *RPParse(pToken **current, char *stack, int *stacklength);
static double Evaluate(double val1, const char *operator, double val2);

static int isoperator(const char *token);
static int cmpprecendence(const char *op1, const char *op2);

static pToken *newtoken(const char *tokenstart, const char *tokenend);

#if 0
static void insertbefore(pToken *base, pToken *this);
#endif

#ifdef TEST_HTTP_EVALUATE
static void printtokens(pToken *start);
#endif

static void insertafter(pToken *base, pToken *this);
static void FreeTokens(pToken *list);

/********************************************************************
 ********************* Other Routine Prototypes *********************
 ********************************************************************/

/********************************************************************
 *********************     Local Data   *****************************
 ********************************************************************/

#define INITIAL_BUFFER_LENGTH 1000
#define MAX_STACK_SIZE 256
#define MAX_OPS 100

/********************************************************************
 *********************     External Routines   **********************
 ********************************************************************/

 /*@@
   @routine    HTTP_ExpressionParse
   @date       Tue Sep 19 21:23:08 2000
   @author     Tom Goodale
   @desc 
   Parses an expression returning a predigested string in RPN.
   @enddesc 
   @calls     
   @calledby   
   @history 
 
   @endhistory 

@@*/
char *HTTP_ExpressionParse(const char *expression)
{
  int buffer_length = INITIAL_BUFFER_LENGTH;
  char *buffer = (char *)malloc(buffer_length);

  if(buffer)
  {
    /* Split the list into tokens */
    pToken *list = Tokenise(expression);
    pToken *temp = list;

#ifdef TEST_HTTP_EVALUATE    
    printtokens(list);
#endif


    /* Convert the list into a string in RPN order */
    buffer = RPParse(&temp, buffer, &buffer_length);

    FreeTokens(list);
  }

  return buffer;
}

 /*@@
   @routine    HTTP_ExpressionEvaluate
   @date       Tue Sep 19 21:23:40 2000
   @author     Tom Goodale
   @desc 
   Evaluates an parsed expression string created by HTTP_ExpressionParse.
   The user passes in a function which is used to evaluate all operands.
   @enddesc 
   @calls     
   @calledby   
   @history 
 
   @endhistory 

@@*/
double HTTP_ExpressionEvaluate(char *buffer, 
                               double (*eval)(const char *, void *),
                               void *data)
{
  double stack[MAX_STACK_SIZE];
  int stackpointer = 0;
  char *first = buffer;
  char *token;

  /* Tokens are seperated by @ signs */
  while((token = strtok(first,"@")))
  {
    first = NULL;

    if(!isoperator(token))
    {
      /* Evaluate and put on stack */
      stack[stackpointer] = eval(token, data);
      stackpointer++;
    }
    else
    {
#ifdef TEST_HTTP_EVALUATE
      printf("Stackpointer is %d, %f %s %f = ", 
             stackpointer, stack[stackpointer-2], token, stack[stackpointer-1]);
#endif
      /* Evaluate operation, clear operands from stack and add the result to the stack. */
      stack[stackpointer-2] = Evaluate(stack[stackpointer-2],token,stack[stackpointer-1]);
      stackpointer--;
#ifdef TEST_HTTP_EVALUATE
      printf("%f\n", stack[stackpointer-1]); 
#endif
    }
  }
  
  return stack[stackpointer-1];
}


/********************************************************************
 *********************     Local Routines   *************************
 ********************************************************************/

 /*@@
   @routine    Tokenise
   @date       Tue Sep 19 21:25:18 2000
   @author     Tom Goodale
   @desc 
   Split an expression into tokens
   @enddesc 
   @calls     
   @calledby   
   @history 
 
   @endhistory 

@@*/
static pToken *Tokenise(const char *expression)
{
  pToken *start   = NULL;
  pToken *current = NULL;
  pToken *new = NULL;

  const char *tokenstart = expression;

  while(*tokenstart)
  {
    const char *tokenend = NULL;
    const char *position;
    /* Remove leading whitespace */ 
    for(; *tokenstart == ' ' || *tokenstart == '\t'; tokenstart++);

    position = tokenstart;

    for(position=tokenstart; *position && *(position+1); position++)
    {
      switch(*(position+1))
      {
        case '+' :
        case '-' :
        case '/' :
        case '*' :
        case '(' :
        case ')' :
        case '<' :
        case '>' :
          tokenend = position; break;
        case '=' :
          if(*position != '<' && *position != '>')
          {
            tokenend = position; 
          }
          break;
        case '&' :
          if(*position != '&')
          {
            tokenend = position;
          }
          break;
        case '|' :
          if(*position != '|')
          {
            tokenend = position;
          }
          break;
        default  :
          switch(*(position))
          {
            case '+' :
            case '-' :
            case '/' :
            case '*' :
            case '(' :
            case ')' :
            case '=' :
            case '&' :
            case '|' :
              tokenend = position; break;
            case '<' :
            case '>' :
              if(*(position+1) && *(position+1) != '=')
              {
                tokenend = position;
              }
              break;
            default  :
              ;
          }
      }

      if(tokenend)
      {
        break;
      }
    }

    /* Have we reached the end of the string ? */
    if(!tokenend)
    {
      tokenend = position;
    }
    
    /* Create a new token */
    new = newtoken(tokenstart, tokenend);

    /* Insert on list */
    if(current)
    {
      insertafter(current, new);
    }
    current = new;

    if(!start)
    {
      start = current;
    }

    if(*tokenend)
    {
      tokenstart = tokenend+1;
    }
    else
    {
      break;
    }
  }
    
  return start;
}

 /*@@
   @routine    RPParse
   @date       Tue Sep 19 21:28:36 2000
   @author     Tom Goodale
   @desc 
   Parses an toke list into Reverse Polish Notation (RPN).
   @enddesc 
   @calls     
   @calledby   
   @history 
 
   @endhistory 

@@*/
#define PUSH(stack, stacklength, value) do                        \
{                                                                 \
  int len = strlen(stack)+strlen(value)+3;                        \
                                                                  \
  if(len > stacklength)                                           \
  {                                                               \
    stack = (char *)realloc(stack, len);                          \
  }                                                               \
  sprintf(stack,"%s@%s",stack,value);                             \
} while(0)


static char *RPParse(pToken **current, char *stack, int *stacklength)
{
  char *retval = stack;
  pToken *this = *current;
  char *operator = NULL;
  int numops = 0;
  char *opstack[MAX_OPS];

  for(this = *current; this && strcmp(this->token,")"); this = this->next)
  {
    if(!strcmp(this->token, "(") && this->next)
    {
      /* This is a sub-group, so parse recursively */
      this = this->next;
      retval = RPParse(&this, retval, stacklength);
      if(! this)
      {
        break;
      }
    }
    else if(!isoperator(this->token))
    {
      PUSH(retval, *stacklength, this->token);
    }
    else
    {
      /* It's an operator */
      if(operator)
      {
        /* We already have an operator */
        int precedence = cmpprecendence(operator, this->token);

        if(precedence > 0)
        {
          /* Higher precedence than previous one so store previous one */
          numops++;
          opstack[numops-1] = operator;
          operator = this->token;
        }
        else
        {
          /* Lower or equal precedence */
          PUSH(retval, *stacklength, operator);
          operator = this->token;
          while(numops > 0)
          {
            if(cmpprecendence(opstack[numops-1], operator) <=0)
            {
              numops--;
              PUSH(retval, *stacklength, opstack[numops]);
            }
            else
            {
              break;
            }
          }
        }
      }
      else
      {
        operator = this->token;
      }
    }
  }

  if(operator)
  {
    PUSH(retval, *stacklength, operator);
    while(numops > 0)
    {
      numops--;
      PUSH(retval, *stacklength, opstack[numops]);
    }
  }

  *current=this;

  return retval;
}


 /*@@
   @routine    Evaluate
   @date       Tue Sep 19 21:35:34 2000
   @author     Tom Goodale
   @desc 
   Evaluates val1 op val2 
   @enddesc 
   @calls     
   @calledby   
   @history 
 
   @endhistory 

@@*/
static double Evaluate(double val1, const char *operator, double val2)
{
  double retval = 0.0;

  if(!strcmp(operator, "+"))
  {
    retval = (val1+val2);
  }
  else if(!strcmp(operator, "-"))
  {
    retval = (val1-val2);
  }
  else if(!strcmp(operator, "/"))
  {
    retval = (val1/val2);
  }
  else if(!strcmp(operator, "*"))
  {
    retval = (val1*val2);
  }
  else if(!strcmp(operator, "&&"))
  {
    retval = (val1 && val2);
  }
  else if(!strcmp(operator, "||"))
  {
    retval = (val1 || val2);
  }
  else if(!strcmp(operator, "="))
  {
    retval = ( val1 == val2);
  }
  else if(!strcmp(operator, "<"))
  {
    retval = (val1 < val2);
  }
  else if(!strcmp(operator, "<="))
  {
    retval = (val1 <= val2);
  }
  else if(!strcmp(operator, ">"))
  {
    retval = (val1 > val2);
  }
  else if(!strcmp(operator, ">="))
  {
    retval = (val1 >= val2);
  }
  else
  {
    fprintf(stderr, "Unknown operation %s", operator);
  }

  return retval;
}
  
 /*@@
   @routine    FreeTokens
   @date       Tue Sep 19 21:39:07 2000
   @author     Tom Goodale
   @desc 
   Frees a list of tokens.
   @enddesc 
   @calls     
   @calledby   
   @history 
 
   @endhistory 

@@*/
void FreeTokens(pToken *list)
{
  pToken *token = list;

  while( token )
  {
    pToken *next = token->next;
    free(token->token);
    free(token);
    token = next;
  }
}  


 /*@@
   @routine    isoperator
   @date       Tue Sep 19 21:30:20 2000
   @author     Tom Goodale
   @desc 
   Tests if a string is an operator or not.
   @enddesc 
   @calls     
   @calledby   
   @history 
 
   @endhistory 

@@*/
static int isoperator(const char *token)
{
  int retval = 0;
  
  if(!strcmp(token, "+") ||
     !strcmp(token, "-") ||
     !strcmp(token, "/") ||
     !strcmp(token, "*") ||
     !strcmp(token, "&&") ||
     !strcmp(token, "||") ||
     !strcmp(token, "=") ||
     !strcmp(token, "<") ||
     !strcmp(token, "<=") ||
     !strcmp(token, ">") ||
     !strcmp(token, ">="))
  {
    retval = 1;
  }

  return retval;
}

 /*@@
   @routine    cmpprecendence
   @date       Wed Sep 20 09:05:59 2000
   @author     Tom Goodale
   @desc 
   Compare the precedence of two operators.
   @enddesc 
   @calls     
   @calledby   
   @history 
 
   @endhistory 

@@*/
static int cmpprecendence(const char *op1, const char *op2)
{
  const char *op;
  int op1prec;
  int op2prec;
  int *prec;

  /* Work out the precedence level for each operator */
  for(op = op1, prec = &op1prec; 
      op ; 
      op = (op == op1 ) ? op2 : NULL, 
      prec = (op == op1) ? &op1prec : &op2prec)
  {
    if(!strcmp(op, "=") ||
       !strcmp(op, "<") ||
       !strcmp(op, "<=") ||
       !strcmp(op, ">") ||
       !strcmp(op, ">="))
    {
      *prec = 1;
    }
    else if(!strcmp(op, "&&") ||
       !strcmp(op, "||"))
    {
      *prec = 2;
    }
    else if(!strcmp(op, "+") ||
            !strcmp(op, "-"))
    {
      *prec = 3;
    }
    else if(!strcmp(op, "/") ||
            !strcmp(op, "*"))
    {
      *prec = 4;
    }
    else
    {
      fprintf(stderr, "Unknown operator '%s'\n", op);
      *prec = 0;
    }
  }

  /* Now see which has the higher precedence */

  return op2prec-op1prec;
}
 
 /*@@
   @routine    newtoken
   @date       Tue Sep 19 21:30:42 2000
   @author     Tom Goodale
   @desc 
   Creates a new token item.
   @enddesc 
   @calls     
   @calledby   
   @history 
 
   @endhistory 

@@*/
static pToken *newtoken(const char *tokenstart, const char *tokenend)
{
  pToken *this = (pToken *)malloc(sizeof(pToken *));

  if(this)
  {
    this->last = NULL;
    this->next = NULL;

    this->token = (char *)malloc(tokenend-tokenstart+2);
    if(this->token)
    {
      const char *position;
      char *newpos;
      for(position=tokenstart, newpos=this->token; 
          position <= tokenend; 
          position++, newpos++)
      {
        *newpos = *position;
      }
      /* Just in case not already null terminated */
      *newpos = 0;

      /* Strip off any trailing spaces */
      for(; newpos >= this->token && 
            (*newpos == 0 || *newpos == ' ' || *newpos == '\t'); newpos--)
      {
        *newpos = 0;
      }
    }
  }

  return this;
}

 /*@@
   @routine    insertbefore
   @date       Tue Sep 19 21:33:39 2000
   @author     Tom Goodale
   @desc 
   Inserts a token before another one in a list.
   @enddesc 
   @calls     
   @calledby   
   @history 
 
   @endhistory 

@@*/
#if 0
static void insertbefore(pToken *base, pToken *this)
{
  if(base && this)
  {
    this->next = base;
    this->last = base->last;
    base->last = this;

    if(this->last)
    {
      this->last->next = this;
    }
  }
}
#endif
    
 /*@@
   @routine    insertafter
   @date       Tue Sep 19 21:34:02 2000
   @author     Tom Goodale
   @desc 
   Inserts a token after another one in a list.
   @enddesc 
   @calls     
   @calledby   
   @history 
 
   @endhistory 

@@*/
static void insertafter(pToken *base, pToken *this)
{
  if(base && this)
  {
    this->last = base;
    this->next = base->next;
    base->next = this;
    
    if(this->next)
    {
      this->next->last = this;
    }
  }
}
  
 /*@@
   @routine    printtokens
   @date       Tue Sep 19 21:34:24 2000
   @author     Tom Goodale
   @desc 
   Debugging function to print out the tokens.
   @enddesc 
   @calls     
   @calledby   
   @history 
 
   @endhistory 

@@*/
#if TEST_HTTP_EVALUATE
static void printtokens(pToken *start)
{
  pToken *token;

  for(token = start; token; token = token->next)
  {
    printf("->%s", token->token);
  }

  printf("\n");
}
#endif /* TEST_HTTP_EVALUATE */

 /*@@
   @routine    printstack
   @date       Tue Sep 19 21:34:48 2000
   @author     Tom Goodale
   @desc 
   Debugging function to print out a predigested string.
   Note that is modifies the string, so it should be passed
   a copy.
   @enddesc 
   @calls     
   @calledby   
   @history 
 
   @endhistory 

@@*/
#if 0
static void printstack(char *stack)
{
  char *first;
  char *token;

  first = stack;

  while((token = strtok(first,"@")))
  {
    first = NULL;
    printf("Token is %s\n", token);
  }
}
#endif


/********************************************************************
 *********************     TEST FUNCTIONS   *************************
 ********************************************************************/

#ifdef TEST_HTTP_EVALUATE

double evaluator(const char *token, void *data)
{
  double retval = strtod(token, NULL);

  /*  fprintf(stderr, "Evaluated '%s' to %f\n", token,retval); */

  return retval;
}


int main(int argc, char *argv[])
{
  char *buffer;

  if(argc < 2)
  {
    printf("Usage: %s \"string\"\n", argv[0]);
  }
  else
  {
    buffer = HTTP_ExpressionParse(argv[1]);

    printf("Value is %f\n", HTTP_ExpressionEvaluate(buffer, evaluator,NULL)); 
  
    free(buffer);
  }
  return 0;
}
  
#endif /* TEST_HTTP_EVALUATE */