File: let.c

package info (click to toggle)
mcl 1%3A14-137-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 10,704 kB
  • ctags: 5,125
  • sloc: ansic: 53,217; sh: 4,448; perl: 3,967; makefile: 422
file content (1776 lines) | stat: -rw-r--r-- 47,880 bytes parent folder | download | duplicates (3)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
/*   (C) Copyright 2001, 2002, 2003, 2004, 2005, 2006, 2007 Stijn van Dongen
 *   (C) Copyright 2008, 2009, 2010, 2011  Stijn van Dongen
 *
 * This file is part of tingea.  You can redistribute and/or modify tingea
 * under the terms of the GNU General Public License; either version 3 of the
 * License or (at your option) any later version.  You should have received a
 * copy of the GPL along with tingea, in the file COPYING.
*/


/*
 *    You probably don't want to look at this code - the reasons are explained
 *    below.  I like the beast though, especially the part that you can specify
 *    callbacks to parse 'external' data.
*/

/*
 * TODO
 *    catch integer overflow.
 *    consider unsigned type. Perhaps implement signed with separate sign.
 *    consider bit operators and unsigned type.
 *    precision.
*/

#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <math.h>

#include "let.h"
#include "ting.h"
#include "ding.h"
#include "alloc.h"
#include "minmax.h"
#include "err.h"
#include "types.h"
#include "ding.h"
#include "compile.h"


/*  **************************************************************************
 * *
 **            Implementation notes (a few).
 *
* 

   Features
 *    All of C's operators in a revised precedence scheme, with exponentiation
 *    added.  The groups of logical operators, bitwise operators, comparison
 *    operators have equal precedence internally (but changing this is a
 *    matter of editing a single table).  Unsigned integers are not supported
 *    (so bitwise complement behaves funnily).  Ternary operator behaves as
 *    should; evaluates only one of its branches.  Boolean logical operators
 *    do shortcircuit. All mathematical functions from math.h and some
 *    additional ones (e.g. abs, round, sign).  Variables can be parsed and
 *    evaluated using user-supplied functions.  Currently, variables must be
 *    recognizable by a special lead character.

   Todos
 *    I may want to pass raam along to compute and flatten after all.
 *    This brings back in the tokids, which are nice to have.
 *    It also means that global callbacks can be localized.
 *
 *    Right now, inf is not caught. isinf() seems not portable though :(
 *
 *    getatoken could be equipped with more error handling facilities now that
 *    user_parse is inserted.  The current behaviour is that parsing control
 *    is transfered to native parsing if user parsing does not succeed.  This
 *    can be used for overloading the special character, e.g.  setting it to
 *    '!' -> user parsing could require a !<..> sequence; if not found, '!'
 *    would be seen as the negation operator.
 *
 *    user_parse and user_eval need to be global in scope as long
 *    as raam is not passed along in compute and flatten,
 *    but that is actually not a problem (apart from reentrancy).
 *
 *    Hashing of function names.
 *
 *    Audit overflow, exceptions, long/double mixing.
 *
 *    Should min(1,2.0) be 1 rather than 1.0 ?  in that case, need special
 *    behaviour for twoary max and min just like now for oneary abs.
 *
 *    Make int to double overflow promotion a trmInit option.
 *
 *    on STATUS_FAIL for parse, write error message in telraam.
 * 
 *    allow functions with empty arguments (e.g. rand()).
 *
 *    add some of the funny stuff provided by fv, f?
 *
 *    tn toktype is used both in lexing/parsing stage and in reduction stage.
 *    not scalable. Future idea:
 *    Implement an intermediate layer between parsing and evaluation.
 *    E.g. convert the result of trmParse() to a stack.

   Done
 *    Errors cascade back. For parse errors all memory seems to be reclaimed
 *    (for all cases tried so far).
 *    After parsing, no other errors should be possible I believe.
 *
 *    made real type, which could be long double. Tis not however,
 *    because long double math does not seem widespread and/or standard.
 *    made num type, which could be long long. Tis not however,
 *    because long long math seems to be C99 (not widespread etc).
 *
 *    enabled user callbacks for variable and function interpolation.

   Integers/Floats
 *    It is tracked which operations result in integers and which do
 *    not. If integer overflow occurs the result is promoted to double.
 *    The internal logic implementing this behaviour dictates that
 *    as long as (flags & TN_ISINT) it must be true that fval ==~ ival.
 *    TODO: make this customizable.
 *    NOTE: doubles pbb can capture all 32-bit integers, but not so for
 *          64-bit integers. May make subtle difference.

   Apology
 *    It's lame to write your own parser rather than lex and yacc but scriptor
 *    wanted to do it one more time than zero.
 *
 *    The result is pretty ad hoc and not generic, what it's got going for it
 *    is that it works.  Also, trmParse() is not that bad I believe, although
 *    it is not very scalable either.  compute() is the trickiest.  Some
 *    provisions were made to get short-circuiting and the ternary op working.
 *    The same data structure is used for tokenization, parsing, and
 *    evaluation. Ugly!

   Implementation notes
 *  . Parse tree is implicitly stored as a linked list.
 *  . Evaluation is done by compute/flatten; precedence and branching are done
 *    during evaluation, rather than (partly) precomputed (which would much be
 *    cleaner).  precedence is done in flatten; branching in compute.
 *  . tn's (token nodes) are used both by lexer, parser, and interpreter,
 *    which is not the nicest way of doing it.
 *  . Could push and convert all tokens to a stack (format), which would unify
 *    operators and functions to some extent, and separate interpretation from
 *    parsing and braching.

   Errors
 *    Currently we have arithmetic error only.
 *    TODO:
 *    Overflow error -- but isinf does not seem portable :(

   Caveat
 *    tnFree/tnDup should not be applied to a TOKEN_CLOSE node, dupwise
 *    speaking. This is because compute currently has a sanity check for
 *    pointer identity before and after its main loop.
 *
 *    tricky spots, unfinished thoughts, future ideas, and omitted assertions
 *    are marked with the sequence 'mq' (or even 'mqmq'), but not all of them.
 *

   Some reminders
 *    routines that must be checked (malloc dependent)
 *       tnDup
 *       tnNewToken
 *       tnPushToken
 *       tnPushThis
 *    routines that need be checked for other reason
 *       tnUser
 *       flatten
 *       compute
 *       getatom
 *       getexpression
 *       trmParse
*/


typedef double real;          /* but we always use double arithmetic      */
                              /* i.e. never use long double               */

#ifdef LET99
   typedef long long num;
#  define NUM_MIN LLONG_MIN   /* this branch has not been tested!         */
#  define NUM_MAX LLONG_MAX   /* and requires modifiation of trmEval      */
#else               
   typedef long num;
#  define NUM_MIN LONG_MIN
#  define NUM_MAX LONG_MAX
#endif


static int debug_g = 0;
static int (*user_parse_g)(mcxTing* txt, int offset) = NULL;
static mcxenum (*user_eval_g)(const char* token, long *ival, double *fval) = NULL;
static char user_char_g = 0;


typedef struct tn          /* the lex/parse/interpret one stop-shop    */
{  mcxTing*    token
;  i32         toktype

;  i32         optype
;  i32         opid

;  real        fval
;  num         ival
;  struct tn*  prev
;  struct tn*  next

;  i32         flags
;
}  tn;                     /* token node, or whatever */


struct telRaam
{  mcxTing  *text
;  mcxTing  *token         /* current token */
;  char*    p
;  mcxbool  buffered       /* should use buffer (pushed back token)? */
;  tn*      node           /* document symantics */
;  tn*      start
;  real     fval
;  num      ival
;  i32      flags
;  i32      toktype
;  i32      depth
;  tn*      stack          /* when converting parsed expression to stack */
;  int      stack_size
;
}  ;


typedef enum
{  TOKEN_EXH   = -1
,  TOKEN_START =  0     /* special start symbol                         */
,  TOKEN_UNIOP =  1     /* unary, 1                                     */
,  TOKEN_BINOP =  2     /* binary, 2                                    */
,  TOKEN_FUN   =  69    /* can be fun, but I mean 6 = (  9 = )          */
,  TOKEN_TRIOP =  3333  /* ternary, let's stress the fact               */
,  TOKEN_TRICATCH =  6667  /* complement of a number wrt another number */
,  TOKEN_CMP   =  12321 /* hum, dunnow really                           */
,  TOKEN_OR    =  11    /* ||                                           */
,  TOKEN_AND   =  88    /* &&                                           */
,  TOKEN_OPEN  =  6     /* like fun, 6 = (                              */
,  TOKEN_CLOSE =  9     /* like fun, 9 = )                              */
,  TOKEN_COMMA =  13579 /* gaps                                         */
,  TOKEN_CONST =  31415 /* PI                                           */
,  TOKEN_USER  =  981   /* G, variable                                  */
}  tokentype   ;


#define  OP_UNI_NEG     1 <<  0                             /*    -     */
#define  OP_UNI_NOT     1 <<  1                             /*    !     */
#define  OP_UNI_COMPL   1 <<  2                             /*    ~     */
                                                           
#define  OP_EXP_EXP     1 <<  3                             /*    **    */
                                                           
#define  OP_MUL_MUL     1 <<  4                             /*    *     */
#define  OP_MUL_FRAC    1 <<  5                             /*    /     */
#define  OP_MUL_DIV     1 <<  6                             /*    //    */
#define  OP_MUL_MOD     1 <<  7                             /*    %     */
                                                           
#define  OP_ADD_ADD     1 <<  8                             /*    +     */
#define  OP_ADD_SUB     1 <<  9                             /*    -     */
                                                           
#define  OP_BIT_LSHIFT  1 << 10                             /*    <<    */
#define  OP_BIT_RSHIFT  1 << 11                             /*    >>    */
#define  OP_BIT_AND     1 << 12                             /*    &     */
#define  OP_BIT_OR      1 << 13                             /*    |     */
#define  OP_BIT_XOR     1 << 14                             /*    ^     */
                                                           
#define  OP_CMP_LT      1 << 15                             /*    <     */
#define  OP_CMP_LQ      1 << 16                             /*    <=    */
#define  OP_CMP_GQ      1 << 17                             /*    >=    */
#define  OP_CMP_GT      1 << 18                             /*    >     */
#define  OP_CMP_EQ      1 << 19                             /*    ==    */
#define  OP_CMP_NE      1 << 20                             /*    !=    */
                                                           
#define  OP_TRI_START   1 << 21                             /*    !     */


#define  OPTYPE_UNI     (OP_UNI_NEG | OP_UNI_NOT | OP_UNI_COMPL)
#define  OPTYPE_EXP     OP_EXP_EXP
#define  OPTYPE_MUL     (OP_MUL_MUL | OP_MUL_FRAC | OP_MUL_DIV | OP_MUL_MOD)
#define  OPTYPE_ADD     (OP_ADD_ADD | OP_ADD_SUB)
#define  OPTYPE_BIT     (OP_BIT_LSHIFT | OP_BIT_RSHIFT \
                      | OP_BIT_AND | OP_BIT_OR | OP_BIT_XOR)
#define  OPTYPE_CMP     (OP_CMP_LT | OP_CMP_LQ | OP_CMP_GT | OP_CMP_GQ \
                      | OP_CMP_EQ | OP_CMP_NE)
#define  OPTYPE_TRI     OP_TRI_START


typedef struct opHook
{  char*    opname
;  i32      opid
;  i32      optype
;  
}  opHook   ;


double sign
(double f
)
   {  return f > 0 ? 1.0 : f < 0 ? -1.0 : 0.0
;  }


double letround
(double f
)
   { return f > 0 ? floor(f+0.5) : ceil(f-0.5)
;  }


double letlog2
(double f) { return f > 0 ? log(f) / log(2.0) : 0.0 ;  }


typedef struct fun1Hook
{  char*    funname
;  double   (*funcd)(double a)
;  i32      funflags
;
}  fun1Hook  ;

#define  FUN_SPECIAL     1
#define  FUN_INTRESULT   2
#define  FUN_OVERLOADED  4

double show_bits(double a) {
      return a;
}

static fun1Hook fun1HookDir[] =
{
   {  "sin",   sin   ,  0    }
,  {  "cos",   cos   ,  0    }
,  {  "tan",   tan   ,  0    }
,  {  "exp",   exp   ,  0    }
,  {  "log",   log   ,  0    }
,  {  "log10", log10 ,  0    }
,  {  "log2",  letlog2  ,  0    }
,  {  "asin",  asin  ,  0    }
,  {  "acos",  acos  ,  0    }
,  {  "atan",  atan  ,  0    }
,  {  "sqrt",  sqrt  ,  0    }
,  {  "abs",   fabs  ,  FUN_SPECIAL     }
,  {  "floor", floor ,  FUN_INTRESULT   }
,  {  "ceil",  ceil  ,  FUN_INTRESULT   }
,  {  "round", letround ,  FUN_INTRESULT   }
,  {  "int",   letround ,  FUN_INTRESULT   }
,  {  "sign",  sign  ,  FUN_INTRESULT   }
,  {  "bits",  show_bits   ,  FUN_SPECIAL }
,  {   NULL,   NULL  ,  0    }
}  ;


double max ( double a, double b ) { return a > b ? a  : b ; }
double min ( double a, double b ) { return a < b ? a  : b ; }
num maxl  ( num a, num b ) { return a > b ? a  : b ; }
num minl  ( num a, num b ) { return a < b ? a  : b ; }


typedef struct fun2Hook
{  char*    funname
;  double   (*funcd)(double a, double b)
;  num      (*funcl)(num a, num b)
;  i32      funflags
;
}  fun2Hook  ;

static fun2Hook fun2HookDir[] =
{
   {  "max",   max   ,  maxl,  0    }
,  {  "min",   min   ,  minl,  0    }
,  {   NULL,   NULL  ,  NULL,  0    }
}  ;

/* mq
if (tn_isint(lft) && tn_isint(rgt) && hook->funcl)
*/


static opHook opHookDir[] =
{
   {  "-",     OP_UNI_NEG,    OPTYPE_UNI }
,  {  "!",     OP_UNI_NOT,    OPTYPE_UNI }
,  {  "~",     OP_UNI_COMPL,  OPTYPE_UNI }

,  {  "**",    OP_EXP_EXP,    OPTYPE_EXP }

,  {  "*",     OP_MUL_MUL,    OPTYPE_MUL }
,  {  "/",     OP_MUL_FRAC,   OPTYPE_MUL }
,  {  "//",    OP_MUL_DIV,    OPTYPE_MUL }
,  {  "%",     OP_MUL_MOD,    OPTYPE_MUL }

,  {  "+",     OP_ADD_ADD,    OPTYPE_ADD }
,  {  "-",     OP_ADD_SUB,    OPTYPE_ADD }

,  {  "<<",    OP_BIT_LSHIFT, OPTYPE_BIT }
,  {  ">>",    OP_BIT_RSHIFT, OPTYPE_BIT }
,  {  "&",     OP_BIT_AND,    OPTYPE_BIT }
,  {  "|",     OP_BIT_OR,     OPTYPE_BIT }
,  {  "^",     OP_BIT_XOR,    OPTYPE_BIT }

,  {  "<",     OP_CMP_LT,     OPTYPE_CMP }
,  {  "<=",    OP_CMP_LQ,     OPTYPE_CMP }
,  {  ">=",    OP_CMP_GQ,     OPTYPE_CMP }
,  {  ">",     OP_CMP_GT,     OPTYPE_CMP }
,  {  "==",    OP_CMP_EQ,     OPTYPE_CMP }
,  {  "!=",    OP_CMP_NE,     OPTYPE_CMP }

,  {  "?",     OP_TRI_START,  OPTYPE_TRI }

,  {  NULL,    0,             0,         }
}  ;


enum
{  EXPECT_ANY  = 1
,  EXPECT_ATOM = 2
}  ;


#define TN_ISINT   1    /* tn token node, object used everywhere */
#define TN_NOINT   2
#define TN_ISNAN   4
#define TN_ISINF   8

#define tn_isint(a)  (a->flags & TN_ISINT)

mcxbool trmIsNan
(  int  flags
)
   {  return flags & TN_ISNAN 
;  }

mcxbool trmError
(  int  flags
)
   {  return flags & (TN_ISNAN | TN_ISINF)
;  }

mcxbool trmIsInf
(  int  flags
)
   {  return flags & TN_ISINF 
;  }

mcxbool trmIsNum
(  int  flags
)
   {  return flags & TN_ISINT
;  }

mcxbool trmIsReal
(  int  flags
)
   {  return !(flags & (TN_ISINT | TN_ISNAN | TN_ISINF))
;  }


mcxstatus getexpression
(  telRaam *raam
)  ;

mcxstatus getatom
(  telRaam* raam
)  ;


void dump
(  tn* node
,  i32  times
,  const char* msg
)  ;


void trmDump
(  telRaam* raam
,  const char* msg
)
   {  dump(raam->start, 0, msg)
;  }


tn* tnNewToken
(  const char* token 
,  i32         toktype
,  real        fval
,  num         ival
)
   {  tn* node = mcxAlloc(sizeof(tn), RETURN_ON_FAIL)

   ;  if (!node)
      return NULL

   ;  if (!(node->token = mcxTingNew(token ? token : "_<>_")))
      {  mcxFree(node)
      ;  return NULL
   ;  }

      node->toktype  =  toktype
   ;  node->optype   =  0
   ;  node->opid     =  0

   ;  node->ival     =  ival
   ;  node->fval     =  fval

   ;  node->next     =  NULL
   ;  node->prev     =  NULL

   ;  node->flags    =  0

   ;  if (debug_g)
      dump(node, 1, "new node")
   ;  return node
;  }


tn* tnDup
(  tn*   this
,  const char* str
)
   {  tn* new =
      tnNewToken
      (  str
      ,  this->toktype
      ,  this->fval
      ,  this->ival
      )
   ;  if (!new)
      return NULL
      
   ;  new->optype = this->optype
   ;  new->next   =  this->next
   ;  new->prev   =  this->prev
   ;  new->flags  =  this->flags

   ;  return new
;  }


mcxstatus tnFree
(  tn*   lft
,  tn*   rgt
)
   {  tn* cur = lft, *next

   ;  while (cur)
      {  
         mcxTingFree(&(cur->token))

      ;  if (debug_g)
         fprintf(stderr, "___ [telraam] freeing node <%p>\n", (void*) cur)

      ;  if (cur == rgt)
         {  mcxFree(cur)
         ;  break
      ;  }
         if (cur->next && cur->next->prev != cur)
         {  mcxErr("tnFree", "free encountered spaghetti")
         ;  return STATUS_FAIL
      ;  }

         next = cur->next
      ;  mcxFree(cur)
      ;  cur = next
   ;  }
      return STATUS_OK
;  }


void tnLink2
(  tn*   one
,  tn*   two
)
   {  if (one)
      one->next = two
   ;  if (two)
      two->prev = one
;  }


void tnLink3
(  tn*   one
,  tn*   two
,  tn*   three
)
   {  if (one)
      one->next = two
   ;  if (three)
      three->prev = two
   
   ;  two->prev = one
   ;  two->next = three
;  }


mcxstatus tnPushToken
(  telRaam* raam
)
   {  i32  toktype = raam->toktype
   ;  tn* new = tnNewToken(raam->token->str, toktype, 0.0, 0)

   ;  if (!new)
      return STATUS_FAIL

   ;  if (toktype == TOKEN_CONST)
         new->fval   =  raam->fval
      ,  new->ival   =  raam->ival
      ,  new->flags  =  raam->flags

   ;  else if
      (  toktype == TOKEN_BINOP
      || toktype == TOKEN_UNIOP
      )
      {  opHook* oh = raam->toktype == TOKEN_BINOP ? opHookDir+3 : opHookDir+0
                              /* bigg phat ugly hack */
                              /* (need to overcome '-' uni/bin ambiguity */
      ;  while (oh->opname)
         {  if (!strcmp(oh->opname, raam->token->str))
            {  new->optype = oh->optype
            ;  new->opid   = oh->opid
            ;  break
         ;  }
            oh++
      ;  }
         if (!oh->opname)
         {  mcxErr("tnPushToken", "no such operator: <%s>", raam->token->str)
         ;  tnFree(new, NULL)
         ;  return STATUS_FAIL
      ;  }
      }
      else if (raam->toktype == TOKEN_FUN)
      {  /* mq: move name resolution to here ? mm, needs arity */
   ;  }
      tnLink3(raam->node, new, NULL)
   ;  raam->node = new
   ;  return STATUS_OK
;  }


mcxstatus tnPushThis
(  telRaam* raam
,  const char* token 
,  i32       toktype
)
   {  tn* new = tnNewToken(token, toktype, 0.0, 0)

   ;  if (!new)
      return STATUS_FAIL

   ;  tnLink3(raam->node, new, NULL)
   ;  raam->node = new
   ;  return STATUS_OK
;  }


void trmDebug
(  void
)
   {  debug_g = 1
;  }


telRaam* trmInit
(  const char* str
)
   {  telRaam* raam=     mcxAlloc(sizeof(telRaam), RETURN_ON_FAIL)

   ;  if (!raam)
      return NULL

   ;  raam->text   =     mcxTingNew(str)
   ;  raam->token  =     mcxTingEmpty(NULL, 30)
   ;  raam->p      =     raam->text->str
   ;  raam->buffered =   FALSE
   ;  raam->node   =     tnNewToken("_start_", TOKEN_START, 0.0, 0)
   ;  raam->start  =     raam->node
   ;  raam->fval   =     0.0
   ;  raam->ival   =     0
   ;  raam->flags  =     0
   ;  raam->depth  =     1
   ;  raam->toktype=     0
   ;  raam->stack  =     NULL

   ;  if (!raam->text || !raam->token || !raam->node)
         mcxFree(raam)
      ,  raam = NULL

   ;  return raam
;  }


mcxstatus trmExit
(  telRaam*  raam
)
   {  if (tnFree(raam->start, raam->node))
      return STATUS_FAIL
   ;  mcxTingFree(&(raam->text))
   ;  mcxTingFree(&(raam->token))
   ;  mcxFree(raam)
   ;  return STATUS_OK
;  }


void untoken
(  telRaam* raam
)
   {  raam->buffered = TRUE
;  }


void dump
(  tn* node
,  i32  times
,  const char* msg
)
   {  tn* prev = NULL
   ;  printf("______ %s\n", msg ? msg : "dumping dumping dumping")
   ;  printf
("%8s"     "%10s"   "%10s"    "%10s"  "%12s" "%10s" "%6s\n"
,"toktype","optype","opclass","token","fval","ival","flags"
)
   ;  while (node)
      {  printf
("%8d"     "%10d"   "%10d"    "%10s"  "%12.4f""%10ld""%6d\n"
         ,  node->toktype
         ,  node->opid
         ,  node->optype
         ,  node->token ? node->token->str : "<>"
         ,  node->fval
         ,  (long) node->ival
         ,  node->flags
         )
      ;  prev = node
      ;  node = node->next
      ;  if (node && (node->prev->next != node || node->prev != prev))
         fprintf
         (  stderr
         ,  "_____ [telraam] PANICK incorrect linking"
            " <%p> n<%p> np<%p> npn<%p>\n"
         ,  (void*) prev
         ,  (void*) node
         ,  (void*) node->prev
         ,  (void*) node->prev->next
         )
      ;  if (!--times)
         break
   ;  }
   }


int getatoken
(  telRaam* raam
,  i32    mode
)
   {  char* p = raam->p
   ;  i32  toktype = 0
   ;  int len
   ;  while (isspace((unsigned char) *p))
      p++
   ;  raam->p = p

   ;  if (!*p)
      {  mcxTingWrite(raam->token, "EOF")
      ;  return TOKEN_EXH
   ;  }

      else if
      (  mode == EXPECT_ATOM
      && (  *p == '-'
         || *p == '!'
         || *p == '~'
         )
      )
      {  toktype = TOKEN_UNIOP
      ;  p = p+1
   ;  }
      else if (*p == ':')
      {  toktype = TOKEN_TRICATCH
      ;  p = p+1
   ;  }
      else if (*p == '&' && *(p+1) == '&')
      {  toktype = TOKEN_AND
      ;  p = p+2
   ;  }
      else if (*p == '|' && *(p+1) == '|')
      {  toktype = TOKEN_OR
      ;  p = p+2
   ;  }
      else if (*p == '?')
      {  toktype = TOKEN_TRIOP
      ;  p = p+1
   ;  }
      else if (*p == ',')
      {  toktype = TOKEN_COMMA
      ;  p = p+1
   ;  }
      else if (isdigit((unsigned char) *p))
      {  int l
      ;  double f
      ;  sscanf(p, "%lf%n", &f, &l)       /* mq need error checking */
      ;  toktype = TOKEN_CONST
      ;  raam->fval = f
      ;  raam->ival = 0
      ;  if (raam->fval < NUM_MIN || raam->fval > NUM_MAX)
         raam->flags = TN_NOINT
      ;  else
         {  raam->flags = mcxStrChrAint(p, isdigit, l) ? 0 : TN_ISINT
         ;  raam->ival = f > 0 ? f + 0.5 : f - 0.5
      ;  }
         p = p+l
   ;  }
      else if (isalpha((unsigned char) *p) || *p == '_')
      {  char* q = p
      ;  while(isalpha((unsigned char) *q) || *q == '_' || isdigit((unsigned char) *q))
         q++
      ;  p = q
      ;  toktype = TOKEN_FUN
   ;  }
      else if (*p == '(' || *p == ')')
      {  toktype = *p == '(' ? TOKEN_OPEN : TOKEN_CLOSE
      ;  p = p+1
   ;  }
      else if
      (  user_char_g == *p
      && (len = user_parse_g(raam->text, p-raam->text->str)) > 0
      )                               /* ^truncintok */
      {  p += len
      ;  toktype = TOKEN_USER
   ;  }
      else
      {  char* q = p
      ;  while (*q == *p || *q == '=')   /* hack */
         q++
      ;  toktype = TOKEN_BINOP
      ;  p = q
   ;  }
      mcxTingNWrite(raam->token, raam->p, (dim) (p-raam->p))
   ;  raam->p = p
   ;  return toktype
;  }


i32  gettoken
(  telRaam* raam
,  i32  mode
)
   {  if (raam->buffered)
      raam->buffered = FALSE
   ;  else
      raam->toktype = getatoken(raam, mode)

   ;  return raam->toktype
;  }


tn* findop
(  tn* end
)
   {  tn* node = end->prev, *max = NULL
   ;  while (node->toktype != TOKEN_OPEN)
      {  if
         (  node->toktype == TOKEN_UNIOP
         || node->toktype == TOKEN_BINOP
         || node->toktype == TOKEN_TRIOP
         )
         {  if
            (  !max
            || node->optype <= max->optype
            )
            max = node
      ;  }
         node = node->prev
   ;  }
      return max
;  }


tn* finduser
(  tn* start
)
   {  tn* node = start->next

   ;  while (node->toktype != TOKEN_CLOSE)
      {  if (node->toktype == TOKEN_USER)
         return node
      ;  node = node->next
   ;  }
      return NULL
;  }


mcxstatus tnUser
(  tn*   usr
)
   {  mcxenum stat = user_eval_g(usr->token->str, &usr->ival, &usr->fval)
   ;  if (stat == TRM_ISNUM)
      {  usr->flags = TN_ISINT
      ;  usr->fval = usr->ival
   ;  }
      else if (stat == TRM_ISREAL)
      usr->flags = 0
   ;  else if (stat == TRM_ISNAN)
      {  usr->flags = TN_ISNAN
      ;  return STATUS_FAIL
   ;  }
      else if (stat == TRM_FAIL)
      {  usr->flags = TN_ISNAN
      ;  return STATUS_FAIL
   ;  }

      usr->toktype = TOKEN_CONST
   ;  return STATUS_OK 
;  }

/*
 *    Flattens a bunch of leafs interspersed with operators.
 *    Leaves received start and corresponding end alone.
*/

mcxstatus flatten
(  tn* start
,  tn* end
)
   {  tn* new, *op, *usr
   ;  real  fval = 0.0
   ;  num   ival = 0
   ;  const char* me = "flatten"

   ;  if
      (  start->toktype != TOKEN_OPEN
      || end->toktype != TOKEN_CLOSE
      )
      {  mcxErr
         (  me
         ,  "wrong toktype - ids (%p, %p)"
         ,  (void*) start, (void*) end
         )
      ;  dump(start, 0, NULL)
      ;  return STATUS_FAIL
   ;  }

      new = start->next

   ;  while ((usr = finduser(start)))
      {  if (tnUser(usr))
         return STATUS_FAIL
   ;  }

      while ((op = findop(end)))
      {
         tn* lft = op->prev
      ;  tn* rgt = op->next   /* ugly in case of UNIOP */
      ;  int err = 0
      ;  i32  flags = 0

      ;  if (op->toktype == TOKEN_UNIOP)
         {  
            real frgt = rgt->fval
         ;  num irgt = rgt->ival

         ;  switch(op->opid)
            {  case OP_UNI_NOT
            :  ival = (tn_isint(rgt) && irgt) ? 0 : frgt ? 0 : 1
            ;  fval = ival  
            ;  flags |= TN_ISINT
         ;  break

            ;  case OP_UNI_NEG
            :  fval = -frgt
            ;  ival = -irgt
         ;  break
                  
            ;  case OP_UNI_COMPL
            :  ival = ~irgt
            ;  fval =  ival
            ;  flags |= TN_ISINT
         ;  break

            ;  default
            :  err = 1
         ;  }
            lft = op
         ;  flags |=  tn_isint(rgt)
            /* mq fval=ival assignment ugly, need overflow check as well :) */
      ;  }

         else if (op->toktype == TOKEN_BINOP)
         {
            real  flft = lft->fval  
         ;  real  frgt = rgt->fval  
         ;  num   ilft = lft->ival  
         ;  num   irgt = rgt->ival  

         ;  if (op->opid & OPTYPE_BIT)
            {  if (!tn_isint(lft))
               ilft = lft->fval        /* fixme: why the reassign? */
            ;  if (!tn_isint(rgt))
               irgt = rgt->fval        /* fixme: why the reassign? */
            ;  if (!tn_isint(rgt) || !tn_isint(lft))
               mcxErr
               (  "let"
               ,  "[flatten][bitop %s] forcing real operands to number"
               ,  op->token->str
               )
         ;  }

            if (lft->toktype != TOKEN_CONST || rgt->toktype != TOKEN_CONST)
            {  mcxErr(me, "this bifoo is not the right foo")
            ;  dump(start, 0, NULL)
            ;  return STATUS_FAIL
         ;  }

            switch(op->opid)
            {
               case OP_MUL_MUL
            :  fval = flft * frgt
            ;  ival = ilft * irgt
            ;  break

            ;  case OP_EXP_EXP
            :  if (flft < 0 && !(rgt->flags & TN_ISINT))
                  fval = 0.0
               ,  flags |= TN_ISNAN
            ;  else
               fval = pow(flft,frgt)
            ;  ival = letround(fval)
            ;  break

            ;  case OP_ADD_ADD
            :  fval = flft + frgt
            ;  ival = ilft + irgt
            ;  break

            ;  case OP_MUL_FRAC
            :  fval = frgt ? (flft / frgt) : 0.0
            ;  ival = irgt ? (ilft / irgt) : 0
            ;  if (tn_isint(lft) && tn_isint(rgt) && ival * irgt == ilft)
               flags |= TN_ISINT
            ;  else
               flags |= TN_NOINT
            ;  if (!frgt)
               flags |= TN_ISNAN
            ;  break

            ;  case OP_MUL_DIV
            :  fval = frgt ? floor(flft/frgt) : 0.0
            ;  ival = irgt ? (ilft / irgt) : 0
            ;  if (!frgt)
               flags |= TN_ISNAN
            ;  break

            ;  case OP_MUL_MOD
            :  fval = frgt ? frgt * (flft/frgt-floor(flft/frgt)) : 0.0
            ;  ival = irgt ? (ilft % irgt) : 0.0
            ;  if (!frgt)
               flags |= TN_ISNAN
            ;  break

            ;  case OP_ADD_SUB
            :  fval = flft - frgt
            ;  ival = ilft - irgt
            ;  break

            ;  case OP_CMP_LT
            :  ival =   tn_isint(lft) && tn_isint(rgt) && (ilft < irgt)
                        ?  1
                        :  flft < frgt
                           ?  1
                           :  0
            ;  flags |= TN_ISINT
            ;  break

            ;  case OP_CMP_LQ
            :  ival =   tn_isint(lft) && tn_isint(rgt) && (ilft <= irgt)
                        ?  1
                        :  flft <= frgt
                           ?  1
                           :  0
            ;  flags |= TN_ISINT
            ;  break

            ;  case OP_CMP_GQ
            :  ival =   tn_isint(lft) && tn_isint(rgt) && (ilft >= irgt)
                        ?  1
                        :  flft >= frgt
                           ?  1
                           :  0
            ;  flags |= TN_ISINT
            ;  break

            ;  case OP_CMP_GT
            :  ival =   tn_isint(lft) && tn_isint(rgt) && (ilft > irgt)
                        ?  1
                        :  flft > frgt
                           ?  1
                           :  0
            ;  flags |= TN_ISINT
            ;  break

            ;  case OP_CMP_EQ
            :  ival =   tn_isint(lft) && tn_isint(rgt) && (ilft == irgt)
                        ?  1
                        :  flft == frgt
                           ?  1
                           :  0
            ;  flags |= TN_ISINT
            ;  break

            ;  case OP_CMP_NE
            :  ival =   tn_isint(lft) && tn_isint(rgt) && (ilft != irgt)
                        ?  1
                        :  flft != frgt
                           ?  1
                           :  0
            ;  flags |= TN_ISINT
            ;  break

            ;  case OP_BIT_LSHIFT
            :  ival = ilft << irgt
            ;  flags |= TN_ISINT
            ;  break

            ;  case OP_BIT_RSHIFT
            :  ival = ilft >> irgt
            ;  flags |= TN_ISINT
            ;  break

            ;  case OP_BIT_AND
            :  ival = ilft & irgt
            ;  flags |= TN_ISINT
            ;  break

            ;  case OP_BIT_OR
            :  ival = ilft | irgt
            ;  flags |= TN_ISINT
            ;  break

            ;  case OP_BIT_XOR
            :  ival = ilft ^ irgt
            ;  flags |= TN_ISINT
            ;  break

            ;  default
            :  err = 1
         ;  }

               /* this rule implements implicit behaviour with overruling:
                * two integers result in an integer unless overruled
                * with the TN_NOINT attribute.
               */

            if (!(flags & TN_NOINT))
            flags |=  tn_isint(lft) & tn_isint(rgt)

               /* next we check whether overflow occurred. If so, discard the
                * integer attribute.  This depends on i) fval follows ival as
                * long as the integer attribute is set and ii) in that pursuit,
                * fval is computed to be similar to ival.
               */

         ;  if ((fval > NUM_MAX || fval < NUM_MIN) && (flags & TN_ISINT))
            flags ^= TN_ISINT

               /* make fval follow ival, otherwise, give ival special
                * value. *Never* should float->int conversion happen
                * in this code; it should be user-enforced.
                * Setting ival to 0 may help show any such behaviour as a bug.
               */

         ;  if (flags & TN_ISINT)
            fval = ival
         ;  else
            ival = 0
      ;  }
         else
         {  mcxErr(me, "panicking at toktype <%ld>", (long) op->toktype)
         ;  return STATUS_FAIL
      ;  }

         if (err)
         {  mcxErr
            (  me
            ,  "op <%s> id <%ld> class <%ld> not yet supported"
            ,  op->token->str
            ,  (long) op->opid
            ,  (long) op->optype
            )
         ;  return STATUS_FAIL
      ;  }

         if (flags & TN_ISNAN)
         {  mcxErr(me, "arithmetic exception for op <%s>", op->token->str)
         ;  return STATUS_FAIL
      ;  }

         if (!(new = tnNewToken("_eval_", TOKEN_CONST, fval, ival)))
         return STATUS_FAIL

      ;  new->flags = flags
                     /* mq need overflow check, nan check etc */
      ;  tnLink3(lft->prev, new, rgt->next)
      ;  if (tnFree(lft, rgt))
         return STATUS_FAIL
   ;  }

      return STATUS_OK
;  }


fun1Hook* getfun1id
(  tn*   start
)
   {  fun1Hook *fh = fun1HookDir+0
   ;  while (fh->funname && strcmp(fh->funname, start->token->str))
      fh++
   ;  return fh->funname ? fh : NULL
;  }


fun2Hook* getfun2id
(  tn*   start
)
   {  fun2Hook *fh = fun2HookDir+0
   ;  while (fh->funname && strcmp(fh->funname, start->token->str))
      fh++
   ;  return fh->funname ? fh : NULL
;  }


tn* funcx
(  tn* start
,  tn* end
)
   {  tn *new, *arg  = end->prev
   ;  real  fval     =  0.0
   ;  num   ival     =  0
   ;  i32   flags    =  0
   ;  int n_args = arg->toktype == TOKEN_CONST
   ;  int err        =  0
   ;  const char* me = "funcx"
   ;  const char* fn = "_init_"

   ;  if
      (  start->toktype != TOKEN_FUN
      || start->next->toktype != TOKEN_OPEN
      || end->toktype != TOKEN_CLOSE
      )
      {  mcxErr(me, "wrong toktype - ids (%p, %p)", (void*) start, (void*) end)
      ;  dump(start, 0, NULL)
      ;  return NULL
   ;  }

      while
      (  arg->toktype == TOKEN_CONST
      && arg->prev->toktype == TOKEN_COMMA
      )
         arg = arg->prev->prev
      ,  n_args++

   ;  if (arg->prev != start->next)
      {  mcxErr(me, "this function foo is not the right foo")
      ;  dump(start, 0, NULL)
      ;  return NULL
   ;  }

      if (n_args == 1)
      {  tn* op1 = arg
      ;  fun1Hook* fh = getfun1id(start)
      ;  if (fh)
         {  fn    =  fh->funname
         ;  if (fh->funflags & FUN_SPECIAL)
            {  if (!strcmp(fn, "abs"))
               {  if (tn_isint(op1))
                  {  ival = op1->ival > 0 ? op1->ival : -op1->ival
                  ;  flags |= TN_ISINT
               ;  }
                  else
                  fval = op1->fval > 0 ? op1->fval : -op1->fval
            ;  }
               else if (!strcmp(fn, "bits"))
               {  if (tn_isint(op1))
                  {  ival = op1->ival
                  ;  flags |= TN_ISINT
                     /* mq show the damn bits */
               ;  }
                  else
                  fval = op1->fval
                     /* mq show the damn bits */
            ;  }
               else
               err = 1
         ;  }
            else
            {  fval  =  (fh->funcd)(op1->fval)
            ;  if
               (  fh->funflags & FUN_INTRESULT
               && fval <= NUM_MAX
               && fval >= NUM_MIN
               )
               {  flags |= TN_ISINT
               ;  ival = (num) fval > 0 ? fval+0.5 : fval - 0.5
            ;  }
            }
         }
         else
         err = 1
   ;  }
      else if (n_args == 2)
      {  
         tn* op1 = arg, *op2 = op1->next->next
      ;  fun2Hook* fh = getfun2id(start)

      ;  if (fh)
         {  fn    =  fh->funname
         ;  if (tn_isint(op1) && tn_isint(op2) && fh->funcl)
            {  ival = (fh->funcl)(op1->ival, op2->ival)
            ;  flags |= TN_ISINT
         ;  }
            else
            fval = (fh->funcd)(op1->fval, op2->fval)
      ;  }
         else
         err = 1
   ;  }
      else
      err = 1

   ;  if (err)
      {  mcxErr
         (  me
         ,  "<%s> [%d] not supported"
         ,  start->token->str
         ,  n_args
         )
      ;  return NULL
   ;  }
      else
      {  if (!(new = tnNewToken(fn, TOKEN_CONST, fval, ival)))
         return NULL
      ;  new->flags = flags
   ;  }

      return new
;  }


tn* match
(  tn*   start
)
   {  int depth = 1
      
   ;  if (start->toktype != TOKEN_OPEN)
      {  mcxErr("match", "node <%p> has wrong toktype", (void*) start)
      ;  return NULL
   ;  }

      while (start->next)
      {
         start = start->next
      ;  if (start->toktype == TOKEN_OPEN)
         depth++
      ;  else if (start->toktype == TOKEN_CLOSE)
         {  depth--
         ;  if (!depth)
            break
      ;  }
      }
      return depth ? NULL : start
;  }


/*
 *    must leave received start and corresponding end alone
*/

mcxstatus compute
(  tn*   start
)
   {  tn* ptr, *new, *end
   ;  const char* me = "compute"  

   ;  if (start->toktype != TOKEN_OPEN)
      {  mcxErr(me, "node <%p> has wrong toktype", (void*) start)
      ;  return(STATUS_FAIL)
   ;  }

      if (!(end =  match(start)))
      {  mcxErr(me, "node <%p> has no match", (void*) start)
      ;  return(STATUS_FAIL)
   ;  }

      ptr   =  start->next

   ;  while (ptr)                         /* ok by the naming police? */
      {
         tn* eosc, *val

      ;  if (ptr->toktype == TOKEN_FUN)
         {
            if (compute(ptr->next))
            return STATUS_FAIL            /* now:: LPT op CM [op CM]* RPT */
         ;  eosc = match(ptr->next)
         ;  if (!eosc || !(val = funcx(ptr, eosc)))
            return STATUS_FAIL            /* now:: fun LPT val RPT       */
         ;  tnLink3(ptr->prev, val, eosc->next)
         ;  if (tnFree(ptr, eosc))
            return STATUS_FAIL
         ;  ptr = val->next
      ;  }

         else if (ptr->toktype == TOKEN_OPEN)
         {
            if (compute(ptr))
            return STATUS_FAIL

         ;  if (!(eosc = match(ptr)))      /* should check singularity */
            return STATUS_FAIL

         ;  if (!(val = tnDup(eosc->prev, "_scope_")))
            return STATUS_FAIL

         ;  tnLink3(ptr->prev, val, eosc->next)

         ;  if (tnFree(ptr, eosc))
            return STATUS_FAIL

         ;  ptr  =  val->next
      ;  }

                                          /* should check presence TRICATCH */
         else if (ptr->toktype == TOKEN_TRIOP)
         {  tn* br1 = ptr->next, *br2, *eobr1, *eobr2    /* branches */
         ;  if (!(eobr1 = match(br1)))
            return STATUS_FAIL

         ;  if (!(br2 = eobr1->next->next))
            return STATUS_FAIL

         ;  eobr2 = match(br2)

         ;  if (ptr->prev->fval)          /* mqmq! logic by fval */
            {  if (compute(br1))
               return STATUS_FAIL

            ;  if (!(new = tnDup(br1->next, "triop1")))
               return STATUS_FAIL

            ;  tnLink3(ptr->prev->prev, new, eobr2->next)

            ;  if (tnFree(ptr->prev, eobr2))
               return STATUS_FAIL
         ;  }
            else
            {  if (compute(br2))
               return STATUS_FAIL

            ;  if (!(new = tnDup(br2->next, "triop2")))
               return STATUS_FAIL

            ;  tnLink3(ptr->prev->prev, new, eobr2->next)
            ;  if (tnFree(ptr->prev, eobr2))
               return STATUS_FAIL
         ;  }
            ptr = new->next
      ;  }
         else if (ptr->toktype == TOKEN_AND)    /* now:: val AND LPT any RPT */
         {  tn* pivot = ptr->prev, *clause=ptr->next, *after
         ;  if (pivot->fval)
            {  if (compute(clause))
               return STATUS_FAIL
           /* should check singularity of result   */
           /*          lpt      val  rpt    ?      */
            ;  after = clause->next->next->next     /* oops, ugly dugly    */
            ;  pivot->fval = clause->next->fval     /* mqmq! logic by fval */
            ;  if (tnFree(pivot->next, after->prev))
               return STATUS_FAIL
            ;  tnLink2(pivot, after)
            ;  ptr = after
         ;  }
            else
            {  tn* eoclause = match(clause)
            ;  tn* any = eoclause ? eoclause->next : NULL
            ;  if (!eoclause || tnFree(pivot->next, eoclause))
               return STATUS_FAIL
            ;  tnLink2(pivot, any)
            ;  ptr = any
         ;  }
            pivot->ival = pivot->fval ? 1 : 0
         ;  pivot->flags |= TN_ISINT
      ;  }
         else if (ptr->toktype == TOKEN_OR)
         {  tn* pivot = ptr->prev, *clause=ptr->next, *after
         ;  if (pivot->fval)
            {  tn* eoclause = match(clause)
            ;  tn* any = eoclause ? eoclause->next : NULL
            ;  if (!eoclause || tnFree(pivot->next, eoclause))
               return STATUS_FAIL
            ;  tnLink2(pivot, any)
            ;  ptr = any
         ;  }
            else
            {  if (compute(clause))
               return STATUS_FAIL
           /* should check singularity of result    */
            ;  after = clause->next->next->next    /* oops, ugly dugly */
            ;  pivot->fval = clause->next->fval    /* mqmq! logic by fval */
            ;  if (tnFree(pivot->next, after->prev))
               return STATUS_FAIL
            ;  tnLink2(pivot, after)
            ;  ptr = after
         ;  }
            pivot->ival = pivot->fval ? 1 : 0
         ;  pivot->flags |= TN_ISINT
      ;  }
         else if (ptr->toktype == TOKEN_CLOSE)
         break
      ;  else
         ptr  = ptr->next
   ;  }

                  /* NOTE: by design we should always have ptr != NULL
                   * that makes the clause to the while (ptr) { } loop
                   * above a bit dodgy.
                  */
      if (ptr != end || ptr->toktype != TOKEN_CLOSE)
      {  mcxErr(me, "ptr does not close")
      ;  dump(ptr->prev, 0, NULL)
      ;  return STATUS_FAIL
   ;  }

      if (flatten(start, ptr))
      return STATUS_FAIL

   ;  return STATUS_OK
;  }


mcxstatus getatom
(  telRaam* raam
)
   {  i32  toktype = gettoken(raam, EXPECT_ATOM)
   ;  const char* me = "getatom"

   ;  if (toktype < 0)
      {  mcxErr(me, "unexpected token <%s>", raam->token->str)
      ;  return STATUS_FAIL
   ;  }

   ;  if (toktype == TOKEN_UNIOP)
      {  if (tnPushToken(raam))
         return STATUS_FAIL
      ;  if (getatom(raam))
         return STATUS_FAIL
   ;  }
      else if (toktype == TOKEN_OPEN)
      {  if (getexpression(raam))
         return STATUS_FAIL

      ;  if ((toktype = gettoken(raam, EXPECT_ANY)) != TOKEN_CLOSE)
         {  mcxErr(me, "no close (token <%ld>)", (long) toktype)
         ;  return STATUS_FAIL
      ;  }
         if (raam->depth < 0)
         {  mcxErr(me, "spurious rpth (atom I)")
         ;  return STATUS_FAIL
      ;  }
      }
      else if (toktype == TOKEN_FUN)
      {  
         if (tnPushToken(raam))
         return STATUS_FAIL

      ;  if (tnPushThis(raam, "_open_", TOKEN_OPEN))
         return STATUS_FAIL

      ;  if ((toktype = gettoken(raam, EXPECT_ANY)) != TOKEN_OPEN)
         {  mcxErr(me, "expect '(' after function symbol")
         ;  return STATUS_FAIL
      ;  }

         while(1)
         {  if (getexpression(raam))
            return STATUS_FAIL

         ;  if (gettoken(raam, EXPECT_ANY) == TOKEN_COMMA)
            {  if (tnPushToken(raam))
               return STATUS_FAIL
         ;  }
            else
            {  untoken(raam)
            ;  break
         ;  }
         }
         if ((toktype = gettoken(raam, EXPECT_ANY)) != TOKEN_CLOSE)
         {  mcxErr(me, "expect ')' closing function symbol")
         ;  return STATUS_FAIL
      ;  }
         if (tnPushThis(raam, "_close_", TOKEN_CLOSE))
         return STATUS_FAIL
   ;  }
      else if (toktype == TOKEN_CONST)
      {  if (tnPushToken(raam))
         return STATUS_FAIL
   ;  }
      else if (toktype == TOKEN_CLOSE)
      {  mcxErr(me, "empty group not allowed")
      ;  return STATUS_FAIL
   ;  }
      else if (toktype == TOKEN_USER)
      {  if (tnPushToken(raam))
         return STATUS_FAIL
   ;  }
      else
      {  mcxErr(me, "unexpected token <%s> (atom)", raam->token->str)
      ;  return STATUS_FAIL
   ;  }

      return STATUS_OK
;  }


mcxstatus getexpression
(  telRaam* raam
)
   {  i32  toktype
   ;  const char* me = "getexpression"
   ;  raam->depth++

   ;  if (tnPushThis(raam, "_open_", TOKEN_OPEN))
      return STATUS_FAIL

   ;  while (1)
      {  
         if (getatom(raam))
         return STATUS_FAIL

      ;  toktype = gettoken(raam, EXPECT_ANY)

      ;  if (toktype == TOKEN_BINOP)
         {  if (tnPushToken(raam))
            return STATUS_FAIL
      ;  }
         else if (toktype == TOKEN_AND)
         {  if (tnPushThis(raam, "_close_", TOKEN_CLOSE))
            return STATUS_FAIL
         ;  if (tnPushToken(raam))
            return STATUS_FAIL
         ;  if (tnPushThis(raam, "_open_", TOKEN_OPEN))
            return STATUS_FAIL
      ;  }
         else if (toktype == TOKEN_OR)
         {  if (tnPushThis(raam, "_close_", TOKEN_CLOSE))
            return STATUS_FAIL
         ;  if (tnPushToken(raam))
            return STATUS_FAIL
         ;  if (tnPushThis(raam, "_open_", TOKEN_OPEN))
            return STATUS_FAIL
      ;  }
         else if (toktype == TOKEN_TRIOP)
         {  if (tnPushThis(raam, "_close_", TOKEN_CLOSE))
            return STATUS_FAIL

         ;  if (tnPushToken(raam))
            return STATUS_FAIL

         ;  if (tnPushThis(raam, "_open_", TOKEN_OPEN))
            return STATUS_FAIL

         ;  if (getexpression(raam))
            return STATUS_FAIL

         ;  if (tnPushThis(raam, "_close_", TOKEN_CLOSE))
            return STATUS_FAIL

         ;  toktype = gettoken(raam, EXPECT_ANY)

         ;  if (toktype != TOKEN_TRICATCH)
            {  mcxErr
               (  me
               ,  "unexpected token <%s> (expression)"
               ,  raam->token->str
               )
            ;  return STATUS_FAIL
         ;  }
            if (tnPushToken(raam))
            return STATUS_FAIL

         ;  if (tnPushThis(raam, "_open_", TOKEN_OPEN))
            return STATUS_FAIL
      ;  }
         else if
         (  toktype == TOKEN_COMMA
         || toktype == TOKEN_CLOSE
         || toktype == TOKEN_EXH
         || toktype == TOKEN_TRICATCH
         )
         {  untoken(raam)
         ;  break
      ;  }
         else
         {  mcxErr
            (  me
            ,  "unexpected token <%s> <%ld> (expression)"
            ,  raam->token->str
            ,  (long) toktype
            )
         ;  return STATUS_FAIL
      ;  }
      }
   
      if (tnPushThis(raam, "_close_", TOKEN_CLOSE))
      return STATUS_FAIL

   ;  raam->depth--
   ;  return STATUS_OK
;  }


mcxstatus trmParse
(  telRaam* raam
)
   {  if (tnPushThis(raam, "_open_", TOKEN_OPEN))
      return STATUS_FAIL

   ;  if (getexpression(raam))
      return STATUS_FAIL

   ;  if (tnPushThis(raam, "_close_", TOKEN_CLOSE))
      return STATUS_FAIL

   ;  if (gettoken(raam, EXPECT_ANY) != TOKEN_EXH)
      {  mcxErr("trmParse", "spurious token <%s>", raam->token->str)
      ;  return STATUS_FAIL
   ;  }

      return STATUS_OK
;  }


void trmRegister
(  telRaam* raam  cpl__unused
,  int      (user_parse)(mcxTing* txt, int offset)
,  mcxenum  (user_eval)(const char* token, long *ival, double *fval)
,  char     user_char
)
   {  user_parse_g = user_parse
   ;  user_eval_g  = user_eval
   ;  user_char_g  = user_char
;  }


int trmEval
(  telRaam* raam
,  long* lp
,  double* fp
)
   {  tn* result
   ;  mcxstatus stat = compute(raam->start->next)
   ;  result = stat ? NULL : (raam->start->next->next)

   ;  if (result)
      {  *lp = result->ival
      ;  *fp = result->fval
      ;  return result->flags
   ;  }

      return -1
;  }



int trmStack
(  telRaam* raam
)
   {  tn* result
   ;  mcxstatus stat = compute(raam->start->next)
   ;  return stat
;  }