summaryrefslogtreecommitdiff
path: root/ipl/packs/itweak/dbg_run.icn
blob: b8a766ba9337430ad5923a8607d6b8ed12cfff46 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
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
############################################################################
#
#	File:     dbg_run.icn
#
#	Subject:  Icon interactive debugging.
#		  Contains an interactive debugging run-time system.
#
#	Author:   Hakan Soderstrom
#
#	Revision: $Revision: 2.21 $
#
###########################################################################
#
# Copyright (c) 1994 Hakan Soderstrom and
# Soderstrom Programvaruverkstad AB, Sweden
# 
# Permission to use, copy, modify, distribute, and sell this software
# and its documentation for any purpose is hereby granted without fee,
# provided that the above copyright notice and this permission notice
# appear in all copies of the software and related documentation.
# 
# THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
# EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
# WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
#
# IN NO EVENT SHALL HAKAN SODERSTROM OR SODERSTROM PROGRAMVARUVERKSTAD
# AB BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL
# DAMAGES OF ANY KIND, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
# OF USE, DATA OR PROFITS, WHETHER OR NOT ADVISED OF THE POSSIBILITY
# OF DAMAGE, AND ON ANY THEORY OF LIABILITY, ARISING OUT OF OR IN
# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
###########################################################################
#
# General note: all names are prefixed in an elaborate way in order to
# avoid name collisions with the debugged program.
# The default prefix for all globally visible names is '__dbg_'.
#
# This is the reason why lists are frequently used instead of records
# (whose field names clutter the global name space).
#
###########################################################################

#
#-------- Constants --------
#

# Versions (this program and 'itweak').
$define PROGRAM_VERSION	"$Revision: 2.21 $"

# Components of a breakpoint descriptor (list).
# Breakpoint id (integer).
$define BRKP_ID		1
# Source file (string).
$define BRKP_FILE	2
# File index.
$define BRKP_FIDX	3
# First line number.
$define BRKP_LINE1	4
# Second line number.
$define BRKP_LINE2	5
# Ignore counter (integer).
$define BRKP_IGNORE	6
# Condition for breaking.
$define BRKP_COND	7
# Commands to perform on break.
$define BRKP_DO		8

# Constants for 'the current breakpoint' and 'the last breakpoint'.
$define BRKP_CURRENT	-1
$define BRKP_LAST	-2

# Keywords for the 'clear' command.
# Definitions must match list in compilation procedure.
$define CLEAR_BREAKPOINT	1
$define CLEAR_COND		2
$define CLEAR_DO		3
$define CLEAR_ECHO		4
$define CLEAR_MACRO		5

# Keywords for the 'info' command.
# Definitions must match list in compilation procedure.
$define INFO_BREAKPOINT		1
$define INFO_ECHO		2
$define INFO_FILES		3
$define INFO_GLOBALS		4
$define INFO_LOCALS		5
$define INFO_MACROS		6
$define INFO_TRACE		7
$define INFO_VERSION		8

# Keywords for the 'set' command.
# Definitions must match list in compilation procedure.
$define SET_ECHO		1
$define SET_PRELUDE		2
$define SET_POSTLUDE		3

# Components of a command definition (list).
# Used for built-in commands as well as user-defined macros.
# Unabbreviated command/macro name (string).
$define CMD_NAME	1
# Command code (an integer corresponding to the name).
$define CMD_CODE	2
# Help text (list of string).
$define CMD_HELP	3
# Compilation procedure; null if macro.
$define CMD_COMPILE	4
# Macro definition (list of command instances, list of list).
# Null if built-in command.
$define CMD_MACRO	5
# Executing procedure, if built-in. Null otherwise.
$define CMD_EXEC	6

# Command codes.
$define BREAK_CMD	1
$define CLEAR_CMD	2
$define COMMENT_CMD	3
$define CONDITION_CMD	4
$define DO_CMD		5
$define END_CMD		6
$define EPRINT_CMD	7
$define FAIL_CMD	8
$define FPRINT_CMD	9
$define FRAME_CMD	10
$define GOON_CMD	11
$define HELP_CMD	12
$define INFO_CMD	13
$define IGNORE_CMD	14
$define MACRO_CMD	15
$define NEXT_CMD	16
$define PRINT_CMD	17
$define SET_CMD		18
$define SOURCE_CMD	19
$define STOP_CMD	20
$define TRACE_CMD	21
$define WHERE_CMD	22
$define USERDEF_CMD	23

# Environment variable for defining the input file (must be a string value).
$define DBG_INPUT_ENV	"DBG_INPUT"

# Environment variable for defining the primary output file
# (must be a string value).
$define DBG_OUTPUT_ENV	"DBG_OUTPUT"

# Prefix for debugging run-time global names.
$define DBG_PREFIX	"__dbg_"

# Maximum source nesting levels.
$define MAX_SOURCE_NESTING	12

# File index is obtained by shifting a small integer left a number of
# positions.
$define FIDX_SHIFT	10

# Prompt string to use in initialization mode.
$define INIT_PROMPT	"debug init $ "

# Execution return status.
# Normal return.
$define OK_STATUS	0
# Break the command loop, resume execution.
$define RESUME_STATUS	1
# Break the command loop, terminate the session.
$define STOP_STATUS	2
# Break the command loop, make the current procedure fail.
$define FAIL_STATUS	3

# Index into '__dbg_g_where'.
$define WHERE_FILE	1
$define WHERE_LINE	2
$define WHERE_PROC	3
$define WHERE_BRKP	4
$define WHERE_PRELUDE	5
$define WHERE_POSTLUDE	6

#
#-------- Record types --------
#

#
#-------- Globals --------
#

global __dbg_default_prelude, __dbg_default_postlude
# The source text for the default pre/postlude (single command assumed).

global __dbg_g_automacro
# The 'prelude' and 'postlude' macros.
# List of two components:
# (1) prelude commands,
# (2) postlude commands.
# Both are lists of compiled commands, not complete macros.

global __dbg_g_brkpcnt
# Counter incremented each break.
# Used to identify the file written by 'display' which is used by several
# commands.
# In this way we can check if we have to write the file anew.

global __dbg_g_brkpdef
# Lookup table for breakpoints.
# Entry key is a breakpoint id (integer).
# Entry value is a breakpoint descriptor (list).

global __dbg_g_brlookup
# Lookup table for breakpoints.
# Entry key is a file index or'ed with a line number (integer).
# Entry value is a breakpoint descriptor (list).

global __dbg_g_brkpid
# Id of the latest breakpoint created (integer).

global __dbg_g_cmd
# Table of command and macro definitions.
# Entry key is an unabbreviated command/macro name.
# Entry value is a command descriptor (list).

global __dbg_g_display
# Name of temporary file used by '__dbg_x_opendisplay' and others.

global __dbg_g_fileidx
# Table mapping source file names on (large) integers.
# Entry key is a source file name (string).
# Entry value is a file index (integer).

global __dbg_g_in
# The file through which debugging input is taken.

global __dbg_g_level
# Value of &level for the interrupted procedure.
# Calculated as &level for the breakpoint procedure - 1.

global __dbg_g_local
# Table containing local variables.
# Entry key is variable name (string).
# Entry value is the value of the variable (any type).

global __dbg_g_out1
# Primary file for debugging output.

global __dbg_g_out2, __dbg_g_out2name
# Secondary file for debugging output; used for 'set echo'.
# Null when no echoing is not active.
# The name of this file.

global  __dbg_g_src
# Stack of input files used by the 'source' command (list of file).
# Empty list when no 'source' command is active.

global __dbg_g_trace
# Current trace level (passed to &trace when resuming execution).

global __dbg_g_where
# A list with data about the current breakpoint.
# Contents (symbolic names below):
# (1) Source file name (string).
# (2) Source line number (integer).
# (3) Procedure name (string).
# (4) The breakpoint causing this break (breakpoint descriptor, a list).

global __dbg_g_white
# This program's definition of white space.

# A note on the use of global '__dbg_test' (defined in 'dbg_init.icn').
# The runtime system assigns this variable one of the following values.
# ** Function 'member' for ordinary testing against the breakpoint sets.
# ** Function 'integer' (which is guaranteed to always fail, given a
# set as its first parameter) in the 'nobreak' mode; execution continues
# without break until the program completes.
# ** Integer '2' which causes a break at every intercept point.
# (Returns the second parameter which is the line number.)

#
#-------- Globals for Icon functions used by the debuggin runtime --------
# In an excruciating effort to avoid being hit by bad manners from the
# program under test we use our own variables for Icon functions.

global __dbg_fany, __dbg_fclose, __dbg_fdelete, __dbg_fexit, __dbg_ffind
global __dbg_fgetenv, __dbg_fimage, __dbg_finsert, __dbg_finteger, __dbg_fior
global __dbg_fishift, __dbg_fkey, __dbg_fmany, __dbg_fmatch
global __dbg_fmove, __dbg_fpop, __dbg_fpos, __dbg_fproc, __dbg_fpush
global __dbg_fput, __dbg_fread, __dbg_fremove, __dbg_freverse, __dbg_fright
global __dbg_fsort, __dbg_fstring, __dbg_ftab, __dbg_ftable, __dbg_ftrim
global __dbg_ftype, __dbg_fupto, __dbg_fwrite, __dbg_fwrites

#
#-------------- Expression management globals -----------		
#

global __dbg_ge_message
# Holds message if there is a conflict in expression compilation or
# evaluation

global __dbg_ge_singular
# Value used as default for the local variable table.
# Must be initialized to an empty list (or other suitable value).

#
#-------- Main --------
#

procedure __dbg_proc (file, line, proc_name, var_name, var_val[])
# This procedure is invoked a first time during initialization with parameters
# all null.
# Then it is called every time we hit a breakpoint during a debugging session.
# The parameters define the breakpoint, as follows,
# 'file': source file name (string).
# 'line': source line number (integer).
# 'proc_name': name of the current procedure (string).
# 'var_name': names of variables local to the current procedure
# (list of string).
# The list is sorted alphabetically.
# 'Local' variables include parameters and static variables.
# 'var_val': The current values of the local variables (list).
# The values occur in the same order as the names in 'var_name'.
# NOTE: In order not to affect the logic of the debugged program this
# procedure MUST FAIL.
# If it returns anything the current procedure will fail immediately.
local bdescr, cond, cmd, idx, tfname
	# Save trace level; turn tracing off.
	__dbg_g_trace := &trace
	&trace := 0

	if \file then { # Not the first-time invocation from "dbg_init".
		# Increment the global breakpoint counter.
		__dbg_g_brkpcnt +:= 1

		# Compute the procedure nesting level.
		__dbg_g_level := &level - 1

		# Begin setting up the 'where' structure.
		__dbg_g_where := [file, line, proc_name, &null]

		# We get here either because of a 'next', or because we hit a
		# breakpoint.
		# If we break because of a 'next' we should not treat this as
		# a breakpoint, even if there is one on this source line.
		if __dbg_test === member then {
			# This is a breakpoint; get it.
			if bdescr := __dbg_g_brlookup[__dbg_fior (__dbg_g_fileidx[file],
						line)] then {
				# Check ignore count.
				((bdescr[BRKP_IGNORE] -:= 1) = -1) | fail
				bdescr[BRKP_IGNORE] := 0
				}
			else
				__dbg_io_cfl ("Mysterious break: %1 (%2:%3).",
					proc_name, file, line)
			}
		else {  # Break caused by 'next'.
			# By convention treated as breakpoint number 0.
			bdescr := __dbg_g_brkpdef[0]
			# Check ignore count.
			((bdescr[BRKP_IGNORE] -:= 1) = -1) | fail
			bdescr[BRKP_IGNORE] := 0
			}
		__dbg_g_where[WHERE_BRKP] := bdescr

		# Create table of locals.
		__dbg_g_local := __dbg_ftable (__dbg_ge_singular)
		every idx := 1 to *var_name do
			__dbg_g_local[var_name[idx]] := var_val[idx]

		# Evaluate the condition of the breakpoint, if any.
		if cond := \(bdescr)[BRKP_COND] then {
			idx := 0
			__dbg_e_eval (cond[1]) & (idx +:= 1)
			# Check for conflict.
			# Make sure we don't resume in such case.
			__dbg_io_cfl ("[%1] condition '%2'\n   %3",
				bdescr[BRKP_ID], cond[2], \__dbg_ge_message) &
				(idx +:= 1)
			(idx > 0) | fail
			}

		# Reset the test procedure (effective if this is a 'next' break).
		__dbg_test := member

		# The first command to execute is the macro attached to the
		# breakpoint, if any; otherwise the prelude.
		cmd := (\(\bdescr)[BRKP_DO] | __dbg_g_automacro[1])
		}
	else {	# Initialize global variables for Icon functions.
		__dbg_func_init ()
		# Initialize breakpoint globals.
		__dbg_g_brkpcnt := 0
		__dbg_g_brkpdef := __dbg_ftable ()
		__dbg_g_brlookup := __dbg_ftable ()
		__dbg_g_brkpid := 0

		# Compute the procedure nesting level.
		__dbg_g_level := &level - 2

		# Create breakpoint number 0, used for 'next' breaks.
		__dbg_g_brkpdef[0] := [0, "*any*", 0, 0, 0, 0, , ]

		# Display file name.
		__dbg_g_display := "_DBG" || &clock[4:6] || &clock[7:0] || ".tmp"

		# More globals.
		__dbg_g_src := []
		__dbg_g_white := ' \t'
		__dbg_ge_singular := []

		# Create file index table.
		idx := -1
		__dbg_g_fileidx := __dbg_ftable ()
		every __dbg_g_fileidx[key(__dbg_file_map)] :=
			__dbg_fishift ((idx +:= 1), FIDX_SHIFT)

		# Open input and output files.
		if tfname := __dbg_fgetenv (DBG_INPUT_ENV) then
			__dbg_g_in := __dbg_x_openfile (tfname)
		(/__dbg_g_in := &input) | __dbg_fpush (__dbg_g_src, &input)

		if tfname := __dbg_fgetenv (DBG_OUTPUT_ENV) then
			__dbg_g_out1 := __dbg_x_openfile (tfname, 1)
		/__dbg_g_out1 := &errout

		# Initialize command definitions.
		__dbg_cmd_init ()

		# Set up the breakpoint data structure.
		# This is not a breakpoint; the following keeps some commands from
		# crashing.
		__dbg_g_local := __dbg_ftable ()
		__dbg_g_where := [&null, 0, "main", &null]
		__dbg_default_prelude :=
		"fprint \"[%1] %2 (%3:%4)\\n\";&bp;&proc;&file;&line"
		__dbg_default_postlude := ""
		__dbg_g_automacro := [[__dbg_c_compile (__dbg_default_prelude)],
			[]]
		cmd := []
		}

	# Command processing.
	repeat {
		case __dbg_c_interp (cmd) of {
		RESUME_STATUS: break
		STOP_STATUS: {
			__dbg_fremove (__dbg_g_display)
			__dbg_io_note ("Debug session terminates.")
			__dbg_fexit (0)
			}
		}
		# Get input until it compiles OK.
		repeat {
			(*__dbg_g_src > 0) | __dbg_fwrites ("$ ")
			if cmd := [__dbg_c_compile (__dbg_io_getline ())] then
				break
			}
		}
	# Run the postlude, if any; status discarded.
	__dbg_c_interp (__dbg_g_automacro[2])
	&trace := __dbg_g_trace
end

#
#-------- Command processing procedures --------
#

procedure __dbg_c_compile (str, macro_def)
# Compiles a command.
# 'str' must be a command to compile (string).
# 'macro_def' must be non-null to indicate a macro is being defined.
# RETURNS a command instance (list), or
# FAILS on conflict.
local cmd, keywd
	str ? {
		__dbg_ftab (__dbg_fmany (__dbg_g_white))
		keywd := __dbg_ftab (__dbg_fupto (__dbg_g_white) | 0)
		if *keywd = 0 then # empty line treated as comment
			return [__dbg_cx_NOOP, COMMENT_CMD]
		__dbg_ftab (__dbg_fmany (__dbg_g_white))
		(cmd := __dbg_c_findcmd (keywd)) | fail
		return cmd[CMD_COMPILE] (cmd, macro_def)
		}
end

procedure __dbg_c_brkpt (not_zero)
# Extracts a breakpoint id from a command.
# A breakpoint id is either an integer, or one of the special forms
# '.' (current), '$' (last defined).
# 'not_zero' may be non-null to indicate that breakpoint number zero
# is not accepted.
# RETURNS a breakpoint identifier (integer) on success;
# FAILS with a suitable conflict message otherwise.
local id, res
	__dbg_ftab (__dbg_fmany (__dbg_g_white))
	(res := (__dbg_finteger (__dbg_ftab (__dbg_fmany (&digits))) |
		2(id := =".", BRKP_CURRENT) |
		2(id := ="$", BRKP_LAST))) | {
		__dbg_io_cfl ("Breakpoint id (integer, '.', '$') expected.")
		fail
		}
	(res > 0) | /not_zero | {
		__dbg_io_cfl ("Breakpoint number 0 not accepted here.")
		fail
		}
	return res
end

procedure __dbg_c_interp (clist)
# Command interpreter.
# 'clist' must be a list of command instances.
# The interpreter may call itself indirectly through commands.
# RETURNS a status code, or
# FAILS on conflict, abandoning its command list.
local cmd, code
	every cmd := !clist do {
		(code := cmd[1]!cmd) | fail
		(code = OK_STATUS) | return code
		}
	return OK_STATUS
end

procedure __dbg_c_findcmd (keywd)
# Finds a command descriptor given a keyword.
# 'keywd' must be a command keyword candidate, possibly abbreviated (string).
# RETURNS a command definition, or
# FAILS with a message on conflict.
local count, cmd, mstr, sep, try
	count := 0
	sep := mstr := ""
	every __dbg_fmatch (keywd, (try := !__dbg_g_cmd)[CMD_NAME], 1, 0) do {
		cmd := try
		count +:= 1
		mstr ||:= sep || cmd[CMD_NAME]
		sep := ", "
		}
	case count of {
	0: {
		__dbg_io_cfl ("%1: unrecognized command.", keywd)
		fail
		}
	1: return cmd
	default : {
		__dbg_io_cfl ("'%1': ambiguous (matches %2).", keywd, mstr)
		fail
		}
	}
end

procedure __dbg_c_findkey (keywd, keylist)
# Finds a command descriptor given a keyword.
# 'keywd' must be a keyword candidate, possibly abbreviated (string).
# 'keylist' must be a list of available keywords.
# RETURNS an integer index into 'keylist', or
# FAILS with a message on conflict.
local count, cmd, idx, mstr, sep
	count := 0
	sep := mstr := ""
	every __dbg_fmatch (keywd, keylist[idx := 1 to *keylist], 1, 0) do {
		count +:= 1
		mstr ||:= sep || keylist[cmd := idx]
		sep := ", "
		}
	case count of {
	0: {
		__dbg_io_cfl ("%1: unrecognized keyword.", keywd)
		fail
		}
	1: return cmd
	default : {
		__dbg_io_cfl ("'%1': ambiguous (matches %2).", keywd, mstr)
		fail
		}
	}
end

procedure __dbg_c_mcompile (fname)
# Compiles a macro.
# 'fname' must contain a file name (string) if the macro definition should
# be read from a file; otherwise null.
# If 'fname' is defined and can be opened, a null value is pushed on the file
# stack before the file, as a mark.
# RETURNS a macro, i.e. a list of compiled commands -- on success.
# FAILS if a conflict arises during the macro definition.
local cfl_count, cmd, f, line, macro
	cfl_count := 0
	macro := []
	if \fname then {
		if f := __dbg_x_openfile (fname) then {
			__dbg_fpush (__dbg_g_src, __dbg_g_in)
			__dbg_fpush (__dbg_g_src, &null)
			__dbg_g_in := f
			}
		else
			fail
		}
	repeat {
		(*__dbg_g_src > 0) | __dbg_fwrites ("> ")
		(line := __dbg_io_getline ()) | break
		if cmd := __dbg_c_compile (line, 1) then {
			if cmd[CMD_CODE] = END_CMD then
				break
			else
				__dbg_fput (macro, cmd)
			}
		 else
			cfl_count +:= 1
		(cfl_count < 30) | break
		}
	/__dbg_g_in := __dbg_fpop (__dbg_g_src)
	if cfl_count = 0 then
		return macro
	else {
		__dbg_io_note ("The definition did not take effect.")
		fail
		}
end

procedure __dbg_c_msource ()
# Checks if the source of a macro is a file.
# RETURNS a file name if there is a '<' followed by a file name.
# RETURNS null if there is nothing but white space.
# FAILS with a message on conflict.
local fname
	__dbg_ftab (__dbg_fmany (__dbg_g_white))
	if ="<" then {
		__dbg_ftab (__dbg_fmany (__dbg_g_white))
		if __dbg_fpos (0) then {
			__dbg_io_cfl ("File name expected.")
			fail
			}
		fname := __dbg_ftrim (__dbg_ftab (0))
		}
	return fname
end

procedure __dbg_x_brkpt (id)
# RETURNS a breakpoint descriptor, given a breakpoint id ('id', integer).
# FAILS with a diagnostic message on conflict.
local bdescr
	bdescr := case id of {
	BRKP_CURRENT:	\__dbg_g_where[WHERE_BRKP] |
			(__dbg_io_cfl ("No current breakpoint."), &null)
	BRKP_LAST:	\__dbg_g_brkpdef[__dbg_g_brkpid] |
		(__dbg_io_cfl ("Breakpoint [%1] undefined.", __dbg_g_brkpid),
			&null)
	default:	\__dbg_g_brkpdef[id] |
			(__dbg_io_cfl ("Breakpoint [%1] undefined.", id), &null)
	}
	return \bdescr
end

procedure __dbg_x_dispglob (f, pat)
# Essentially performs the 'info globals' command.
# 'f' must be a display file open for input.
# 'pat' must be a substring that variable names must contain.
local fchanged, line, word
static func
initial {
	func := set ()
	# A set containing all function names.
	every insert (func, function ())
	}
	fchanged := []
	until __dbg_fread (f) == "global identifiers:"
	repeat {
		(line := __dbg_fread (f)) | break
		word := []
		line ? repeat {
			__dbg_ftab (__dbg_fmany (__dbg_g_white))
			if __dbg_fpos (0) then
				break
			__dbg_fput (word, __dbg_ftab (__dbg_fupto (__dbg_g_white) | 0))
			}
		__dbg_fmatch (DBG_PREFIX, word[1]) | (word[1] == word[-1]) |
		if __dbg_ffind (pat, word[1]) then
			__dbg_io_info ("%1", word[1])

		# Check if function name has been used for other things.
		if member (func, word[1]) then {
			(word[-2] == "function" & word[-1] == word[1]) |
			put (fchanged, word[1])
			}
		}
	if *fchanged > 0 then {
		__dbg_io_note ("The following global(s) no longer hold their usual Icon functions:")
		every __dbg_io_wrline ("  " || !fchanged)
		}
end

procedure __dbg_x_dispinit (f)
# Reads the display file, skipping over lines caused by the debugger.
# 'f' must be the display file, open for input.
# RETURNS the first 'significant' line.
# NOTE that you must take care of the 'co-expression' line before calling
# this procedure.
local line
	until __dbg_fmatch (DBG_PREFIX, line := __dbg_fread (f))
	while line[1] == " " | __dbg_fmatch (DBG_PREFIX, line) do
		line := __dbg_fread (f)
	return line
end

procedure __dbg_x_lbreak (bdescr)
# Lists the nominal definition of a breakpoint.
# 'bdescr' may be a breakpoint descriptor, or null.
# If null all breakpoints are listed.
local bd, blist, cond, dodef, tmplist
	(blist := [\bdescr]) | {
		tmplist := __dbg_fsort (__dbg_g_brkpdef)
		blist := []
		every __dbg_fput (blist, (!tmplist)[2])
		}
	every bd := !blist do {
		dodef := if \bd[BRKP_DO] then "  DO defined" else ""
		__dbg_io_info ("[%1] %2 %3:%4%5", bd[BRKP_ID], bd[BRKP_FILE],
			bd[BRKP_LINE1], bd[BRKP_LINE2], dodef)
		if cond := \bd[BRKP_COND] then
			__dbg_io_info ("   CONDITION: %1", cond[2])
		}
end

procedure __dbg_x_openfile (fname, output, quiet)
# Opens a file.
# 'fname' must be the name of the file to open.
# 'output' must be non-null if the file is to be opened for output.
# 'quiet' must be non-null to prevent a conflict from generating a message.
# RETURNS an open file on success;
# FAILS with a message otherwise, unless 'quiet' is set.
# FAILS silently if 'quiet' is set.
local f, mode, modestr
	if \output then {
		mode := "w"
		modestr := "output"
		}
	else {
		mode := "r"
		modestr := "input"
		}
	(f := open (fname, mode)) | (\quiet & fail) |
	__dbg_io_cfl ("Cannot open '%1' for %2.", fname, modestr)
	return \f
end

procedure __dbg_x_opendisplay ()
# Opens the display file for reading; writes it first, if necessary.
# RETURNS a file open for input on success.
# FAILS with a message on conflict.
local f, res
	if f := __dbg_x_openfile (__dbg_g_display,, 1) then {
		if __dbg_finteger (__dbg_fread (f)) = __dbg_g_brkpcnt then
			res := f
		else
			__dbg_fclose (f)
		}
	\res | {
		(f := __dbg_x_openfile (__dbg_g_display, 1)) | fail
		__dbg_fwrite (f, __dbg_g_brkpcnt)
		display (, f)
		__dbg_fclose (f)
		(f := __dbg_x_openfile (__dbg_g_display)) | fail
		__dbg_fread (f) # Throw away breakpoint counter.
		res := f
		}
	return res
end

#-------- Command compilation procedures --------
# 'macro_def' must be non-null to indicate that a macro is being defined.
# The command compilation procedures must return a list representing the
# compiled command, or fail on conflict.
# When they are invoked the keyword and any following white space has been
# parsed.


procedure __dbg_cc_break (cmd, macro_def)
local fidx, fname, line1, line2
	__dbg_fany (&digits) | (fname := __dbg_ftab (__dbg_fupto (__dbg_g_white))) | {
		__dbg_io_cfl ("File name and/or line number expected.")
		fail
		}

	# Get file name.
	if \fname then {
		(fidx := \__dbg_g_fileidx[fname]) | {
			__dbg_io_cfl ("File name '%1' not recognized.", fname)
			fail
			}
		}
	else if fname := \__dbg_g_where[WHERE_FILE] then
		fidx := __dbg_g_fileidx[fname]
	else { # init mode
		__dbg_io_cfl ("File name required.")
		fail
		}

	# Get line number(s).
	__dbg_ftab (__dbg_fmany (__dbg_g_white))
	(line1 := __dbg_finteger (__dbg_ftab (__dbg_fmany (&digits)))) | {
		__dbg_io_cfl ("Line number expected.")
		fail
		}
	__dbg_ftab (__dbg_fmany (__dbg_g_white))
	if =":" then {
		__dbg_ftab (__dbg_fmany (__dbg_g_white))
			(line2 := __dbg_finteger (__dbg_ftab (__dbg_fmany (&digits)))) | {
				__dbg_io_cfl ("Line number expected.")
				fail
				}
		}
	else
		line2 := line1
	(line1 <= line2 < 1000000) | {
		__dbg_io_cfl ("Weird line number.")
		fail
		}

	# Create an almost finished breakpoint descriptor (id is missing).
	return [cmd[CMD_EXEC], cmd[CMD_CODE], [ , fname, fidx, line1, line2, 0, ,]]
end

procedure __dbg_cc_clear (cmd, macro_def)
# A compound command.
local keyidx, parm
static ckey
initial ckey := ["breakpoint", "condition", "do", "echo", "macro"]
	(keyidx := __dbg_c_findkey (__dbg_ftab (__dbg_fupto (__dbg_g_white) | 0), ckey)) |
		fail
	__dbg_ftab (__dbg_fmany (__dbg_g_white))
	case keyidx of {
	CLEAR_BREAKPOINT:
		(parm := __dbg_c_brkpt (1)) | fail
	(CLEAR_COND | CLEAR_DO):
		(parm := __dbg_c_brkpt ()) | fail
	CLEAR_MACRO:
		(parm := __dbg_e_idf ()) | {
			__dbg_io_cfl ("Macro name expected.")
			fail
			}
	}
	return [cmd[CMD_EXEC], cmd[CMD_CODE], ckey, keyidx, parm]
end

procedure __dbg_cc_condition (cmd, macro_def)
local brkpt, expr
	(brkpt := __dbg_c_brkpt ()) | fail
	# This makes the expression cleaner, but not necessary.
	__dbg_ftab (__dbg_fmany (__dbg_g_white))
	(expr := __dbg_e_compile (__dbg_ftab (0))) | {
		__dbg_io_cfl (__dbg_ge_message)
		fail
		}
	(*expr = 1) | __dbg_io_note ("Last %1 expressions ignored.", *expr - 1)
	return [cmd[CMD_EXEC], cmd[CMD_CODE], brkpt, expr[1]]
end

procedure __dbg_cc_do (cmd, macro_def)
local brkpt, fname
	/macro_def | {
		__dbg_io_cfl ("Sorry, nested macros not accepted.")
		fail
		}
	(brkpt := __dbg_c_brkpt ()) | fail
	(fname := __dbg_c_msource ()) | fail
	return [cmd[CMD_EXEC], cmd[CMD_CODE], brkpt, fname]
end

procedure __dbg_cc_end (cmd, macro_def)
	\macro_def | {
		__dbg_io_cfl ("'end' out of context.")
		fail
		}
	return [cmd[CMD_EXEC], cmd[CMD_CODE]]
end

procedure __dbg_cc_eprint (cmd, macro_def)
local expr
	(expr := __dbg_e_compile (__dbg_ftab (0))) | {
		__dbg_io_cfl (__dbg_ge_message)
		fail
		}
	(*expr = 1) | __dbg_io_note ("Last %1 expressions ignored.", *expr - 1)
	return [cmd[CMD_EXEC], cmd[CMD_CODE], expr[1]]
end

procedure __dbg_cc_frame (cmd, macro_def)
local frame_no
	__dbg_fpos (0) | (frame_no := __dbg_finteger (__dbg_ftab (__dbg_fmany (&digits ++ '-')))) | {
		__dbg_io_cfl ("Frame number expected.")
		fail
		}
	return [cmd[CMD_EXEC], cmd[CMD_CODE], frame_no]
end

procedure __dbg_cc_goon (cmd, macro_def)
local opt
	__dbg_fpos (0) | __dbg_fmatch (opt := __dbg_ftab (__dbg_fmany (&lcase)), "nobreak", 1, 0) | {
		__dbg_io_cfl ("Expected 'nobreak', found '%1'.", opt)
		fail
		}
	return [cmd[CMD_EXEC], cmd[CMD_CODE], opt]
end

procedure __dbg_cc_help (cmd, macro_def)
local keywd
	__dbg_fpos (0) | (keywd := __dbg_ftab (__dbg_fmany (&lcase))) | {
		__dbg_io_cfl ("Command keyword expected.")
		fail
		}
	return [cmd[CMD_EXEC], cmd[CMD_CODE], keywd]
end

procedure __dbg_cc_ignore (cmd, macro_def)
local brkpt, count
	(brkpt := __dbg_c_brkpt ()) | fail
	__dbg_ftab (__dbg_fmany (__dbg_g_white))
	(count := __dbg_finteger (__dbg_ftab (__dbg_fmany (&digits ++ '+-')))) | {
		__dbg_io_cfl ("Integer ignore count expected.")
		fail
		}
	return [cmd[CMD_EXEC], cmd[CMD_CODE], brkpt, count]
end

procedure __dbg_cc_info (cmd, macro_def)
# A compound command.
local keyidx, parm
static ckey
initial ckey := ["breakpoint", "echo", "files", "globals", "locals", "macros",
	"trace", "version"]
	(keyidx := __dbg_c_findkey (__dbg_ftab (__dbg_fupto (__dbg_g_white) | 0), ckey)) |
		fail
	__dbg_ftab (__dbg_fmany (__dbg_g_white))
	if keyidx = INFO_BREAKPOINT then
		__dbg_fpos (0) | (parm := __dbg_c_brkpt ()) | fail
	else if keyidx = INFO_GLOBALS then
		__dbg_fpos (0) | (parm := __dbg_ftab (__dbg_fupto (__dbg_g_white) | 0))
	return [cmd[CMD_EXEC], cmd[CMD_CODE], ckey, keyidx, parm]
end

procedure __dbg_cc_macro (cmd, macro_def)
local fname, idf
	/macro_def | {
		__dbg_io_cfl ("Sorry, nested macros not accepted.")
		fail
		}
	(idf := __dbg_ftab (__dbg_fmany (&lcase))) | {
		__dbg_io_cfl ("Macro name expected.")
		fail
		}
	(fname := __dbg_c_msource ()) | fail
	return [cmd[CMD_EXEC], cmd[CMD_CODE], idf, fname]
end

procedure __dbg_cc_next (cmd, macro_def)
local count
	__dbg_ftab (__dbg_fmany (__dbg_g_white))
	__dbg_fpos (0) | (count := __dbg_finteger (__dbg_ftab (__dbg_fmany (&digits ++ '+-')))) | {
		__dbg_io_cfl ("Integer ignore count expected.")
		fail
		}
	return [cmd[CMD_EXEC], cmd[CMD_CODE], count]
end

procedure __dbg_cc_print (cmd, macro_def)
# Used to compile 'fprint' and 'print'.
local expr
	(expr := __dbg_e_compile (__dbg_ftab (0))) | {
		__dbg_io_cfl (__dbg_ge_message)
		fail
		}
	return [cmd[CMD_EXEC], cmd[CMD_CODE], expr]
end

procedure __dbg_cc_set (cmd, macro_def)
# A compound command.
local keyidx, parm
static ckey
initial ckey := ["echo", "prelude", "postlude"]
	(keyidx := __dbg_c_findkey (__dbg_ftab (__dbg_fupto (__dbg_g_white) | 0), ckey)) |
		fail
	__dbg_ftab (__dbg_fmany (__dbg_g_white))
	case keyidx of {
	SET_ECHO: {
		parm := __dbg_ftrim (__dbg_ftab (__dbg_fupto (__dbg_g_white) | 0))
		(*parm > 0) | {
			__dbg_io_cfl ("File name expected.")
			fail
			}
		}
	(SET_PRELUDE | SET_POSTLUDE):
		(parm := __dbg_c_msource ()) | fail
	}
	return [cmd[CMD_EXEC], cmd[CMD_CODE], ckey, keyidx, parm]
end

procedure __dbg_cc_source (cmd, macro_def)
# The 'source' command is different from other commands, because it is not
# really compiled; it takes effect immediately.
# In contrast to macro compilation, no null marker is pushed on the file stack.
# RETURNS a dummy 'source' command.
local f, fname, res
	__dbg_ftab (__dbg_fmany (__dbg_g_white))
	if __dbg_fpos (0) then
		__dbg_io_cfl ("File name expected.")
	else {
		fname := __dbg_ftrim (__dbg_ftab (0))
		if *__dbg_g_src >= MAX_SOURCE_NESTING then
			__dbg_io_cfl ("%1: Too deeply nested 'source' file.", fname)
		else if f := __dbg_x_openfile (fname) then {
			__dbg_fpush (__dbg_g_src, __dbg_g_in)
			__dbg_g_in := f
			res := [cmd[CMD_EXEC], cmd[CMD_CODE], fname]
			}
		}
	return \res
end

procedure __dbg_cc_trace (cmd, macro_def)
local tlevel
	(tlevel := __dbg_finteger (__dbg_ftab (__dbg_fmany (&digits ++ '+-')))) | {
		__dbg_io_cfl ("Integer value expected.")
		fail
		}
	return [cmd[CMD_EXEC], cmd[CMD_CODE], \tlevel]
end

procedure __dbg_cc_SIMPLE (cmd, macro_def)
# Used to compile all keyword-only commands, including macros.
	return [cmd[CMD_EXEC], cmd[CMD_CODE], cmd[CMD_MACRO]]
end

#-------- Command executing procedures --------
# The first parameter of these procedures is the procedure itself.
# (Not a very interesting parameter.)
# The command executing procedures must return a return code on success.
# Return codes are defined among the symbolic constants.
# The procedures must fail on conflict.


procedure __dbg_cx_break (proced, ccode, brkp)
local id, bpset, fidx, line1, line2
	# Add the breakpoint id to the descriptor.
	brkp[BRKP_ID] := id := (__dbg_g_brkpid +:= 1)
	__dbg_io_wrline ("[" || id || "]")
	# Make sure we can find the breakpint descriptor, given its id.
	__dbg_g_brkpdef[id] := brkp
	# Install the breakpoint lines in the lookup table.
	fidx := brkp[BRKP_FIDX]
	line1 := brkp[BRKP_LINE1]
	line2 := brkp[BRKP_LINE2]
	every __dbg_g_brlookup[__dbg_fior (fidx, line1 to line2)] := brkp
	# Add the line numbers to the breakpoint set.
	bpset := __dbg_file_map[brkp[BRKP_FILE]]
	every __dbg_finsert (bpset, line1 to line2)
	return OK_STATUS
end

procedure __dbg_cx_clear (proced, ccode, ckey, keyidx, parm)
# 'ckey' will be a list containing all the possible keywords to 'clear'.
# 'keyidx' is an index into that list, indicating a subcommand.
local bdescr, bpset, cmd, fidx, lcode, line, line1, line2
	if keyidx = (CLEAR_BREAKPOINT | CLEAR_COND | CLEAR_DO) then
		(bdescr := __dbg_x_brkpt (parm)) | fail
	else if keyidx = CLEAR_MACRO then
		(cmd := __dbg_c_findcmd (parm)) | fail
	case keyidx of {
	CLEAR_BREAKPOINT: {
		__dbg_fdelete (__dbg_g_brkpdef, bdescr[BRKP_ID])
		fidx := bdescr[BRKP_FIDX]
		line1 := bdescr[BRKP_LINE1]
		line2 := bdescr[BRKP_LINE2]
		bpset := __dbg_file_map[bdescr[BRKP_FILE]]
		# The range of lines once defined for the breakpoint might
		# have been overwritten by later breakpoints.
		every lcode := __dbg_fior (fidx, line := line1 to line2) do {
			if __dbg_g_brlookup[lcode] === bdescr then {
				__dbg_fdelete (__dbg_g_brlookup, lcode)
				__dbg_fdelete (bpset, line)
				}
			}
		}
	CLEAR_COND:	bdescr[BRKP_COND] := &null
	CLEAR_DO:	bdescr[BRKP_DO] := &null
	CLEAR_ECHO: {
		__dbg_fclose (\__dbg_g_out2)
		__dbg_g_out2 := &null
		}
	CLEAR_MACRO: {
		(cmd := __dbg_c_findcmd (parm)) | fail
		__dbg_fdelete (__dbg_g_cmd, cmd[CMD_NAME])
		}
	}
	return OK_STATUS
end

procedure __dbg_cx_condition (proced, ccode, brkpt, expr)
local bdescr
	(bdescr := __dbg_x_brkpt (brkpt)) | fail
	bdescr[BRKP_COND] := expr
	return OK_STATUS
end

procedure __dbg_cx_do (proced, ccode, brkpt, fname)
local bdescr
	(bdescr := __dbg_x_brkpt (brkpt)) | fail
	(bdescr[BRKP_DO] := __dbg_c_mcompile (fname)) | fail
	return OK_STATUS
end

procedure __dbg_cx_eprint (proced, ccode, expr)
local count, val
	__dbg_io_wrline ("{" || expr[2] || "}")
	count := 0
	every val := __dbg_fimage (__dbg_e_eval (expr[1])) do {
		if __dbg_io_cfl (\__dbg_ge_message) then
			fail
		else
			__dbg_io_wrline ("" || __dbg_fright ((count +:= 1), 3) ||
				": " || val)
		}
	return OK_STATUS
end

procedure __dbg_cx_fprint (proced, ccode, elist)
# 'elist' must be a list on the format returned by '__dbg_e_compile'.
local expr, fmt, idx, sval, val
	val := []
	every expr := !elist do {
		__dbg_fput (val, __dbg_e_eval (expr[1]) | "&fail")
		if __dbg_io_cfl (\__dbg_ge_message) then
			fail
		}
	(fmt := __dbg_fstring (val[1])) | {
		__dbg_io_cfl ("Expected format string; got '%1'.", __dbg_fimage (val[1]))
		fail
		}
	sval := []
	every idx := 2 to *val do {
		__dbg_fput (sval, __dbg_fstring (val[idx])) | {
		__dbg_io_cfl ("Expression not string-convertible: {%1} %2",
			elist[idx][2], __dbg_fimage (val[idx]))
			fail
			}
		}
	__dbg_io_wrstr (__dbg_x_subst (fmt, sval))
	return OK_STATUS
end

procedure __dbg_cx_frame (proced, ccode, frame_spec)
local f, frame_no, idx, line
	frame_no := if \frame_spec then {
		if frame_spec < 0 then __dbg_g_level + frame_spec else frame_spec
		} else __dbg_g_level
	(1 <= frame_no <= __dbg_g_level) | {
		__dbg_io_cfl ("Invalid frame number.")
		fail
		}
	(f := __dbg_x_opendisplay ()) | fail
	line := __dbg_x_dispinit (f)
	idx := __dbg_g_level
	while idx > frame_no do {
		repeat if (line := __dbg_fread (f))[1] ~== " " then
				break
		idx -:= 1
		}
	__dbg_io_info ("(%1) %2", frame_no, line)
	repeat {
		if (line := __dbg_fread (f))[1] ~== " " then
			break
		line ? {
			__dbg_ftab (__dbg_fmany (__dbg_g_white))
			=DBG_PREFIX | __dbg_io_info ("%1", line, *line > 0)
			}
		}
	__dbg_fclose (f)
	return OK_STATUS
end

procedure __dbg_cx_goon (proced, ccode, nobreak)
	if \nobreak then {
		__dbg_test := integer
		__dbg_fremove (__dbg_g_display)
		}
	return RESUME_STATUS
end

procedure __dbg_cx_help (proced, ccode, keywd)
# 'keywd' will be an identifier if the command had a keyword.
local cmd, hstr
	if cmd := __dbg_c_findcmd (\keywd) then {
		if hstr := \cmd[CMD_HELP] then
			__dbg_io_wrline (hstr)
		else
			__dbg_io_note ("No help available for '%1'.", cmd[CMD_NAME])
		}
	else
__dbg_io_wrline ("Available commands: (all keywords may be abbreviated)\n_
break		(set breakpoint)\n_
clear		(clear breakpoint or debugger parameter)\n_
condition	(attach condition to breakpoint)\n_
do		(attach macro to breakpoint)\n_
end		(terminate macro definition)\n_
eprint		(print every value from expression)\n_
fprint		(formatted print)\n_
frame		(inspect procedure call chain)\n_
goon		(resume execution)\n_
help		(print explanatory text)\n_
ignore		(set ignore counter on breakpoint)\n_
info		(print information about breakpoint or debugger parameter)\n_
macro		(define new command)\n_
next		(resume execution, break on every line)\n_
print		(print expressions)\n_
set		(set a debugger parameter)\n_
source		(read debugging commands from file)\n_
stop		(terminate program and debugging session)\n_
trace		(set value of Icon &trace)\n_
where		(print procedure call chain)\n\n_
An expression may be formed from a large subset of Icon operators; integer,\n_
string, list literals; locals from the current procedure, and globals.\n_
Procedure/function invocation, subscripting, record field reference is\n_
supported. Several keywords are also included.\n\n_
New/altered keywords,\n_
\	&bp, &breakpoint	current breakpoint id (integer)\n_
\	&file			current breakpoint source file name (string)\n_
\	&line			current breakpoint line number (integer)\n_
\	&proc			current breakpoint procedure name (string)")
	return OK_STATUS
end

procedure __dbg_cx_ignore (proced, ccode, brkpt, count)
local bdescr
	(bdescr := __dbg_x_brkpt (brkpt)) | fail
	bdescr[BRKP_IGNORE] := count
	return OK_STATUS
end

procedure __dbg_cx_info (proced, ccode, ckey, keyidx, parm)
# 'ckey' will be a list containing all the possible keywords to 'info'.
# 'keyidx' is an index into that list, indicating a subcommand.
local cmd, bdescr, f, nlist, version
	case keyidx of {
	INFO_BREAKPOINT:
		if \parm then {
			(bdescr := __dbg_x_brkpt (parm)) | fail
			__dbg_x_lbreak (bdescr)
			}
		else
			__dbg_x_lbreak ()
	INFO_ECHO:
		if \__dbg_g_out2 then
			__dbg_io_info ("Echo file: %1.", __dbg_g_out2name)
		else
			__dbg_io_info ("No echo file.")
	INFO_FILES: {
		nlist := []
		every __dbg_fput (nlist, __dbg_fkey (__dbg_file_map))
		nlist := __dbg_fsort (nlist)
		__dbg_io_info ("Tweaked source files in this program:")
		every __dbg_io_info ("   %1", !nlist)
		}
	INFO_GLOBALS: {
		(f := __dbg_x_opendisplay ()) | fail
		if \parm then
			__dbg_x_dispglob (f, parm)
		else
			__dbg_x_dispglob (f, "")
		__dbg_fclose (f)
		}
	INFO_LOCALS: {
		nlist := []
		every __dbg_fput (nlist, __dbg_fkey (__dbg_g_local))
		nlist := __dbg_fsort (nlist)
		__dbg_io_info ("Local identifiers in the current procedure:",
			*nlist > 0)
		every __dbg_io_info ("   %1", !nlist)
		}
	INFO_MACROS: {
		nlist := []
		every \(cmd := !__dbg_g_cmd)[CMD_MACRO] do
			__dbg_fput (nlist, cmd[CMD_NAME])
		nlist := __dbg_fsort (nlist)
		__dbg_io_info ("Currently defined macros:", *nlist > 0)
		every __dbg_io_info ("   %1", !nlist)
		}
	INFO_TRACE:
		__dbg_io_info ("Current trace level: %1.", __dbg_g_trace)
	INFO_VERSION: {
		version := (PROGRAM_VERSION ? (__dbg_ftab (__dbg_fupto (&digits)),
			__dbg_ftab (__dbg_fmany (&digits++'.'))))
		__dbg_io_info ("Program tweaked by itweak version %1.\n_
		This is runtime version %2.", __dbg_itweak_ver, version)
		}
	}
	return OK_STATUS
end

procedure __dbg_cx_macro (proced, ccode, idf, fname)
# Executes a 'macro' statement (not the resulting macro).
# 'fname' contains a file name (string) if the macro definition should be
# read from a file; otherwise null.
# SIDE EFFECT: Adds a command definition to '__dbg_g_cmd' on success.
local count, macro, mstr, sep, try
	count := 0
	mlist := []
	# Macro name must not be an abbreviation of an existing command.
	every __dbg_fmatch (idf, try := (!__dbg_g_cmd)[CMD_NAME], 1, 0) do {
		count +:= 1
		__dbg_fput (mlist, try)
		}
	# Check that no existing command is an abbreviation of macro name.
	every __dbg_fmatch (try := (!__dbg_g_cmd)[CMD_NAME], idf, 1, 0) do {
		count +:= 1
		(try == !mlist) | __dbg_fput (mlist, try)
		}
	(count = 0) | {
		mstr := sep := ""
		every mstr ||:= sep || !mlist do
			sep := ", "
		__dbg_io_cfl ("'%1' clashes with existing command (%2).", idf, mstr)
		fail
		}
	(macro := __dbg_c_mcompile (fname)) | fail
	__dbg_g_cmd[idf] := [idf, USERDEF_CMD, , __dbg_cc_SIMPLE, macro, __dbg_cx_userdef]
	return OK_STATUS
end

procedure __dbg_cx_next (proced, ccode, count)
# 'count' may be an ignore count.
	__dbg_g_brkpdef[0][BRKP_IGNORE] := \count
	__dbg_test := 2
	return RESUME_STATUS
end

procedure __dbg_cx_print (proced, ccode, elist)
# 'elist' must be a list on the format returned by '__dbg_e_compile'.
local expr, val
	every expr := !elist do {
		val := (__dbg_fimage (__dbg_e_eval (expr[1])) | "&fail")
		if __dbg_io_cfl (\__dbg_ge_message) then
			fail
		else
			__dbg_io_wrline ("{" || expr[2] || "} " || val)
		}
	return OK_STATUS
end

procedure __dbg_cx_set (proced, ccode, ckey, keyidx, parm)
# 'ckey' will be a list containing all the possible keywords to 'set'.
# 'keyidx' is an index into that list, indicating a subcommand.
	case keyidx of {
	SET_ECHO: {
		(__dbg_g_out2 := __dbg_x_openfile (parm, 1)) | fail
		__dbg_g_out2name := parm
		}
	SET_PRELUDE:
		(__dbg_g_automacro[1] := __dbg_c_mcompile (parm)) | fail
	SET_POSTLUDE:
		(__dbg_g_automacro[2] := __dbg_c_mcompile (parm)) | fail
	}
	return OK_STATUS
end

procedure __dbg_cx_stop (proced, ccode)
	return STOP_STATUS
end

procedure __dbg_cx_trace (proced, ccode, tlevel)
	__dbg_g_trace := tlevel
	return OK_STATUS
end

procedure __dbg_cx_where (proced, ccode)
local f, idf, idx, line
	(f := __dbg_x_opendisplay ()) | fail
	__dbg_io_info ("Current call stack in %1:", __dbg_fread (f))
	idx := __dbg_g_level
	line := __dbg_x_dispinit (f)
	repeat {
		idf := (line ? __dbg_ftab (__dbg_fupto (__dbg_g_white)))
		if idf == "global" then
			break
		if *idf > 0 then {
			__dbg_io_info ("(%1) %2", idx, idf)
			idx -:= 1
			}
		(line := __dbg_fread (f)) | break # Sanity.
		}
	__dbg_fclose (f)
	return OK_STATUS
end

procedure __dbg_cx_userdef (proced, ccode, macro)
	return __dbg_c_interp (macro)
end

procedure __dbg_cx_NOOP (proced, ccode)
	return OK_STATUS
end

#
#-------- General-purpose procedures --------
#

procedure __dbg_x_fld_adj (str)
# Part of 'subst' format string parsing.
# 'str' must be a parameter string identified by the beginning part of a
# placeholder ('%n').
# This procedure checks if the placeholder contains a fixed field width
# specifier.
# A fixed field specifier begins with '<' or '>' and continues with the field
# width expressed as a decimal literal.
# RETURNS 'str' possibly inserted in a fixed width field.
local just, init_p, res, wid
static fwf
initial fwf := '<>'
	init_p := &pos
	if (just := if ="<" then left else if =">" then right) &
		(wid := __dbg_finteger (__dbg_ftab (__dbg_fmany (&digits)))) then
		res := just (str, wid)
	else {
		res := str
		&pos := init_p
		}
	return res
end

procedure __dbg_x_subst (msg, parm)
# Substitutes parameters in a message template.
# 'msg' must be a message template (string).
# 'parm' must be a list of parameters (list of string-convertible), or null.
# It may also be a string.
local esc, res, sub
static p_digit
initial p_digit := '123456789'
	\parm | return msg
	parm := [__dbg_fstring (parm)]
	res := ""
	msg ? until __dbg_fpos (0) do {
		res ||:= __dbg_ftab (__dbg_fupto ('%\\') | 0)
		if ="%" then res ||:= {
			if __dbg_fany (p_digit) then {
				sub := (\parm[__dbg_finteger (__dbg_fmove (1))] | "")
				__dbg_x_fld_adj (sub)	
				}
			else if __dbg_fany ('%') then
				__dbg_fmove (1)
			else ""
			}
		else if ="\\" then res ||:= case esc := __dbg_fmove (1) of {
			"n": "\n"
			"t": "\t"
			default: esc
			}
		}
	return res
end

#
#-------- Input/Output procedures --------
#

procedure __dbg_io_cfl (format, parm[])
# Writes a conflict message to debugging output.
# 'format' must be a format string.
# 'parm' must be string-convertibles to insert into placeholders in the
# format string, if any.
# RETURNS 1 (i.e. always succeeds).
	__dbg_io_wrline ("[debug CONFLICT] " || __dbg_x_subst (format, parm))
	return 1
end

procedure __dbg_io_getline ()
# RETURNS the next line from debugging input, or
# FAILS on end of file.
local line
	(line := __dbg_fread (__dbg_g_in)) | {
		__dbg_fclose (__dbg_g_in)
		# Check for a macro definition marker.
		\(__dbg_g_in := __dbg_fpop (__dbg_g_src)) | fail
		if *__dbg_g_src > 0 then
			return __dbg_io_getline ()
		}
	__dbg_fwrite (\__dbg_g_out2, "$ ", \line)
	return \line
end

procedure __dbg_io_info (format, parm[])
# Writes an info message to debugging output.
# 'format' must be a format string.
# 'parm' must be string-convertibles to insert into placeholders in the
# format string, if any.
	__dbg_io_wrline (__dbg_x_subst (format, parm))
end

procedure __dbg_io_note (format, parm[])
# Writes a note to debugging output.
# 'format' must be a format string.
# 'parm' must be string-convertibles to insert into placeholders in the
# format string, if any.
	__dbg_io_wrline ("[debug NOTE] " || __dbg_x_subst (format, parm))
end

procedure __dbg_io_wrline (line)
# Writes a string and a newline to debugging output.
# 'line' must be the string to write.
# It may contains additional newlines.
	__dbg_fwrite (__dbg_g_out1, line)
	__dbg_fwrite (\__dbg_g_out2, line)
end

procedure __dbg_io_wrstr (line)
# Writes a string without a newline to debugging output.
# 'line' must be the string to write.
# It may contains additional newlines.
	__dbg_fwrites (__dbg_g_out1, line)
	__dbg_fwrites (\__dbg_g_out2, line)
end

#
#-------- Function initialization ---------
#
procedure __dbg_func_init ()
	__dbg_fany	:= any
	__dbg_fclose	:= close
	__dbg_fdelete	:= delete
	__dbg_fexit	:= exit
	__dbg_ffind	:= find
	__dbg_fgetenv	:= getenv
	__dbg_fimage	:= image
	__dbg_finsert	:= insert
	__dbg_finteger	:= integer
	__dbg_fior	:= ior
	__dbg_fishift	:= ishift
	__dbg_fkey	:= key
	__dbg_fmany	:= many
	__dbg_fmatch	:= match
	__dbg_fmove	:= move
	__dbg_fpop	:= pop
	__dbg_fpos	:= pos
	__dbg_fproc	:= proc
	__dbg_fpush	:= push
	__dbg_fput	:= put
	__dbg_fread	:= read
	__dbg_fremove	:= remove
	__dbg_freverse	:= reverse
	__dbg_fright	:= right
	__dbg_fsort	:= sort
	__dbg_fstring	:= string
	__dbg_ftab	:= tab
	__dbg_ftable	:= table
	__dbg_ftrim	:= trim
	__dbg_ftype	:= type
	__dbg_fupto	:= upto
	__dbg_fwrite	:= write
	__dbg_fwrites	:= writes
end

#
#-------- Command initialization ---------
#

procedure __dbg_cmd_init ()
# Initialize command definitions.
	__dbg_g_cmd := __dbg_ftable ()
### break
		__dbg_g_cmd["break"] := ["break", BREAK_CMD,
"	break [file] [line [: line]]\n_
Sets a breakpoint on a line or a range of lines. The file name (if present)\n_
must be one of the tweaked files (cf. the 'info files' command). If omitted\n_
the file of the current breakpoint is assumed. The identity of the new\n_
breakpoint (an integer) is displayed. It may be used in other commands.\n_
Besides an integer there are two other ways to identify a breakpoint,\n_
\	.	(dot) the current breakpoint,\n_
\	$	(dollar) the last breakpoint defined by a 'break' command.\n_
Breakpoint 0 (zero) is special; see the 'next' command.\n\n_
As a rule a breakpoint takes effect AFTER the breakpointed line has been\n_
executed. If two breakpoints are defined on the same line, only the latest\n_
is in effect.",
__dbg_cc_break, , __dbg_cx_break]
### clear
		__dbg_g_cmd["clear"] := ["clear", CLEAR_CMD,
"	clear breakpoint brkpt\n_
Deletes breakpoint identified by 'brkpt'.\n_
\	clear condition brkpt\n_
Removes condition from breakpoint 'brkpt'. The breakpoint becomes\n_
unconditional.\n_
\	clear do brkpt\n_
Removes commands associated with breakpoint 'brkpt'.\n_
\	clear echo\n_
Stops output to echo file.\n_
\	clear macro name\n_
Removes macro identified by 'name'.",
__dbg_cc_clear, , __dbg_cx_clear]
### comment
		__dbg_g_cmd["#"] := ["#", COMMENT_CMD,
"	# comment text\n_
A line beginning with '#' is ignored.",
__dbg_cc_SIMPLE, , __dbg_cx_NOOP]
### condition
		__dbg_g_cmd["condition"] := ["condition", CONDITION_CMD,
"	condition brkpt expr\n_
Attaches a condition to breakpoint 'brkpt'. The expression 'expr' must\n_
succeed for a break to occur.",
__dbg_cc_condition, , __dbg_cx_condition]
### do
		__dbg_g_cmd["do"] := ["do", DO_CMD,
"	do brkpt [<filename]\n_
Attaches commands to the breakpoint identified by 'brkpt'. The commands\n_
are entered interactively (terminate with 'end'), or are read from a file.",
__dbg_cc_do, , __dbg_cx_do]
### end
		__dbg_g_cmd["end"] := ["end", END_CMD,
"	end\n_
Terminates a macro definition.",
__dbg_cc_end, , __dbg_cx_NOOP]
### eprint
		__dbg_g_cmd["eprint"] := ["eprint", EPRINT_CMD,
"	eprint expr\n_
Prints image of every value generated by expression 'expr'.",
__dbg_cc_eprint, , __dbg_cx_eprint]
### fprint
		__dbg_g_cmd["fprint"] := ["fprint", FPRINT_CMD,
"	fprint format-expr {; expr}\n_
Formatted print. The first expression must evaluate to a format string,\n_
possibly containing placeholders (%1, %2, etc). The result of evaluating\n_
remaining expressions will be substituted for the placeholders. You must\n_
make sure their values are string-convertible (the 'image' function is\n_
available). Insert '\\n' in format string to obtain newline.",
__dbg_cc_print, , __dbg_cx_fprint]
### frame
		__dbg_g_cmd["frame"] := ["frame", FRAME_CMD,
"	frame [n]\n_
Shows a call frame. 'n' may be an integer frame number (obtained from\n_
the 'where' command), or may be omitted. Omitted frame number = current\n_
procedure. Negative frame number is relative to the current procedure.\n_
The command prints the image of all local variables.",
__dbg_cc_frame, , __dbg_cx_frame]
### goon
		__dbg_g_cmd["goon"] := ["goon", GOON_CMD,
"	goon [nobreak]\n_
Resumes execution. With 'nobreak': lets the program run to completion\n_
without breaking.",
__dbg_cc_goon, , __dbg_cx_goon]
### help
		__dbg_g_cmd["help"] := ["help", HELP_CMD,
"	help [command]\n_
Displays information. Prints short command description if command keyword\n_
is included. Otherwise prints list of available commands.",
__dbg_cc_help, , __dbg_cx_help]
### ignore
		__dbg_g_cmd["ignore"] := ["ignore", IGNORE_CMD,
"	ignore brkpt count\n_
Sets the ignore counter of breakpoint 'brkpt'. 'count' may be a positive\n_
or negative integer. It replaces the previous ignore counter value.\n_
A breakpoint with a non-zero ignore count does not cause a break, but the\n_
ignore count is decremented by 1.",
__dbg_cc_ignore, , __dbg_cx_ignore]
### info
		__dbg_g_cmd["info"] := ["info", INFO_CMD,
"	info breakpoint [brkpt]\n_
Prints info about breakpoint identified by 'brkpt', or about all\n_
breakpoints if 'brkpt' is omitted.\n_
\	info echo\n_
Prints the current 'echo' file name, if any.\n_
\	info files\n_
Prints names of source files with tweaked ucode in this program.\n_
\	info globals [substr]\n_
Prints names of global variables. The optional substring limits output\n_
to global names containing this substring.\n_
\	info locals\n_
Prints names of all local variables in current procedure.\n_
\	info macros\n_
Prints names of all currently defined macros.\n_
\	info trace\n_
Prints the current value of &trace.\n_
\	info version\n_
Prints itweak and runtime versions.",
__dbg_cc_info, , __dbg_cx_info]
### macro
		__dbg_g_cmd["macro"] := ["macro", MACRO_CMD,
"	macro name\n_
Creates a new command called 'name'. The command will consist of\n_
subsequent lines, up to a line containing 'end'.\n_
\	macro name <filename\n_
As above, but macro definition read from a file. 'end' command optional.",
__dbg_cc_macro, , __dbg_cx_macro]
### next
		__dbg_g_cmd["next"] := ["next", NEXT_CMD,
"	next [count]\n_
Resumes execution as if a breakpoint were defined on every line. An\n_
ignore count may be included (see the 'ignore' command). A break\n_
caused by 'next' is considered breakpoint 0 (zero), even if an\n_
ordinary breakpoint is in effect on the same line. The 'condition',\n_
'do', 'info' commands accept 0 as a breakpoint number.",
__dbg_cc_next, , __dbg_cx_next]
### print
		__dbg_g_cmd["print"] := ["print", PRINT_CMD,
"	print expr {; expr}\n_
Evaluates and print image of expression(s). Only the first value from\n_
each expression is printed. '&fail' printed if an expression fails.",
__dbg_cc_print, , __dbg_cx_print]
### set
		__dbg_g_cmd["set"] := ["set", SET_CMD,
"	set echo filename\n_
Starts echoing output to a file.\n_
\	set prelude [<file]\n_
Defines a macro to be exeucted at breaks. The default prelude is\n_
\	fprint \"[%1] %2 (%3:%4)\\n\";&bp;&proc;&file;&line\n_
It prints breakpoint number, procedure name, source file name, and\n_
line number.\n_
\	set postlude [<file]\n_
Defines a macro to be executed when resuming execution. The default\n_
postlude does nothing.",
__dbg_cc_set, , __dbg_cx_set]
### source
		__dbg_g_cmd["source"] := ["source", SOURCE_CMD,
"	source filename\n_
Reads commands from a file. Takes effect immediately when used in a macro\n_
definition.",
__dbg_cc_source, , __dbg_cx_NOOP]
### stop
		__dbg_g_cmd["stop"] := ["stop", STOP_CMD,
"	stop\n_
Stops the program and terminates the debugging session.",
__dbg_cc_SIMPLE, , __dbg_cx_stop]
### trace
		__dbg_g_cmd["trace"] := ["trace", TRACE_CMD,
"	trace count\n_
Sets the value of the Icon trace counter (&trace) to 'count'.",
__dbg_cc_trace, , __dbg_cx_trace]
### where
		__dbg_g_cmd["where"] := ["where", WHERE_CMD,
"	where\n_
Prints the call chain leading up to the current procedure.\n_
Displays frame numbers which may be used by the 'frame' command.",
__dbg_cc_SIMPLE, , __dbg_cx_where]
end

############### EXPRESSIONS ##############################
#
# Parses a fair subset of Icon expressions.
# Compiles them into a linear post-fix representation.
# Evaluates.
# Somewhat adapted to the debugging environment, but
# generally useful with small modifications.
#
##########################################################

#
#-------------- Expression management constants ----------
#

$define IDENT_T		1
$define INTEGER_T	2
$define STRING_T	3
$define SPECIAL_T	4
$define FIELD_T		5
$define LIST_T		6
$define EXPR_T		8
$define ELIST_T		9
$define UNOP_T		10
$define BINOP_T		11
$define TEROP_T		12
$define INVOKE_T	13

$define NOTN_OP		901
$define ISN_OP		902
$define SIZ_OP		903
$define BNG_OP		904
$define NEG_OP		905

$define ALT_OP		1501
$define CNJ_OP		1401
# N -- numerical comparison.
$define NEQ_OP		1301
$define NNE_OP		1302
$define NLE_OP		1303
$define NLT_OP		1304
$define NGE_OP		1305
$define NGT_OP		1306
# L -- lexical comparison.
$define LLT_OP		1307
$define LLE_OP		1308
$define LEQ_OP		1309
$define LNE_OP		1310
$define LGE_OP		1311
$define LGT_OP		1312
$define EQ_OP		1313
$define NE_OP		1314
$define ADD_OP		1201
$define SUBTR_OP	1202
$define UNION_OP	1203
$define DIFF_OP		1204
$define CAT_OP		1101
$define LCAT_OP		1102
$define MUL_OP		1001
$define DIV_OP		1002
$define REM_OP		1003
$define ISCT_OP		1004
$define EXP_OP		1001
$define INVOKE_OP	801
$define SSC_OP		802
$define PART_OP		803
$define FLD_OP		804

$define CLOCK_SP	1
$define CURRENT_SP	2
$define DATE_SP		3
$define DATELINE_SP	4
$define POS_SP		5
$define REGIONS_SP	6
$define SOURCE_SP	7
$define STORAGE_SP	8
$define SUBJECT_SP	9
$define VERSION_SP	10

$define BREAK_SP	101
$define FILE_SP		102
$define LEVEL_SP	103
$define LINE_SP		104
$define PROC_SP		105
$define TRACE_SP	106

#
#-------------- Expression parsing ----------------------		
#

procedure __dbg_e_compile (str)
# Compiles one or more expressions separated by a semicolon.
# 'str' must be the candidate expression (string).
# RETURNS a list of lists where each sublist has the following components:
# (1) The compiled expression in postfix representation (list).
# This representation can be used with the '__dbg_e_eval' procedure.
# (2) The expression source string.
# FAILS on conflict.
# SIDE EFFECT: Assigns a message (string) to '__dbg_ge_message' on conflict;
# assigns &null otherwise.
local elist, res1, res2, pos1, pos2
	elist := []
	# Parse the expression(s).
	str ? repeat {
		pos1 := &pos
		(res1 := 1(__dbg_e_expr(), pos2:= &pos, __dbg_e_ws (),
			(__dbg_fpos (0) | __dbg_fany (';')))) | {
			__dbg_ge_message := "Expression syntax error."
			fail
			}
		# Linearize, convert to postfix.
		__dbg_ge_message := &null
		res2 := []
		__dbg_e_ecode (res1, res2)
		# Check for conflict.
		/__dbg_ge_message | fail
		__dbg_fput (elist, [res2, str[pos1:pos2]])
		if __dbg_fpos (0) then
			break
		else {
			__dbg_fmove (1)
			__dbg_e_ws ()
			}
		}
	return elist
end

procedure __dbg_e_expr()
	__dbg_ftab (__dbg_fmany (' \t'))
	suspend [__dbg_e_term()] |
 		([__dbg_e_term(), __dbg_e_bin()] ||| __dbg_e_expr())
end

procedure __dbg_e_term()
	__dbg_ftab (__dbg_fmany (' \t'))
	suspend [__dbg_e_factor()] |
		[__dbg_e_factor(), __dbg_e_form()] |
		[__dbg_e_un(), __dbg_e_factor()] |
		[__dbg_e_un(), __dbg_e_factor(), __dbg_e_form()]
end
	
procedure __dbg_e_form()
	__dbg_ftab (__dbg_fmany (' \t'))
	suspend 2(=".", [FLD_OP, [FIELD_T, __dbg_e_idf()]]) |
		2(="[", [SSC_OP, __dbg_e_expr()], ="]") |
		2(="(", [INVOKE_OP, __dbg_e_elist()], =")") |
		2(="[", [PART_OP, __dbg_e_expr(),
			3(__dbg_e_ws(), =":", __dbg_e_expr())], ="]") |
 		(2(=".", [FLD_OP, [FIELD_T, __dbg_e_idf()]]) ||| __dbg_e_form()) |
		(2(="[", [SSC_OP, __dbg_e_expr()], ="]") ||| __dbg_e_form()) |
		(2(="(", [INVOKE_OP, __dbg_e_elist()], =")") ||| __dbg_e_form()) |
		(2(="[", [PART_OP, __dbg_e_expr(),
			3(__dbg_e_ws(), =":", __dbg_e_expr())], ="]") |||
			__dbg_e_form())
end

procedure __dbg_e_elist()
	__dbg_ftab (__dbg_fmany (' \t'))
	suspend [] |
		[__dbg_e_expr()] |
		[__dbg_e_expr()] ||| 3(__dbg_e_ws(), =",", __dbg_e_elist())
end

procedure __dbg_e_factor()
	__dbg_ftab (__dbg_fmany (' \t'))
	suspend [IDENT_T, __dbg_e_idf()] |
		[INTEGER_T, __dbg_e_ilit()] |
		[STRING_T, __dbg_e_slit()] |
		[SPECIAL_T, (="&", __dbg_e_idf())] |
		2(="(", [EXPR_T, __dbg_e_expr()], __dbg_e_ws(), =")") |
		2(="[", [LIST_T, __dbg_e_elist()], __dbg_e_ws(), ="]")
end

procedure __dbg_e_idf()
static char1, char2
initial {
	char1 := &ucase ++ &lcase ++ '_'
	char2 := char1 ++ &digits
	}
	suspend __dbg_ftab (__dbg_fmany (char1)) || (__dbg_ftab (__dbg_fmany (char2)) | "")
end

procedure __dbg_e_ilit()
	suspend __dbg_ftab (__dbg_fmany (&digits))
end

procedure __dbg_e_strend()
static signal, nonsignal
initial {
	signal := '\"\\'
	nonsignal := ~signal
	}
	suspend 2(="\"", "") |
		1(__dbg_e_stresc(), ="\"") |
		(__dbg_e_stresc() || __dbg_ftab (__dbg_fmany (nonsignal)) || __dbg_e_strend()) |
		(__dbg_e_stresc() || __dbg_e_strend())
end

procedure __dbg_e_stresc()
	suspend (="\\n", "\n") |
		(="\\t", "\t") |
		(="\\r", "\r") |
		(="\\", __dbg_fmove (1))
end

procedure __dbg_e_slit()
static signal, nonsignal
initial {
	signal := '\"\\'
	nonsignal := ~signal
	}
	suspend 2(="\"",
		(__dbg_ftab (__dbg_fmany (nonsignal)) || __dbg_e_strend()) | __dbg_e_strend())
end

procedure __dbg_e_un()
# Sequence of unary operators.
# Always succeeds.
# NOTE: Assumes no space between operators.
static unop
initial unop := '\\/*!-'
	__dbg_ftab (__dbg_fmany (' \t'))
	suspend [UNOP_T, __dbg_ftab (__dbg_fmany (unop))]
end

procedure __dbg_e_bin()
# Binary operators.
static optab
initial {
	# Table of operators.
	# Operators are coded as decimal integers where the hundreds
	# digit defines precedence.
	optab := table()
	optab["|"] :=		ALT_OP
	optab["&"] :=		CNJ_OP
	optab["="] :=		NEQ_OP
	optab["~="] :=		NNE_OP
	optab["<="] :=		NLE_OP
	optab["<"] :=		NLT_OP
	optab[">="] :=		NGE_OP
	optab[">"] :=		NGT_OP
	optab["<<"] :=		LLT_OP
	optab["<<="] :=		LLE_OP
	optab["=="] :=		LEQ_OP
	optab["~=="] :=		LNE_OP
	optab[">>="] :=		LGE_OP
	optab[">>"] :=		LGT_OP
	optab["==="] :=		EQ_OP
	optab["~==="] :=	NE_OP
	optab["+"] :=		ADD_OP
	optab["-"] :=		SUBTR_OP
	optab["++"] :=		UNION_OP
	optab["--"] :=		DIFF_OP
	optab["||"] :=		CAT_OP
	optab["|||"] :=		LCAT_OP
	optab["*"] :=		MUL_OP
	optab["/"] :=		DIV_OP
	optab["%"] :=		REM_OP
	optab["**"] :=		ISCT_OP
	optab["^"] :=		EXP_OP
	}
	__dbg_ftab (__dbg_fmany (' \t'))
	suspend \optab[__dbg_fmove (3)] |
		\optab[__dbg_fmove (2)] |
		\optab[__dbg_fmove (1)] |
		\optab[=("~===")]
end

procedure __dbg_e_ws()
# Removes optional white space.
# The point is that it always succeeds.
	__dbg_ftab (__dbg_fmany (' \t'))
	return 1
end

#-------------- Linearization ----------------------		

procedure __dbg_e_ecode (ex, res)
# 'Evaluates' the list resulting from pattern matching.
# Produces a single list with everything in postfix order.
# 'ex' must be an expression in the form that '__dbg_e_compile' generates.
# 'res' must be an (empty) list where the expression elements are to
# be inserted.
# Always FAILS.
# SIDE EFFECT: Adds elements to 'res'.
# Assigns a message string to '__dbg_ge_message' on conflict.
local opnd, oprt, op_stack
	if *ex = 1 then
		__dbg_e_tcode (ex[1], res)
	else {
		op_stack := []
		opnd := create !ex
		__dbg_e_tcode (@opnd, res)
		while oprt := @opnd do {
			while (op_stack[1]/100) <= (oprt/100) do
				__dbg_fput (res, __dbg_e_proc ([BINOP_T, __dbg_fpop (op_stack),]))
			__dbg_fpush (op_stack, oprt)
			__dbg_e_tcode (@opnd, res)
			}
		while __dbg_fput (res, __dbg_e_proc ([BINOP_T, __dbg_fpop (op_stack),]))
		}
end

procedure __dbg_e_tcode (tm, res)
# Disentangles a term.
local comp, unary
static special, unop
initial {
	special := __dbg_ftable ()
	# The 'normal' keywords.
	special["clock"] :=	CLOCK_SP
	special["current"] :=	CURRENT_SP
	special["date"] :=	DATE_SP
	special["dateline"] :=	DATELINE_SP
	special["pos"] :=	POS_SP
	special["regions"] :=	REGIONS_SP
	special["source"] :=	SOURCE_SP
	special["storage"] :=	STORAGE_SP
	special["subject"] :=	SUBJECT_SP
	special["trace"] :=	TRACE_SP
	special["version"] :=	VERSION_SP
	
	# The special keywords.
	special["bp"] :=BREAK_SP
	special["breakpoint"] :=BREAK_SP
	special["file"]	:=	FILE_SP
	special["level"] :=	LEVEL_SP
	special["line"] :=	LINE_SP
	special["proc"] :=	PROC_SP

	unop := __dbg_ftable ()
	unop["\\"] :=	NOTN_OP
	unop["/"] :=	ISN_OP
	unop["*"] :=	SIZ_OP
	unop["!"] :=	BNG_OP
	unop["-"] :=	NEG_OP
	}
	every comp := !tm do case comp[1] of {
	UNOP_T:	unary := comp	# Save for later.
	INTEGER_T: {
		comp[2] := __dbg_finteger (comp[2])
		__dbg_fput (res, comp)
		}
	SPECIAL_T: {
		if comp[2] := \special[comp[2]] then
			__dbg_fput (res, comp)
		else
			__dbg_ge_message := "'" || comp[2] ||
				"': unrecognized special identifier."
		}
	EXPR_T:		__dbg_e_ecode (comp[2], res)
	LIST_T:	{
		every __dbg_e_ecode (!comp[2], res)
		__dbg_fput (res, [LIST_T, *comp[2]])
		}
	(FLD_OP | SSC_OP | INVOKE_OP | PART_OP) :
		__dbg_e_fcode (comp, res)
	default:	__dbg_fput (res, comp)
	# This includes: IDENT_T, STRING_T
	}
	every __dbg_fput (res, __dbg_e_proc ([UNOP_T, unop[!__dbg_freverse ((\unary)[2])],]))
end

procedure __dbg_e_fcode (fm, res)
# Disentangles a form.
# The operators have the same precedence; stack not needed.
local comp, opnd, oprt
	comp := create !fm
	while oprt := @comp do {
		opnd := @comp	# There is at least one operand.
		case oprt of {
		FLD_OP:	{
			__dbg_fput (res, opnd)
			__dbg_fput (res, [BINOP_T, oprt, __dbg_e_field])
		}
		SSC_OP:	{
			__dbg_e_ecode (opnd, res)
			__dbg_fput (res, [BINOP_T, oprt, __dbg_fproc ("[]", 2)])
		}
		INVOKE_OP: {
			every __dbg_e_ecode (!opnd, res)
			__dbg_fput (res, [INVOKE_T, *opnd])
		}
		PART_OP: {
			__dbg_e_ecode (opnd, res)
			__dbg_e_ecode (@comp, res)
			__dbg_fput (res, [TEROP_T, oprt, __dbg_fproc ("[:]", 3)])
		}
		default: __dbg_ge_message := __dbg_fimage (oprt) || ": weird operator."
		}
		}
end

procedure __dbg_e_proc (op_d)
# 'op_d' must be an operator descriptor (list(3)).
# RETURNS the descriptor with the 3rd component filled in by a
# procedure/function.
static opt
initial {
	opt := __dbg_ftable ()
	opt[NOTN_OP] :=		__dbg_fproc ("\\", 1)
	opt[ISN_OP] :=		__dbg_fproc ("/", 1)
	opt[SIZ_OP] :=		__dbg_fproc ("*", 1)
	opt[BNG_OP] :=		__dbg_fproc ("!", 1)
	opt[NEG_OP] :=		__dbg_fproc ("-", 1)
	opt[ALT_OP] :=		__dbg_e_alt
	opt[CNJ_OP] :=		__dbg_e_cnj
	opt[NEQ_OP] :=		__dbg_fproc ("=", 2)
	opt[NNE_OP] :=		__dbg_fproc ("~=", 2)
	opt[NLE_OP] :=		__dbg_fproc ("<=", 2)
	opt[NLT_OP] :=		__dbg_fproc ("<", 2)
	opt[NGE_OP] :=		__dbg_fproc (">=", 2)
	opt[NGT_OP] :=		__dbg_fproc (">", 2)
	opt[LLT_OP] :=		__dbg_fproc ("<<", 2)
	opt[LLE_OP] :=		__dbg_fproc ("<<=", 2)
	opt[LEQ_OP] :=		__dbg_fproc ("==", 2)
	opt[LNE_OP] :=		__dbg_fproc ("~==", 2)
	opt[LGE_OP] :=		__dbg_fproc (">>=", 2)
	opt[LGT_OP] :=		__dbg_fproc (">>", 2)
	opt[EQ_OP] :=		__dbg_fproc ("===", 2)
	opt[NE_OP] :=		__dbg_fproc ("~===", 2)
	opt[ADD_OP] :=		__dbg_fproc ("+", 2)
	opt[SUBTR_OP] :=	__dbg_fproc ("-", 2)
	opt[UNION_OP] :=	__dbg_fproc ("++", 2)
	opt[DIFF_OP] :=		__dbg_fproc ("--", 2)
	opt[CAT_OP] :=		__dbg_fproc ("||", 2)
	opt[LCAT_OP] :=		__dbg_fproc ("|||", 2)
	opt[MUL_OP] :=		__dbg_fproc ("*", 2)
	opt[DIV_OP] :=		__dbg_fproc ("/", 2)
	opt[REM_OP] :=		__dbg_fproc ("%", 2)
	opt[ISCT_OP] :=		__dbg_fproc ("**", 2)
	opt[EXP_OP] :=		__dbg_fproc ("^", 2)
	opt[SSC_OP] :=		__dbg_fproc ("[]", 2)
	opt[PART_OP] :=		__dbg_fproc ("[:]", 2)
	opt[FLD_OP] :=		__dbg_e_field
	}
	op_d[3] := opt[op_d[2]]
	return op_d
end

#-------------- Evaluation ----------------------		

procedure __dbg_e_eval (expr)
# Evaluates a compiled expression.
# 'expr' must be an expression using the representation created by
# '__dbg_e_compile' (list).
# GENERATES all expression values.
# SIDE EFFECT: Assigns a message (string) to '__dbg_ge_message' on conflict;
# assigns &null otherwise.
local val
	__dbg_ge_message := &null
	&error := -1
	every val := __dbg_e_eval1 (expr, []) do {
		&error := 0
		suspend val
		__dbg_ge_message := &null
		&error := -1
		}
	if &error < -1 then
		__dbg_ge_message := "Error number " || &errornumber || ": " ||
		&errortext || "." ||
		(("\nOffending value: " || __dbg_fimage (\&errorvalue) || ".") | "")
	&error := 0
end

procedure __dbg_e_alt (opnd1, opnd2)
# Our version of alternation.
	suspend (opnd1 | opnd2)
end

procedure __dbg_e_cnj (opnd1, opnd2)
# Our version of conjunction.
	suspend (opnd1 & opnd2)
end

procedure __dbg_e_field (opnd1, opnd2)
# Record field access.
# Any better way to determine if a value is a record of any type?
static builtin
initial {
	builtin := __dbg_ftable ()
	builtin["co-expression"] := 1
	builtin["cset"] := 1
	builtin["file"] := 1
	builtin["integer"] := 1
	builtin["list"] := 1
	builtin["null"] := 1
	builtin["procedure"] := 1
	builtin["real"] := 1
	builtin["set"] := 1
	builtin["string"] := 1
	builtin["table"] := 1
	}
	if \builtin[__dbg_ftype (opnd1)] then {
		__dbg_ge_message := "Record expected; found " || __dbg_fimage (opnd1)
		fail
		}
	suspend opnd1[opnd2]
end

procedure __dbg_e_ident (idf)
# Evaluates an identifier.
local val
	(val := ((__dbg_ge_singular ~=== __dbg_g_local[idf]) | variable (idf))) | {
		__dbg_ge_message := "Identifier '" || idf || "' not visible."
		fail
		}
	suspend val
end

procedure __dbg_e_special (sp_code)
# Evaluates a special identifier.
	suspend case sp_code of {
	# Regular Icon keyword variables.
	CLOCK_SP:	&clock
	CURRENT_SP:	&current
	DATE_SP:	&date
	DATELINE_SP:	&dateline
	POS_SP:		&pos
	REGIONS_SP:	&regions
	SOURCE_SP:	&source
	STORAGE_SP:	&storage
	SUBJECT_SP:	&subject
	VERSION_SP:	&version
	# Special keywords.
	BREAK_SP:	(\__dbg_g_where[WHERE_BRKP])[BRKP_ID]
	FILE_SP:	__dbg_g_where[WHERE_FILE]
	LEVEL_SP:	__dbg_g_level
	LINE_SP:	__dbg_g_where[WHERE_LINE]
	PROC_SP:	__dbg_g_where[WHERE_PROC]
	TRACE_SP:	__dbg_g_trace
	default: {
		__dbg_ge_message := __dbg_fimage (sp_code) ||
			": weird special identifier code."
		fail
		}
	}
end

procedure __dbg_e_eval1 (expr, stack)
# Evaluates an expression.
# 'stack' must be the current evaluation stack (list).
# The procedure is recursive; the initial invocation must supply an
# empty list.
local comp
	(comp := expr[1]) | while suspend __dbg_fpop (stack) | fail
	suspend __dbg_e_eval1 (expr[2:0], case comp[1] of {
	IDENT_T:	stack ||| [__dbg_e_ident (comp[2])]
	SPECIAL_T:	stack ||| [__dbg_e_special (comp[2])]
	LIST_T:		stack[1:-comp[2]] ||| [stack[-comp[2]:0]]
	UNOP_T:		stack[1:-1] ||| [comp[3](stack[-1])]
	BINOP_T:	stack[1:-2] ||| [comp[3]!stack[-2:0]]
	TEROP_T:	stack[1:-3] ||| [comp[3]!stack[-3:0]]
	INVOKE_T:	stack[1:-(comp[2]+1)] |||
				[stack[-(comp[2]+1)]!stack[-comp[2]:0]]
	default:	stack ||| [comp[2]]
	})
end