aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/tcl/generic/tclCompExpr.c
blob: 74b12c171e6f49cb9e70bd31472fec44fb2a53f6 (plain) (blame)
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
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
/* 
 * tclCompExpr.c --
 *
 *	This file contains the code to compile Tcl expressions.
 *
 * Copyright (c) 1996-1997 Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * SCCS: @(#) tclCompExpr.c 1.31 97/08/07 10:14:07
 */

#include "tclInt.h"
#include "tclCompile.h"

/*
 * The stuff below is a bit of a hack so that this file can be used in
 * environments that include no UNIX, i.e. no errno: just arrange to use
 * the errno from tclExecute.c here.
 */

#ifndef TCL_GENERIC_ONLY
#include "tclPort.h"
#else
#define NO_ERRNO_H
#endif

#ifdef NO_ERRNO_H
extern int errno;			/* Use errno from tclExecute.c. */
#define ERANGE 34
#endif

/*
 * Boolean variable that controls whether expression compilation tracing
 * is enabled.
 */

#ifdef TCL_COMPILE_DEBUG
static int traceCompileExpr = 0;
#endif /* TCL_COMPILE_DEBUG */

/*
 * The ExprInfo structure describes the state of compiling an expression.
 * A pointer to an ExprInfo record is passed among the routines in
 * this module.
 */

typedef struct ExprInfo {
    int token;			/* Type of the last token parsed in expr.
				 * See below for definitions. Corresponds
				 * to the characters just before next. */
    int objIndex;		/* If token is a literal value, the index of
				 * an object holding the value in the code's
				 * object table; otherwise is NULL. */
    char *funcName;		/* If the token is FUNC_NAME, points to the
				 * first character of the math function's
				 * name; otherwise is NULL. */
    char *next;			/* Position of the next character to be
				 * scanned in the expression string. */
    char *originalExpr;		/* The entire expression that was originally
				 * passed to Tcl_ExprString et al. */
    char *lastChar;		/* Pointer to terminating null in
				 * originalExpr. */
    int hasOperators;		/* Set 1 if the expr has operators; 0 if
				 * expr is only a primary. If 1 after
				 * compiling an expr, a tryCvtToNumeric
				 * instruction is emitted to convert the
				 * primary to a number if possible. */
    int exprIsJustVarRef;	/* Set 1 if the expr consists of just a
				 * variable reference as in the expression
				 * of "if $b then...". Otherwise 0. If 1 the
				 * expr is compiled out-of-line in order to
				 * implement expr's 2 level substitution
				 * semantics properly. */
    int exprIsComparison;	/* Set 1 if the top-level operator in the
				 * expr is a comparison. Otherwise 0. If 1,
				 * because the operands might be strings,
				 * the expr is compiled out-of-line in order
				 * to implement expr's 2 level substitution
				 * semantics properly. */
} ExprInfo;

/*
 * Definitions of the different tokens that appear in expressions. The order
 * of these must match the corresponding entries in the operatorStrings
 * array below.
 */

#define LITERAL		0
#define FUNC_NAME	(LITERAL + 1)
#define OPEN_BRACKET	(LITERAL + 2)
#define CLOSE_BRACKET	(LITERAL + 3)
#define OPEN_PAREN	(LITERAL + 4)
#define CLOSE_PAREN	(LITERAL + 5)
#define DOLLAR		(LITERAL + 6)
#define QUOTE		(LITERAL + 7)
#define COMMA		(LITERAL + 8)
#define END		(LITERAL + 9)
#define UNKNOWN		(LITERAL + 10)

/*
 * Binary operators:
 */

#define MULT		(UNKNOWN + 1)
#define DIVIDE		(MULT + 1)
#define MOD		(MULT + 2)
#define PLUS		(MULT + 3)
#define MINUS		(MULT + 4)
#define LEFT_SHIFT	(MULT + 5)
#define RIGHT_SHIFT	(MULT + 6)
#define LESS		(MULT + 7)
#define GREATER		(MULT + 8)
#define LEQ		(MULT + 9)
#define GEQ		(MULT + 10)
#define EQUAL		(MULT + 11)
#define NEQ		(MULT + 12)
#define BIT_AND		(MULT + 13)
#define BIT_XOR		(MULT + 14)
#define BIT_OR		(MULT + 15)
#define AND		(MULT + 16)
#define OR		(MULT + 17)
#define QUESTY		(MULT + 18)
#define COLON		(MULT + 19)

/*
 * Unary operators. Unary minus and plus are represented by the (binary)
 * tokens MINUS and PLUS.
 */

#define NOT		(COLON + 1)
#define BIT_NOT		(NOT + 1)

/*
 * Mapping from tokens to strings; used for debugging messages. These
 * entries must match the order and number of the token definitions above.
 */

#ifdef TCL_COMPILE_DEBUG
static char *tokenStrings[] = {
    "LITERAL", "FUNCNAME",
    "[", "]", "(", ")", "$", "\"", ",", "END", "UNKNOWN",
    "*", "/", "%", "+", "-",
    "<<", ">>", "<", ">", "<=", ">=", "==", "!=",
    "&", "^", "|", "&&", "||", "?", ":",
    "!", "~"
};
#endif /* TCL_COMPILE_DEBUG */

/*
 * Declarations for local procedures to this file:
 */

static int		CompileAddExpr _ANSI_ARGS_((Tcl_Interp *interp,
			    ExprInfo *infoPtr, int flags,
			    CompileEnv *envPtr));
static int		CompileBitAndExpr _ANSI_ARGS_((Tcl_Interp *interp,
			    ExprInfo *infoPtr, int flags,
			    CompileEnv *envPtr));
static int		CompileBitOrExpr _ANSI_ARGS_((Tcl_Interp *interp,
			    ExprInfo *infoPtr, int flags,
			    CompileEnv *envPtr));
static int		CompileBitXorExpr _ANSI_ARGS_((Tcl_Interp *interp,
			    ExprInfo *infoPtr, int flags,
			    CompileEnv *envPtr));
static int		CompileCondExpr _ANSI_ARGS_((Tcl_Interp *interp,
			    ExprInfo *infoPtr, int flags,
			    CompileEnv *envPtr));
static int		CompileEqualityExpr _ANSI_ARGS_((Tcl_Interp *interp,
			    ExprInfo *infoPtr, int flags,
			    CompileEnv *envPtr));
static int		CompileLandExpr _ANSI_ARGS_((Tcl_Interp *interp,
			    ExprInfo *infoPtr, int flags,
			    CompileEnv *envPtr));
static int		CompileLorExpr _ANSI_ARGS_((Tcl_Interp *interp,
			    ExprInfo *infoPtr, int flags,
			    CompileEnv *envPtr));
static int		CompileMathFuncCall _ANSI_ARGS_((Tcl_Interp *interp,
			    ExprInfo *infoPtr, int flags,
			    CompileEnv *envPtr));
static int		CompileMultiplyExpr _ANSI_ARGS_((Tcl_Interp *interp,
			    ExprInfo *infoPtr, int flags,
			    CompileEnv *envPtr));
static int		CompilePrimaryExpr _ANSI_ARGS_((Tcl_Interp *interp,
			    ExprInfo *infoPtr, int flags,
			    CompileEnv *envPtr));
static int		CompileRelationalExpr _ANSI_ARGS_((
    			    Tcl_Interp *interp, ExprInfo *infoPtr,
			    int flags, CompileEnv *envPtr));
static int		CompileShiftExpr _ANSI_ARGS_((Tcl_Interp *interp,
			    ExprInfo *infoPtr, int flags,
			    CompileEnv *envPtr));
static int		CompileUnaryExpr _ANSI_ARGS_((Tcl_Interp *interp,
			    ExprInfo *infoPtr, int flags,
			    CompileEnv *envPtr));
static int		GetToken _ANSI_ARGS_((Tcl_Interp *interp,
			    ExprInfo *infoPtr, CompileEnv *envPtr));

/*
 * Macro used to debug the execution of the recursive descent parser used
 * to compile expressions.
 */

#ifdef TCL_COMPILE_DEBUG
#define HERE(production, level) \
    if (traceCompileExpr) { \
	fprintf(stderr, "%*s%s: token=%s, next=\"%.20s\"\n", \
		(level), " ", (production), tokenStrings[infoPtr->token], \
		infoPtr->next); \
    }
#else
#define HERE(production, level)
#endif /* TCL_COMPILE_DEBUG */

/*
 *----------------------------------------------------------------------
 *
 * TclCompileExpr --
 *
 *	This procedure compiles a string containing a Tcl expression into
 *	Tcl bytecodes. This procedure is the top-level interface to the
 *	the expression compilation module, and is used by such public
 *	procedures as Tcl_ExprString, Tcl_ExprStringObj, Tcl_ExprLong,
 *	Tcl_ExprDouble, Tcl_ExprBoolean, and Tcl_ExprBooleanObj.
 *
 *	Note that the topmost recursive-descent parsing routine used by
 *	TclCompileExpr to compile expressions is called "CompileCondExpr"
 *	and not, e.g., "CompileExpr". This is done to avoid an extra
 *	procedure call since such a procedure would only return the result
 *	of calling CompileCondExpr. Other recursive-descent procedures
 *	that need to parse expressions also call CompileCondExpr.
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->termOffset is filled in with the offset of the character in
 *	"string" just after the last one successfully processed; this might
 *	be the offset of the ']' (if flags & TCL_BRACKET_TERM), or the
 *	offset of the '\0' at the end of the string.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the expression.
 *
 *	envPtr->exprIsJustVarRef is set 1 if the expression consisted of
 *	a single variable reference as in the expression of "if $b then...".
 *	Otherwise it is set 0. This is used to implement Tcl's two level
 *	expression substitution semantics properly.
 *
 *	envPtr->exprIsComparison is set 1 if the top-level operator in the
 *	expr is a comparison. Otherwise it is set 0. If 1, because the
 *	operands might be strings, the expr is compiled out-of-line in order
 *	to implement expr's 2 level substitution semantics properly.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the expression at runtime.
 *
 *----------------------------------------------------------------------
 */

int
TclCompileExpr(interp, string, lastChar, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    char *string;		/* The source string to compile. */
    char *lastChar;		/* Pointer to terminating character of
				 * string. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    Interp *iPtr = (Interp *) interp;
    ExprInfo info;
    int maxDepth = 0;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    int result;

#ifdef TCL_COMPILE_DEBUG
    if (traceCompileExpr) {
	fprintf(stderr, "expr: string=\"%.30s\"\n", string);
    }
#endif /* TCL_COMPILE_DEBUG */

    /*
     * Register the builtin math functions the first time an expression is
     * compiled.
     */

    if (!(iPtr->flags & EXPR_INITIALIZED)) {
	BuiltinFunc *funcPtr;
	Tcl_HashEntry *hPtr;
	MathFunc *mathFuncPtr;
	int i;

	iPtr->flags |= EXPR_INITIALIZED;
	i = 0;
	for (funcPtr = builtinFuncTable; funcPtr->name != NULL; funcPtr++) {
	    Tcl_CreateMathFunc(interp, funcPtr->name,
		    funcPtr->numArgs, funcPtr->argTypes,
		    (Tcl_MathProc *) NULL, (ClientData) 0);
	    
	    hPtr = Tcl_FindHashEntry(&iPtr->mathFuncTable, funcPtr->name);
	    if (hPtr == NULL) {
		panic("TclCompileExpr: Tcl_CreateMathFunc incorrectly registered '%s'", funcPtr->name);
		return TCL_ERROR;
	    }
	    mathFuncPtr = (MathFunc *) Tcl_GetHashValue(hPtr);
	    mathFuncPtr->builtinFuncIndex = i;
	    i++;
	}
    }

    info.token = UNKNOWN;
    info.objIndex = -1;
    info.funcName = NULL;
    info.next = string;
    info.originalExpr = string;
    info.lastChar = lastChar;
    info.hasOperators = 0;
    info.exprIsJustVarRef = 1;	/* will be set 0 if anything else is seen */
    info.exprIsComparison = 0;	/* set 1 if topmost operator is <,==,etc. */

    /*
     * Get the first token then compile an expression.
     */

    result = GetToken(interp, &info, envPtr);
    if (result != TCL_OK) {
	goto done;
    }
    
    result = CompileCondExpr(interp, &info, flags, envPtr);
    if (result != TCL_OK) {
	goto done;
    }
    if (info.token != END) {
	Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
		"syntax error in expression \"", string, "\"", (char *) NULL);
	result = TCL_ERROR;
	goto done;
    }
    if (!info.hasOperators) {
	/*
	 * Attempt to convert the primary's object to an int or double.
	 * This is done in order to support Tcl's policy of interpreting
	 * operands if at all possible as first integers, else
	 * floating-point numbers.
	 */
	
	TclEmitOpcode(INST_TRY_CVT_TO_NUMERIC, envPtr);
    }
    maxDepth = envPtr->maxStackDepth;

    done:
    envPtr->termOffset = (info.next - string);
    envPtr->maxStackDepth = maxDepth;
    envPtr->exprIsJustVarRef = info.exprIsJustVarRef;
    envPtr->exprIsComparison = info.exprIsComparison;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * CompileCondExpr --
 *
 *	This procedure compiles a Tcl conditional expression:
 *	condExpr ::= lorExpr ['?' condExpr ':' condExpr]
 *
 *	Note that this is the topmost recursive-descent parsing routine used
 *	by TclCompileExpr to compile expressions. It does not call an
 *	separate, higher-level "CompileExpr" procedure. This avoids an extra
 *	procedure call since such a procedure would only return the result
 *	of calling CompileCondExpr. Other recursive-descent procedures that
 *	need to parse expressions also call CompileCondExpr.
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the expression.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the expression at runtime.
 *
 *----------------------------------------------------------------------
 */

static int
CompileCondExpr(interp, infoPtr, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    ExprInfo *infoPtr;		/* Describes the compilation state for the
				 * expression being compiled. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    int maxDepth = 0;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    JumpFixup jumpAroundThenFixup, jumpAroundElseFixup;
				/* Used to update or replace one-byte jumps
				 * around the then and else expressions when
				 * their target PCs are determined. */
    int elseCodeOffset, currCodeOffset, jumpDist, result;
    
    HERE("condExpr", 1);
    result = CompileLorExpr(interp, infoPtr, flags, envPtr);
    if (result != TCL_OK) {
	goto done;
    }
    maxDepth = envPtr->maxStackDepth;
    
    if (infoPtr->token == QUESTY) {
	result = GetToken(interp, infoPtr, envPtr); /* skip over the '?' */
	if (result != TCL_OK) {
	    goto done;
	}

	/*
	 * Emit the jump around the "then" clause to the "else" condExpr if
	 * the test was false. We emit a one byte (relative) jump here, and
	 * replace it later with a four byte jump if the jump target is more
	 * than 127 bytes away.
	 */

	TclEmitForwardJump(envPtr, TCL_FALSE_JUMP, &jumpAroundThenFixup);

	/*
	 * Compile the "then" expression. Note that if a subexpression
	 * is only a primary, we need to try to convert it to numeric.
	 * This is done in order to support Tcl's policy of interpreting
	 * operands if at all possible as first integers, else
	 * floating-point numbers.
	 */

	infoPtr->hasOperators = 0;
	infoPtr->exprIsJustVarRef = 0;
	infoPtr->exprIsComparison = 0;
	result = CompileCondExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = TclMax(envPtr->maxStackDepth, maxDepth);
	if (infoPtr->token != COLON) {
	    Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
		    "syntax error in expression \"", infoPtr->originalExpr,
		    "\"", (char *) NULL);
	    result = TCL_ERROR;
	    goto done;
	}
	if (!infoPtr->hasOperators) {
	    TclEmitOpcode(INST_TRY_CVT_TO_NUMERIC, envPtr);
	}
	result = GetToken(interp, infoPtr, envPtr); /* skip over the ':' */
	if (result != TCL_OK) {
	    goto done;
	}

	/*
	 * Emit an unconditional jump around the "else" condExpr.
	 */

	TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP,
	        &jumpAroundElseFixup);

	/*
	 * Compile the "else" expression.
	 */

	infoPtr->hasOperators = 0;
	elseCodeOffset = TclCurrCodeOffset();
	result = CompileCondExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = TclMax(envPtr->maxStackDepth, maxDepth);
	if (!infoPtr->hasOperators) {
	    TclEmitOpcode(INST_TRY_CVT_TO_NUMERIC, envPtr);
	}

	/*
	 * Fix up the second jump: the unconditional jump around the "else"
	 * expression. If the distance is too great (> 127 bytes), replace
	 * it with a four byte instruction and move the instructions after
	 * the jump down.
	 */

	currCodeOffset = TclCurrCodeOffset();
	jumpDist = (currCodeOffset - jumpAroundElseFixup.codeOffset);
	if (TclFixupForwardJump(envPtr, &jumpAroundElseFixup, jumpDist, 127)) {
	    /*
	     * Update the else expression's starting code offset since it
	     * moved down 3 bytes too.
	     */
	    
	    elseCodeOffset += 3;
	}
	
	/*
	 * Now fix up the first branch: the jumpFalse after the test. If the
	 * distance is too great, replace it with a four byte instruction
	 * and update the code offsets for the commands in both the "then"
	 * and "else" expressions.
	 */

	jumpDist = (elseCodeOffset - jumpAroundThenFixup.codeOffset);
	TclFixupForwardJump(envPtr, &jumpAroundThenFixup, jumpDist, 127);

	infoPtr->hasOperators = 1;

	/*
	 * A comparison is not the top-level operator in this expression.
	 */

	infoPtr->exprIsComparison = 0;
    }

    done:
    envPtr->maxStackDepth = maxDepth;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * CompileLorExpr --
 *
 *	This procedure compiles a Tcl logical or expression:
 *	lorExpr ::= landExpr {'||' landExpr}
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the expression.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the expression at runtime.
 *
 *----------------------------------------------------------------------
 */

static int
CompileLorExpr(interp, infoPtr, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    ExprInfo *infoPtr;		/* Describes the compilation state for the
				 * expression being compiled. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    int maxDepth;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    JumpFixupArray jumpFixupArray;
				/* Used to fix up the forward "short
				 * circuit" jump after each or-ed
				 * subexpression to just after the last
				 * subexpression. */
    JumpFixup jumpTrueFixup, jumpFixup;
    				/* Used to emit the jumps in the code to
				 * convert the first operand to a 0 or 1. */
    int fixupIndex, jumpDist, currCodeOffset, objIndex, j, result;
    Tcl_Obj *objPtr;
    
    HERE("lorExpr", 2);
    result = CompileLandExpr(interp, infoPtr, flags, envPtr);
    if ((result != TCL_OK) || (infoPtr->token != OR)) {
	return result;		/* envPtr->maxStackDepth is already set */
    }

    infoPtr->hasOperators = 1;
    infoPtr->exprIsJustVarRef = 0;
    maxDepth = envPtr->maxStackDepth;
    TclInitJumpFixupArray(&jumpFixupArray);
    while (infoPtr->token == OR) {
	result = GetToken(interp, infoPtr, envPtr); /* skip over the '||' */
	if (result != TCL_OK) {
	    goto done;
	}

	if (jumpFixupArray.next == 0) {
	    /*
	     * Just the first "lor" operand is on the stack. The following
	     * is slightly ugly: we need to convert that first "lor" operand
	     * to a "0" or "1" to get the correct result if it is nonzero.
	     * Eventually we'll use a new instruction for this.
	     */

	    TclEmitForwardJump(envPtr, TCL_TRUE_JUMP, &jumpTrueFixup);
	    
	    objIndex = TclObjIndexForString("0", 1, /*allocStrRep*/ 0,
					    /*inHeap*/ 0, envPtr);
	    objPtr = envPtr->objArrayPtr[objIndex];

	    Tcl_InvalidateStringRep(objPtr);
	    objPtr->internalRep.longValue = 0;
	    objPtr->typePtr = &tclIntType;
	    
	    TclEmitPush(objIndex, envPtr);
	    TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &jumpFixup);

	    jumpDist = (TclCurrCodeOffset() - jumpTrueFixup.codeOffset);
	    if (TclFixupForwardJump(envPtr, &jumpTrueFixup, jumpDist, 127)) {
		panic("CompileLorExpr: bad jump distance %d\n", jumpDist);
	    }
	    objIndex = TclObjIndexForString("1", 1, /*allocStrRep*/ 0,
				            /*inHeap*/ 0, envPtr);
	    objPtr = envPtr->objArrayPtr[objIndex];

	    Tcl_InvalidateStringRep(objPtr);
	    objPtr->internalRep.longValue = 1;
	    objPtr->typePtr = &tclIntType;
	    
	    TclEmitPush(objIndex, envPtr);

	    jumpDist = (TclCurrCodeOffset() - jumpFixup.codeOffset);
	    if (TclFixupForwardJump(envPtr, &jumpFixup, jumpDist, 127)) {
		panic("CompileLorExpr: bad jump distance %d\n", jumpDist);
	    }
	}

	/*
	 * Duplicate the value on top of the stack to prevent the jump from
	 * consuming it.
	 */

	TclEmitOpcode(INST_DUP, envPtr);

	/*
	 * Emit the "short circuit" jump around the rest of the lorExp if
	 * the previous expression was true. We emit a one byte (relative)
	 * jump here, and replace it later with a four byte jump if the jump
	 * target is more than 127 bytes away.
	 */

	if (jumpFixupArray.next == jumpFixupArray.end) {
	    TclExpandJumpFixupArray(&jumpFixupArray);
	}
	fixupIndex = jumpFixupArray.next;
	jumpFixupArray.next++;
	TclEmitForwardJump(envPtr, TCL_TRUE_JUMP,
	        &(jumpFixupArray.fixup[fixupIndex]));
	
	/*
	 * Compile the subexpression.
	 */

	result = CompileLandExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = TclMax((envPtr->maxStackDepth + 1), maxDepth);

	/*
	 * Emit a "logical or" instruction. This does not try to "short-
	 * circuit" the evaluation of both operands of a Tcl "||" operator,
	 * but instead ensures that we either have a "1" or a "0" result.
	 */

	TclEmitOpcode(INST_LOR, envPtr);
    }

    /*
     * Now that we know the target of the forward jumps, update the jumps
     * with the correct distance. Also, if the distance is too great (> 127
     * bytes), replace the jump with a four byte instruction and move the
     * instructions after the jump down.
     */
    
    for (j = jumpFixupArray.next;  j > 0;  j--) {
	fixupIndex = (j - 1);	/* process closest jump first */
	currCodeOffset = TclCurrCodeOffset();
	jumpDist = (currCodeOffset - jumpFixupArray.fixup[fixupIndex].codeOffset);
	TclFixupForwardJump(envPtr, &(jumpFixupArray.fixup[fixupIndex]), jumpDist, 127);
    }

    /*
     * We get here only if one or more ||'s appear as top-level operators.
     */

    done:
    infoPtr->exprIsComparison = 0;
    TclFreeJumpFixupArray(&jumpFixupArray);
    envPtr->maxStackDepth = maxDepth;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * CompileLandExpr --
 *
 *	This procedure compiles a Tcl logical and expression:
 *	landExpr ::= bitOrExpr {'&&' bitOrExpr}
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the expression.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the expression at runtime.
 *
 *----------------------------------------------------------------------
 */

static int
CompileLandExpr(interp, infoPtr, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    ExprInfo *infoPtr;		/* Describes the compilation state for the
				 * expression being compiled. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    int maxDepth;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    JumpFixupArray jumpFixupArray;
				/* Used to fix up the forward "short
				 * circuit" jump after each and-ed
				 * subexpression to just after the last
				 * subexpression. */
    JumpFixup jumpTrueFixup, jumpFixup;
    				/* Used to emit the jumps in the code to
				 * convert the first operand to a 0 or 1. */
    int fixupIndex, jumpDist, currCodeOffset, objIndex, j, result;
    Tcl_Obj *objPtr;

    HERE("landExpr", 3);
    result = CompileBitOrExpr(interp, infoPtr, flags, envPtr);
    if ((result != TCL_OK) || (infoPtr->token != AND)) {
	return result;		/* envPtr->maxStackDepth is already set */
    }

    infoPtr->hasOperators = 1;
    infoPtr->exprIsJustVarRef = 0;
    maxDepth = envPtr->maxStackDepth;
    TclInitJumpFixupArray(&jumpFixupArray);
    while (infoPtr->token == AND) {
	result = GetToken(interp, infoPtr, envPtr); /* skip over the '&&' */
	if (result != TCL_OK) {
	    goto done;
	}

	if (jumpFixupArray.next == 0) {
	    /*
	     * Just the first "land" operand is on the stack. The following
	     * is slightly ugly: we need to convert the first "land" operand
	     * to a "0" or "1" to get the correct result if it is
	     * nonzero. Eventually we'll use a new instruction.
	     */

	    TclEmitForwardJump(envPtr, TCL_TRUE_JUMP, &jumpTrueFixup);
	     
	    objIndex = TclObjIndexForString("0", 1, /*allocStrRep*/ 0,
				            /*inHeap*/ 0, envPtr);
	    objPtr = envPtr->objArrayPtr[objIndex];

	    Tcl_InvalidateStringRep(objPtr);
	    objPtr->internalRep.longValue = 0;
	    objPtr->typePtr = &tclIntType;
	    
	    TclEmitPush(objIndex, envPtr);
	    TclEmitForwardJump(envPtr, TCL_UNCONDITIONAL_JUMP, &jumpFixup);

	    jumpDist = (TclCurrCodeOffset() - jumpTrueFixup.codeOffset);
	    if (TclFixupForwardJump(envPtr, &jumpTrueFixup, jumpDist, 127)) {
		panic("CompileLandExpr: bad jump distance %d\n", jumpDist);
	    }
	    objIndex = TclObjIndexForString("1", 1, /*allocStrRep*/ 0,
				            /*inHeap*/ 0, envPtr);
	    objPtr = envPtr->objArrayPtr[objIndex];

	    Tcl_InvalidateStringRep(objPtr);
	    objPtr->internalRep.longValue = 1;
	    objPtr->typePtr = &tclIntType;
	    
	    TclEmitPush(objIndex, envPtr);

	    jumpDist = (TclCurrCodeOffset() - jumpFixup.codeOffset);
	    if (TclFixupForwardJump(envPtr, &jumpFixup, jumpDist, 127)) {
		panic("CompileLandExpr: bad jump distance %d\n", jumpDist);
	    }
	}

	/*
	 * Duplicate the value on top of the stack to prevent the jump from
	 * consuming it.
	 */

	TclEmitOpcode(INST_DUP, envPtr);

	/*
	 * Emit the "short circuit" jump around the rest of the landExp if
	 * the previous expression was false. We emit a one byte (relative)
	 * jump here, and replace it later with a four byte jump if the jump
	 * target is more than 127 bytes away.
	 */

	if (jumpFixupArray.next == jumpFixupArray.end) {
	    TclExpandJumpFixupArray(&jumpFixupArray);
	}
	fixupIndex = jumpFixupArray.next;
	jumpFixupArray.next++;
	TclEmitForwardJump(envPtr, TCL_FALSE_JUMP,
		&(jumpFixupArray.fixup[fixupIndex]));
	
	/*
	 * Compile the subexpression.
	 */

	result = CompileBitOrExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = TclMax((envPtr->maxStackDepth + 1), maxDepth);

	/*
	 * Emit a "logical and" instruction. This does not try to "short-
	 * circuit" the evaluation of both operands of a Tcl "&&" operator,
	 * but instead ensures that we either have a "1" or a "0" result.
	 */

	TclEmitOpcode(INST_LAND, envPtr);
    }

    /*
     * Now that we know the target of the forward jumps, update the jumps
     * with the correct distance. Also, if the distance is too great (> 127
     * bytes), replace the jump with a four byte instruction and move the
     * instructions after the jump down.
     */
    
    for (j = jumpFixupArray.next;  j > 0;  j--) {
	fixupIndex = (j - 1);	/* process closest jump first */
	currCodeOffset = TclCurrCodeOffset();
	jumpDist = (currCodeOffset - jumpFixupArray.fixup[fixupIndex].codeOffset);
	TclFixupForwardJump(envPtr, &(jumpFixupArray.fixup[fixupIndex]),
	        jumpDist, 127);
    }

    /*
     * We get here only if one or more &&'s appear as top-level operators.
     */

    done:
    infoPtr->exprIsComparison = 0;
    TclFreeJumpFixupArray(&jumpFixupArray);
    envPtr->maxStackDepth = maxDepth;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * CompileBitOrExpr --
 *
 *	This procedure compiles a Tcl bitwise or expression:
 *	bitOrExpr ::= bitXorExpr {'|' bitXorExpr}
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the expression.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the expression at runtime.
 *
 *----------------------------------------------------------------------
 */

static int
CompileBitOrExpr(interp, infoPtr, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    ExprInfo *infoPtr;		/* Describes the compilation state for the
				 * expression being compiled. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    int maxDepth = 0;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    int result;

    HERE("bitOrExpr", 4);
    result = CompileBitXorExpr(interp, infoPtr, flags, envPtr);
    if (result != TCL_OK) {
	goto done;
    }
    maxDepth = envPtr->maxStackDepth;
    
    while (infoPtr->token == BIT_OR) {
	infoPtr->hasOperators = 1;
	infoPtr->exprIsJustVarRef = 0;
	result = GetToken(interp, infoPtr, envPtr); /* skip over the '|' */
	if (result != TCL_OK) {
	    goto done;
	}

	result = CompileBitXorExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = TclMax((envPtr->maxStackDepth + 1), maxDepth);
	
	TclEmitOpcode(INST_BITOR, envPtr);

	/*
	 * A comparison is not the top-level operator in this expression.
	 */

	infoPtr->exprIsComparison = 0;
    }

    done:
    envPtr->maxStackDepth = maxDepth;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * CompileBitXorExpr --
 *
 *	This procedure compiles a Tcl bitwise exclusive or expression:
 *	bitXorExpr ::= bitAndExpr {'^' bitAndExpr}
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the expression.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the expression at runtime.
 *
 *----------------------------------------------------------------------
 */

static int
CompileBitXorExpr(interp, infoPtr, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    ExprInfo *infoPtr;		/* Describes the compilation state for the
				 * expression being compiled. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    int maxDepth = 0;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    int result;

    HERE("bitXorExpr", 5);
    result = CompileBitAndExpr(interp, infoPtr, flags, envPtr);
    if (result != TCL_OK) {
	goto done;
    }
    maxDepth = envPtr->maxStackDepth;
    
    while (infoPtr->token == BIT_XOR) {
	infoPtr->hasOperators = 1;
	infoPtr->exprIsJustVarRef = 0;
	result = GetToken(interp, infoPtr, envPtr); /* skip over the '^' */
	if (result != TCL_OK) {
	    goto done;
	}

	result = CompileBitAndExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = TclMax((envPtr->maxStackDepth + 1), maxDepth);
	
	TclEmitOpcode(INST_BITXOR, envPtr);

	/*
	 * A comparison is not the top-level operator in this expression.
	 */

	infoPtr->exprIsComparison = 0;
    }

    done:
    envPtr->maxStackDepth = maxDepth;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * CompileBitAndExpr --
 *
 *	This procedure compiles a Tcl bitwise and expression:
 *	bitAndExpr ::= equalityExpr {'&' equalityExpr}
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the expression.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the expression at runtime.
 *
 *----------------------------------------------------------------------
 */

static int
CompileBitAndExpr(interp, infoPtr, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    ExprInfo *infoPtr;		/* Describes the compilation state for the
				 * expression being compiled. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    int maxDepth = 0;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    int result;

    HERE("bitAndExpr", 6);
    result = CompileEqualityExpr(interp, infoPtr, flags, envPtr);
    if (result != TCL_OK) {
	goto done;
    }
    maxDepth = envPtr->maxStackDepth;
    
    while (infoPtr->token == BIT_AND) {
	infoPtr->hasOperators = 1;
	infoPtr->exprIsJustVarRef = 0;
	result = GetToken(interp, infoPtr, envPtr); /* skip over the '&' */
	if (result != TCL_OK) {
	    goto done;
	}

	result = CompileEqualityExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = TclMax((envPtr->maxStackDepth + 1), maxDepth);
	
	TclEmitOpcode(INST_BITAND, envPtr);

	/*
	 * A comparison is not the top-level operator in this expression.
	 */

	infoPtr->exprIsComparison = 0;
    }

    done:
    envPtr->maxStackDepth = maxDepth;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * CompileEqualityExpr --
 *
 *	This procedure compiles a Tcl equality (inequality) expression:
 *	equalityExpr ::= relationalExpr {('==' | '!=') relationalExpr}
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the expression.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the expression at runtime.
 *
 *----------------------------------------------------------------------
 */

static int
CompileEqualityExpr(interp, infoPtr, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    ExprInfo *infoPtr;		/* Describes the compilation state for the
				 * expression being compiled. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    int maxDepth = 0;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    int op, result;

    HERE("equalityExpr", 7);
    result = CompileRelationalExpr(interp, infoPtr, flags, envPtr);
    if (result != TCL_OK) {
	goto done;
    }
    maxDepth = envPtr->maxStackDepth;

    op = infoPtr->token;
    while ((op == EQUAL) || (op == NEQ)) {
	infoPtr->hasOperators = 1;
	infoPtr->exprIsJustVarRef = 0;
	result = GetToken(interp, infoPtr, envPtr); /* skip over == or != */
	if (result != TCL_OK) {
	    goto done;
	}

	result = CompileRelationalExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = TclMax((envPtr->maxStackDepth + 1), maxDepth);

	if (op == EQUAL) {
	    TclEmitOpcode(INST_EQ, envPtr);
	} else {
	    TclEmitOpcode(INST_NEQ, envPtr);
	}
	
	op = infoPtr->token;

	/*
	 * A comparison _is_ the top-level operator in this expression.
	 */
	
	infoPtr->exprIsComparison = 1;
    }

    done:
    envPtr->maxStackDepth = maxDepth;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * CompileRelationalExpr --
 *
 *	This procedure compiles a Tcl relational expression:
 *	relationalExpr ::= shiftExpr {('<' | '>' | '<=' | '>=') shiftExpr}
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the expression.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the expression at runtime.
 *
 *----------------------------------------------------------------------
 */

static int
CompileRelationalExpr(interp, infoPtr, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    ExprInfo *infoPtr;		/* Describes the compilation state for the
				 * expression being compiled. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    int maxDepth = 0;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    int op, result;

    HERE("relationalExpr", 8);
    result = CompileShiftExpr(interp, infoPtr, flags, envPtr);
    if (result != TCL_OK) {
	goto done;
    }
    maxDepth = envPtr->maxStackDepth;

    op = infoPtr->token;
    while ((op == LESS) || (op == GREATER) || (op == LEQ) || (op == GEQ)) {
	infoPtr->hasOperators = 1;
	infoPtr->exprIsJustVarRef = 0;
	result = GetToken(interp, infoPtr, envPtr); /* skip over the op */
	if (result != TCL_OK) {
	    goto done;
	}

	result = CompileShiftExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = TclMax((envPtr->maxStackDepth + 1), maxDepth);

	switch (op) {
	case LESS:
	    TclEmitOpcode(INST_LT, envPtr);
	    break;
	case GREATER:
	    TclEmitOpcode(INST_GT, envPtr);
	    break;
	case LEQ:
	    TclEmitOpcode(INST_LE, envPtr);
	    break;
	case GEQ:
	    TclEmitOpcode(INST_GE, envPtr);
	    break;
	}

	op = infoPtr->token;

	/*
	 * A comparison _is_ the top-level operator in this expression.
	 */
	
	infoPtr->exprIsComparison = 1;
    }

    done:
    envPtr->maxStackDepth = maxDepth;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * CompileShiftExpr --
 *
 *	This procedure compiles a Tcl shift expression:
 *	shiftExpr ::= addExpr {('<<' | '>>') addExpr}
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the expression.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the expression at runtime.
 *
 *----------------------------------------------------------------------
 */

static int
CompileShiftExpr(interp, infoPtr, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    ExprInfo *infoPtr;		/* Describes the compilation state for the
				 * expression being compiled. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    int maxDepth = 0;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    int op, result;

    HERE("shiftExpr", 9);
    result = CompileAddExpr(interp, infoPtr, flags, envPtr);
    if (result != TCL_OK) {
	goto done;
    }
    maxDepth = envPtr->maxStackDepth;

    op = infoPtr->token;
    while ((op == LEFT_SHIFT) || (op == RIGHT_SHIFT)) {
	infoPtr->hasOperators = 1;
	infoPtr->exprIsJustVarRef = 0;
	result = GetToken(interp, infoPtr, envPtr); /* skip over << or >> */
	if (result != TCL_OK) {
	    goto done;
	}

	result = CompileAddExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = TclMax((envPtr->maxStackDepth + 1), maxDepth);

	if (op == LEFT_SHIFT) {
	    TclEmitOpcode(INST_LSHIFT, envPtr);
	} else {
	    TclEmitOpcode(INST_RSHIFT, envPtr);
	}

	op = infoPtr->token;

	/*
	 * A comparison is not the top-level operator in this expression.
	 */

	infoPtr->exprIsComparison = 0;
    }

    done:
    envPtr->maxStackDepth = maxDepth;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * CompileAddExpr --
 *
 *	This procedure compiles a Tcl addition expression:
 *	addExpr ::= multiplyExpr {('+' | '-') multiplyExpr}
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the expression.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the expression at runtime.
 *
 *----------------------------------------------------------------------
 */

static int
CompileAddExpr(interp, infoPtr, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    ExprInfo *infoPtr;		/* Describes the compilation state for the
				 * expression being compiled. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    int maxDepth = 0;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    int op, result;

    HERE("addExpr", 10);
    result = CompileMultiplyExpr(interp, infoPtr, flags, envPtr);
    if (result != TCL_OK) {
	goto done;
    }
    maxDepth = envPtr->maxStackDepth;

    op = infoPtr->token;
    while ((op == PLUS) || (op == MINUS)) {
	infoPtr->hasOperators = 1;
	infoPtr->exprIsJustVarRef = 0;
	result = GetToken(interp, infoPtr, envPtr); /* skip over + or - */
	if (result != TCL_OK) {
	    goto done;
	}

	result = CompileMultiplyExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = TclMax((envPtr->maxStackDepth + 1), maxDepth);

	if (op == PLUS) {
	    TclEmitOpcode(INST_ADD, envPtr);
	} else {
	    TclEmitOpcode(INST_SUB, envPtr);
	}

	op = infoPtr->token;

	/*
	 * A comparison is not the top-level operator in this expression.
	 */

	infoPtr->exprIsComparison = 0;
    }

    done:
    envPtr->maxStackDepth = maxDepth;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * CompileMultiplyExpr --
 *
 *	This procedure compiles a Tcl multiply expression:
 *	multiplyExpr ::= unaryExpr {('*' | '/' | '%') unaryExpr}
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the expression.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the expression at runtime.
 *
 *----------------------------------------------------------------------
 */

static int
CompileMultiplyExpr(interp, infoPtr, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    ExprInfo *infoPtr;		/* Describes the compilation state for the
				 * expression being compiled. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    int maxDepth = 0;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    int op, result;

    HERE("multiplyExpr", 11);
    result = CompileUnaryExpr(interp, infoPtr, flags, envPtr);
    if (result != TCL_OK) {
	goto done;
    }
    maxDepth = envPtr->maxStackDepth;

    op = infoPtr->token;
    while ((op == MULT) || (op == DIVIDE) || (op == MOD)) {
	infoPtr->hasOperators = 1;
	infoPtr->exprIsJustVarRef = 0;
	result = GetToken(interp, infoPtr, envPtr); /* skip over * or / */
	if (result != TCL_OK) {
	    goto done;
	}

	result = CompileUnaryExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = TclMax((envPtr->maxStackDepth + 1), maxDepth);

	if (op == MULT) {
	    TclEmitOpcode(INST_MULT, envPtr);
	} else if (op == DIVIDE) {
	    TclEmitOpcode(INST_DIV, envPtr);
	} else {
	    TclEmitOpcode(INST_MOD, envPtr);
	}

	op = infoPtr->token;

	/*
	 * A comparison is not the top-level operator in this expression.
	 */

	infoPtr->exprIsComparison = 0;
    }

    done:
    envPtr->maxStackDepth = maxDepth;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * CompileUnaryExpr --
 *
 *	This procedure compiles a Tcl unary expression:
 *	unaryExpr ::= ('+' | '-' | '~' | '!') unaryExpr | primaryExpr
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the expression.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the expression at runtime.
 *
 *----------------------------------------------------------------------
 */

static int
CompileUnaryExpr(interp, infoPtr, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    ExprInfo *infoPtr;		/* Describes the compilation state for the
				 * expression being compiled. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    int maxDepth = 0;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    int op, result;

    HERE("unaryExpr", 12);
    op = infoPtr->token;
    if ((op == PLUS) || (op == MINUS) || (op == BIT_NOT) || (op == NOT)) {
	infoPtr->hasOperators = 1;
	infoPtr->exprIsJustVarRef = 0;
	result = GetToken(interp, infoPtr, envPtr); /* skip over the op */
	if (result != TCL_OK) {
	    goto done;
	}

	result = CompileUnaryExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = envPtr->maxStackDepth;

	switch (op) {
	case PLUS:
	    TclEmitOpcode(INST_UPLUS, envPtr);
	    break;
	case MINUS:
	    TclEmitOpcode(INST_UMINUS, envPtr);
	    break;
	case BIT_NOT:
	    TclEmitOpcode(INST_BITNOT, envPtr);
	    break;
	case NOT:
	    TclEmitOpcode(INST_LNOT, envPtr);
	    break;
	}

	/*
	 * A comparison is not the top-level operator in this expression.
	 */

	infoPtr->exprIsComparison = 0;
    } else {			/* must be a primaryExpr */
	result = CompilePrimaryExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = envPtr->maxStackDepth;
    }

    done:
    envPtr->maxStackDepth = maxDepth;
    return result;
}

/*
 *----------------------------------------------------------------------
 *
 * CompilePrimaryExpr --
 *
 *	This procedure compiles a Tcl primary expression:
 *	primaryExpr ::= literal | varReference | quotedString |
 *			'[' command ']' | mathFuncCall | '(' condExpr ')'
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the expression.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the expression at runtime.
 *
 *----------------------------------------------------------------------
 */

static int
CompilePrimaryExpr(interp, infoPtr, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    ExprInfo *infoPtr;		/* Describes the compilation state for the
				 * expression being compiled. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    int maxDepth = 0;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    int theToken;
    char *dollarPtr, *quotePtr, *cmdPtr, *termPtr;
    int result = TCL_OK;

    /*
     * We emit tryCvtToNumeric instructions after most of these primary
     * expressions in order to support Tcl's policy of interpreting operands
     * as first integers if possible, otherwise floating-point numbers if
     * possible.
     */

    HERE("primaryExpr", 13);
    theToken = infoPtr->token;

    if (theToken != DOLLAR) {
	infoPtr->exprIsJustVarRef = 0;
    }
    switch (theToken) {
    case LITERAL:		/* int, double, or string in braces */
	TclEmitPush(infoPtr->objIndex, envPtr);
	maxDepth = 1;
	break;
	
    case DOLLAR:		/* $var variable reference */
	dollarPtr = (infoPtr->next - 1);
	envPtr->pushSimpleWords = 1;
	result = TclCompileDollarVar(interp, dollarPtr,
		infoPtr->lastChar, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = envPtr->maxStackDepth;
	infoPtr->next = (dollarPtr + envPtr->termOffset);
	break;
	
    case QUOTE:			/* quotedString */
	quotePtr = infoPtr->next;
	envPtr->pushSimpleWords = 1;
	result = TclCompileQuotes(interp, quotePtr,
		infoPtr->lastChar, '"', flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = envPtr->maxStackDepth;
	infoPtr->next = (quotePtr + envPtr->termOffset);
	break;
	
    case OPEN_BRACKET:		/* '[' command ']' */
	cmdPtr = infoPtr->next;
	envPtr->pushSimpleWords = 1;
	result = TclCompileString(interp, cmdPtr,
		infoPtr->lastChar, (flags | TCL_BRACKET_TERM), envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	termPtr = (cmdPtr + envPtr->termOffset);
	if (*termPtr == ']') {
	    infoPtr->next = (termPtr + 1); /* advance over the ']'. */
	} else if (termPtr == infoPtr->lastChar) {
	    /*
	     * Missing ] at end of nested command.
	     */
	    
	    Tcl_ResetResult(interp);
	    Tcl_AppendToObj(Tcl_GetObjResult(interp),
	            "missing close-bracket", -1);
	    result = TCL_ERROR;
	    goto done;
	} else {
	    panic("CompilePrimaryExpr: unexpected termination char '%c' for nested command\n", *termPtr);
	}
	maxDepth = envPtr->maxStackDepth;
	break;
	
    case FUNC_NAME:
	result = CompileMathFuncCall(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = envPtr->maxStackDepth;
	break;
	
    case OPEN_PAREN:
	result = GetToken(interp, infoPtr, envPtr); /* skip over the '(' */
	if (result != TCL_OK) {
	    goto done;
	}
	infoPtr->exprIsComparison = 0;
	result = CompileCondExpr(interp, infoPtr, flags, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
	maxDepth = envPtr->maxStackDepth;
	if (infoPtr->token != CLOSE_PAREN) {
	    goto syntaxError;
	}
	break;
	
    default:
	goto syntaxError;
    }

    if (theToken != FUNC_NAME) {
	/*
	 * Advance to the next token before returning.
	 */
	
	result = GetToken(interp, infoPtr, envPtr);
	if (result != TCL_OK) {
	    goto done;
	}
    }

    done:
    envPtr->maxStackDepth = maxDepth;
    return result;

    syntaxError:
    Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
	    "syntax error in expression \"", infoPtr->originalExpr,
	    "\"", (char *) NULL);
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * CompileMathFuncCall --
 *
 *	This procedure compiles a call on a math function in an expression:
 *	mathFuncCall ::= funcName '(' [condExpr {',' condExpr}] ')'
 *
 * Results:
 *	The return value is TCL_OK on a successful compilation and TCL_ERROR
 *	on failure. If TCL_ERROR is returned, then the interpreter's result
 *	contains an error message.
 *
 *	envPtr->maxStackDepth is updated with the maximum number of stack
 *	elements needed to execute the function.
 *
 * Side effects:
 *	Adds instructions to envPtr to evaluate the math function at
 *	runtime.
 *
 *----------------------------------------------------------------------
 */

static int
CompileMathFuncCall(interp, infoPtr, flags, envPtr)
    Tcl_Interp *interp;		/* Used for error reporting. */
    ExprInfo *infoPtr;		/* Describes the compilation state for the
				 * expression being compiled. */
    int flags;			/* Flags to control compilation (same as
				 * passed to Tcl_Eval). */
    CompileEnv *envPtr;		/* Holds resulting instructions. */
{
    Interp *iPtr = (Interp *) interp;
    int maxDepth = 0;		/* Maximum number of stack elements needed
				 * to execute the expression. */
    MathFunc *mathFuncPtr;	/* Info about math function. */
    int objIndex;		/* The object array index for an object
				 * holding the function name if it is not
				 * builtin. */
    Tcl_HashEntry *hPtr;
    char *p, *funcName;
    char savedChar;
    int result, i;

    /*
     * infoPtr->funcName points to the first character of the math
     * function's name. Look for the end of its name and look up the
     * MathFunc record for the function.
     */

    funcName = p = infoPtr->funcName;
    while (isalnum(UCHAR(*p)) || (*p == '_')) {
	p++;
    }
    infoPtr->next = p;
    
    result = GetToken(interp, infoPtr, envPtr); /* skip over func name */
    if (result != TCL_OK) {
	goto done;
    }
    if (infoPtr->token != OPEN_PAREN) {
	goto syntaxError;
    }
    result = GetToken(interp, infoPtr, envPtr); /* skip over '(' */
    if (result != TCL_OK) {
	goto done;
    }
    
    savedChar = *p;
    *p = 0;
    hPtr = Tcl_FindHashEntry(&iPtr->mathFuncTable, funcName);
    if (hPtr == NULL) {
	Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
		"unknown math function \"", funcName, "\"", (char *) NULL);
	result = TCL_ERROR;
	*p = savedChar;
	goto done;
    }
    mathFuncPtr = (MathFunc *) Tcl_GetHashValue(hPtr);

    /*
     * If not a builtin function, push an object with the function's name.
     */

    if (mathFuncPtr->builtinFuncIndex < 0) {   /* not builtin */
	objIndex = TclObjIndexForString(funcName, -1, /*allocStrRep*/ 1,
				        /*inHeap*/ 0, envPtr);
	TclEmitPush(objIndex, envPtr);
	maxDepth = 1;
    }

    /*
     * Restore the saved character after the function name.
     */

    *p = savedChar;

    /*
     * Compile the arguments for the function, if there are any.
     */

    if (mathFuncPtr->numArgs > 0) {
	for (i = 0;  ;  i++) {
	    infoPtr->exprIsComparison = 0;
	    result = CompileCondExpr(interp, infoPtr, flags, envPtr);
	    if (result != TCL_OK) {
		goto done;
	    }
    
	    /*
	     * Check for a ',' between arguments or a ')' ending the
	     * argument list.
	     */
    
	    if (i == (mathFuncPtr->numArgs-1)) {
		if (infoPtr->token == CLOSE_PAREN) {
		    break;	/* exit the argument parsing loop */
		} else if (infoPtr->token == COMMA) {
		    Tcl_ResetResult(interp);
		    Tcl_AppendToObj(Tcl_GetObjResult(interp),
		            "too many arguments for math function", -1);
		    result = TCL_ERROR;
		    goto done;
		} else {
		    goto syntaxError;
		}
	    }
	    if (infoPtr->token != COMMA) {
		if (infoPtr->token == CLOSE_PAREN) {
		    Tcl_ResetResult(interp);
		    Tcl_AppendToObj(Tcl_GetObjResult(interp),
		            "too few arguments for math function", -1);
		    result = TCL_ERROR;
		    goto done;
		} else {
		    goto syntaxError;
		}
	    }
	    result = GetToken(interp, infoPtr, envPtr); /* skip over , */
	    if (result != TCL_OK) {
		goto done;
	    }
	    maxDepth++;
	}
    }

    if (infoPtr->token != CLOSE_PAREN) {
	goto syntaxError;
    }
    result = GetToken(interp, infoPtr, envPtr); /* skip over ')' */
    if (result != TCL_OK) {
	goto done;
    }
    
    /*
     * Compile the call on the math function. Note that the "objc" argument
     * count for non-builtin functions is incremented by 1 to include the
     * the function name itself.
     */

    if (mathFuncPtr->builtinFuncIndex >= 0) { /* a builtin function */
	TclEmitInstUInt1(INST_CALL_BUILTIN_FUNC1,
			mathFuncPtr->builtinFuncIndex, envPtr);
    } else {
	TclEmitInstUInt1(INST_CALL_FUNC1, (mathFuncPtr->numArgs+1), envPtr);
    }

    /*
     * A comparison is not the top-level operator in this expression.
     */

    done:
    infoPtr->exprIsComparison = 0;
    envPtr->maxStackDepth = maxDepth;
    return result;

    syntaxError:
	Tcl_AppendStringsToObj(Tcl_GetObjResult(interp),
		"syntax error in expression \"", infoPtr->originalExpr,
		"\"", (char *) NULL);
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * GetToken --
 *
 *	Lexical scanner used to compile expressions: parses a single 
 *	operator or other syntactic element from an expression string.
 *
 * Results:
 *	TCL_OK is returned unless an error occurred. In that case a standard
 *	Tcl error is returned, using the interpreter's result to hold an
 *	error message. TCL_ERROR is returned if an integer overflow, or a
 *	floating-point overflow or underflow occurred while reading in a
 *	number. If the lexical analysis is successful, infoPtr->token refers
 *	to the next symbol in the expression string, and infoPtr->next is
 *	advanced past the token. Also, if the token is a integer, double, or
 *	string literal, then infoPtr->objIndex the index of an object
 *	holding the value in the code's object table; otherwise is NULL.
 *
 * Side effects:
 *	Object are added to envPtr to hold the values of scanned literal
 *	integers, doubles, or strings.
 *
 *----------------------------------------------------------------------
 */

static int
GetToken(interp, infoPtr, envPtr)
    Tcl_Interp *interp;			/* Interpreter to use for error
					 * reporting. */
    register ExprInfo *infoPtr;         /* Describes the state of the
					 * compiling the expression,
					 * including the resulting token. */
    CompileEnv *envPtr;			/* Holds objects that store literal
					 * values that are scanned. */
{
    register char *src;		/* Points to current source char. */
    register char c;		/* The current char. */
    register int type;		/* Current char's CHAR_TYPE type. */
    char *termPtr;		/* Points to char terminating a literal. */
    char savedChar;		/* Holds the character termporarily replaced
				 * by a null character during processing of
				 * literal tokens. */
    int objIndex;		/* The object array index for an object
				 * holding a scanned literal. */
    long longValue;		/* Value of a scanned integer literal. */
    double doubleValue;		/* Value of a scanned double literal. */
    Tcl_Obj *objPtr;

    /*
     * First initialize the scanner's "result" fields to default values.
     */
    
    infoPtr->token = UNKNOWN;
    infoPtr->objIndex = -1;
    infoPtr->funcName = NULL;

    /*
     * Scan over leading white space at the start of a token. Note that a
     * backslash-newline is treated as a space.
     */

    src = infoPtr->next;
    c = *src;
    type = CHAR_TYPE(src, infoPtr->lastChar);
    while ((type & (TCL_SPACE | TCL_BACKSLASH)) || (c == '\n')) {
	if (type == TCL_BACKSLASH) {
	    if (src[1] == '\n') {
		src += 2;
	    } else {
		break;	/* no longer white space */
	    }
	} else {
	    src++;
	}
	c = *src;
	type = CHAR_TYPE(src, infoPtr->lastChar);
    }
    if (src == infoPtr->lastChar) {
	infoPtr->token = END;
	infoPtr->next = src;
	return TCL_OK;
    }

    /*
     * Try to parse the token first as an integer or floating-point
     * number. Don't check for a number if the first character is "+" or
     * "-". If we did, we might treat a binary operator as unary by mistake,
     * which would eventually cause a syntax error.
     */

    if ((*src != '+') && (*src != '-')) {
	int startsWithDigit = isdigit(UCHAR(*src));
	
	if (startsWithDigit && TclLooksLikeInt(src)) {
	    errno = 0;
	    longValue = strtoul(src, &termPtr, 0);
	    if (errno == ERANGE) {
		char *s = "integer value too large to represent";
		
		Tcl_ResetResult(interp);
		Tcl_AppendToObj(Tcl_GetObjResult(interp), s, -1);
		Tcl_SetErrorCode(interp, "ARITH", "IOVERFLOW", s,
			(char *) NULL);
		return TCL_ERROR;
	    }

	    /*
	     * Find/create an object in envPtr's object array that contains
	     * the integer.
	     */
	    
	    savedChar = *termPtr;
	    *termPtr = '\0';
	    objIndex = TclObjIndexForString(src, termPtr - src,
		    /*allocStrRep*/ 0, /*inHeap*/ 0, envPtr);
	    *termPtr = savedChar;  /* restore the saved char */

	    objPtr = envPtr->objArrayPtr[objIndex];
	    Tcl_InvalidateStringRep(objPtr);
	    objPtr->internalRep.longValue = longValue;
	    objPtr->typePtr = &tclIntType;
	    
	    infoPtr->token = LITERAL;
	    infoPtr->objIndex = objIndex;
	    infoPtr->next = termPtr;
	    return TCL_OK;
	} else if (startsWithDigit || (*src == '.')
	        || (*src == 'n') || (*src == 'N')) {
	    errno = 0;
	    doubleValue = strtod(src, &termPtr);
	    if (termPtr != src) {
		if (errno != 0) {
		    TclExprFloatError(interp, doubleValue);
		    return TCL_ERROR;
		}

		/*
		 * Find/create an object in the object array containing the
		 * double.
		 */
		
		savedChar = *termPtr;
		*termPtr = '\0';
		objIndex = TclObjIndexForString(src, termPtr - src,
			/*allocStrRep*/ 1, /*inHeap*/ 0, envPtr);
		*termPtr = savedChar;  /* restore the saved char */
		
		objPtr = envPtr->objArrayPtr[objIndex];
		objPtr->internalRep.doubleValue = doubleValue;
		objPtr->typePtr = &tclDoubleType;
		
		infoPtr->token = LITERAL;
		infoPtr->objIndex = objIndex;
		infoPtr->next = termPtr;
		return TCL_OK;
	    }
	}
    }

    /*
     * Not an integer or double literal. Check next for a string literal
     * in braces.
     */

    if (*src == '{') {
	int level = 0;		 /* The {} nesting level. */
	int hasBackslashNL = 0;  /* Nonzero if '\newline' was found. */
	char *string = src+1;	 /* Points just after the starting '{'. */
	char *last;		 /* Points just before terminating '}'. */
	int numChars;		 /* Number of chars in braced string. */
	char savedChar;		 /* Holds the character from string
				  * termporarily replaced by a null char
				  * during braced string processing. */
	int numRead;

	/*
	 * Check first for any backslash-newlines, since we must treat
	 * backslash-newlines specially (they must be replaced by spaces).
	 */
	
	while (1) {
	    if (src == infoPtr->lastChar) {
		Tcl_ResetResult(interp);
		Tcl_AppendToObj(Tcl_GetObjResult(interp),
		        "missing close-brace", -1);
		return TCL_ERROR;
	    } else if (CHAR_TYPE(src, infoPtr->lastChar) == TCL_NORMAL) {
		src++;
		continue;
	    }
	    c = *src++;
	    if (c == '{') {
		level++;
	    } else if (c == '}') {
		--level;
		if (level == 0) {
		    last = (src - 2); /* i.e. just before terminating } */
		    break;
		}
	    } else if (c == '\\') {
		if (*src == '\n') {
		    hasBackslashNL = 1;
		}
		(void) Tcl_Backslash(src-1, &numRead);
		src += numRead - 1;
	    }
	}

	/*
	 * Create a string object for the braced string. This starts at
	 * "string" and ends just after "last" (which points to the final
	 * character before the terminating '}'). If backslash-newlines were
	 * found, we copy characters one at a time into a heap-allocated
	 * buffer and do backslash-newline substitutions.
	 */
	
	numChars = (last - string + 1);
	savedChar = string[numChars];
	string[numChars] = '\0';
	if (hasBackslashNL && (numChars > 0)) {
	    char *buffer = ckalloc((unsigned) numChars + 1);
	    register char *dst = buffer;
	    register char *p = string;
	    while (p <= last) {
		c = *dst++ = *p++;
		if (c == '\\') {
		    if (*p == '\n') {
			dst[-1] = Tcl_Backslash(p-1, &numRead);
			p += numRead - 1;
		    } else {
			(void) Tcl_Backslash(p-1, &numRead);
			while (numRead > 1) {
			    *dst++ = *p++;
			    numRead--;
			}
		    }
		}
	    }
	    *dst = '\0';
	    objIndex = TclObjIndexForString(buffer, dst - buffer,
		    /*allocStrRep*/ 1, /*inHeap*/ 1, envPtr);
	} else {
	    objIndex = TclObjIndexForString(string, numChars,
		    /*allocStrRep*/ 1, /*inHeap*/ 0, envPtr);
	}
	string[numChars] = savedChar;   /* restore the saved char */

	infoPtr->token = LITERAL;
	infoPtr->objIndex = objIndex;
	infoPtr->next = src;
	return TCL_OK;
    }

    /*
     * Not an literal value.
     */

    infoPtr->next = src+1;   /* assume a 1 char token and advance over it */
    switch (*src) {
	case '[':
	    infoPtr->token = OPEN_BRACKET;
	    return TCL_OK;

	case ']':
	    infoPtr->token = CLOSE_BRACKET;
	    return TCL_OK;

	case '(':
	    infoPtr->token = OPEN_PAREN;
	    return TCL_OK;

	case ')':
	    infoPtr->token = CLOSE_PAREN;
	    return TCL_OK;

	case '$':
	    infoPtr->token = DOLLAR;
	    return TCL_OK;

	case '"':
	    infoPtr->token = QUOTE;
	    return TCL_OK;

	case ',':
	    infoPtr->token = COMMA;
	    return TCL_OK;

	case '*':
	    infoPtr->token = MULT;
	    return TCL_OK;

	case '/':
	    infoPtr->token = DIVIDE;
	    return TCL_OK;

	case '%':
	    infoPtr->token = MOD;
	    return TCL_OK;

	case '+':
	    infoPtr->token = PLUS;
	    return TCL_OK;

	case '-':
	    infoPtr->token = MINUS;
	    return TCL_OK;

	case '?':
	    infoPtr->token = QUESTY;
	    return TCL_OK;

	case ':':
	    infoPtr->token = COLON;
	    return TCL_OK;

	case '<':
	    switch (src[1]) {
		case '<':
		    infoPtr->next = src+2;
		    infoPtr->token = LEFT_SHIFT;
		    break;
		case '=':
		    infoPtr->next = src+2;
		    infoPtr->token = LEQ;
		    break;
		default:
		    infoPtr->token = LESS;
		    break;
	    }
	    return TCL_OK;

	case '>':
	    switch (src[1]) {
		case '>':
		    infoPtr->next = src+2;
		    infoPtr->token = RIGHT_SHIFT;
		    break;
		case '=':
		    infoPtr->next = src+2;
		    infoPtr->token = GEQ;
		    break;
		default:
		    infoPtr->token = GREATER;
		    break;
	    }
	    return TCL_OK;

	case '=':
	    if (src[1] == '=') {
		infoPtr->next = src+2;
		infoPtr->token = EQUAL;
	    } else {
		infoPtr->token = UNKNOWN;
	    }
	    return TCL_OK;

	case '!':
	    if (src[1] == '=') {
		infoPtr->next = src+2;
		infoPtr->token = NEQ;
	    } else {
		infoPtr->token = NOT;
	    }
	    return TCL_OK;

	case '&':
	    if (src[1] == '&') {
		infoPtr->next = src+2;
		infoPtr->token = AND;
	    } else {
		infoPtr->token = BIT_AND;
	    }
	    return TCL_OK;

	case '^':
	    infoPtr->token = BIT_XOR;
	    return TCL_OK;

	case '|':
	    if (src[1] == '|') {
		infoPtr->next = src+2;
		infoPtr->token = OR;
	    } else {
		infoPtr->token = BIT_OR;
	    }
	    return TCL_OK;

	case '~':
	    infoPtr->token = BIT_NOT;
	    return TCL_OK;

	default:
	    if (isalpha(UCHAR(*src))) {
		infoPtr->token = FUNC_NAME;
		infoPtr->funcName = src;
		while (isalnum(UCHAR(*src)) || (*src == '_')) {
		    src++;
		}
		infoPtr->next = src;
		return TCL_OK;
	    }
	    infoPtr->next = src+1;
	    infoPtr->token = UNKNOWN;
	    return TCL_OK;
    }
}

/*
 *----------------------------------------------------------------------
 *
 * Tcl_CreateMathFunc --
 *
 *	Creates a new math function for expressions in a given
 *	interpreter.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	The function defined by "name" is created or redefined. If the
 *	function already exists then its definition is replaced; this
 *	includes the builtin functions. Redefining a builtin function forces
 *	all existing code to be invalidated since that code may be compiled
 *	using an instruction specific to the replaced function. In addition,
 *	redefioning a non-builtin function will force existing code to be
 *	invalidated if the number of arguments has changed.
 *
 *----------------------------------------------------------------------
 */

void
Tcl_CreateMathFunc(interp, name, numArgs, argTypes, proc, clientData)
    Tcl_Interp *interp;			/* Interpreter in which function is
					 * to be available. */
    char *name;				/* Name of function (e.g. "sin"). */
    int numArgs;			/* Nnumber of arguments required by
					 * function. */
    Tcl_ValueType *argTypes;		/* Array of types acceptable for
					 * each argument. */
    Tcl_MathProc *proc;			/* Procedure that implements the
					 * math function. */
    ClientData clientData;		/* Additional value to pass to the
					 * function. */
{
    Interp *iPtr = (Interp *) interp;
    Tcl_HashEntry *hPtr;
    MathFunc *mathFuncPtr;
    int new, i;

    hPtr = Tcl_CreateHashEntry(&iPtr->mathFuncTable, name, &new);
    if (new) {
	Tcl_SetHashValue(hPtr, ckalloc(sizeof(MathFunc)));
    }
    mathFuncPtr = (MathFunc *) Tcl_GetHashValue(hPtr);

    if (!new) {	
	if (mathFuncPtr->builtinFuncIndex >= 0) {
	    /*
	     * We are redefining a builtin math function. Invalidate the
             * interpreter's existing code by incrementing its
             * compileEpoch member. This field is checked in Tcl_EvalObj
             * and ObjInterpProc, and code whose compilation epoch doesn't
             * match is recompiled. Newly compiled code will no longer
             * treat the function as builtin.
	     */

	    iPtr->compileEpoch++;
	} else {
	    /*
	     * A non-builtin function is being redefined. We must invalidate
             * existing code if the number of arguments has changed. This
	     * is because existing code was compiled assuming that number.
	     */

	    if (numArgs != mathFuncPtr->numArgs) {
		iPtr->compileEpoch++;
	    }
	}
    }
    
    mathFuncPtr->builtinFuncIndex = -1;	/* can't be a builtin function */
    if (numArgs > MAX_MATH_ARGS) {
	numArgs = MAX_MATH_ARGS;
    }
    mathFuncPtr->numArgs = numArgs;
    for (i = 0;  i < numArgs;  i++) {
	mathFuncPtr->argTypes[i] = argTypes[i];
    }
    mathFuncPtr->proc = proc;
    mathFuncPtr->clientData = clientData;
}