-
Notifications
You must be signed in to change notification settings - Fork 0
/
expr-code.c
3206 lines (3079 loc) · 133 KB
/
expr-code.c
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
//---------------------------------------------------------------------------
/* expression handling code and other generally useful code for Builder C++ */
/*----------------------------------------------------------------------------
* Copyright (c) 2012, 2013,2022, 2024 Peter Miller
*
* 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 AUTHOR OR COPYRIGHT HOLDER 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.
*--------------------------------------------------------------------------*/
/* expression handling code and other generally useful code for Builder C++
Expressions (in decreasing priority)
+/-constants, +/-()
*,/,%
+,-
>>,<<
<,>,>=,<=
==,!=
&
^
|
&&
||
(C) Peter Miller Sept 2012 [Note NO company copyright for this code]
Written assuming Borland builder 5.
Should compile with Builder 6, the latest versions of builder use w_char's for GUI functions and so would need changes.
expression handler is pure C code.
Version 0.1 26-9-2012 has basic crprintf and working lookup & install
version 0.2 4/10/12 has working crprintf & lookup & install
version 0.3 5/10/12 many more binary operators added & improved error handling
version 0.4 8/10/12 predefined functions added, as well as ~,!
version 0.5 10/10/12 - can now actually execute rpn to evaluate expressions
version 0.6 11/10/12 - constants (like pi) added.
hex numbers (0xdddd) can be entered
~constant evaluated at compile time rather than run time.
simple rpn optimiser added (for constant expressions converts to just the constant value ).
interface to outside world improved now to_rpn(s) is the only function that takes a string
version 0.7 12/10/12 - added ? operator
added assign_expr() to allow assignments of variables to expressions
version 1.0 15/10/12 - expr optimisation made much more agressive (incrementally looks for a constant expression as it compiles rpn)
bool getfloat(char *s double *d) added that reads a floating point number (only) returns true if valid
simple regular expression matches supported using regex_match();
version 1.1 16/10/12 - added lin_reg(), log_reg() and deriv() [deriv is just dummy !]
version 1.2 19/10/12 - added csv parsing code
version 1.3 22/10/12 - added get_line to read a line from the file with no limits on line length.
deriv() added at last. Uses a noise reducing derivative whenever possible.
fastexp(x) added. 3% max rel error, and very low errors for small x (|x|<0.17).
version 1.4 23/10/12 - more complex string matching expressions added - sexpr()
version 1.5 24/10/12 - sexpr now supports "" in matched strings
- sexpr now supports ~ "regular expression" (already had ! so no need for a !~ )
version 1.6 26/10/12 - various routines changed to take float[] params ratther than double []
version 1.7 29/10/12 - log_lin_reg() added
version 1.8 30/10/12 - log_diff_lin_reg() added
version 1.9 31/10/12 - fastlog() added
version 1.10 1/11/12 - much more accurate (but a bit slower) fastlog()
version 1.11 8/11/12 - stdint.h header created. Much more accurate fastexp(), left less accurate version as fasterexp(), added fasterlog().
version 1.12 10/11/12 - added Application->ProcessMessages() called to crprintf to allow windows to update on this call (and added to monitor function of optimiser)
optimiser can be run as a thread if required.
version 2.0 20/11/12 - linear regression changed to only take 1 pass over data.
version 2.1 21/11/12 - linear regression changed to only use means on 1 pass. (note r2 value is unchecked).
version 2.2 22/11/12 - linear regression changed so 1 and 2 pass versions both give identical (correct) results - incl r^2
version 2.3 22/11/12 - define onepassreg allows selection of 1 or 2 pass linear regression on all variants.
getfloatgt0() and getfloatge0() added.
version 2.4 22/11/12 - generalised (2 param) least squares added.
version 2.5 24/11/12 - fastsqrt() & fastersqrt() added.
version 2.6 26/11/12 - fastsqrt & fastersqrt made faster (and fastersqrt more accurate).
fastinv() & fasterinv() added which can be used to remove divisions from code which may result in a speedup if division is slow (especially if multiply is fast).
version 2.7 26/11/12 - fastersqrt() error reduced.
version 2.8 28/11/12 - fastexp() rewritten base on using polynomial fit to error of fasterexp() - slightly faster (but a bit less accurate)
version 2.9 29/11/12 - fastlog() - tried to speed up using a polynomial in same way as fastexp() - failed - orig code was the best !
version 2.10 30/11/12 - fastlog() - sped up using 2 polymonials (one near 1 and the other elsewhere)- avoids the use of fp divides.
version 2.11 1/12/12 - added t90 and t99 to give t-scores and r2test90 r2test99 to give corresponding values to check r2 against.
fastinv() and fasterinv() improved. fastinv now uses an iteration for 1/x which speeds it up.
version 3.0 19-1-13 - copyright notices/license clarified on all code ("Expat" license used)
radarcharts added to gnuplot
version 3.1 31-1-13 - validate_num() and cvalidate_num() added for input validation, fpabs converted to inline.
version 3.2 2-2-13 - min(), max() added to expression evaluator , added matrix.cpp/matrix.h (to allocate/free 2D matrices )
version 3.3 3-2-13 - save_gui() and restore_gui() added work for editboxes, radiogroups & TCSpinedits
version 3.4 3-5-13 - added nextafterf() function
version 3.5 2-8-13 - added general purpose hash functions
- added SetCursorToEnd()
version 4.0 23-8-13 - changed so that does not need access to Form1 in this code (required so could be moved into "common-files")
version 4.1 7-3-2021 - added void leastsquares_rat3(float *y,float *x,int start, int end, double *a, double *b, double *c)
version 4.2 27/3/2020 - added Allow_dollar_T option to allow variables of form $T1 to appresr in expressions
version 5.0 31/7/2022 - added wchar_t versions of some functions to make porting to builder 10 simpler
version 5.1 11/9/2022 - merged csvgraph and common-files versions as had diverged.
version 6.0 14/9/2022 - split out pure C code - rprintf.cpp and getfloat.cpp made seperate files.
version 7.0 25/2/2024 - NAN added as constant, comparison (== and !=) made to work as expected (ie NAN=NAN=true)
version 7.1 30/4/2024 - called expr0 (rather than expr1()) after "(" (either in expressions or function calls). means ? operator works in these situations..
*/
#include "expr-code.h"
#include <cstdlib> /* for malloc() and free() */
#include <string.h> /* for strcmp() etc */
#include <stdarg.h> /* for va_start etc */
#include <stdio.h> /* for printf etc */
#include <time.h>
#include <ctype.h> /* isspace etc */
#include <math.h>
#include <float.h> /* _isnan() */
#include <values.h> /* MAXFLOAT etc */
#include <stdint.h> /* for uint32_t etc */
#include "interpolate.h"
#define onepassreg /* if defined use functions that only make 1 pass over data for regression, otherwise 2 passes are used . Normally 1 pass is faster and gives same results as 2 pass */
#define STATIC_ASSERT(condition) extern int STATIC_ASSERT_##__FILE__##__LINE__[2*!!(condition)-1] /* check at compile time and works in a global or function context see https://scaryreasoner.wordpress.com/2009/02/28/checking-sizeof-at-compile-time/ */
/* for numeric expression code */
static void expr0(void); /* deal with ?: operators */
static void expr1(void); /* lowest priority binary operator */
static void expr2(void);
static void expr3(void);
static void expr4(void);
static void expr5(void);
static void expr6(void);
static void expr7(void);
static void expr8(void);
static void expr9(void);
static void expr10(void); /* highest priority binary operator */
static void fact(void); /* recognises constants, variables, parenthesized expressions */
static double execute_rpn_from(size_t from); /* execute rpn created by previous call to to_rpn() from specified start to end & return result */
static void opt_const(size_t from); /* if rpn from onwards evaluates to a constant then replace it just with a constant */
/* for string matching expressions */
static bool sexpr1(void); /* deal with & */
static bool sexpr2(void); /* deal with & */
static bool sexpr3(void); /* deal with (), $n= "..." or $n != "..." */
static bool scmp(int i); /* $n == "..." */
static char **sexpr_in; /* global variables - csv_parsed input & max nos columns */
static int sexpr_n;
static char *sexpr_cp; /* pointer into input expression string */
static bool sflag; /* true if expression is valid, false if not */
/* general purpose hash functions based on Fowler/Noll/Vo hash fnv-1a , with optional "mixing" at the end */
void hash_reset(uint32_t *h) // reset hash h to its initial value
{*h=2166136261;
}
static uint32_t hash_internal(const char *s,uint32_t hash) // returns start_hash "plus" string s
{uint32_t newchar;
while(s!=NULL && *s!= '\0')
{newchar=(uint32_t)(*s++); /* get next character */
hash^=newchar;
hash*=16777619; // "magic number" defined for FNV algorithm
}
return hash;
}
void hash_add(const char *s, uint32_t *h) // adds string s to hash h, updates h
{*h=hash_internal(s,*h);
}
uint32_t hash_str(const char *s) // returns hash of string , always starting from the same initial value for hash
{uint32_t hash;
hash_reset(&hash);
hash=hash_internal(s,hash);
// this following code is proposed in http://home.comcast.net/~bretm/hash/6.html as a way to ensure even a short string impacts all bits of the hash
// this is not necessary when we are hashing a whole file, but could be useful when hashing for a "symbol table" or similar.
hash += hash<<13;
hash ^= hash >>7;
hash += hash <<3;
hash ^= hash >>17;
hash += hash <<5;
return hash;
}
/* table lookup code based on K&R The C programming language (1st Ed) section 6.6 */
#define HASHSIZE 128 /* number of different hash values - this does not restrict the number of items that can be stored */
/* ideally this is a power of 2, if its not the last entry in the hashtab may have less items in it than the others (assuming "uniform" distribution of keys) */
static pnlist hashtab[HASHSIZE]; /* array pointers to nlist structures (which are allocated using malloc() )*/
#if 1
static int hash(const char *s)
{
return hash_str(s) % HASHSIZE;
}
#else
/* very simple hash */
static int hash(char *s)
{int hashval;
for(hashval=0;*s!= '\0';)
{hashval+= *s++; /* simplest possible hash - just add up characters - not critical to performance so left simple */
if(hashval<0) hashval = -hashval; /* trap "overflow" to ensure hashval is always positive [needed for % later] */
}
return hashval % HASHSIZE;
}
#endif
pnlist lookup(const char *s) /* lookup s , returns pointer to struct snlist or NULL if not found */
{pnlist np;
for(np=hashtab[hash(s)];np!=NULL;np=np->next)
{if (strcmp(s,np->name)==0)
return np; /* found it */
}
return NULL; /* not found */
}
char *strsave(const char *s); /* forward declaration to avoid compiler warning */
char *strsave(const char *s) /* save a copy of string s using malloc , returns NULL if no space */
{char *p;
if((p=(char *)(malloc(strlen(s)+1))) != NULL)
{strcpy(p,s); /* got space, copy string */
}
return p;
}
pnlist install(const char *name) /* adds name to hashtab if it does not exist, returns pointer to entry created or NULL on error */
{pnlist np;
int hashval;
if((np=lookup(name))==NULL)
{ /* not found , create new entry */
np=(pnlist)( malloc(sizeof(*np)));
if(np==NULL) return NULL;/* out space */
if((np->name=strsave(name))==NULL)
return NULL; /* not enough space for "string" name */
np->value=0.0; /* default value */
hashval=hash(np->name);
np->next=hashtab[hashval]; /* assumes hashtab initialised to NULL */
hashtab[hashval]=np; /* insert at start of linked list of items from this hashvalue */
}
/* else already found */
return np;
}
/* expression evaluator code */
/* recursive descent evaluation used */
#define MAXRPN 1000 /* max bytes in rpn generated */
static bool flag; /* used in recursive descent parser is true if expression was OK */
static unsigned int nos_vars; /* number of variables in expression [0 means expression will evaluate to a constant] */
static char *e; /* expression as a string */
static unsigned char rpn[MAXRPN];
static size_t rpnptr; /* index into rpn[] next token will be placed */
typedef enum _token {LOR,LAND,OR,XOR,AND,EQ,NEQ,LESS,GT,LE,GE,SHIFTR,SHIFTL,ADD,SUB,MULT,DIV,MOD,MINUS,LNOT,NOT,CONSTANT,VARIABLE,
ACOS,ASIN,ATAN,SIN,COS,TAN,LOG,EXP,SQRT,POW,COSH,SINH,TANH,FABS,QN,MAX,MIN} token;
#pragma option -w-pin /* ignore W8-61 Initialisation is only partially bracketed that would be created by struct functions below */
static struct functions /* list of predefined functions/constants - must be in alphabetic order */
{ const char *keyword;
int nosargs; /* number of arguments, eg pow(x,y) has 2 , -1 means its a constant (and brackets not then needed)*/
token tk; /* corresponding token */
double value; /* value if its a constant [by convention set to 0 if its not a constant]*/
} funtab[]=
{ {"abs",1,FABS,0},
{"acos",1,ACOS,0},
{"asin",1,ASIN,0},
{"atan",1,ATAN,0},
{"cos",1,COS,0},
{"cosh",1,COSH,0},
{"exp",1,EXP,0},
{"log",1,LOG,0},
{"max",2,MAX,0},
{"min",2,MIN,0},
{"nan",-1,CONSTANT, __builtin_nan("0") }, // NAN is not considered by the compiler as a constant
{"pi",-1,CONSTANT, M_PI},
{"pow",2,POW,0},
{"sin",1,SIN,0},
{"sinh",1,SINH,0},
{"sqrt",1,SQRT,0},
{"tan",1,TAN,0},
{"tanh",1,TANH,0}
};
bool check_function_tab()
{ /* checks above table is in alphabetic order - returns true if it is, false if not */
int i;
int n= sizeof(funtab)/sizeof(struct functions); /* nos elements in above table */
int errs=0;
for(i=1;i<n;++i)
{if(strcmp(funtab[i-1].keyword,funtab[i].keyword)>=0)
errs++;
}
// crprintf("check_function() %d functions in table, %d errors found\n",n,errs);
return errs==0;
}
static int lookup_fun(char *name)
{/* returns index into array, -1 if not found . uses binary search */
int low,high,mid; // must be signed to work !
int cond;
int n=sizeof(funtab)/sizeof(struct functions); /* size of table */
low=0;
high=n-1;
while (low<=high)
{mid=(low+high)>>1;
if((cond=strcmp(name,funtab[mid].keyword))<0)
high=mid-1;
else if (cond > 0)
low=mid+1;
else return mid; /* found */
}
return -1; /* not found */
}
static void rpn_init(void) /* initialise ready for rpn creation */
{ rpnptr=0;
flag=true;
nos_vars=0;
}
static void addrpn_op(token op) /* add operator to rpn */
{if(rpnptr<MAXRPN)
{rpn[rpnptr++]=(unsigned char)op;
}
}
static void addrpn_c(unsigned char c) /* add 1 byte to rpn */
{if(rpnptr<MAXRPN)
{rpn[rpnptr++]=c;
}
}
static void addrpn_constant(double v) /* add double constant to rpn */
{union u_tag {
unsigned char c[sizeof(double)];
double d;
} u;
size_t i;
addrpn_op(CONSTANT);
u.d=v;
for(i=0;i<sizeof(double);++i) /* write out all 8 bytes of value */
{
addrpn_c(u.c[i]);
}
}
static void addrpn_variable(pnlist v) /* adds variable to rpn */
{union u_tag {
unsigned char c[sizeof(pnlist)];
pnlist p;
} u;
size_t i;
addrpn_op(VARIABLE);
u.p=v;
for(i=0;i<sizeof(pnlist);++i) /* write out all 4/8 bytes of pointer */
{
addrpn_c(u.c[i]);
}
}
bool last_expression_ok() /* returns true if last expression was correct in syntax , false otherwise */
{ return flag;
}
void to_rpn(char *expression)
{ /* convert expression to rpn, expression just returns a value and contains no assignments*/
e=expression;
rpn_init();
expr0();
if(*e!='\0') flag=false; /* expression was valid - but did not finish at the end of the string */
if(rpnptr>=MAXRPN) flag=false; /* expression too complex [rpn too long] */
}
void optimise_rpn()
/* optimise rpn generated by prior call to to_rpn() */
{
#if 1
/* optimisation is part of parser, this is just the final step... */
opt_const(0); /* if whole expression evaluates to a constant, then just make expression a single constant */
#else
/* for now just do simplest thing of optimising expression if its completely a constant */
if(flag && nos_vars==0)
{/* whole expression is valid & a constant - evaluate it then just make result a constant */
double d=execute_rpn();
if(flag)
{/* if executed OK */
rpn_init(); /* restore rpn */
addrpn_constant(d); /* make it just a constant */
}
}
#endif
}
void assign_expr(char *expression) /* deal with assignments , evaluates expression and stores result in variable ; allows multiple assignments on one line */
{char *start,lastc; /* start of variable name, and character that terminates name */
pnlist v;/* variable */
e=expression;
while(1)
{rpn_init(); /* rpn is only for an expression - so need to restart after every ; */
while(isspace(*e))++e; /* skip whitespace */
if(isalpha(*e) || *e=='_')
{/* variable must start with a letter or an underline */
start=e;
while(isalnum(*e) || *e=='_') /* variables can include letters, digits, _ */
++e;
lastc= *e; /* termination - 1st char not part of variable name */
*e='\0'; /* make a variable a null terminated string for now */
v=install(start); /* lookup in symbol table, will create new entry if required */
*e=lastc; /* restore input string back to what it was */
if(v==NULL)
{/* error - no space ? */
flag=false;
return;
}
/* if we get here have a valid variable "in" v */
}
else
{/* no variable name found */
flag=false;
return;
}
while(isspace(*e))++e; /* skip whitespace */
if(*e!='=')
{flag=false; /* = must come after variable name */
return;
}
++e; /* skip = */
expr0(); /* get expression */
if(!(*e=='\0' || *e==';')) flag=false; /* expression was valid - but did not finish at the end of the string or ; */
if(rpnptr>=MAXRPN) flag=false; /* expression too complex [rpn too long] */
if(flag) /* expression valid */
{double d=execute_rpn(); /* execute expression */
if(flag)
{/* if executed OK */
v->value=d; /* set variables value to the result of the expression */
}
}
if(!flag) return;/* some error - done */
if(*e==';')
{++e;
continue; /* ; so lets do it all again */
}
else return; /* done */
} /* end of while(1) */
}
static void expr0(void) /* deal with ?: operators */
/* note if we really wanted to we could optimise a constant before the ? to only execute one of the 2 other expressions - this is NOT done here */
{size_t start_rpnptr=rpnptr; /* allows us to check if the result of this is a constant */
expr1();
if(!flag) return;
while(isspace(*e))++e; /* skip whitespace */
while(*e=='?')
{++e; /* pass over ? */
expr0(); /* expression value if true - need to call expr0 here as 1==2? 3==4?1:0 :1 is valid as is 1==2?2:3 ? 1: 0 )2nd done by while loop here */
if(!flag) return;
while(isspace(*e))++e; /* skip whitespace */
if(*e!=':')
{/* error : expected */
flag=false;
return;
}
++e; /* pass over : */
expr0(); /* expression value if false */
if(!flag) return;
while(isspace(*e))++e; /* skip whitespace */
addrpn_op(QN);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
}
static void expr1(void) /* lowest priority binary operator || */
{size_t start_rpnptr=rpnptr; /* allows us to check if the result of this is a constant */
expr2();
if(!flag) return;
while(isspace(*e))++e; /* skip whitespace */
while(flag)
{
if(*e=='|' && *(e+1)=='|')
{e+=2;
expr2();
if(!flag) return;
addrpn_op(LOR);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else flag=false;
}
flag=true;
}
static void expr2(void) /* binary operator && */
{size_t start_rpnptr=rpnptr; /* allows us to check if the result of this is a constant */
expr3();
if(!flag) return;
while(isspace(*e))++e; /* skip whitespace */
while(flag)
{if(*e=='&' && *(e+1)=='&')
{e+=2;
expr3();
if(!flag) return;
addrpn_op(LAND);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else flag=false;
}
flag=true;
}
static void expr3(void) /* binary operator | */
{size_t start_rpnptr=rpnptr; /* allows us to check if the result of this is a constant */
expr4();
if(!flag) return;
while(isspace(*e))++e; /* skip whitespace */
while(flag)
{if(*e=='|' && *(e+1)!='|') /* | and not || */
{++e;
expr4();
if(!flag) return;
addrpn_op(OR);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else flag=false;
}
flag=true;
}
static void expr4(void) /* binary operator ^ */
{size_t start_rpnptr=rpnptr; /* allows us to check if the result of this is a constant */
expr5();
if(!flag) return;
while(isspace(*e))++e; /* skip whitespace */
while(flag)
{if(*e=='^')
{++e;
expr5();
if(!flag) return;
addrpn_op(XOR);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else flag=false;
}
flag=true;
}
static void expr5(void) /* binary operator & */
{size_t start_rpnptr=rpnptr; /* allows us to check if the result of this is a constant */
expr6();
if(!flag) return;
while(isspace(*e))++e; /* skip whitespace */
while(flag)
{if(*e=='&' && *(e+1)!='&') /* & and not && */
{++e;
expr6();
if(!flag) return;
addrpn_op(AND);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else flag=false;
}
flag=true;
}
static void expr6(void) /* binary operators ==, !=*/
{size_t start_rpnptr=rpnptr; /* allows us to check if the result of this is a constant */
expr7();
if(!flag) return;
while(isspace(*e))++e; /* skip whitespace */
while(flag)
{if(*e=='=' && *(e+1)=='=')
{e+=2;
expr7();
if(!flag) return;
addrpn_op(EQ);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else if(*e=='!' && *(e+1)=='=')
{e+=2;
expr7();
if(!flag) return;
addrpn_op(NEQ);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else flag=false;
}
flag=true;
}
static void expr7(void) /* binary operators <,>,<=,>= */
{size_t start_rpnptr=rpnptr; /* allows us to check if the result of this is a constant */
expr8();
if(!flag) return;
while(isspace(*e))++e; /* skip whitespace */
while(flag)
{if(*e=='<' && *(e+1)=='=') /* must check 2 character tokens before 1 character ! */
{e+=2;
expr8();
if(!flag) return;
addrpn_op(LE);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else if(*e=='>' && *(e+1)=='=')
{e+=2;
expr8();
if(!flag) return;
addrpn_op(GE);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else if(*e=='<')
{++e;
expr8();
if(!flag) return;
addrpn_op(LESS);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else if(*e=='>')
{++e;
expr8();
if(!flag) return;
addrpn_op(GT);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else flag=false;
}
flag=true;
}
static void expr8(void) /* binary operators >>,<< */
{size_t start_rpnptr=rpnptr; /* allows us to check if the result of this is a constant */
expr9();
if(!flag) return;
while(isspace(*e))++e; /* skip whitespace */
while(flag)
{if(*e=='>' && *(e+1)=='>')
{e+=2;
expr9();
if(!flag) return;
addrpn_op(SHIFTR);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else if(*e=='<' && *(e+1)=='<')
{e+=2;
expr9();
if(!flag) return;
addrpn_op(SHIFTL);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else flag=false;
}
flag=true;
}
static void expr9(void) /* binary operators +,- */
{size_t start_rpnptr=rpnptr; /* allows us to check if the result of this is a constant */
expr10();
if(!flag) return;
while(isspace(*e))++e; /* skip whitespace */
while(flag)
{if(*e=='+')
{++e;
expr10();
if(!flag) return;
addrpn_op(ADD);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else if(*e=='-')
{++e;
expr10();
if(!flag) return;
addrpn_op(SUB);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else flag=false;
}
flag=true;
}
static void expr10(void) /* highest priority binary operators, *,/,% */
{size_t start_rpnptr=rpnptr; /* allows us to check if the result of this is a constant */
fact();
if(!flag) return;
while(isspace(*e))++e; /* skip whitespace */
while(flag)
{if(*e=='*')
{++e;
fact();
if(!flag) return;
addrpn_op(MULT);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else if(*e=='/')
{++e;
fact();
if(!flag) return;
addrpn_op(DIV);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else if(*e=='%')
{++e;
fact();
if(!flag) return;
addrpn_op(MOD);
opt_const(start_rpnptr); /* see if we can optimise this all as a constant */
}
else flag=false;
}
flag=true;
}
static void fact(void) /* recognises constants, variables, (predefined) functions, parenthesized expressions */
{bool isneg=false;
bool islognot=false; /* ! */
bool isnot=false; /* ~ */
size_t start_rpnptr=rpnptr; /* allows us to check if the result of this is a constant */
while(isspace(*e))++e; /* skip whitespace */
/* note the C standard appears to only allow one monadic operator (-,+,!,~) so thats whats implemented here */
if(*e=='-')
{/* monadic minus */
++e;
while(isspace(*e))++e; /* skip whitespace */
isneg=true;
}
else if(*e=='+')
{/* monadic plus [allowed in C89 and seems reasonable as "+1" is a sensible expression */
++e;
while(isspace(*e))++e; /* skip whitespace */
}
else if(*e=='!')
{/* monadic logical NOT */
++e;
while(isspace(*e))++e; /* skip whitespace */
islognot=true;
}
else if(*e=='~')
{/* monadic bitwise NOT */
++e;
while(isspace(*e))++e; /* skip whitespace */
isnot=true;
}
#ifdef Allow_dollar_vars_in_expr
/* new code allows variables named $1.. $999... like awk - these can only be read from (they are assumed to be automatically set eg from a column of a csv file) */
if(isalpha(*e) || *e=='_' || *e=='$')
{/* variable/function/constant (eg pi) must start with a letter or an underline or $ */
char *start=e,lastc;
pnlist v;
int i;
if(*e=='$')
{++e; /* skip $ */
#ifdef Allow_dollar_T
/* allow $T1 etc to refer to trace 1 */
if(*e=='t' || *e=='T') ++e; // just need to skip t here, code below checks that a number follows
#endif
if(!isdigit(*e) || *e=='0')
{
flag=false; /* $ must be followed by an integer 1 or more [0 is not allowed] */
return;
}
while(isdigit(*e))
++e; /* can be followed by any number of digits */
}
else
{/* "standard variable" (does not start with $ */
while(isalnum(*e) || *e=='_') /* variables can include letters, digits, _ */
++e;
}
#else
/* original code that does not allow $xxx variable names */
if(isalpha(*e) || *e=='_')
{/* variable/function/constant (eg pi) must start with a letter or an underline */
char *start=e,lastc;
pnlist v;
int i;
while(isalnum(*e) || *e=='_') /* variables can include letters, digits, _ */
++e;
#endif
lastc= *e; /* termination - 1st char not part of variable name */
*e='\0'; /* make a variable a null terminated string for now */
// crprintf("before lookup_fun(%s)\n",start);
i=lookup_fun(start);
// crprintf("lookup_fun(%s) returns %d\n",start,i);
if(i>=0 && funtab[i].nosargs == -1)
{ /* constant found (like "pi" ) */
double d=funtab[i].value;
*e=lastc; /* restore input string back to what it was */
addrpn_constant(d);
}
else if (i>=0)
{/* valid function name found */
int nosargs=funtab[i].nosargs;
*e=lastc; /* restore input string back to what it was */
while(isspace(*e))++e; /* skip whitespace */
if(*e!='(')
{flag=false; /* function must be followed by ( */
return;
}
++e; /* skip over ( , then get a list of comma seperated arguments */
while(nosargs-- >0)
{expr0(); /* get an expression */
if(!flag) return; /* error */
if(nosargs>0)
{/* more arguments to come, need a comma now */
while(isspace(*e))++e; /* skip whitespace */
if(*e!=',')
{flag=false;
return;
}
++e; /* skip over , */
}
}
while(isspace(*e))++e; /* skip whitespace */
if(*e!=')')
{flag=false; /* no trailing ) in function call */
return;
}
++e; /* skip over ) */
addrpn_op(funtab[i].tk); /* RPN to actually execute function */
}
else
{/* try to see it its a variable */
#ifdef Allow_dollar_vars_in_expr
if(*start=='$')
v=install(start); /* lookup variable in symbol table - adding it if required as $nnn "variables" are predefined */
else
#endif
v=lookup(start); /* lookup in symbol table */
*e=lastc; /* restore input string back to what it was */
if(v==NULL)
{/* error - variable not defined */
flag=false;
return;
}
else
{
addrpn_variable(v);
++nos_vars; /* keep count of number of variables in expression */
}
}
}
else if(isdigit(*e)|| *e=='.')
{ /* constant must start with a number or a decimal point */
/* hex numbers starting 0x or 0X are supported */
double d;
if(*e=='0' && (*(e+1)=='x' || *(e+1)=='X'))
d=strtol(e,&e,0); /* 0x=> hex number - note bitwise operators assume 32bit unsigned ints but this allows entry of larger numbers [which may not be exactly represented as a double] */
else d=strtod(e,&e); /* floating point number */
/*crprintf("constant %g\n",d);*/
addrpn_constant(d);
}
else if(*e=='(')
{ /* bracketed expression */
++e;
expr0();
if(!flag) return;
while(isspace(*e))++e; /* skip whitespace */
if(*e==')')
{++e; /* flag already true because of if(!flag) above so no need to set it again here */
}
else flag=false; /* error missing ")" */
}
else
{flag=false; /* error */
}
if(flag)
{/* if no errors so far, then deal with monadic operators here , note if these apply to a constant they will be optimised out by call to opt_const() below */
if(isneg) addrpn_op(MINUS);
if(islognot) addrpn_op(LNOT);
if(isnot) addrpn_op(NOT);
}
opt_const(start_rpnptr); /* see if we can optimise this all away to a single constant */
}
void print_rpn() /* print rpn for debugging */
{size_t i,j;
union u_tagc {
unsigned char c[sizeof(double)];
double d;
} uconst;
union u_tagv {
unsigned char c[sizeof(pnlist)];
pnlist p;
} uvar;
if(flag)
crprintf("Flag=true. rpn=");
else
crprintf("Flag=false. rpn=");
for(i=0;i<rpnptr;++i)
{switch((token)(rpn[i]))
{
case LOR: crprintf("<LOR>"); break;
case LAND: crprintf("<LAND>"); break;
case OR: crprintf("<OR>"); break;
case XOR: crprintf("<XOR>"); break;
case AND: crprintf("<AND>"); break;
case EQ: crprintf("<EQ>"); break;
case NEQ: crprintf("<NEQ>"); break;
case LESS: crprintf("<LESS>"); break;
case GT: crprintf("<GT>"); break;
case LE: crprintf("<LE>"); break;
case GE: crprintf("<GE>"); break;
case SHIFTR: crprintf("<SHIFTR>"); break;
case SHIFTL: crprintf("<SHIFTL>"); break;
case ADD: crprintf("<ADD>"); break;
case SUB: crprintf("<SUB>"); break;
case MULT: crprintf("<MULT>"); break;
case DIV: crprintf("<DIV>"); break;
case MOD: crprintf("<MOD>"); break;
case MINUS: crprintf("<MINUS>"); break;
case LNOT: crprintf("<LNOT>"); break;
case NOT: crprintf("<NOT>"); break;
/* functions */
case ACOS: crprintf("<ACOS>"); break;
case ASIN: crprintf("<ASIN>"); break;
case ATAN: crprintf("<ATAN>"); break;
case SIN: crprintf("<SIN>"); break;
case COS: crprintf("<COS>"); break;
case TAN: crprintf("<TAN>"); break;
case LOG: crprintf("<LOG>"); break;
case EXP: crprintf("<EXP>"); break;
case SQRT: crprintf("<SQRT>"); break;
case POW: crprintf("<POW>"); break;
case COSH: crprintf("<COSH>"); break;
case SINH: crprintf("<SINH>"); break;
case TANH: crprintf("<TANH>"); break;
case FABS: crprintf("<ABS>"); break;
case MAX: crprintf("<MAX>"); break;
case MIN: crprintf("<MIN>"); break;
case QN: crprintf("<QN>"); break;
case CONSTANT: crprintf("<CONSTANT=");
for(j=0;j<sizeof(double);++j)
{
crprintf("%02x",rpn[++i]);
uconst.c[j]=rpn[i];
}
crprintf(":%g>",uconst.d);
break;
case VARIABLE: crprintf("<VARIABLE=");
for(j=0;j<sizeof(pnlist);++j)
{
crprintf("%02x",rpn[++i]);
uvar.c[j]=rpn[i];
}
crprintf(":%s:%g>",uvar.p->name,uvar.p->value);
break;
// default: crprintf("<??%02x>",rpn[i]); break;
}
}
}
#define MAXSTACK 30 /* maxsize of stack */
static double stack[MAXSTACK];
static unsigned int sp;
static bool rpn_constant; /* used to show if rpn expression is a constant */
double execute_rpn() /* execute rpn created by previous call to to_rpn() & return result */
{return execute_rpn_from(0);
}
void opt_const(size_t from) /* if rpn from specified location to end is a constant then just replace it with a constant */
{bool t_flag=flag; /* save a copy of flag and restore it at the end */
double d=execute_rpn_from(from);
if(flag & rpn_constant)
{rpnptr=from; /* can delete entire expression and replace with a constant */
addrpn_constant(d);
}
flag=t_flag;
}
static double execute_rpn_from(size_t from) /* execute rpn created by previous call to to_rpn() from specified start to end & return result */
{size_t i,j;
union u_tagc {
unsigned char c[sizeof(double)];
double d;
} uconst;
union u_tagv {
unsigned char c[sizeof(pnlist)];
pnlist p;
} uvar;
if(!flag)
{/* expression error - return 0 */
return 0.0;
}
rpn_constant=true; /* assume rpn is a constant, set to false if any variables found in rpn */
sp=0;
/* valid expression - execute it */
for(i=from;i<rpnptr;++i)
{switch((token)(rpn[i]))
{/* note 1 - 2 => 1 2 - so we need [sp-2]=[sp-2] OP [sp-1] */
case LOR: stack[sp-2]=(stack[sp-2]!=0) || (stack[sp-1]!=0); sp-=1; break;
case LAND: stack[sp-2]=(stack[sp-2]!=0) && (stack[sp-1]!=0); sp-=1; break;
/* bitwise operators work on uisigned ints (32 bits) which can be exactly represented as doubles */
case OR: stack[sp-2]= (unsigned int)(stack[sp-2]) | (unsigned int)(stack[sp-1]); sp-=1; break;
case XOR: stack[sp-2]= (unsigned int)(stack[sp-2]) ^ (unsigned int)(stack[sp-1]); sp-=1; break;
case AND: stack[sp-2]= (unsigned int)(stack[sp-2]) & (unsigned int)(stack[sp-1]); sp-=1; break;
case EQ: if(isnan(stack[sp-1]) || isnan(stack[sp-2]) )
{// deal with NAN's as special case as we want NAN=NAN to give true
stack[sp-2]=(isnan(stack[sp-1]) && isnan(stack[sp-2]) ) ;