-
Notifications
You must be signed in to change notification settings - Fork 5
/
libast.c
2583 lines (2449 loc) · 90.1 KB
/
libast.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
/*******************************************************************************
* libast.c: this file is part of the libast library.
* libast: C library for evaluating expressions with the abstract syntax tree.
* Github repository:
https://github.com/cheng-zhao/libast
* Copyright (c) 2020 Cheng Zhao <zhaocheng03@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include <ctype.h>
#include <limits.h>
#include <string.h>
#include <math.h>
#include "libast.h"
/*============================================================================*\
Macros
\*============================================================================*/
/* Error codes */
#define AST_ERR_MEMORY (-1)
#define AST_ERR_INIT (-2)
#define AST_ERR_STRING (-3)
#define AST_ERR_DTYPE (-4)
#define AST_ERR_TOKEN (-5)
#define AST_ERR_VAR (-6)
#define AST_ERR_EXIST (-7)
#define AST_ERR_NOEXP (-8)
#define AST_ERR_VALUE (-9)
#define AST_ERR_SIZE (-10)
#define AST_ERR_EVAL (-11)
#define AST_ERR_NVAR (-12)
#define AST_ERR_MISMATCH (-13)
#define AST_ERR_UNKNOWN (-99)
#define AST_ERRNO(ast) (((ast_error_t *)ast->error)->errno)
#define AST_IS_ERROR(ast) (AST_ERRNO(ast) != 0)
/* Mixture data types. */
#define AST_DTYPE_NULL 0
#define AST_DTYPE_INTEGER (AST_DTYPE_INT | AST_DTYPE_LONG)
#define AST_DTYPE_REAL (AST_DTYPE_FLOAT | AST_DTYPE_DOUBLE)
#define AST_DTYPE_NUMBER (AST_DTYPE_INTEGER | AST_DTYPE_REAL)
#define AST_DTYPE_NATIVE (AST_DTYPE_BOOL | AST_DTYPE_NUMBER)
#define AST_DTYPE_ALL (AST_DTYPE_NATIVE | AST_DTYPE_STRING)
/* Data type for numerical literals in boolean expressions. */
#define AST_DTYPE_NUM4BOOL (AST_DTYPE_LONG | AST_DTYPE_DOUBLE)
/*============================================================================*\
Internal data structures
\*============================================================================*/
/* Definitions of tokens. */
typedef enum {
AST_TOK_UNDEF = 0, /* undefined token */
AST_TOK_NUM = 1, /* a number */
AST_TOK_STRING = 2, /* a string literal */
AST_TOK_VAR = 3, /* a variable */
AST_TOK_PAREN_LEFT = 4, /* `(` : left parenthesis */
AST_TOK_PAREN_RIGHT = 5, /* `)` : right parenthesis */
AST_TOK_ABS = 6, /* abs : absolute value */
AST_TOK_SQRT = 7, /* sqrt : square root */
AST_TOK_LN = 8, /* ln : log_e */
AST_TOK_LOG = 9, /* log : log_10 */
AST_TOK_ISFINITE = 10, /* isfinite */
AST_TOK_NEG = 11, /* `-` : negative */
AST_TOK_LNOT = 12, /* `!` : logical NOT */
AST_TOK_BNOT = 13, /* `~` : bitwise NOT */
AST_TOK_EXP = 14, /* `**` : Exponent */
AST_TOK_MUL = 15, /* `*` : multiplication */
AST_TOK_DIV = 16, /* `/` : division */
AST_TOK_REM = 17, /* `%` : remainder */
AST_TOK_ADD = 18, /* `+` : addition */
AST_TOK_MINUS = 19, /* `-` : subtraction */
AST_TOK_LEFT = 20, /* `<<` : left shift */
AST_TOK_RIGHT = 21, /* `>>` : right shift */
AST_TOK_LT = 22, /* `<` : less than */
AST_TOK_LE = 23, /* `<=` : less or equal */
AST_TOK_GT = 24, /* `>` : greater than */
AST_TOK_GE = 25, /* `>=` : greater or equal */
AST_TOK_EQ = 26, /* `==` : equal to */
AST_TOK_NEQ = 27, /* `!=` : not equal to */
AST_TOK_BAND = 28, /* `&` : bitwise AND */
AST_TOK_BXOR = 29, /* `^` : bitwise XOR */
AST_TOK_BOR = 30, /* `|` : bitwise OR */
AST_TOK_LAND = 31, /* `&&` : logical AND */
AST_TOK_LOR = 32 /* `||` : logical OR */
} ast_tok_t;
/* Types of the tokens. */
typedef enum {
AST_TOKT_NULL, /* undefined token */
AST_TOKT_UOPT, /* a unary operator */
AST_TOKT_BOPT, /* a binary operator */
AST_TOKT_PAREN, /* parenthesis */
AST_TOKT_FUNC, /* pre-defined function */
AST_TOKT_VALUE, /* number or string literal */
AST_TOKT_VAR /* variable */
} ast_tok_type_t;
/* Operator attributes. */
typedef struct {
ast_tok_type_t type; /* type of the token */
int precedence; /* precedence of the token */
int argc; /* number of arguments */
int idtype; /* accepted argument dtype */
int odtype; /* returned data type */
} ast_tok_attr_t;
static const ast_tok_attr_t ast_tok_attr[] = {
/** token **/
/* type precedence argc idtype odtype */
/** AST_TOK_UNDEF **/
{AST_TOKT_NULL, -1, 1, AST_DTYPE_NULL, AST_DTYPE_NULL},
/** AST_TOK_NUM **/
{AST_TOKT_VALUE, 99, 0, AST_DTYPE_NULL, AST_DTYPE_NUMBER},
/** AST_TOK_STRING **/
{AST_TOKT_VALUE, 99, 0, AST_DTYPE_NULL, AST_DTYPE_STRING},
/** AST_TOK_VAR **/
{AST_TOKT_VAR, 99, 0, AST_DTYPE_NULL, AST_DTYPE_ALL},
/** AST_TOK_PAREN_LEFT : `(` **/
{AST_TOKT_PAREN, 88, 2, AST_DTYPE_NULL, AST_DTYPE_ALL},
/** AST_TOK_PAREN_RIGHT : `)` **/
{AST_TOKT_PAREN, 88, 2, AST_DTYPE_NULL, AST_DTYPE_ALL},
/** AST_TOK_ABS : `abs` **/
{AST_TOKT_FUNC, 88, 1, AST_DTYPE_NUMBER, AST_DTYPE_NUMBER},
/** AST_TOK_SQRT : `sqrt` **/
{AST_TOKT_FUNC, 88, 1, AST_DTYPE_NUMBER, AST_DTYPE_REAL},
/** AST_TOK_LN : `ln` **/
{AST_TOKT_FUNC, 88, 1, AST_DTYPE_NUMBER, AST_DTYPE_REAL},
/** AST_TOK_LOG : `log` **/
{AST_TOKT_FUNC, 88, 1, AST_DTYPE_NUMBER, AST_DTYPE_REAL},
/** AST_TOK_ISFINITE : isfinite **/
{AST_TOKT_FUNC, 88, 1, AST_DTYPE_REAL, AST_DTYPE_BOOL},
/** AST_TOK_NEG : `-` **/
{AST_TOKT_UOPT, 12, 1, AST_DTYPE_NUMBER, AST_DTYPE_NUMBER},
/** AST_TOK_LNOT : `!` **/
{AST_TOKT_UOPT, 12, 1, AST_DTYPE_NATIVE, AST_DTYPE_BOOL},
/** AST_TOK_BNOT : `~` **/
{AST_TOKT_UOPT, 12, 1, AST_DTYPE_INTEGER, AST_DTYPE_INTEGER},
/** AST_TOK_EXP : `**` **/
{AST_TOKT_BOPT, 11, 2, AST_DTYPE_NUMBER, AST_DTYPE_NUMBER},
/** AST_TOK_MUL : *` **/
{AST_TOKT_BOPT, 10, 2, AST_DTYPE_NUMBER, AST_DTYPE_NUMBER},
/** AST_TOK_DIV : `/` **/
{AST_TOKT_BOPT, 10, 2, AST_DTYPE_NUMBER, AST_DTYPE_NUMBER},
/** AST_TOK_REM : `%` **/
{AST_TOKT_BOPT, 10, 2, AST_DTYPE_NUMBER, AST_DTYPE_NUMBER},
/** AST_TOK_ADD : `+` **/
{AST_TOKT_BOPT, 9, 2, AST_DTYPE_NUMBER, AST_DTYPE_NUMBER},
/** AST_TOK_MINUS : `-` **/
{AST_TOKT_BOPT, 9, 2, AST_DTYPE_NUMBER, AST_DTYPE_NUMBER},
/** AST_TOK_LEFT : `<<` **/
{AST_TOKT_BOPT, 8, 2, AST_DTYPE_INTEGER, AST_DTYPE_INTEGER},
/** AST_TOK_RIGHT : `>>` **/
{AST_TOKT_BOPT, 8, 2, AST_DTYPE_INTEGER, AST_DTYPE_INTEGER},
/** AST_TOK_LT : `<` **/
{AST_TOKT_BOPT, 7, 2, AST_DTYPE_NUMBER, AST_DTYPE_BOOL},
/** AST_TOK_LE : `<=` **/
{AST_TOKT_BOPT, 7, 2, AST_DTYPE_NUMBER, AST_DTYPE_BOOL},
/** AST_TOK_GT : `>` **/
{AST_TOKT_BOPT, 7, 2, AST_DTYPE_NUMBER, AST_DTYPE_BOOL},
/** AST_TOK_GE : `>=` **/
{AST_TOKT_BOPT, 7, 2, AST_DTYPE_NUMBER, AST_DTYPE_BOOL},
/** AST_TOK_EQ : `==` **/
{AST_TOKT_BOPT, 6, 2, AST_DTYPE_ALL, AST_DTYPE_BOOL},
/** AST_TOK_NEQ : `!=` **/
{AST_TOKT_BOPT, 6, 2, AST_DTYPE_ALL, AST_DTYPE_BOOL},
/** AST_TOK_BAND : `&` **/
{AST_TOKT_BOPT, 5, 2, AST_DTYPE_INTEGER, AST_DTYPE_INTEGER},
/** AST_TOK_BXOR : `^` **/
{AST_TOKT_BOPT, 4, 2, AST_DTYPE_INTEGER, AST_DTYPE_INTEGER},
/** AST_TOK_BOR : `|` **/
{AST_TOKT_BOPT, 3, 2, AST_DTYPE_INTEGER, AST_DTYPE_INTEGER},
/** AST_TOK_LAND : `&&` **/
{AST_TOKT_BOPT, 2, 2, AST_DTYPE_BOOL, AST_DTYPE_BOOL},
/** AST_TOK_LOR : `||` **/
{AST_TOKT_BOPT, 1, 2, AST_DTYPE_BOOL, AST_DTYPE_BOOL}
};
/* Tagged union for variables with different data types. */
typedef struct {
int dtype;
union {
bool bval; int ival; long lval; float fval; double dval;
struct ast_string_struct_t { size_t len; char *str; } sval;
} v;
} ast_var_t;
/* Data structure for error handling. */
typedef struct {
int errno; /* identifier of the error */
long vidx; /* index of the variable on error */
const char *tpos; /* position of the token on error */
const char *msg; /* error message */
bool *vset; /* check if the variable is set */
} ast_error_t;
/* The abstract syntax tree (AST). */
typedef struct ast_tree_struct {
ast_tok_t type; /* type of the token */
ast_var_t value; /* value of the token */
const char *ptr; /* poisition in the expression */
struct ast_tree_struct *parent; /* parent node */
struct ast_tree_struct *left; /* left child node */
struct ast_tree_struct *right; /* right child node */
} ast_node_t;
/*============================================================================*\
Functions for interface handling
\*============================================================================*/
/******************************************************************************
Function `ast_init`:
Initialise the interface of the abstract syntax tree.
Return:
The pointer to the interface on success; NULL on error.
******************************************************************************/
ast_t *ast_init(void) {
ast_t *ast = malloc(sizeof *ast);
if (!ast) return NULL;
ast_error_t *err = malloc(sizeof(ast_error_t));
if (!err) {
free(ast);
return NULL;
}
err->errno = 0;
err->vidx = 0;
err->tpos = err->msg = NULL;
err->vset = NULL;
ast->error = err;
ast->nvar = 0;
ast->var = NULL;
ast->vidx = NULL;
ast->exp = NULL;
ast->ast = NULL;
return ast;
}
/******************************************************************************
Function `ast_msg`:
Record the error message.
Arguments:
* `ast`: interface of the abstract syntax tree;
* `msg`: the null terminated error message;
* `vidx`: index of the variable on error;
* `tpos`: pointer to the token on error.
******************************************************************************/
static void ast_msg(ast_t *ast, const char *msg, const long vidx,
const char *tpos) {
if (!ast || !ast->error) return;
ast_error_t *err = (ast_error_t *) ast->error;
err->msg = msg;
err->vidx = vidx;
err->tpos = tpos;
}
/*============================================================================*\
Functions for handling variables with different data types
\*============================================================================*/
/******************************************************************************
Function `ast_set_var_value`:
Set the value of a variable.
Arguments:
* `var`: pointer to the variable (assume memory has been allocated);
* `value`: pointer to the value;
* `size`: length of the string type variable;
* `dtype`: data type of the value (no validation performed).
******************************************************************************/
static inline void ast_set_var_value(ast_var_t *var, const void *value,
const size_t size, const ast_dtype_t dtype) {
var->dtype = dtype;
switch (dtype) {
case AST_DTYPE_BOOL: var->v.bval = *((bool *) value); break;
case AST_DTYPE_INT: var->v.ival = *((int *) value); break;
case AST_DTYPE_LONG: var->v.lval = *((long *) value); break;
case AST_DTYPE_FLOAT: var->v.fval = *((float *) value); break;
case AST_DTYPE_DOUBLE: var->v.dval = *((double *) value); break;
case AST_DTYPE_STRING:
var->v.sval.str = (char *) value;
var->v.sval.len = size;
break;
default: return;
}
}
/******************************************************************************
Function `ast_vidx_pos`:
Find the insertion position of the variable index in a sorted index array.
Arguments:
* `arr`: pointer to the array for variable indices;
* `num`: number of elements in the array;
* `var`: index of the variable to be inserted.
Return:
-(index + 1) if the array contains the value;
the index for the insertion otherwise.
******************************************************************************/
static long ast_vidx_pos(const long *arr, const long num, const long vidx) {
long l, u;
l = 0;
u = num - 1;
while (l <= u) {
long i = ((unsigned long) l + (unsigned long) u) >> 1;
if (arr[i] < vidx) l = i + 1;
else if (arr[i] > vidx) u = i - 1;
else return -(i + 1); /* the element is already there */
}
return l;
}
/******************************************************************************
Function `ast_init_var`:
Initialise the variable array.
Arguments:
* `ast`: interface of the abstract syntax tree;
* `dtype`: data type of the expression.
Return:
Pointer to the array.
******************************************************************************/
static void *ast_init_var(ast_t *ast, const ast_dtype_t dtype) {
ast_error_t *err = (ast_error_t *) ast->error;
err->vset = calloc(ast->nvar, sizeof(bool));
if (!err->vset) return NULL;
if (dtype == AST_DTYPE_BOOL) {
ast_var_t *var = calloc(ast->nvar, sizeof *var);
if (!var) return NULL;
for (long i = 0; i < ast->nvar; i++) var[i].dtype = AST_DTYPE_ALL;
return var;
}
if (dtype == AST_DTYPE_INT) {
int *var = calloc(ast->nvar, sizeof *var);
return var;
}
if (dtype == AST_DTYPE_LONG) {
long *var = calloc(ast->nvar, sizeof *var);
return var;
}
if (dtype == AST_DTYPE_FLOAT) {
float *var = calloc(ast->nvar, sizeof *var);
return var;
}
if (dtype == AST_DTYPE_DOUBLE) {
double *var = calloc(ast->nvar, sizeof *var);
return var;
}
AST_ERRNO(ast) = AST_ERR_DTYPE;
return NULL;
}
/******************************************************************************
Function `ast_set_var`:
Set the value of a variable in the variable array
Arguments:
* `ast`: interface of the abstract syntax tree;
* `idx`: index of the variable (starting from 1);
* `value`: pointer to a variable holding the value to be set;
* `size`: length of the string type variable;
* `dtype`: data type of the value.
Return:
Zero on success; non-zero on error.
******************************************************************************/
int ast_set_var(ast_t *ast, const long idx, const void *value,
const size_t size, ast_dtype_t dtype) {
if (!ast) return AST_ERR_INIT;
if(AST_IS_ERROR(ast)) return AST_ERRNO(ast);
if (!ast->nvar) return 0;
if (!value) return AST_ERRNO(ast) = AST_ERR_VALUE;
if (idx <= 0) {
ast_msg(ast, "unexpected variable index", idx, NULL);
return AST_ERRNO(ast) = AST_ERR_VAR;
}
/* Nothing to be done if this variable is not required. */
const long pos = -ast_vidx_pos(ast->vidx, ast->nvar, idx) - 1;
if (pos < 0) return 0;
long lval;
double dval;
ast_var_t *var;
switch (ast->dtype) {
case AST_DTYPE_BOOL:
var = (ast_var_t *) ast->var + pos;
/* Convert int to long. */
if (dtype == AST_DTYPE_INT) {
lval = (long) (*((int *) value));
value = &lval;
dtype = AST_DTYPE_LONG;
}
/* Convert float to double. */
else if (dtype == AST_DTYPE_FLOAT) {
dval = (double) (*((float *) value));
value = &dval;
dtype = AST_DTYPE_DOUBLE;
}
/* Raise an error if the data type is not valid for this variable. */
if (!(dtype & var->dtype)) {
ast_msg(ast, "unexpected data type for variable", idx, NULL);
return AST_ERRNO(ast) = AST_ERR_VAR;
}
ast_set_var_value(var, value, size, dtype);
break;
case AST_DTYPE_INT:
if (dtype != ast->dtype) {
ast_msg(ast, "int type variable expected", idx, NULL);
return AST_ERRNO(ast) = AST_ERR_VAR;
}
*((int *) ast->var + pos) = *((int *) value);
break;
case AST_DTYPE_LONG:
if (dtype == AST_DTYPE_LONG)
*((long *) ast->var + pos) = *((long *) value);
/* Convert int to long. */
else if (dtype == AST_DTYPE_INT)
*((long *) ast->var + pos) = (long) (*((int *) value));
else {
ast_msg(ast, "long type variable expected", idx, NULL);
return AST_ERRNO(ast) = AST_ERR_VAR;
}
break;
case AST_DTYPE_FLOAT:
if (dtype == AST_DTYPE_FLOAT)
*((float *) ast->var + pos) = *((float *) value);
/* Convert int to float. */
else if (dtype == AST_DTYPE_INT)
*((float *) ast->var + pos) = (float) (*((int *) value));
/* Convert long to float. */
else if (dtype == AST_DTYPE_LONG)
*((float *) ast->var + pos) = (float) (*((long *) value));
else {
ast_msg(ast, "float type variable expected", idx, NULL);
return AST_ERRNO(ast) = AST_ERR_VAR;
}
break;
case AST_DTYPE_DOUBLE:
if (dtype == AST_DTYPE_DOUBLE)
*((double *) ast->var + pos) = *((double *) value);
else if (dtype == AST_DTYPE_INT)
*((double *) ast->var + pos) = (double) (*((int *) value));
else if (dtype == AST_DTYPE_LONG)
*((double *) ast->var + pos) = (double) (*((long *) value));
else if (dtype == AST_DTYPE_FLOAT)
*((double *) ast->var + pos) = (double) (*((float *) value));
else {
ast_msg(ast, "double type variable expected", idx, NULL);
return AST_ERRNO(ast) = AST_ERR_VAR;
}
break;
default:
ast_msg(ast, "unknown error for variable", idx, NULL);
return AST_ERRNO(ast) = AST_ERR_VAR;
}
((ast_error_t *) ast->error)->vset[pos] = true;
return 0;
}
/******************************************************************************
Function `ast_save_vidx`:
Record the index of a variable if necessary;
Arguments:
* `ast`: interface of the abstract syntax tree;
* `idx`: the index to be recorded.
******************************************************************************/
static void ast_save_vidx(ast_t *ast, const long idx) {
const long pos = (ast->vidx) ? ast_vidx_pos(ast->vidx, ast->nvar, idx) : 0;
if (pos < 0) return; /* the index has already been recorded */
if (ast->nvar == LONG_MAX) { /* there is no more space for the insertion */
AST_ERRNO(ast) = AST_ERR_NVAR;
return;
}
/* Check if the allocated space is enough. */
if ((ast->nvar & (ast->nvar - 1)) == 0) { /* nvar is 0 or power of 2 */
long size = 1;
if (LONG_MAX / 2 < ast->nvar) size = LONG_MAX;
else if (ast->nvar) size = ast->nvar << 1; /* double the size */
long *tmp = realloc(ast->vidx, size * sizeof(long));
if (!tmp) {
AST_ERRNO(ast) = AST_ERR_MEMORY;
return;
}
ast->vidx = tmp;
}
/* Right shift the existing elements. */
if (ast->nvar && pos < ast->nvar)
memmove(ast->vidx + pos + 1, ast->vidx + pos,
(ast->nvar - pos) * sizeof(long));
ast->vidx[pos] = idx;
ast->nvar += 1;
}
/*============================================================================*\
Functions for string manipulation
\*============================================================================*/
/******************************************************************************
Function `ast_skip_space`:
Skip whitespaces.
Arguments:
* `src`: the null-terminated input string.
Return:
Pointer to the first non-whitespace character of the string.
******************************************************************************/
static inline const char *ast_skip_space(const char *src) {
const char *dst = src;
while (isspace(*dst)) dst++;
return dst;
}
/******************************************************************************
Function `ast_copy_str`:
Copy a string to a new block of memory.
Arguments:
* `src`: the null-terminated input string.
Return:
Pointer to the copied string.
******************************************************************************/
static inline char *ast_copy_str(const char *src) {
size_t size = strlen(src);
char *dst = calloc(size + 1, sizeof(char));
if (!dst) return NULL;
memcpy(dst, src, size * sizeof(char));
return dst;
}
/******************************************************************************
Function `ast_parse_num`:
Convert a numerical token into a number.
Arguments:
* `ast`: interface of the abstract syntax tree;
* `str`: the input string;
* `res`: the resulting number;
* `end`: pointer to the first character that is not interpreted.
Return:
Zero on success; non-zero on error.
******************************************************************************/
static int ast_parse_num(ast_t *ast, const char *str, ast_var_t *res,
char **end) {
/* Validate arguments. */
if (!ast) return AST_ERR_INIT;
if (AST_IS_ERROR(ast)) return AST_ERRNO(ast);
int ival;
long lval;
float fval;
double dval;
switch (ast->dtype) {
case AST_DTYPE_INT:
lval = strtol(str, end, 10);
if (lval >= INT_MAX || lval <= INT_MIN) {
ast_msg(ast, "overflow detected for int type", 0, str);
return AST_ERRNO(ast) = AST_ERR_TOKEN;
}
ival = (int) lval;
ast_set_var_value(res, &ival, 0, AST_DTYPE_INT);
break;
case AST_DTYPE_LONG:
lval = strtol(str, end, 10);
if (lval == LONG_MAX || lval == LONG_MIN) {
ast_msg(ast, "overflow detected for long type", 0, str);
return AST_ERRNO(ast) = AST_ERR_TOKEN;
}
ast_set_var_value(res, &lval, 0, AST_DTYPE_LONG);
break;
case AST_DTYPE_FLOAT:
fval = strtof(str, end);
if (fval == HUGE_VALF) {
ast_msg(ast, "overflow detected for float type", 0, str);
return AST_ERRNO(ast) = AST_ERR_TOKEN;
}
ast_set_var_value(res, &fval, 0, AST_DTYPE_FLOAT);
break;
case AST_DTYPE_DOUBLE:
dval = strtod(str, end);
if (dval == HUGE_VAL) {
ast_msg(ast, "overflow detected for double type", 0, str);
return AST_ERRNO(ast) = AST_ERR_TOKEN;
}
ast_set_var_value(res, &dval, 0, AST_DTYPE_DOUBLE);
break;
case AST_DTYPE_BOOL:
/* Try to convert to double. */
dval = strtod(str, end);
if (dval == HUGE_VAL) {
ast_msg(ast, "overflow detected for double type", 0, str);
return AST_ERRNO(ast) = AST_ERR_TOKEN;
}
/* Check if it can also be long. */
if (dval > LONG_MIN && dval < LONG_MAX && str != *end) {
bool is_long = true;
for (const char *tmp = str; tmp < *end; tmp++) {
if (!isdigit(*tmp)) {
is_long = false;
break;
}
}
if (is_long) {
lval = strtol(str, end, 10);
ast_set_var_value(res, &lval, 0, AST_DTYPE_LONG);
break;
}
}
ast_set_var_value(res, &dval, 0, AST_DTYPE_DOUBLE);
break;
default:
return AST_ERRNO(ast) = AST_ERR_DTYPE;
}
if (*end - str == 0) { /* no character is parsed */
ast_msg(ast, "unrecognised number", 0, str);
return AST_ERRNO(ast) = AST_ERR_TOKEN;
}
return 0;
}
/******************************************************************************
Function `ast_parse_str`:
Retrieve a string literal from the expression.
Arguments:
* `ast`: interface of the abstract syntax tree;
* `str`: the input string;
* `res`: the resulting tagged union for different data types;
* `end`: pointer to the first character that is not interpreted.
Return:
Zero on success; non-zero on error.
******************************************************************************/
static int ast_parse_str(ast_t *ast, const char *str, ast_var_t *res,
const char **end) {
const char *c = str + 1;
while (*c != '\0' && *c != *str) c++;
if (*c == '\0') {
ast_msg(ast, "unbalanced quotation mark", 0, str);
return AST_ERRNO(ast) = AST_ERR_TOKEN;
}
ast_set_var_value(res, str + 1, c - str - 1, AST_DTYPE_STRING);
*end = c + 1;
return 0;
}
/******************************************************************************
Function `ast_parse_var`:
Convert the index of a variable into a long number.
Arguments:
* `ast`: interface of the abstract syntax tree;
* `str`: the input string;
* `vidx`: retrieved index of the variable;
* `end`: pointer to the first character that is not interpreted.
Return:
Zero on success; non-zero on error.
******************************************************************************/
static int ast_parse_var(ast_t *ast, const char *str, long *vidx,
const char **end) {
const char *c = str + 1;
if (*c >= '1' && *c <= '9') { /* number 1 - 9 */
*vidx = *c - '0';
*end = c + 1;
return 0;
}
else if (*c == AST_VAR_START) {
/* Get the variable index (long integer). */
long idx = 0;
for (++c; isdigit(*c); c++) {
int digit = *c - '0';
/* Overflow detection. */
if (LONG_MAX / 10 < idx) {
ast_msg(ast, "the variable index is too large", 0, str);
return AST_ERRNO(ast) = AST_ERR_TOKEN;
}
idx *= 10;
if (LONG_MAX - digit < idx) {
ast_msg(ast, "the variable index is too large", 0, str);
return AST_ERRNO(ast) = AST_ERR_TOKEN;
}
idx += digit;
}
if (idx > 0 && *c == AST_VAR_END) {
*vidx = idx;
*end = c + 1;
return 0;
}
}
ast_msg(ast, "unrecognised variable", 0, str);
return AST_ERRNO(ast) = AST_ERR_TOKEN;
}
/*============================================================================*\
Functions for the abstract syntax tree manipulation
\*============================================================================*/
/******************************************************************************
Function `ast_create`:
Create a new node of the abstract syntax tree.
Arguments:
* `type`: type of the node;
* `value`: value of the node.
Return:
The address of the node.
******************************************************************************/
static ast_node_t *ast_create(const ast_tok_t type, const ast_var_t value) {
ast_node_t *node = malloc(sizeof *node);
if (!node) return NULL;
node->type = type;
node->value = value;
node->ptr = NULL;
node->parent = node->left = node->right = NULL;
return node;
}
/******************************************************************************
Function `ast_root`:
Find the root node of the abstract syntax tree.
Arguments:
* `node`: an arbitrary node of the tree.
Return:
Address of the root node.
******************************************************************************/
static inline ast_node_t *ast_root(ast_node_t *node) {
while (node->parent) node = node->parent;
return node;
}
/******************************************************************************
Function `ast_delete`:
Deleta a node from the abstract syntax tree, once a pair of parenthesis
is parsed.
Arguments:
* `node`: the node to be removed.
******************************************************************************/
static void ast_delete(ast_node_t *node) {
/* This node should have only the left child. */
ast_node_t *tmp = node->left;
/* Copy contents from the left child. */
node->type = tmp->type;
node->value = tmp->value;
node->ptr = tmp->ptr;
node->left = tmp->left;
node->right = tmp->right;
if (node->left) node->left->parent = node;
if (node->right) node->right->parent = node;
/* Delete the left child. */
free(tmp);
}
/******************************************************************************
Function `ast_insert`:
Insert a token to the abstract syntax tree.
Arguments:
* `node`: current node of the tree;
* `tok`: token for the new node;
* `value`: value for the new node;
* `str`: position of the token in the expression.
Return:
The address of the inserted node.
******************************************************************************/
static ast_node_t *ast_insert(ast_node_t *node, const ast_tok_t tok,
const ast_var_t value, const char *str) {
/* No need to ceate a new node if this is the first token. */
if (node->type == AST_TOK_UNDEF) {
node->type = tok;
node->value = value;
node->ptr = str;
return node;
}
/* Create a new node. */
ast_node_t *new = ast_create(tok, value);
if (!new) return NULL;
new->ptr = str;
/* Insert a new node to the abstract syntax tree. */
if (ast_tok_attr[tok].type == AST_TOKT_BOPT) {
/* Find the right ancestor given the precedence and associativity. */
while (node->parent && node->parent->type != AST_TOK_PAREN_LEFT &&
ast_tok_attr[node->parent->type].type != AST_TOKT_FUNC &&
((ast_tok_attr[node->parent->type].type != AST_TOKT_UOPT &&
ast_tok_attr[node->parent->type].precedence >=
ast_tok_attr[tok].precedence) ||
/* Right-to-left associativity for unary operators. */
(ast_tok_attr[node->parent->type].type == AST_TOKT_UOPT &&
ast_tok_attr[node->parent->type].precedence >
ast_tok_attr[tok].precedence)))
node = node->parent;
new->left = node;
if (node->parent) { /* insert between two nodes */
new->parent = node->parent;
if (node == node->parent->left) node->parent->left = new;
else node->parent->right = new;
}
node->parent = new; /* new root */
return new;
}
/* Insert an effective leaf to the abstract syntax tree. */
else { /* AST_TOK_PAREN_LEFT || AST_TOKT_UOPT/FUNC/VALUE */
if (!node->left) {
node->left = new;
new->parent = node;
}
else {
node->right = new;
new->parent = node;
}
}
return new;
}
/*============================================================================*\
Functions for clean-up
\*============================================================================*/
/******************************************************************************
Function `ast_free`:
Free memory allocated for the abstract syntax tree.
Arguments:
* `node`: the root node of the abstract syntax tree.
******************************************************************************/
static void ast_free(ast_node_t *node) {
if (!node) return;
ast_free(node->left);
ast_free(node->right);
free(node);
}
/******************************************************************************
Function `ast_destroy`:
Release memory allocated for the abstract syntax tree.
Arguments:
* `ast`: interface of the abstract syntax tree.
******************************************************************************/
void ast_destroy(ast_t *ast) {
if (!ast) return;
ast_error_t *err = (ast_error_t *) ast->error;
if (err->vset) free(err->vset);
free(ast->error);
if (ast->exp) free(ast->exp);
if (ast->var) free(ast->var);
if (ast->vidx) free(ast->vidx);
ast_free((ast_node_t *) ast->ast);
free(ast);
}
/*============================================================================*\
Functions for the parser
\*============================================================================*/
/******************************************************************************
Function `ast_parse_token`:
Parse the token and push it to the abstract syntax tree.
Arguments:
* `ast`: interface of the abstract syntax tree;
* `src`: the string on processing.
******************************************************************************/
static void ast_parse_token(ast_t *ast, ast_node_t *node, const char *src) {
if (!ast || AST_IS_ERROR(ast)) return;
src = ast_skip_space(src); /* skip whitespaces */
const char *c = src;
/* Number of leaves. */
int argc = 0;
if (node->left) argc++;
if (node->right) argc++;
if (!(*c)) {
/* Number of leaves is smaller than the arguments of this operator. */
if (argc < ast_tok_attr[node->type].argc) {
ast_msg(ast, "incomplete expression", 0, src);
AST_ERRNO(ast) = AST_ERR_TOKEN;
}
/* Open parenthesis. */
do node = node->parent;
while (node && node->type != AST_TOK_PAREN_LEFT &&
ast_tok_attr[node->type].type != AST_TOKT_FUNC);
if (node) {
ast_msg(ast, "unclosed parenthesis", 0, src);
AST_ERRNO(ast) = AST_ERR_TOKEN;
}
return;
}
/* Check the token, so no check is performed in `ast_insert`. */
ast_tok_t tok = AST_TOK_UNDEF;
switch (*c) {
case 'i': /* for inf or isfinite */
if (c[1] == 's' && c[2] == 'f' && c[3] == 'i' && c[4] == 'n'
&& c[5] == 'i' && c[6] == 't' && c[7] == 'e' && c[8] == '(') {
c += 8;
tok = AST_TOK_ISFINITE;
}
break;
case '.':
if (ast->dtype != AST_DTYPE_BOOL && (ast->dtype & AST_DTYPE_REAL) == 0)
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9': tok = AST_TOK_NUM; break;
case '\'':
case '"': tok = AST_TOK_STRING; break;
case AST_VAR_FLAG: tok = AST_TOK_VAR; break;
case '(': tok = AST_TOK_PAREN_LEFT; break;
case ')': tok = AST_TOK_PAREN_RIGHT; break;
case 'a':
if (c[1] == 'b' && c[2] == 's' && c[3] == '(') {
c += 3;
tok = AST_TOK_ABS;
}
break;
case 's':
if (c[1] == 'q' && c[2] == 'r' && c[3] == 't' && c[4] == '(') {
c += 4;
tok = AST_TOK_SQRT;
}
break;
case 'l':
if (c[1] == 'n' && c[2] == '(') {
c += 2;
tok = AST_TOK_LN;
}
else if (c[1] == 'o' && c[2] == 'g' && c[3] == '(') {
c += 3;
tok = AST_TOK_LOG;
}
break;
case '+': tok = AST_TOK_ADD; break;
case '-':
if (argc >= ast_tok_attr[node->type].argc) tok = AST_TOK_MINUS;
else tok = AST_TOK_NEG;
break;
case '!':
if (c[1] == '=') {
c++;
tok = AST_TOK_NEQ;
}
else tok = AST_TOK_LNOT;
break;
case '~': tok = AST_TOK_BNOT; break;
case '*':
if (c[1] == '*') {
c++;
tok = AST_TOK_EXP;
}
else tok = AST_TOK_MUL;
break;
case '/': tok = AST_TOK_DIV; break;
case '%': tok = AST_TOK_REM; break;
case '<':
if (c[1] == '<') {
c++;
tok = AST_TOK_LEFT;
}
else if (c[1] == '=') {