hexicon-compiler 0.3.0

The Hexicon compiler: source text to a program image
Documentation
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
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
import hexad;

/* ------------------------------------------------------------------------ */
/*
 *   Temporary scaffolding for the game world.  This gives us information
 *   on scope, pronoun antecedents, and other information the parser needs
 *   from the game world.  
 */
World: PreinitObject
    /*
     *   Get the list of objects in scope 
     */
    scope()
    {
        local s = scope_;

        if (s == nil)
            scope_ = s = Q.scopeList(now.player);

        return s;
    }

    /* cached scope list */
    scope_ = nil

    /* 
     *   A list of all Mentionables in the game, useful for building scope lists
     *   for resolving Topics.
     */
    universalScope = nil
    
    buildUniversalScope()
    {
        local vec = new Vector(100);
        forEachInstance(Mentionable, {o: vec.append(o) });
        universalScope = vec.toList;
    }
    
    execute()
    {
        buildUniversalScope();
    }
    
    
;


/* ------------------------------------------------------------------------ */
/*
 *   Parser is the class that implements the main parsing procedure, namely
 *   taking a line of text from the player, figuring out what it means, and
 *   executing it.
 *   
 *   The conventional IF parsing loop simply consists of reading a line of
 *   text from the player, calling Parser.parse() on the string, and
 *   repeating.
 *   
 *   In most cases you'll just need a single Parser instance.  The Parser
 *   object keeps track of unfinished commands, such as when we need to ask
 *   for disambiguation help or for a missing object.  If for some reason
 *   you want to keep multiple sets of this kind of state (reading input
 *   from more than one player, for example), you can create as many Parser
 *   instances as needed.  
 */
class Parser: object
    /*
     *   Auto-Look: Should we treat an empty command line (i.e., the user
     *   just presses Return) as a LOOK AROUND command?
     *   
     *   The traditional handling since the Infocom era has always been to
     *   treat an empty command line as a parsing error, and display an
     *   error message along the lines of "I beg your pardon?".  Given that
     *   an empty command line has no conflicting meaning, though, we
     *   *could* assign it a meaning.
     *   
     *   But what meaning should that be?  A blank line is the simplest
     *   possible command for a player to enter, so it would make sense to
     *   define it as some very commonly used command.  It's also fairly
     *   easy to enter a blank line accidentally (which is partly why the
     *   traditional reply is an error message), so the command should be
     *   benign - it shouldn't be a problem to enter it unintentionally.
     *   It can't be anything with parallel verbs, like NORTH, since then
     *   there'd be no good reason to pick NORTH instead of, say, SOUTH.
     *   Finally, it has to be intransitive, since it obviously won't
     *   involve an object name.  The obvious candidates that fit all of
     *   these criteria are LOOK and INVENTORY.  LOOK is probably the more
     *   useful and the more frequently used of the two, so it's the one we
     *   choose by default.
     *   
     *   If this property is set to true, we'll perform a LOOK AROUND
     *   command when the player enters a blank command line.  If nil,
     *   we'll show an error message.  
     */
    autoLook = true

    /*
     *   Default Actions: Should we treat a command line that consists entirely
     *   of a single noun phrase to be a "Default Action" on the named object?
     *   The precise meaning of the default action varies by object.  For most
     *   objects, it's EXAMINE.  For locations, it's GO TO.
     *
     *   We make the default value true, but it can be set to nil if setting it to true results in
     *   some odd parser behavior.
     */
    
    defaultActions = true

    /*
     *   Should we attempt automatic spelling correction?  If this is true, whenever a command
     *   fails, we'll check for a word that we don't recognize; if we find one, we'll try applying
     *   spelling correction to see if we can come up with a working command.
     *
     *   Our spelling correction algorithm is designed to be quite conservative.  In particular, we
     *   generally limit candidates for "correct" words to the vocabulary for objects that are
     *   actually in scope, which avoids revealing the existence of objects that haven't been seen
     *   yet; and we only apply a correction when it yields a command that parses and resolves
     *   correctly.  When we can't correct a command and get something resolvable, we don't even
     *   mention that we tried.  This avoids the bizarre, random guesses at "corrections" that often
     *   show up in other applications, and more importantly avoids giving away information that the
     *   player shouldn't know yet.
     *
     *   We set this to true by default, in an attempt to reduce the player's typing workload by
     *   automatically correcting simple typos when possible.  If for some reason the spelling
     *   corrector is problematic in a particular game, you can disable it by setting this property
     *   to nil.
     *
     *   As an experiment, change the default value to be nil when we're in a conversation and true
     *   otherwise, since over-zealous spelling corrections can be particularly troublesome in a
     *   conversational context.
     */
    autoSpell = (now.player.currentInterlocutor == nil)

    /*
     *   Maximum spelling correction time, in milliseconds.  The spelling
     *   correction process is iterative, and each iteration involves a new
     *   parsing attempt.  On a fast machine this doesn't tend to be
     *   noticeable, but it's conceivable that a pathological case could
     *   involve a large number of attempts that could be noticeably slow
     *   on an older machine.  To avoid stalling the game while we
     *   overanalyze the spelling possibilities, we set an upper bound to
     *   the actual elapsed time for spelling correction.  Each time we
     *   consider a new correction candidate, we'll check the elapsed time,
     *   and abort the process if it exceeds this limit.  Note that this
     *   limit doesn't limit the parsing time itself - we'll never
     *   interrupt that mid-stream.  
     */
    spellTimeLimit = 250

    /*
     *   When the parser doesn't recognize a word, should it say so?  If
     *   this property is set to true, when parsing fails, we'll scan the
     *   command line for a word that's not in the dictionary and show a
     *   message such as "I don't know the word <foo>."  If this property
     *   is nil, the parser will instead simply say that it doesn't
     *   recognize the syntax, or that the object in question isn't
     *   present, without saying specifically which word wasn't recognized,
     *   or indeed even admitting that there was such a thing.
     *   
     *   There are two schools of thought on this, both concerned with
     *   optimizing the user experience.
     *   
     *   The first school holds that the parser's job is to be as helpful
     *   as possible.  First and foremost, that means we should understand
     *   the user's input as often as possible.  But when we can't, it
     *   means that we should be do our best to explain what we didn't
     *   understand, to help the user formulate a working command next
     *   time.  In the case of a word the parser doesn't recognize, we can
     *   be pretty sure that the unknown word is the reason we can't
     *   understand the input.  The best way to help the user correct the
     *   problem is to let them know exactly which word we didn't know,
     *   rather than make them guess at what we didn't understand.  This is
     *   the way the classic Infocom games worked.
     *   
     *   The second school holds that the user's overriding interest is
     *   maintaining suspension of disbelief, and that the parser should do
     *   its best not to interfere with that.  A major aspect of this in IF
     *   the illusion that the game world is as boundless as the real
     *   world.  Missing dictionary words tend to break this illusion: if
     *   the user types EXAMINE ZEBRA, and the parser replies that it
     *   doesn't know the word "zebra", we've suddenly exposed a limit of
     *   the game world.  If we instead play coy and simply say that
     *   there's no zebra currently present, we allow the player to imagine
     *   that a zebra might yet turn up.  This is the way Inform games
     *   typically work.
     *   
     *   Each approach has its advantages and disadvantages, adherents and
     *   detractors, and it seems that neither one is objectively "right".
     *   It comes down to taste.  But there seems to be a clear preference
     *   among the majority of players in the modern era for the second
     *   approach.  The key factor is probably that typical IF commands are
     *   so short that it's easy enough to spot a typo without help from
     *   the parser, so the clarity benefits of "unknown word" messages
     *   seem considerably outweighed by the harm they do to the illusion
     *   of boundlessness.  So, our default is the second option, playing
     *   coy.  
     */
    showUnknownWords = nil

    /*
     *   The character a command was addressed to, from the words before its
     *   first comma, or nil: the one character in the player's scope whom
     *   those words name, leaving out addresseeSkipWords (the language's
     *   articles).
     */
    addresseeOf(toks)
    {
        local comma = toks.indexWhich({ t: getTokVal(t) == ',' });
        if (comma == nil || comma == 1 || now.player == nil)
            return nil;

        local words = toks.sublist(1, comma - 1).mapAll({ t: getTokVal(t) })
            .subset({ w: addresseeSkipWords.indexOf(w) == nil });
        if (words.length() == 0)
            return nil;

        local found = Q.scopeList(now.player).toList().subset(
            { o: o.ofKind(Actor) && o != now.player && o.matchName(words) });
        return found.length() == 1 ? found[1] : nil;
    }

    addresseeSkipWords = []

    /*
     *   Parse and execute a command line.  This is the main parsing
     *   routine.  We take the text of a command line, parse it against the
     *   grammar defined in the language module, resolve the noun phrases
     *   to game-world objects, and execute the action.  If the command
     *   line has more than one verb phrase, we repeat the process for each
     *   one.
     *   
     *   'str' is the text of the command line, as entered by the player.
     */
    parse(str)
    {
        /* Make sure our current SpecialVerb is set to nil before we start parsing a new command. */
        specialVerbMgr.currentSV = nil;
        
        /* tokenize the input */
        local toks;
        try
        {
            /* run the command tokenizer over the input string */
            toks = cmdTokenizer.tokenize(str);
            
            /* Dispose of any unwanted terminal punctuation */
            while(toks.length > 0 && getTokType(toks[toks.length]) == tokPunct)
                toks = toks.removeElementAt(toks.length);
            
        }
        catch (TokErrorNoMatch err)
        {
            /* 
             *   The tokenizer found a character (usually a punctuation
             *   mark) that doesn't fit any of the token rules.  
             */
            showMsg(token error, 'I don\'t understand the punctuation {1}',
                 err.curChar_);

           
            
            
            /* give up on the parse */
            return;
        }

        /* 
         *   Assume initially that the actor is the player character, but only
         *   if we don't have a question, since if the player is replying to a
         *   question the actor may already have been resolved.
         */
        if(question == nil)
            libGlobal.curActor = now.player;        
        
        /* no spelling corrections have been attempted yet */
        local history = new transient SpellingHistory(self);

        /* we're starting with the first command in the string */
        local firstCmd = true;

        /* parse the tokens */
        try
        {
            /* if there are no tokens, simply perform the empty command */
            if (toks.length() == 0)
            {
                /* 
                 *   this counts as a new command, so forget any previous
                 *   question or typo information 
                 */
                question = nil;
                lastTokens = nil;

                /* process an empty command */
                emptyCommand();

                /* we're done */
                return;
            }

            /* check for an OOPS command */
            local lst = oopsCommand.parseTokens(toks, cmdDict);
            if (lst.length() != 0)
            {
                /* this only works if we have an error to correct */
                local ui;
                if (lastTokens == nil
                    || (ui = spellingCorrector.findUnknownWord(lastTokens))
                        == nil)
                {
                    /* OOPS isn't available - throw an error */
                    throw new CantOopsError();
                }
                
                /* apply the correction, and proceed to parse the result */
                toks = OopsProduction.applyCorrection(lst[1], lastTokens, ui);
            }
            
             /* Update the vocabulary of any game objects with alternating/changing vocab. */
            updateVocab();
            
             /* Allow the specialVerb Manager to adjust our toks */            
            toks = specialVerbMgr.matchSV(toks);  
            
            /*   
             *   Parse each predicate in the command line, until we run out
             *   of tokens.  The beginning of a whole new command line is
             *   definitely the beginning of a sentence, so start parsing
             *   with firstCommandPhrase.  
             */
            for (local root = firstCommandPhrase ; toks.length() != 0 ; )
            {
                /* we don't have a parse list yet */
                local cmdLst = nil;

                /* 
                 *   we haven't found a resolution error in a non-command
                 *   parsing yet 
                 */
                local qErr = nil, defErr = nil;

                /* 
                 *   If we have an outstanding question, and it takes
                 *   priority over interpreting input as a new command, try
                 *   parsing the input against the question.  Only do this
                 *   on the first command on the line - a question answer
                 *   has to be the entire input, so if we've already parsed
                 *   earlier commands on the same line, this definitely
                 *   isn't an answer to a past question.  
                 */
                if (firstCmd && question != nil && question.priority)
                {
                    /* try parsing against the Question */
                    local l = question.parseAnswer(toks, cmdDict);

                    /* if it parsed and resolved, this is our command */
                    if (l != nil && l.cmd != nil)
                        cmdLst = l;

                    /* if it parsed but didn't resolved, note the error */
                    if (l != nil)
                        qErr = l.getResErr();
                }

                /* 
                 *   if the question didn't grab it, try parsing as a whole
                 *   new command against the ordinary command grammar
                 */
                if (cmdLst == nil || cmdLst.cmd == nil)
                {
                    cmdLst = new CommandList(
                        root, toks, cmdDict, { p: new Command(p) });
                }

                /* 
                 *   If we didn't find any resolvable commands, and this is
                 *   the first command, check to see if it's an answer to
                 *   an outstanding query.  We only check this if the
                 *   regular grammar parsing fails, because anything that
                 *   looks like a valid new command overrides a past query.
                 *   This is important because some of the short, common
                 *   commands sometimes can look like noun phrases, so we
                 *   explicitly give preference to interpreting these as
                 *   brand new commands.  
                 */
                if (cmdLst.cmd == nil
                    && firstCmd
                    && question != nil
                    && !question.priority)
                {
                    /* try parsing against the Question */
                    local l = question.parseAnswer(toks, cmdDict);

                    /* if it parsed and resolved, this is our command */
                    if (l != nil && l.cmd != nil)
                        cmdLst = l;

                    /* if it parsed but didn't resolved, note the error */
                    if (l != nil)
                        qErr = l.getResErr();
                }

                /*
                 *   If we don't have a command yet, and this is the first
                 *   command on the line, handle it as a conversational command
                 *   if conversation is in progress; otherwise if default
                 *   actions are enabled, check to see if the command looks like
                 *   a single noun phrase.  If so, handle it as the default
                 *   action on the noun.
                 */
                if (cmdLst.cmd == nil
                    && firstCmd)
                {
                    local l;                   
                    
                    
                    /* 
                     *   If a conversation is in progress parse the command line
                     *   as the single topic object phrase of a Say command,
                     *   provided that the first word on the command line
                     *   doesn't match a possible action.
                     */
                    
                    if(now.player.currentInterlocutor != nil
                       && cmdLst.length == 0 
                       && Q.canTalkTo(now.player,
                                      now.player.currentInterlocutor)
                       && str.find(',') == nil
                       && now.player.currentInterlocutor.allowImplicitSay())
                    {
                         l = new CommandList(
                            topicPhrase, toks, cmdDict,
                            { p: new Command(SayAction, p) });
                        
                        libGlobal.lastCommandForUndo = str;
                        savepoint();
                    }
                    /* 
                     *   If the player char is not in conversation with anyone,
                     *   and the first word of the command doesn't match a possible
                     *   command verb, then try parsing the command line as a
                     *   single direct object phrase for the DefaultAction verb,
                     *   provided defaultActions are enabled (which they are
                     *   by default).
                     */
                    else if(defaultActions)                                                
                        l = new CommandList(
                            defaultCommandPhrase, toks, cmdDict,
                            { p: new Command(p) });                       
                    
                    
                       
                    /* accept a curable reply */
                    if (l != nil && l.acceptCurable() != nil)
                    {
                        cmdLst = l;
                        
                        /* note any resolution error */
                        defErr = l.getResErr();
                    }
                }
                
                /*
                 *   If we've applied a spelling correction, and the
                 *   command match didn't consume the entire input, make
                 *   sure what's left of the input has a valid parsing as
                 *   another command.  This ensures that we don't get a
                 *   false positive by excessively shortening a command,
                 *   which we can sometimes do by substituting a word like
                 *   "then" for another word.  
                 */
                if (cmdLst.length() != nil
                    && history.hasCorrections())
                {
                    /* get the best available parsing */
                    local c = cmdLst.getBestCmd();

                    /* if it doesn't use all the tokens, check what's left */
                    if (c != nil && c.tokenLen < toks.length())
                    {
                        /* try parsing the next command */
                        local l = commandPhrase.parseTokens(
                            c.nextTokens, cmdDict);

                        /* 
                         *   if that didn't work, invalidate the command by
                         *   substituting an empty command list 
                         */
                        if (l.length() == 0)
                            cmdLst = new CommandList();
                    }
                }
                
                /* 
                 *   If we didn't find a parsing at all, it's a generic "I
                 *   don't understand" error.  If we found a parsing, but
                 *   not a resolution, reject it if it's a spelling
                 *   correction.  We only want completely clean spelling
                 *   corrections, without any errors.
                 */
                if (cmdLst.length() == 0
                    || (history.hasCorrections()
                        && cmdLst.getResErr() != nil
                        && !cmdLst.getResErr().allowOnRespell))
                {
                    /* 
                     *   If we were able to parse the input using one of
                     *   the non-command interpretations, use the
                     *   resolution error from that parsing.  Otherwise, we
                     *   simply can't make any sense of this input, so use
                     *   the generic "I don't understand" error. 
                     */
                    local err = (qErr != nil ? qErr :
                                 defErr != nil ? defErr :
                                 new NotUnderstoodError());
                    
                    /* look for a spelling correction */
                    local newToks = history.checkSpelling(toks, err);
                    if (newToks != nil)
                    {
                        /* parse again with the new tokens */
                        toks = newToks;
                        continue;
                    }

                    /* 
                     *   There's no spelling correction available.  If we've 
                     *   settled on an auto-examine or question error, skip 
                     *   that and go back to "I don't understand" after 
                     *   all.  We don't want to assume Auto-Examine unless we
                     *   actually have something to examine, since we can 
                     *   parse noun phrase grammar out of practically any 
                     *   input.  
                     */
                    if (err is in (defErr, qErr))
                    {
                        /* return to the not-understood error */
                        err = new NotUnderstoodError();
                        
                        /* check spelling again with this error */
                        newToks = history.checkSpelling(toks, err);
                        if (newToks != nil)
                        {
                            /* parse again with the new tokens */
                            toks = newToks;
                            continue;
                        }
                    
                        
                        /* 
                         *   We didn't find any spelling corrections this time
                         *   through.  Since we're rolling back to the
                         *   not-understood error, discard any spelling
                         *   corrections we attempted with other
                         *   interpretations.
                         */
                        history.clear();                   
                    }
                
                    /* fail with the error */
                    throw err;
                }

                /* if we found a resolvable command, execute it */
                if (cmdLst.cmd != nil)
                {
                    /* get the winning Command */
                    local cmd = cmdLst.cmd;
                    
                    /* 
                     *   We next have to ensure that the player hasn't entered
                     *   multiple nouns in a slot that only allows a single noun
                     *   in the grammar. If the player has entered two objects
                     *   like "the bat and the ball" in such a case, the
                     *   badMulti flag will be set on the command object, so we
                     *   first test for that and abort the command with a
                     *   suitable error message if badMulti is not nil (by
                     *   throwing a BadMultiError
                     *
                     *   Unfortunately the badMulti flag doesn't get set if the
                     *   player enters a multiple object as a plural (e.g.
                     *   "bats"), so we need to trap this case too. We do that
                     *   by checking whether there's multiple objects in the
                     *   direct, indirect and accessory object slots at the same
                     *   time as the grammar tag matching the slot in question
                     *   is 'normal', which it is only for a single noun match.
                     */
                     
                    if(cmd && cmd.verbProd != nil &&                        
                        (cmd.badMulti != nil 
                       || (cmd.verbProd.dobjMatch != nil &&
                           cmd.verbProd.dobjMatch.grammarTag == 'normal'
                           && cmd.dobjs.length > 1)
                       ||
                       (cmd.verbProd.iobjMatch != nil &&
                           cmd.verbProd.iobjMatch.grammarTag == 'normal'
                           && cmd.iobjs.length > 1)                          
                        ||
                       (cmd.verbProd.accMatch != nil &&
                           cmd.verbProd.accMatch.grammarTag == 'normal'
                           && cmd.accs.length > 1)
                           ))
                        cmd.cmdErr = new BadMultiError(cmd.np);
                    
                    /* if this command has a pending error, throw it */
                    if (cmd.cmdErr != nil)
                        throw cmd.cmdErr;

                    /* 
                     *   Forget any past question and typo information.
                     *   The new command is either an answer to this
                     *   question, or it's simply ignoring the question; in
                     *   either case, the question is no longer in play for
                     *   future input.  
                     */
                    question = nil;
                    lastTokens = nil;
                    
                    /* note any spelling changes */
                    history.noteSpelling(toks);
                    
                    /* execute the command */
                    cmd.exec();
                    
                    /* start over with a new spelling correction history */
                    history = new transient SpellingHistory(self);
                    
                    /* 
                     *   Set the root grammar production for the next
                     *   predicate.  If the previous command ended the
                     *   sentence, start a new sentence; otherwise, use the
                     *   additional clause syntax. 
                     */
                    root = cmd.endOfSentence
                        ? firstCommandPhrase : commandPhrase;
                    
                    /* we're no longer on the first command in the string */
                    firstCmd = nil;
                    
                    /* go back and parse the remainder of the command line */
                    toks = cmd.nextTokens;
                    continue;
                }

                /*
                 *   We weren't able to resolve any of the parse trees.  If
                 *   one of the errors is "curable", meaning that the
                 *   player can fix it by answering a question, pick the
                 *   first of those, in predicate priority order.
                 *   Otherwise, just pick the first command overall in
                 *   predicate priority order.  In either case, since we
                 *   didn't find any working alternatives, it's time to
                 *   actually show the error and fail the command.  
                 */
                local c = cmdLst.acceptAny();

                /* 
                 *   If the error isn't curable, check for spelling errors,
                 *   time permitting.  Don't bother doing this with a
                 *   curable error, since that will have its own way of
                 *   solving the problem that reflects a better
                 *   understanding of the input than considering it a
                 *   simple typo.  
                 */
                if (!c.cmdErr.curable)
                {
                    /*
                     *   For spelling correction purposes, if this is an
                     *   unmatched noun error, but the command has a misc
                     *   word list and an empty noun phrase, treat this as
                     *   a "not understood" error.  The combination of noun
                     *   phrase errors suggests that we took a word that
                     *   was meant to be part of the verb, and incorrectly
                     *   parsed it as part of a noun phrase, leaving the
                     *   verb structure and other noun phrase incomplete.
                     *   This is really a verb syntax error, not a noun
                     *   phrase error.  
                     */
                    local spellErr = c.cmdErr;
                    if (c.cmdErr.ofKind(UnmatchedNounError)
                        && c.miscWordLists.length() > 0
                        && c.missingNouns > 0)
                        spellErr = new NotUnderstoodError();

                    /* try spelling correction */
                    local newToks = history.checkSpelling(toks, spellErr);

                    /* if that worked, try the corrected command */
                    if (newToks != nil)
                    {
                        /* parse again with the new tokens */
                        toks = newToks;
                        continue;
                    }
                }

                /* re-throw the error that caused the resolution to fail */
                throw c.cmdErr;
            }
        }
        catch (ParseError err)
        {
            /* 
             *   roll back any spelling changes to the last one that
             *   improved matters 
             */
            local h = history.rollback(toks, err);
            toks = h.oldToks;
            err = h.parseError;

            /* 
             *   if this is a curable error, it poses a question, which the
             *   player can answer on the next input 
             */
            if (err.curable)
                question = new ParseErrorQuestion(err);
            
            /* 
             *   If the current error isn't curable, and unknown word
             *   disclosure is enabled, and there's a word in the command
             *   that's not in the dictionary, replace the parsing error
             *   with an unknown word error.  
             */
            local ui;
            if (!err.curable
                && showUnknownWords
                && (ui = spellingCorrector.findUnknownWord(toks)) != nil)
            {
                /* find the misspelled word in the original tokens */
                err = new UnknownWordError(getTokOrig(toks[ui]));
            }
            
            /* 
             *   If the new error isn't an error in an OOPS command, save
             *   the token list for an OOPS command next time out. 
             */
            if (!err.ofKind(OopsError))
                lastTokens = toks;
            
            /* log any spelling changes we kept */
            history.noteSpelling(toks);

            /*
             *   Display the error we finally decided upon, noting first whom
             *   the command was addressed to, if it began with someone's name
             *   and a comma (PRIEST, XYZZY): a game's messages can then
             *   answer in that character's voice (now.addressee).
             */
            libGlobal.parseAddressee = addresseeOf(toks);
            try
                showParseError(err);
            finally
                libGlobal.parseAddressee = nil;
        }
        catch (CommandSignal sig)
        {
            /* 
             *   On any command signal we haven't caught so far, simply
             *   stop processing this command line.  
             */
        }
    }

    /*
     *   The token list from the last command, if an error occurred.  This
     *   is the token list that we'll retry if the player enters an OOPS
     *   command.  
     */
    lastTokens = nil

    /*
     *   Show the error that a command could not be made of: by default, as
     *   the error displays itself. An extension can show something else
     *   (the choices extension shows the current moment's choices).
     */
    showParseError(err) { err.display(); }

    /*
     *   The outstanding Question object.  When we ask an interactive
     *   question (such as a disambiguation query, a missing noun phrase
     *   query, or a custom question from the game), this is set to the
     *   Question waiting to be answered.  We parse the next command
     *   against the Question to see if it's a reply, and if so we execute
     *   the reply.  
     */
    question = nil

    /*
     *   Execute an empty command line.  The parse() routine calls this
     *   when given a blank command line (i.e., the user simply pressed the
     *   Return key).  By default, we execute a Look Around command if
     *   autoLook is enabled, otherwise we show the "I beg your pardon"
     *   error.
     */
    emptyCommand()
    {
        if (autoLook)
            new Command(Look).exec();
        else
        {
            /* 
             *   The player entered an empty command line (i.e., pressed
             *   Return at the command prompt, without typing anything else
             *   first).  Note that this error can only occur if Auto-Look
             *   is disabled, since otherwise an empty command implicitly
             *   means LOOK AROUND.  
             */
            showMsg(empty command line, 'I beg your pardon?');

        }
    }
    
    /* 
     *   The action to be tried if the parser can't find a verb in the command
     *   line and tries to parse the command line as the single object of a
     *   DefaultAction command instead.
     */
    
    DefaultAction = ExamineOrGoTo
    
    /*  Return an rmcXXXX enum code depending on the state of Parser.question */
    rmcType()
    {
        if(Parser.question != nil && Parser.question.err != nil)
        {
            /* 
             *   If the Parser error is an EmptyNounError then we're asking for
             *   an object.
             */
            if(Parser.question.err.ofKind(EmptyNounError))
                return rmcAskObject;
            
            /* 
             *   If the Parser error is an AmbiguousError then we're requesting
             *   disambiguation.
             */
            if(Parser.question.err.ofKind(AmbiguousError))
                return rmcDisambig;            
        }
        
        /* 
         *   If there's no special situation, assume we're reading a standard
         *   command.
         */
        return rmcCommand;
    }
    
    /* 
     *   Update the vocabulary of items in the game for which it might vary; specifically those with
     *   an altVocab defined.
     */
    updateVocab()
    {
        /* Retrieve the list of items that have alternating vocabulary. */
        local lst = libGlobal.altVocabLst;
        
        /* 
         *   If the list is longer than a certain amount, it may become more efficient to iterate
         *   over only those items in the list that are already in scope.
         */
        if(lst.length > 30)
        {
            /* Get a list of items in scope. */
            local scope = Q.scopeList(now.player).toList();
            
            /* Reduce our list of variable vocab items to include only those in scope. */
            lst = lst.intersect(scope);
            
        }
        
        /* Call updateVocab() on every item in our list. */
        lst.forEach({ x: x.updateVocab() });
    }
;

/* ------------------------------------------------------------------------ */
/*
 *   Base class for command execution signals.  These allow execution
 *   handlers to terminate execution for the current command line or
 *   portion of the command line.  
 */
class CommandSignal: Exception
;


/* 
 *   Terminate the entire command line.
 */
class ExitCommandLineSignal: CommandSignal
;
    

/* ------------------------------------------------------------------------ */
/*
 *   A CommandList is a set of potential parsings for a given input with a
 *   given grammar.  
 */
class CommandList: object
    /*
     *   new CommandList(prod, toks, dict, wrapper) - construct a new
     *   CommandList object by parsing an input token list.  'prod' is the
     *   GrammarRule to parse against; 'toks' is the token list; 'dict' is
     *   the main parser dictionary; 'wrapper' is a callback function that
     *   maps a parse tree to a Command object.
     *   
     *   new CommandList(Command) - construct a CommandList containing a
     *   single pre-resolved Command object.  
     */
    construct([args])
    {
        /* check which argument list we have */        
        if (args.matchProto([GrammarRule, Collection, Dictionary, TypeFunction]))
        {
            /* retrieve the arguments */
            local prod = args[1], toks = args[2], dict = args[3],
                wrapper = args[4];

            /* parse the token list, and map the list to Command objects  */
            cmdLst = prod.parseTokens(toks, dict).mapAll(wrapper);
            
            /* sort in priority order */
            cmdLst = Command.sortList(cmdLst);
            
            /* 
             *   Go through the list, looking for an item with noun phrases we
             *   can resolve.  Take the first item that we can properly
             *   resolve.  
             */
            foreach (local c in cmdLst)
            {
                try
                {                    
                    /* resolve this phrase */
                    c.resolveNouns();
                    
                    /* success - take this as the result; look no further */
                    /* 
                     *   But only if we haven't yet got a command or the new
                     *   command didn't have to create a new Topic object.
                     */
                    if(cmd == nil || !c.madeTopic)
                        cmd = c;
                    
                    /* 
                     *   But if this command had to create a new Topic object,
                     *   let's go on to see if we can find a better match.
                     */
                    if(!cmd.madeTopic)
                       break;
                }
                catch(InsufficientNounsError err)
                {
                    c.cmdErr = err;
                    throw err;
                }
                catch(NoneInOwnerError err)
                {
                    c.cmdErr = err;
                    throw err;
                }
                
                catch (ParseError err)
                {
                    /* save the error with the command */
                    c.cmdErr = err;
                    
                    /* 
                     *   That didn't resolve correctly.  But don't actually
                     *   show the error message yet; instead, continue through
                     *   the list to see if we can find another alternative
                     *   that we can resolve.
                     *   
                     *   If it's the first curable error we've seen, note it. 
                     */
                    if (err.curable && curable == nil)
                        curable = c;
                }
            }
        }
        else if (args.matchProto([Command]))
        {
            /* get the command - it's the single list entry */
            cmd = args[1];
            cmdLst = [cmd];
        }
        else if (args.matchProto([]))
        {
            /* empty command list */
            cmd = nil;
            cmdLst = [];
        }
        else
            throw new ArgumentMismatchError();
    }

    /* number of parsings in the list */
    length() { return cmdLst.length(); }

    /*
     *   Accept a curable resolution as the actual resolution.  If we don't
     *   have an error-free resolution, we'll set 'cmd' to the curable
     *   resolution.  Returns true if we have any resolution, nil if not.  
     */
    acceptCurable()
    {
        /* if we don't have an error-free resolution, accept a curable one */
        if (cmd == nil)
            cmd = curable;

        /* indicate whether we have a resolution now */
        return cmd;
    }

    /*
     *   Accept ANY command, with or without a resolution error, curable or
     *   not.  We'll take the error-free resolution if we have one,
     *   otherwise the resolution with a curable error, otherwise just the
     *   first parsing in priority order. 
     */
    acceptAny()
    {
        /* accept the best command, and return it */
        return cmd = getBestCmd();
    }

    /*
     *   Get the most promising command from the available parsings.  This
     *   returns the first successfully resolved command in priority order,
     *   if any; otherwise the first command with a curable error, if any;
     *   otherwise the first command in priority order.  
     */
    getBestCmd()
    {
        /* if we have a parsed and resolved command, return it */
        if (cmd != nil)
            return cmd;

        /* if we have a curable command, return it */
        if (curable != nil)
            return curable;

        /* if we have any parsing at all, return the first one */
        if (cmdLst.length() > 0)
            return cmdLst[1];

        /* we don't have any parsing */
        return nil;
    }

    /*
     *   Get the resolution error, if any.  If we parsed but didn't
     *   resolve, this returns the error from the first parsing in priority
     *   order.  
     */
    getResErr()
    {
        /* if we resolved a command, return any error from it */
        if (cmd != nil)
            return cmd.cmdErr;

        /* if we have a curable error, return it */
        if (curable != nil)
            return curable.cmdErr;

        /* otherwise, return the first item with a cmdErr */
        local c = cmdLst.valWhich({ c: c.cmdErr != nil });
        return (c != nil ? c.cmdErr : nil);
    }

    /* our list of Command objects */
    cmdLst = []

    /* 
     *   Our resolved Command.  This is the first parsing in our list that
     *   (in priority order) we were able to resolve with no errors.  
     */
    cmd = nil

    /* 
     *   Our semi-resolved Command.  When we can't find a command that
     *   resolves without errors, we'll set this to the first one (in
     *   priority order) that resolves with a curable error.  
     */
    curable = nil
;


/* ------------------------------------------------------------------------ */
/*
 *   A Question is an interactive question we ask the player via the
 *   regular command line.  The player then has the option to answer the
 *   question, or to ignore the question and enter a new command.
 *   
 *   The parser uses Question objects internally to handle certain errors
 *   that the player can fix by entering additional information, such as
 *   disambiguation queries and missing noun phrase queries.  Games can use
 *   Question objects for other, custom interactions.
 *   
 *   The basic Question object is incomplete - you have to subclass it to
 *   get a functional question handler.  In particular, you must provide a
 *   parseAnswer() routine that parses the reply and creates a Command to
 *   carry out the action of answering the question.  
 */
class Question: object
    /*
     *   Priority: Should the answer be parsed before checking for a
     *   regular command entry?  If this is true, the parser will try
     *   parsing the player's input as an answer to this question BEFORE it
     *   tries parsing the input as a regular command.  If the answer
     *   parses, we'll assume it really is an answer to the question, and
     *   we won't even try parsing it as a new command.
     *   
     *   For disambiguation and missing noun queries, the parser only
     *   parses question replies AFTER parsing regular commands.  Replies
     *   to these questions are frequently very short, abbreviated noun
     *   phrases - maybe just a single adjective or noun.  It's fairly
     *   common for there be at least a few nouns that are the same as
     *   verbs in the game, so the input after a disambiguation or missing
     *   noun reply can often be interpreted equally well as a new verb or
     *   as a reply to the question.  There's probably no theoretical basis
     *   for choosing one over the other when this happens, but in practice
     *   it seems that it's usually better to treat the reply as a new
     *   command.  So, by default we set this property to nil, to give
     *   priority to a new command.
     *   
     *   Custom questions posed by the game might want to give higher
     *   priority to the answer interpretation, though.  Yes/No questions
     *   in particular will probably want to do this, because otherwise the
     *   parser would take the answer as a conversational overture to any
     *   nearby NPC.  
     */
    priority = nil
    
    /*
     *   Parse the answer.  'toks' is the token list of the user's input,
     *   and 'dict' is the main parser Dictionary object.
     *   
     *   If the input does look like a valid answer to the question,
     *   returns a CommandList with the parsed reply.  If not, returns nil,
     *   in which case the parser will continue trying to parse the input
     *   as a whole new command.
     *   
     *   By default, we simply return nil.  Subclasses/instances must
     *   override this to provide the custom answer parsing.  
     */
    parseAnswer(toks, dict) { return nil; }

    /* the answer template */
    answerTemplate = nil
;

/*
 *   A GramQuestion is a question handler that parses an answer using a
 *   grammar rule.
 */
class GramQuestion: Question
    /*
     *   Create a simple question.  'prod' is the root GrammarRule to use
     *   for parsing the reply.  'func' is a callback function that carries
     *   out the action of the answering the question.  'func' is invoked
     *   with a single argument giving the Command object representing the
     *   answer; you can get the match tree from the Command if you need
     *   the parsed form of the answer input.  
     */
    construct(prod, func)
    {
        answerProd = prod;
        answerFunc = func;
    }

    /*
     *   Parse the answer.  We'll match the token list against the grammar
     *   rule.  If we find a match, we'll call makeCommand() to create the
     *   command to carry out the action of answering the question.  
     */
    parseAnswer(toks, dict)
    {
        /* try parsing against our grammar rule */
        return new CommandList(
            answerProd, toks, dict, { p: makeCommand(p) });
    }

    /*
     *   Create a Command object for a successful grammar match.  'prod' is
     *   the root match object of the grammar match.  This returns a
     *   suitable Command that carries out the action of answering the
     *   question.  
     */
    makeCommand(prod) { return new FuncCommand(prod, answerFunc); }

    /* the GrammarRule rule that we use to parse the answer */
    answerProd = nil

    /* the callback function that carries out the reply action */
    answerFunc = nil
;

/*
 *   A YesNoQuestion is a simple subclass of Question for asking
 *   interactive questions with Yes or No answers. 
 */
class YesNoQuestion: GramQuestion
    /*
     *   Create - 'func' is the callback function to invoke on answering
     *   the question.  This is invoked with one argument, true if the
     *   answer was Yes, nil if the answer was No.  
     */
    construct(func)
    {
        /* 
         *   Parse our answer against the simple yes-or-no grammar.  To
         *   execute the answer, call the user's callback, providing the
         *   yes/no result from the Command.  The yes-or-no production sets
         *   the yesOrNoAnswer property in the Command during the build
         *   process.  
         */
        inherited(yesOrNoPhrase, { cmd: func(cmd.yesOrNoAnswer) });
    }

    /* 
     *   parse Yes/No replies ahead of new commands, since we'd otherwise
     *   never get an answer - the parser would always match the reply to a
     *   conversational verb instead 
     */
    priority = true
;

/*
 *   A RexQuestion is a simple subclass of Question for parsing answers
 *   with regular expressions. 
 */
class RexQuestion: Question
    /*
     *   Create - 'pat' is the regular expression pattern, as either a
     *   string or a Regex object.  We'll parse an answer simply by
     *   matching it against the regular expression; if we match, we'll
     *   take it as an answer.  'func' is a callback function that we'll
     *   call to carry out the action of answering the question.  We'll
     *   invoke this with one argument giving the literal text of the
     *   input.  
     */
    construct(pat, func)
    {
        answerPat = pat;
        answerFunc = func;
    }

    parseAnswer(toks, dict)
    {
        /* reconstruct the string input */
        local str = cmdTokenizer.buildOrigText(toks);

        /* check for a match to our pattern */
        if (regexMatch(answerPat, str,) != nil)
        {
            /* set up a single-entry command list for the answer */
            return new CommandList(new FuncCommand(
                nil, { cmd: answerFunc(str) }));
        }
        else
        {
            /* no match */
            return nil;
        }
    }

    /* the regular expression pattern to match */
    answerPat = nil

    /* the callback to invoke on answering */
    answerFunc = nil
;

/*
 *   An ErrorQuestion is a subclass of Question for curable parsing errors.
 */
class ParseErrorQuestion: Question
    construct(err)
    {
        /* remember the ParseError object */
        self.err = err;
    }

    parseAnswer(toks, dict)
    {
        /* ask the error to parse the response */
        return err.tryCuring(toks, dict);
    }

    /* the curable ParseError that posed the question */
    err = nil
    
    /* 
     *   Should we prioritize interpreting player input to a parser query as a response to that
     *   query over interpreting it as a nea command (where the latter is possible)? By default we
     *   do (since this seems more likely to reflect player intention in this case), although game
     *   code can override if desired.
     */
    priority = true
;


/* ------------------------------------------------------------------------ */
/*
 *   A Distinguisher is an abstract parser object that represents one way
 *   that we can tell two objects apart, both in the name we display and in
 *   command input.
 *   
 *   Note that this class is designed primarily for the parser's internal
 *   use, to facilitate some bookkeeping that we have to do during
 *   disambiguation.  It's not really designed as an extensibility
 *   mechanism, because it's not usually enough to just add a new instance:
 *   you usually also have to add grammar for whatever new phrasing the new
 *   distinguisher represents, plus object resolution code to handle the
 *   new form of qualification.  
 */
class Distinguisher: object
    /* 
     *   Sorting order.  The parser sorts the master list of distinguishers
     *   in ascending order of this value to determine the order of
     *   application.  
     */
    sortOrder = 0

    /*
     *   Compare two objects for equivalence under this distinguisher.
     *   Returns true if the objects are equivalent, nil others. 
     */
    equal(a, b) { return nil; }

    /* 
     *   Is this distinguisher applicable to the given object?  Some
     *   distinguishers can only apply to certain objects.  For example, a
     *   Lit/Unlit distinguisher can only be applied to objects with that
     *   state variable, because there's no vocabulary that we can add to
     *   an object without the variable.  (We can talk about "lit" and
     *   "unlit" matches, but we don't have any standard vocabulary to talk
     *   about "unlightable" matches.)  
     */
    appliesTo(obj) { return true; }

    /*
     *   Apply the distinguisher.  Returns a DistResult object with the
     *   results.  
     */
    apply(lst)
    {
        /* create the results object */
        local r = new DistResult(self);

        /* set up the list of applicable objects */
        r.appliesTo = lst.subset({ obj: appliesTo(obj) });

        /* make a to-do vector, starting with all applicable items */
        local toDo = new Vector(10, r.appliesTo);

        /* process each item in the to-do list */
        while (toDo.length() > 0)
        {
            /* pop the last item */
            local obj = toDo.pop();

            /* start a partition list for this item and its equivalents */
            local sv = new Vector(10);

            /* start the partition with the current object */
            sv.append(obj);

            /* add the new partition to the partition list */
            r.partitioned.append(sv);

            /* scan the to-do list for items equivalent to obj */
            for (local i = toDo.length() ; i > 0 ; --i)
            {
                /* get this item and check for equivalence to obj */
                local obj2 = toDo[i];
                if (equal(obj, obj2))
                {
                    /* it's equivalent to obj, so add it to obj's partition */
                    sv.append(obj2);

                    /* it's been processed; remove it from the to-do list */
                    toDo.removeElementAt(i);
                }
            }
        }

        /* return the result object */
        return r;
    }

    /* class property: master list of all distinguishers */
    all = []

    /* during initialization, build the master list */
    classInit()
    {
        /* add each instance to the master list */
        forEachInstance(Distinguisher, {d: all += d});

        /* arrange by sortOrder */
        all = all.sort(SortAsc, {a, b: a.sortOrder - b.sortOrder});
    }

    /* make sure the StateDistinguisher instances are constructed first */
    classInitFirst = [StateDistinguisher]

    /*
     *   Class method: generate distinguishing names for a list of objects.
     *   This generates names that distinguish the objects from one
     *   another, by applying as many Distinguishers as needed to come up
     *   with unique names.
     *   
     *   If 'article' is true, we'll use a definite or indefinite article,
     *   as appropriate: definite if the name we settle upon uniquely
     *   identifies the object within the list, indefinite if not.  If
     *   'article' is nil, the names don't have articles at all.
     *   
     *   Returns a list of [name, [objects]] sublists.  The name is a
     *   string giving the distinguished name; the [objects] sub-sublist is
     *   a list of the objects known under that name.  
     */
    getNames(objs, article, disambig = nil)
    {        
        /* start with an empty result list */
        local names = new Vector(objs.length());

        /* start with an empty list of distinguisher results */
        local dres = new Vector(Distinguisher.all.length());

        /* apply each distinguisher to our objects, saving the results */
        foreach (local d in Distinguisher.all)
            dres.append(d.apply(objs));
        
        /* 
         *   Note whether we're trying to disambiguate by name in a context where we might want to
         *   prioritize disambigNames
         */
        Distinguisher.disambiguating = disambig;

        /* find the distinguishing characteristics for each object */
        while (objs.length() != 0)
        {
            /* treat the to-do list as a stack: pop an object */
            local obj = objs.pop();

            /* get the subset of dist results that apply to this object */
            local ores = dres.subset({ r: r.appliesTo.indexOf(obj) != nil });

            /*
             *   What we're after is the minimum set of distinguishers that
             *   can tell this object apart from as many of the others as
             *   possible.
             *   
             *   In the best case, there's a single distinguisher that can
             *   pick out this object uniquely.  For example, if this is
             *   the lit match, and all the other matches are unlit, the
             *   Lit/Unlit State distinguisher is all we need: 'lit'
             *   uniquely identifies this object among our set.  If that's
             *   the case, obj will appear in the Lit/Unlit list in its own
             *   partition, with no other objects.
             *   
             *   It might be that there's no one distinguisher that can
             *   tell obj apart from all of the others.  But perhaps a
             *   combination of two distinguishers can: perhaps obj is one
             *   of two lit matches, and one of two matches belonging to
             *   Bob, but it's the only lit match belonging to Bob.  We'd
             *   thus find obj in two partitions of two objects each;
             *   intersecting the two will yield a list with just one
             *   element, so we'd get down to a unique object again.
             *   
             *   We might not ever get down to a single-object partition,
             *   even after combining several distinguishers, since we
             *   might be truly indistinguishable from one or more other
             *   objects.  In such a case, we'll have to group the objects
             *   and ask if the player means "*a* lit match of Bob's", say.
             *   
             *   In any case, our fastest route to the smallest set is to
             *   start with the smallest set, and intersect against larger
             *   sets until we get down to one object or run out of other
             *   sets to intersect.  So start by sorting the results by the
             *   size of the partition in which obj appears, smallest to
             *   largest.  
             */
            ores.sort(SortAsc, new function(a, b)
            {
                /* sort by partition size */
                local asiz = a.partSize(obj);
                local bsiz = b.partSize(obj);

                /* if they differ, sort according to the relative sizes */
                if (asiz != bsiz)
                    return asiz - bsiz;

                /* same size partitions; sort by Distinguisher order */
                return a.distinguisher.sortOrder - b.distinguisher.sortOrder;
            });

            /* we haven't used any distinguishers yet */
            local used = new Vector(10);

            /* 
             *   Start with the first distinguisher in the list, and its
             *   initial set.  Note that we're guaranteed to have at least
             *   one result in the list, since the basic name distinguisher
             *   applies to everything.  
             */
            used.append(ores[1].distinguisher);
            local rem = ores[1].partition(obj).toList();

            /* 
             *   now apply additional distinguishers until we get the set
             *   down to one object, or run out of distinguishers 
             */
            for (local i = 2, local olen = ores.length() ;
                 rem.length() > 1 && i <= olen ; ++i)
            {
                /* 
                 *   figure the intersection of this distinguisher
                 *   partition with the remaining set 
                 */
                local rcur = ores[i];
                local isect = rem.intersect(rcur.partition(obj).toList());

                /* 
                 *   If that reduced the set size, keep the result.  Ignore
                 *   distinguishers that don't reduce the set size, because
                 *   they don't help - they'd just add words to the
                 *   generated name without helping to tell things apart.  
                 */
                if (isect.length() < rem.length())
                {
                    /* keep the reduced list */
                    rem = isect;

                    /* note that we used this distinguisher */
                    used.append(rcur.distinguisher);
                }
            }

            /* 
             *   We've thrown out as many distinguishable items as
             *   possible, and in the process we've built a list of the
             *   distinguishing characteristics that we needed in order to
             *   tell this object apart from the others.  Generate the
             *   name, based on that list of characteristics.  If we
             *   whittled the set size down to a single object, use a
             *   definite article; otherwise, we have a group of
             *   indistinguishable objects, so use an indefinite article to
             *   refer to an arbitrary one of these.  
             */
            local rlen = rem.length();
            local nm = obj.distinguishedName(
                article ? (rlen == 1 ? Definite : Indefinite) : Unqualified,
                used);

            /* 
             *   This name covers the whole group, so remove all of the of
             *   additional objects from the to-do list.  (We've already
             *   removed the first one, so don't waste time looking for it
             *   again.)  
             */
            for (local i = 2 ; i <= rlen ; ++i)
                objs.removeElement(rem[i]);

            /* append this name result */
            names.append([nm, rem]);
        }

        /* return the name list */
        return names;
    }
    
    disambiguating = nil
;

/*
 *   Result object from applying a Distinguisher to a set of objects. 
 */
class DistResult: object
    construct(dist)
    {
        /* remember the distinguisher */
        distinguisher = dist;

        /* set up a vector for the partition list */
        partitioned = new Vector(10);
    }

    /* get the partition in which 'obj' appears */
    partition(obj)
    {
        return partitioned.valWhich({ p: p.indexOf(obj) != nil });
    }

    /* get the size of the partition in which 'obj' appears */
    partSize(obj)
    {
        return partition(obj).length();
    }

    /* the objects that the distinguisher applies to */
    appliesTo = []

    /* 
     *   The partitioned list of objects.  This is a list of lists.  Each
     *   sublist is a group of objects we can't distinguish from one
     *   another.  Each object in appliesTo appears once in a sublist, and
     *   each object in a sublist appears in appliesTo.  
     */
    partitioned = []

    /* the Distinguisher that these results come from */
    distinguisher = nil
;

/*
 *   The basic name distinguisher distinguishes objects by their base names.
 *   This is the first distinguisher we apply, since the name is always the
 *   easiest way to tell objects apart in parsing. However since one name could
 *   be entirely contained within another (e.g. 'ball' and 'red ball') we
 *   consider the names as equal for this purpose if one of them is part of the
 *   other.
 */
nameDistinguisher: Distinguisher
    sortOrder = 100 
    equal(a, b) { return a.name.find(b.name) || b.name.find(a.name); }
;

/*
 *   The disambiguation name distinguisher.  This distinguishes objects by
 *   their disambiguation names.  We apply this immediately after the basic
 *   name distinguisher, since the disambiguation name is a custom name
 *   provided by the author for the express purpose of distinguishing the
 *   object in parsing.  
 */
disambigNameDistinguisher: Distinguisher
    sortOrder = Distinguisher.disambiguating ? 50: 100 // EXPERIMENT to try prioritizing the disambigNameDistinguisher
    equal(a, b) { return a.disambigName == b.disambigName; }
;

/*
 *   The class for state distinguishers.  A state distinguisher tells
 *   objects apart based on their having distinct current values for a
 *   given state.  During preinit, we create a separate instance of this
 *   for each State object in the game.  
 */
class StateDistinguisher: Distinguisher
    sortOrder = 300

    /* we distinguish based on each object's current value for the state */
    equal(a, b) { return a.(state.stateProp) == b.(state.stateProp); }

    /* we only apply to objects that have our state variable */
    appliesTo(obj) { return state.appliesTo(obj); }
    
    /* build from a State */
    construct(st)
    {
        /* remember the state object */
        state = st;
    }

    /* during preinit, build an instance for each State */
    classInit()
    {
        forEachInstance(State, {st: stateList += new StateDistinguisher(st)});
    }

    /* the State this distinguisher tests */
    state = nil

    /* class property: the list of state distinguisher instances */
    stateList = []
;


/*
 *   Owner distinguisher.  This tells objects apart based on their nominal
 *   owners (and only applies to objects with nominal owners at all).  
 */
ownerDistinguisher: Distinguisher
    sortOrder = 400
    appliesTo(obj) { return obj.nominalOwner() != nil; }
    equal(a, b) { return a.nominalOwner() == b.nominalOwner(); }
;

/*
 *   Location distinguisher.  This tells objects apart based on their
 *   immediate containers. 
 */
locationDistinguisher: Distinguisher
    sortOrder = 500
    equal(a, b) { return a.location == b.location; }
;

/*
 *   Contents distinguisher.  This tells objects apart based on their
 *   nominal contents (and only applies to objects with nominal contents at
 *   all).  Note that we're interested in the *names* of the contents, so
 *   even if two objects have different contents objects, they're still
 *   considered equal if the contents' names match.  (E.g., two "buckets of
 *   water" are indistinguishable, even if the contents are two distinct
 *   "water" objects.  But "bucket of water" and "bucket of fish" are
 *   distinguishable.)  
 */
contentsDistinguisher: Distinguisher
    sortOrder = 600
    appliesTo(obj) { return obj.distinguishByContents != nil; }
    equal(a, b)
    {
        local ac = a.nominalContents(), bc = b.nominalContents();
        return (ac != nil ? ac.name : nil) == (bc != nil ? bc.name : nil);
    }
;
    

/* ------------------------------------------------------------------------ */
/*
 *   A NounPhrase object represents a noun phrase within a command line.
 *   This class handles the mapping from the text of the noun phrase in the
 *   input to the game-world objects that the noun phrase refers to.
 *   
 *   This object encompasses a core noun phrase plus all of its qualifiers.
 *   Qualifiers can themselves be noun phrases: possessives, locationals,
 *   and contents phrases contain subsidiary noun phrases, so we represent
 *   these qualifiers with subsidiary NounPhrase objects.  
 */
class NounPhrase: object
    /* create */
    construct(parent, prod)
    {
        /* 
         *   remember the parent NounPhrase and the grammar production
         *   match object that's the source of the noun phrase
         */
        self.parent = parent;
        self.prod = self.coreProd = prod;
    }

    /* clone - create a modifiable copy based on this original noun phrase */
    clone()
    {
        /* create a new object with my same property values */
        local cl = createClone();

        /* make safe copies of any vectors */
        foreach (local p in cl.properties())
        {
            local v;
            if (cl.propType(p) == TypeObject && (v = cl.(p)).ofKind(Vector))
                cl.(p) = new Vector(v.length(), v);
        }

        /* return the clone */
        return cl;
    }

    /* 
     *   By default, use the original input text of my "core" production as
     *   the name we show for this noun phrase in error messages.  The core
     *   production is the noun phrase minus any qualifiers (articles,
     *   possessives, locational phrases, etc).
     *   
     *   As we successfully resolve qualifiers, we'll expand this to
     *   include the qualifying phrases.  Any error we find after resolving
     *   a qualifier will necessary apply to the qualified form, so we want
     *   to include the qualifier in any error message.
     *   
     *   For example, if the original phrase is BUCKET OF FISH ON TABLE,
     *   we'll start out with the core phrase of BUCKET.  We'll next
     *   resolve the contents qualifier, OF FISH.  Assuming that we find a
     *   BUCKET OF FISH, that becomes the new error name.  If we then fail
     *   to find such an object ON TABLE, we'll be able to report that
     *   there's no BUCKET OF FISH on the table.  This is better than
     *   reporting that we don't see any BUCKET on the table, because there
     *   could in fact be a different bucket on the table.  
     */
    errName = (errNameProd.getText())

    /* the source of the error name is initially the core production */
    errNameProd = (coreProd)

    /*
     *   Expand the error-message name to include the given qualifier.
     *   We'll find the common parent of the core production and the given
     *   qualifier's production, and use its text as the new error name. 
     */
    expandErrName(np)
    {
        /* 
         *   look for the common parent of 'np' and the current error name
         *   source 
         */
        for (local prod = np.prod ; prod != nil ; prod = prod.parent)
        {
            /* 
             *   if this is also a parent of errNameProd, we've found the
             *   common parent 
             */
            if (prod == errNameProd || errNameProd.isChildOf(prod))
            {
                /* establish this as the new error name source */
                errNameProd = prod;

                /* no need to keep looking */
                break;
            }
        }
    }

    /*
     *   Does this NounPhrase contain the given NounPhrase?  Returns true
     *   if NounPhrase is self, or one of our qualifier noun phrases
     *   contains it. 
     */
    contains(np)
    {
        return (np == self
                || (possQual != nil && possQual.contains(np))
                || (locQual != nil && locQual.contains(np))
                || (exclusions != nil
                    && exclusions.indexWhich({ x: x.contains(np) }) != nil));
    }
    
    /*
     *   Get the list of objects matching the vocabulary words in our noun
     *   phrase.  Populates our 'matches' property with a vector of matching
     *   objects.  This doesn't look at any of our qualifiers, or attempt
     *   to disambiguate contextually; it simply finds everything in scope
     *   that the noun phrase could refer to.  
     */
    matchVocab(cmd)
    {
        /* start with an empty vector */
        local v = new Vector(32);

        /* get the current scope list */        
        cmd.action.buildScopeList();
        local scope = cmd.action.scopeList;

        /* check what kind of phrase we have */
        if (pronoun != nil)
        {
            /* it's a pronoun - resolved based on the antecedent */
            addMatches(v, pronoun.resolve(), 0);

            /* if there are no antecedents, flag the error */
            if (v.length() == 0)
                throw new NoAntecedentError(self, pronoun);

            /* filter for in-scope objects (or reflexive placeholders) */
            v = v.subset(
                { m: m.obj.ofKind(Pronoun) || scope.find(m.obj) });

            /* if that leaves nothing, flag the error */
            if (v.length() == 0)
                throw new AntecedentScopeError(cmd, self, pronoun);

        }
        else if (determiner == All && tokens == [])
        {
            /* ALL - use everything in scope applicable to the verb */
            addMatches(v, cmd.action.getAllUnhidden(cmd, role), 0);
            cmd.matchedAll = true;
        }
        else
        {
            /* 
             *   It's a named object.  Our 'tokens' property is a list of
             *   the words in the noun phrase in the user input.  Match it
             *   against the objects in physical scope.
             */
            v.appendAll(matchNameScope(cmd, scope));
        }

        /* save the match list so far */
        npMatches = v;

        /* if we have a contents qualifier, match its vocabulary */
        if (contQual != nil)
        {
            /* match vocabulary */
            contQual.matchVocab(cmd);

            /* apply the qualifier to keep only matching items */
            contQual.applyContQual();

            /* if that empties our list, flag it */
            if (npMatches.length() == 0)
                throw new NoneWithContentsError(cmd, self, contQual);

            /* 
             *   Expand the error text name to include the contents
             *   qualifier, since any subsequent failure to match will be
             *   against the result of this qualification.  For example, if
             *   the phrase is BUCKET OF FISH ON TABLE, we've now limited
             *   the scope to just BUCKET OF FISH, so if we fail to find
             *   such an object on the table it'll be because there's no
             *   BUCKET OF FISH on the table, not because there's simply no
             *   BUCKET.  
             */
            expandErrName(contQual);
        }

        /* if we have a possessive qualifier, apply it */
        if (possQual != nil)
        {
            /* match vocabulary for the possessive phrase */
            possQual.matchVocabPoss(cmd);

            /* 
             *   apply the qualifier, filtering out things not owned by the
             *   object named in the qualifier 
             */
            possQual.applyPossessive();

            /* if that empties our list, flag it */
            if (npMatches.length() == 0)
                throw new NoneInOwnerError(cmd, self, possQual);

            /* expand the error text to include the possessive qualifier */
            expandErrName(possQual);
        }

        /* if we have a locational qualifier, match its vocabulary */
        if (locQual != nil)
        {
            /* match vocabulary */
            locQual.matchVocab(cmd);

            /* apply the qualifier to keep only properly located items */
            locQual.applyLocational();

            /* if that empties our list, flag it */
            if (npMatches.length() == 0)
                throw new NoneInLocationError(cmd, self, locQual);

            /* expand the error name to include the locational */
            expandErrName(locQual);
        }

        /* if there's an exclusion list, apply it */
        if (exclusions != nil)
            exclusions.forEach({ x: x.applyExclusion(cmd) });
    }

    /*
     *   Add matching objects to a match vector.  'lst' can be a list or
     *   vector of objects, or a single object.  'match' is the MatchXxx
     *   flag value returned from the object name match, if applicable.  
     */
    addMatches(vec, lst, match)
    {
        /* ignore nil */
        if (lst == nil)
            return;

        /* wrap each item in an NPMatch object and add it to the vector */
        vec.appendAll(valToList(lst).mapAll({ obj: new NPMatch(self, obj, match) }));
    }

    /*
     *   Find the vocabulary matches for a given noun phrase within a given
     *   scope list.  Add all of the matches to the given vector.  
     */
    matchNameScope(cmd, scope)
    {
        /* set up a vector for the results */
        local v = new Vector(32);
        
        /*
         *   Run through the scope list and ask each object if it matches
         *   the noun phrase.  Keep the ones that match.  
         */
        foreach (local obj in scope)
        {
            /* ask this object if it matches */
            local match = obj.matchName(tokens);
            
            /* if it matches, include it in the results */
            if (match)
                v.append(new NPMatch(self, obj, match));
        }

        /*
         *   Now narrow the list according to the match strength.  Only
         *   keep the matches that have the maximum strength of the list.
         */
        if (v.length() > 0)
        {
            /* sort in descending order of strength */
            v.sort(SortDesc, { a, b: a.strength - b.strength });

            /* 
             *   discard everything that doesn't match the highest strength
             *   (which is the first element's strength, since we've sorted
             *   in descending order) 
             */
            v = v.subset({ a: a.strength == v[1].strength });
        }
        else
        {
            /* the list is empty - complain about it */
            throw new UnmatchedNounError(cmd, self);
        }

        /* return the list */
        return v;
    }

    /*
     *   Match vocabulary for a possessive qualifier phrase.
     *   
     *   Possessive matching has somewhat different rules than for ordinary
     *   noun phrases.
     *   
     *   First, possessive pronouns (HIS, HER, ITS, THEIR) *can* act like
     *   reflexives, in that they can refer back to earlier clauses in the
     *   same predicate: ASK BOB ABOUT HIS MOTHER.  However, they can also
     *   refer to previous commands: SEARCH BOB; TAKE HIS WALLET.  The
     *   deciding factor is whether or not there's an earlier noun phrase
     *   in the command that matches in gender and number; if so, we use
     *   the reflexive meaning, otherwise we use the external referent.
     *   
     *   Second, the scope for ordinary noun phrases has to be expanded to
     *   include the owners of the objects in scope.  If we have a wallet
     *   that we know belongs to Bob, we should be able to refer to it as
     *   "Bob's wallet" whether or not Bob himself is in scope.  So, for
     *   the purposes of the possessive, Bob is in scope even if he
     *   wouldn't be for an ordinary noun phrase.  
     */
    matchVocabPoss(cmd)
    {
        /* start with an empty vector */
        local v = npMatches = new Vector(32);

        /* check what kind of phrase we have */
        if (pronoun != nil)
        {
            /* 
             *   It's a possessive pronoun (HIS, HER, ITS, etc).
             *   Possessive pronouns can refer back to something in the
             *   same sentence (ASK BOB ABOUT HIS WALLET) or to earlier
             *   commands (SEARCH BOB; TAKE HIS WALLET).
             *   
             *   If it's a second-person possessive (YOUR), and there's an
             *   addressee actor, it refers to the actor.  For example,
             *   "Bob, give me your wallet".
             *   
             *   Look at the preceding noun phrases in the predicate to see
             *   if we can find an object that matches this pronoun.  If
             *   so, use it as the antecedent.  If not, use the regular
             *   antecedent.  
             */
            local done = nil;
            cmd.forEachNP(new function(np)
            {
                /* if we've already finished, ignore this noun phrase */
                if (done)
                    return;

                /* 
                 *   if this is our parent, stop looking - pronoun
                 *   references of this sort are always back references 
                 */
                if (np == parent)
                {
                    done = true;
                    return;
                }

                /* 
                 *   If this is the addressee actor, and we have a
                 *   second-person possessive pronoun (YOUR), the pronoun
                 *   refers to the actor. 
                 */
                if (np.role == ActorRole && pronoun.person == 2)
                {
                    v.appendAll(np.npMatches);
                    done = true;
                    return;
                }

                /* check for matches to this pronoun in this match list */
                local s = np.npMatches.subset(
                    { o: pronoun.matchObj(o.obj) });

                /* 
                 *   if we found any matches, use them, and stop looking -
                 *   we only want to use the nearest match 
                 */
                if (s.length() != 0)
                {
                    v.appendAll(s);
                    done = true;
                }
            });

            /* 
             *   if we didn't find any matches, use the antecedent from a
             *   previous command, if available 
             */
            if (v.length() == 0)
                v.appendAll(pronoun.resolve().mapAll({
                    x: new NPMatch(self, x, 0) }));
        }
        else
        {
            /* 
             *   It's a named object.  We need an expanded scope list that
             *   includes the owners of the objects referred to by the
             *   underlying noun phrase that we qualify.  
             */
            local expScope = new Vector(32);
            foreach (local obj in parent.npMatches)
            {
                /* 
                 *   if this object has an owner or owners, add it/them to
                 *   the expanded scope list 
                 */
                local owner = obj.obj.owner;
                if (owner != nil)
                    expScope.appendAll(owner);
            }

            /* add the objects in scope, filtering out duplicates */
            expScope.appendUnique(World.scope.toList());

            /* now build the match list using the expanded scope */
            v.appendAll(matchNameScope(cmd, expScope));
        }

        /* 
         *   a possessive qualifier can itself have a possessive qualifier
         *   (BOB'S MOTHER'S HAT), so go resolve that as well 
         */
        if (possQual != nil)
            possQual.matchVocabPoss(cmd);
    }

    /*
     *   Apply this possessive phrase's qualification.  This filters the
     *   underlying (parent) noun list to keep only objects owned by the
     *   object(s) named in this noun phrase.  
     */
    applyPossessive()
    {
        /* 
         *   First, do "reverse" filtering: consider only owners who own
         *   something that's in the underlying noun list.  For example, if
         *   there are two guards present, but only one of them is carrying
         *   a sword, GUARD'S SWORD must refer to the guard who's carrying
         *   a sword.
         *   
         *   (Take a subset of our own objects, keeping each object 'o'
         *   where there's something in the parent list owned by 'o'.  That
         *   is, there's an object 'p' in the parent list where 'p' is
         *   owned by 'o'.)  
         */
        local m = npMatches.subset(
            { o: parent.npMatches.indexWhich(
                { p: p.obj.ownedBy(o.obj) }) != nil });

        /* if the reverse filter didn't rule everything out, apply it */
        if (m.length() > 0)
            npMatches = m;
        
        /* next, apply any possessive qualifier of my own */
        if (possQual != nil)
            possQual.applyPossessive();

        /* filter parent objects not owned by anything in my list */
        parent.npMatches = parent.npMatches.subset(
            { p: npMatches.indexWhich(
                { o: p.obj.ownedBy(o.obj) }) != nil });
    }

    /*
     *   Apply this contents qualifier phrase's qualification.  This
     *   filters the underlying (parent) noun list to keep only objects
     *   that contain the object(s) named in this noun list.  
     */
    applyContQual()
    {
        /* 
         *   First, do the reverse filtering, to keep only objects that
         *   could be inside objects in the underlying list.  
         */
        local m = npMatches.subset(
            { o: parent.npMatches.indexWhich(
                { p: o.obj.isChild(p.obj, nil) }) != nil });

        /* if that didn't rule everything out, apply the filter */
        if (m.length() > 0)
            npMatches = m;

        /* next, apply any locational qualifier of my own */
        if (contQual != nil)
            contQual.applyContQual();

        /* filter parent objects not containing anything in my list */
        parent.npMatches = parent.npMatches.subset(
            { p: npMatches.indexWhich(
                { o: o.obj.isChild(p.obj, nil) }) != nil });
    }
    
    /*
     *   Apply this locational phrase's qualification.  This filters the
     *   underlying (parent) noun list to keep only objects located within
     *   the object(s) named in this noun phrase.  
     */
    applyLocational()
    {
        /* 
         *   First, do the reverse filtering, to keep only objects that
         *   could contain objects in the underlying list. 
         */
        local m = npMatches.subset(
            { o: parent.npMatches.indexWhich(
                { p: p.obj.isChild(o.obj, locType) }) != nil });

        /* if that didn't rule everything out, apply the filter */
        if (m.length() > 0)
            npMatches = m;

        /* next, apply any locational qualifier of my own */
        if (locQual != nil)
            locQual.applyLocational();

        /* first, try limiting to items DIRECTLY in the location */
        m = parent.npMatches.subset(
            { p: npMatches.indexWhich(
                { o: p.obj.isDirectChild(o.obj, locType) }) != nil });

        /* if there weren't any, try items indirectly in the location */
        if (m.length() == 0)
            m = parent.npMatches.subset(
                { p: npMatches.indexWhich(
                    { o: p.obj.isChild(o.obj, locType) }) != nil });

        /* save the filtered list in the parent */
        parent.npMatches = m;
    }
    
    /*
     *   Apply an exclusion item.  This resolves the vocabulary for the
     *   exclusion phrase and filters the matching item(s) noun phrase out
     *   of the parent list.  
     */
    applyExclusion(cmd)
    {
        /* do our vocabulary matching */
        matchVocab(cmd);

        /* filter the parent list to exclude everything we matched */
        parent.npMatches = parent.npMatches.subset(
            { p: npMatches.indexWhich(
                { o: o.obj == p.obj }) == nil });
    }

    /*
     *   Select the objects from among the vocabulary matches.  This
     *   narrows the list of possible vocabulary matches for our noun
     *   phrase to find the actual object or objects the player is
     *   referencing.
     *   
     *   When this is called, we've already filled in the match list with
     *   all objects in scope that match the vocabulary of the core noun
     *   phrase (including non-reflexive pronouns and ALL), and we've
     *   applied any possessive, locational, and exclusion qualifiers.
     *   What we're left with is the list of in-scope objects that meet all
     *   of the specifications contained in the entire noun phrase.  In
     *   other words, we've squeezed all available information out of the
     *   noun phrase itself.  If the result is ambiguous, then, we'll have
     *   to look beyond the noun phrase, to the broader semantic content of
     *   the overall command.  
     *   
     *   There are three possible "goals" for what our final object list
     *   should look like after disambiguation.  Only one goal applies to
     *   each particular noun phrase; which it is depends on the grammar of
     *   the phrase:
     *   
     *   1.  Definite mode: TAKE BOOK, TAKE THE BOOK, TAKE BOTH BOOKS, TAKE
     *   THE THREE BOOKS.  The goal in definite mode is to choose the given
     *   number of objects, *and* to make sure that the player could *only*
     *   have meant those precise objects.  In other words, we're not
     *   allowed to make an arbitrary choice: in natural language, the
     *   definite mode says that the speaker believes the listener knows
     *   which *particular* object or objects the speaker is referring to.
     *   If we're not absolutely sure which objects the player is talking
     *   about, we have a disagreement with the player's apparent
     *   expectations and must ask for clarification.
     *   
     *   2.  Indefinite mode: TAKE A BOOK, TAKE ANY BOOK, TAKE TWO BOOKS.
     *   The goal is to choose the given number of objects from the
     *   possible matches, arbitrarily choosing from the available objects.
     *   
     *   3. Plural mode: TAKE BOOKS, TAKE THE BOOKS, TAKE ALL BOOKS.  The
     *   goal here is to choose all of the matching objects.  
     */
    selectObjects(cmd)
    {
        /* take the mode from the determiner */
        local mode = determiner;
        
        /* 
         *   If the player typed ALL or ANY or some such response in response to
         *   a disambiguation response, that response will have set a determiner
         *   we need to use instead.
         */
        if(cmd.disambig.length > 0)
            mode = cmd.disambig[1][1].determiner;
        

        /* 
         *   Sort the matches by listing order.  If we have a plural, this
         *   will make the order of processing more logical when there's
         *   some kind of natural order (such as alphabetized or numbered
         *   items).  
         */
        npMatches.groupSort(
            { ent, idx: [ent.obj.disambigGroup, ent.obj.disambigOrder] });

        /* if there's no determiner, assume definite */
        if (mode == nil)
            mode = Definite;

        /*
         *   If we're in Definite mode and we don't have a quantifier,
         *   check for a plural noun phrase.  A plural without a specific
         *   number puts us in Plural mode.  Consider the noun phrase to be
         *   plural if it matched any of our objects with plural usage.
         *   Even if some objects were singular in usage, one plural is
         *   enough to suggest that the name has plural usage. 
         */
        if (mode == Definite
            && quantifier == nil
            && npMatches.indexWhich({ m: m.match & MatchPlural }) != nil)
            mode = All;

        /* 
         *   Figure the target quantity.  If there's a quantifier, it's the
         *   quantifier value; otherwise we implicitly want a singleton.
         *   Note that the quantifier is ignored in Plural mode, since we
         *   simply want to match all of the objects in this case.  
         */
        local num = (quantifier != nil ? quantifier : 1);

        /*
         *   If we don't have enough objects to satisfy the request,
         *   complain about it. 
         */
        if (num > npMatches.length() 
            && objs.indexWhich({o: o.canSupply}) == nil)
            throw new InsufficientNounsError(cmd, self);
        
        if (mode == Definite && isAllEquivalent(npMatches) && npMatches.length > 1)
            mode = Indefinite;

        
        for(local cur in objs)
            cur.filterResolveList(self, cmd, mode);
        
        /* select the goal based on the mode */
        switch (mode)
        {
        case Definite:        
            /* 
             *   Definite mode.  If we have more than the desired number,
             *   we must disambiguate.  
             */
            if (npMatches.length() > num)
                disambiguate(cmd, num, cmd.action);
            else
                /* 
                 *   If we don't disambiguate we don't run the verify routine
                 *   that stores a reference to the object selected for this
                 *   role so that it can be available to the verify routine for
                 *   the other role; so we store a reference now.
                 */
                cmd.action.(role.objProp) = cmd.(role.objListProp)[1].obj;
            break;

        case Indefinite:
            /*
             *   Indefinite mode - we must select the desired number, but
             *   we can do so arbitrarily.  Simply select the first 'num'
             *   in the list.
             */
            
            /* start by getting object rankings from the verb */
            cmd.action.scoreObjects(cmd, role, npMatches);
            
            /* sort by score (highest to lowest), except for the ActorRole */
            npMatches.sort(SortDesc, { a, b: a.score - b.score });
            
            if (npMatches.length() > num)
                npMatches.removeRange(num + 1, npMatches.length());

            /* flag the objects as arbitrarily chosen */
            npMatches.forEach({ m: m.flags |= SelArbitrary });
            cmd.matchedMulti = true;
            break;

        case All:
            /* 
             *   Plural mode - select all of the objects.  Simply use the
             *   set we've already built.  Flag the selections as plural.  
             */
            npMatches.forEach({ m: m.flags |= SelPlural });

            /* 
             *   A plural that matched one thing is as if that thing were
             *   named: TAKE DETONATORS, for one string of them, is "Taken."
             */
            if (npMatches.length() > 1)
                cmd.matchedMulti = true;
            break;
        }
    }

    /* 
     *   Determine whether all matches in the matchList are impossible to
     *   disambiguate.
     */
    isAllEquivalent(matchList){
        local names = Distinguisher.getNames(
            matchList.mapAll({ x: x.obj }), nil);
        return (names.length() == 1);
    }
    
    /*
     *   Disambiguate the match list to select the given target number of
     *   objects.  
     */
    disambiguate(cmd, num, action)
    {
        /* start by getting object rankings from the verb */
        action.scoreObjects(cmd, role, npMatches);

        /* sort by score (highest to lowest) */
        npMatches.sort(SortDesc, { a, b: a.score - b.score });

        /* 
         *   To pick automatically, we need exactly 'num' objects at the
         *   highest score.  The sort put the object with the highest score
         *   at the start of the list, so the high-scoring subset is the
         *   subset that matches the first object's score.
         *   
         *   We only disambiguate in definite mode, and definite mode in
         *   input is the player's way of telling us that they think there
         *   are exactly this many objects that obviously apply to their
         *   command.  The score tells us which objects *we* think are the
         *   obvious choices for the command.  If we come up with the same
         *   set size that the player expressed, then we presumably
         *   understand what the player is saying.  If our set size differs
         *   from theirs, we're not thinking alike, so we need to ask for
         *   clarification.  
         */
        local sub = npMatches.subset({x: x.score == npMatches[1].score});
        
        if (isAllEquivalent(sub))
            sub.setLength(num);
        
        if (sub.length() == num)
        {
            /* 
             *   We have the desired number of most obvious matches, so
             *   we've successfully disambiguated it.  We might want to
             *   announce the selection, since we're making a guess, so
             *   generate a name for each that distinguishes it from the
             *   other items we could have matched.  
             */
            local names = Distinguisher.getNames(
                npMatches.mapAll({ x: x.obj }), nil);            

            /* save the disambiguated subset */
            npMatches = sub;

            /* mark each as disambiguated, and save the distinctive name */
            foreach (local m in npMatches)
            {
                m.flags |= SelDisambig;
                m.name = names.valWhich({ n: n[2].indexOf(m.obj) != nil })[1];
            }
            
            /* we've successfully disambiguated the phrase */
            return;
        }        
        else if (sub.length() > num && num > 1)                    
        {
            /*            
             *   We've asked for a definite number of 2 or more items, but there
             *   are different options among the best matches.  This poses a
             *   problem because there's no good disambiguation we can possibly
             *   ask here. So we just give up and ask them to be more specific.
             *   I can imagine someone responding to this message by just
             *   retyping a more specific form of the noun phrase. For example,
             *   after GET THE TWO MATCHES doesn't work, they might just want to
             *   type THE LIT MATCH AND AN UNLIT MATCH, but currently the parser
             *   does not do this.  Probably the showMsg should also refer to the
             *   specific noun phrase that is ambiguous in its message.
             */
            throw new AmbiguousMultiDefiniteError(cmd,self);
        }
    
        /*
         *   We have more than what we need in the highest scoring section,
         *   so make this the matches and proceed with disambiguation.
         *   This line makes it so that when you say something like "drop match"
         *   it will only try to disambiguate among the things you are holding.
         *   I think this behavior is more desirable, but am not certain.
         */
        npMatches = sub;
        

        /* it's still ambiguous, so throw an error to ask for help */
        ambigError(cmd);
        npMatches.setLength(num);
    }

    /*
     *   Throw an ambiguous noun phrase error for the current match list. 
     */
    ambigError(cmd)
    {
        /* if we have a reply to a past disambiguation question, apply it */
        local disambig = cmd.fetchDisambigReply();
        if (disambig != nil)
        {
            /* start a list for the result */
            local dmatches = new Vector(npMatches.length());

            /* add the object(s) selected by each noun phrase in the reply */
            foreach (local dnp in disambig)
            {
                /* 
                 *   resolve this noun phrase of the reply and add its
                 *   selections to the master list 
                 */
                dmatches.appendAll(
                    dnp.applyDisambig(cmd, npMatches, disambigNameList));
            }

            /* 
             *   If we get this far, we have a valid result set now, even
             *   if it's not of the original size.  The reply can select a
             *   different number of objects than originally implied, since
             *   the reply can say something like "the red one and the blue
             *   one" to pick more than one of the offered objects.  
             */
            npMatches = dmatches;
            return;
        }

        /* 
         *   Still ambiguous, so we need to ask for clarification, with a
         *   question like "Which do you mean, the red book, or the blue
         *   book?"  Generate the list of names.  
         */
        local nameList = Distinguisher.getNames(
            npMatches.mapAll({ x: x.obj }), true , true);

        /* 
         *   Sort by disambigGroup and disambigOrder.  Note that it's
         *   possible for a set to have more than one item with a
         *   disambigGroup, and these might not match.  We can't break up a
         *   set, though, so we'll just have to pick one group arbitrarily
         *   for the whole set. 
         */
        nameList.groupSort(new function(entry, idx)
        {
            /* find an arbitrary entry in the set with a disambigGroup */
            local gobj = entry[2].valWhich({ x: x.disambigGroup != nil });
            
            /* if we found one, use its group and order; otherwise use nil */
            return gobj != nil
                ? [gobj.disambigGroup, gobj.disambigOrder]
                : [nil, idx];
        });

        /* 
         *   remember this list, since it determines the meanings of
         *   ordinals ("the second one") in the reply 
         */
        disambigNameList = nameList;       
        
        /* throw the still-ambiguous error */
        throw new AmbiguousError(cmd, self, nameList);
        
        
    }

    /*
     *   Apply this noun phrase as a disambiguation reply to the given
     *   original list of matches to an ambiguous noun phrase.  
     */
    applyDisambig(cmd, ambigMatches, nameList)
    {
        /* 
         *   Start with the ambiguous list.  Our goal is to narrow the list
         *   that the original noun phrase matched, so start with the list
         *   and remove items that don't match the additional vocabulary
         *   and/or qualifiers in the reply.  
         */
        npMatches = ambigMatches;

        /* if there's an ordinal, pick out the selected item */
        if (ordinal != nil)
        {
            /* pick the name list entry based on the list position */
            local n;
            if (ordinal == -1 && nameList.length() > 0)
                n = nameList[nameList.length()];
            else if (ordinal >= 1 && ordinal <= nameList.length())
                n = nameList[ordinal];
            else
                throw new OrdinalRangeError(self, ordinal);

            /* 
             *   take the first object from the group, and build a resolved
             *   object list with this object 
             */
            n = n[2][1];
            npMatches = npMatches.subset({ m: m.obj == n });
        }

        /* if there's a locational qualifier, apply it */
        if (locQual != nil)
        {
            /* apply the locational qualifier */
            locQual.matchVocab(cmd);
            locQual.applyLocational();

            /* if that empties our list, flag it */
            if (npMatches.length() == 0)
                throw new NoneInLocationError(cmd, parent, locQual);
        }
                
        /* if there's a possessive qualifier, apply it */
        if (possQual != nil)
        {
            /* apply the possessive qualifier */
            possQual.matchVocabPoss(cmd);
            possQual.applyPossessive();

            /* if that empties our list, flag it */
            if (npMatches.length() == 0)
                throw new NoneInOwnerError(cmd, parent, possQual);
        }

        /* if there's a contents qualifier, apply it */
        if (contQual != nil)
        {
            /* apply the qualifier */
            contQual.matchVocab(cmd);
            contQual.applyContQual();

            /* if that empties our list, flag it */
            if (npMatches.length() == 0)
                throw new NoneWithContentsError(cmd, parent, contQual);
        }

        /* if there's vocabulary, apply it */
        if (tokens.length() > 0)
        {
            /*
             *   The basic vocabulary of the reply isn't as simple to
             *   handle as it might seem, since the words could refer to
             *   the object itself, a container, an owner, or the nominal
             *   contents.  Consider:
             *   
             *   Which bucket do you mean, the empty bucket, the bucket on
             *   the shelf, the tall fisherman's bucket, or the bucket of
             *   water?
             *   
             *   Players are accustomed to being able to answer these
             *   questions by entering just a word or two from the prompt,
             *   so we'd want to accept EMPTY, SHELF, TALL, and WATER for
             *   the respective choices.
             *   
             *   So: first assume that the reply refers to the object
             *   itself.  If we don't find any matches, try the other
             *   possibilities: containers, owners, and nominal contents.  
             */
            if (tokens.length() > 0 && npMatches.length() > 0)
            {
                /* first try applying the words to the object itself */
                local m = npMatches.subset(
                    { o: o.obj.matchNameDisambig(tokens) != 0 });
                
                /* if that didn't match anything, try containers */
                if (m.length() == 0)
                {
                    /* get the list of in-scope objects matching the tokens */
                    local locs = World.scope.subset(
                        { o: o.matchNameDisambig(tokens) != 0 });

                    /* get the subset of 'matches' that are in 'locs' */
                    m = npMatches.subset(
                        { o: locs.indexWhich(
                            { l: o.obj.isChild(l, nil) }) != nil });
                }
                
                /* if we still don't have any matches, try owners */
                if (m.length() == 0)
                {
                    /* get the list of scope objects plus potential owners */
                    local owners = new Vector(50, World.scope.toList());
                    foreach (local obj in npMatches)
                    {
                        local owner = obj.obj.owner;
                        if (owner != nil)
                            owners.appendAll(owner);
                    }

                    /* get the subset matching the tokens */
                    owners = owners.subset(
                        { o: o.matchNameDisambig(tokens) != 0 });

                    /* get the subset of 'matches' with owners in 'owners' */
                    m = npMatches.subset(
                        { o: owners.indexWhich(
                            { l: o.obj.ownedBy(l) }) != nil });
                }
                
                /* if we still don't have any matches, try nominal contents */
                if (m.length() == 0)
                {
                    /* get the list of in-scope objects matching the tokens */
                    local conts = World.scope.subset(
                        { c: c.matchNameDisambig(tokens) != 0 });

                    /* get the subset of 'matches' with contents in 'conts' */
                    m = npMatches.subset(
                        { o: conts.indexOf(o.obj.nominalContents) != nil });
                }
                
                /* if we've eliminated everything, it's an error */
                if (m.length() == 0)
                    throw new UnmatchedNounError(cmd, self);

                /* we're out of things to try, so take what we have */
                npMatches = m;
            }
        }

        /* determine how many the reply *wants* to select */
        local num = (quantifier != nil ? quantifier : 1);

        /* if we don't have enough, it's an error */
        if (npMatches.length() < num)
            throw new InsufficientNounsError(cmd, self);
        
        if (determiner == Definite && isAllEquivalent(npMatches))
            determiner = Indefinite;
        
        /* determine the actual number available */
        switch (determiner)
        {
        case Definite:
            /* 
             *   They want exactly the number indicated.  If we still have
             *   more than this, it's *still* ambiguous, so throw another
             *   ambiguity error to further disambiguate the new list.
             *   Otherwise, we're set.  
             */
            if (num < npMatches.length())
                ambigError(cmd);
            break;
            
        case Indefinite:
            /* indefinite - arbitrarily select any 'num' of the items */
            if (npMatches.length() > num)
                npMatches.removeRange(num + 1, npMatches.length());

            /* mark them as arbitrary */
            npMatches.forEach({ m: m.flags |= SelArbitrary });
            break;
            
        case All:
            /* all - keep all of the items */
            break;
        }

        /* return our final match list */
        return npMatches;
    }

    /*
     *   Resolve ALL.  This is called on a separate pass after
     *   selectObjects(), because two-object verbs sometimes resolve ALL in
     *   one slot according to the selection in the other slot.  
     */
    resolveAll(cmd)
    {
        /* if this is a simple ALL phrase, re-resolve it */
        if (determiner == All)
        {
            /* 
             *   If it's just ALL, re-match the vocabulary to pick up the
             *   final ALL list.  Otherwise, take the subset of the ALL
             *   list that matches the vocabulary. 
             */
            if (tokens == [])
            {
                /* it's just ALL - start over with the final ALL list */
                matchVocab(cmd);
            }
            else
            {
                /* 
                 *   it's ALL <somethings> - take the subset that's in the
                 *   final ALL list 
                 */
                local all = cmd.action.getAll(cmd, role);
                local sub = npMatches.subset({ m: all.indexOf(m.obj) != nil });

                /* 
                 *   If we found any objects in the intersection, keep only
                 *   the subset, since this is the set that actually makes
                 *   sense for this command.  If the subset is empty,
                 *   though, ignore it and stick with the objects we've
                 *   already selected based on the vocabulary; these will
                 *   probably fail the command, but that'll make more sense
                 *   to the player than claiming there's nothing matching
                 *   the description they gave.  
                 */
                if (sub.length() != 0)
                    npMatches = sub;
            }
        }
    }
    
    /*
     *   Resolve reflexive pronouns.  Our Command calls this AFTER
     *   resolving all of the regular noun phrases, because reflexives
     *   refer back to other nouns in the same command.  
     */
    resolveReflexives(cmd)
    {
        /* if we have a reflexive pronoun object in the list, resolve it */
        if (npMatches.length() == 1 && npMatches[1].obj.ofKind(Pronoun))
        {
            /* 
             *   We have a reflexive pronoun pending.  Ask the command for
             *   the current meaning of the reflexive.  
             */
            npMatches = cmd.resolveReflexive(npMatches[1].obj).mapAll(
                { x: new NPMatch(self, x, 0) });

            /* it's an error if that didn't yield anything */
            if (npMatches.length() == 0)
                throw new NoAntecedentError(self, pronoun);
        }
        else
        {
            /*
             *   This isn't a reflexive, so it's a candidate to be an
             *   antecedent of a reflexive later in the phrase.  Pass it
             *   along to the command to note for future use.  Since we
             *   visit the noun phrases in their order of appearance in the
             *   command, we'll naturally have the latest one before the
             *   pronoun when we encounter a pronoun, which is exactly what
             *   we want: a reflexive pronoun binds to the nearest
             *   preceding noun that matches in gender, number, etc.  
             */
            npMatches.forEach({ match: cmd.saveReflexiveAnte(match.obj) });

            /* also save the entire list, for THEMSELVES */
            cmd.saveReflexiveAnte(npMatches.mapAll({ x: x.obj }));
        }
    }

    /* Build the 'objs' list from the match list */
    buildObjList()
    {
        objs = npMatches.mapAll({x: x.obj});
    }

    /* 
     *   List of NPMatch objects.  This is populated during the matchName
     *   phase with the list of possible vocabulary matches, and then
     *   reduced during disambiguation to the final set.  
     */
    npMatches = []

    /* 
     *   List of resolved objects.  This is populated after disambiguation
     *   from the 'matches' set - it contains the same objects, but simply
     *   the objects rather than the NPMatch wrappers. 
     */
    objs = []

    /* add a literal to this phrase */
    addLiteral(tok) { tokens += tok; }

    /* add a possessive qualifier, returning the new noun phrase */
    addPossessive(prod)
    {
        /* create, store, and return a new noun phrase for the possessor */
        return possQual = new NounPhrase(self, prod);
    }

    /* add a contents qualifier, returning the new noun phrase */
    addContents(prep, prod)
    {
        /* remember the contents preposition */
        contPrep = prep;

        /* create, store, and return a new noun phrase for the contents */
        return contQual = new NounPhrase(self, prod);
    }

    /* add a locational qualifier, returning the new noun phrase */
    addLocation(locType, prod)
    {
        /* create a new noun phrase for the location */
        locQual = new NounPhrase(self, prod);

        /* set its location type */
        locQual.locType = locType;

        /* return the new phrase */
        return locQual;
    }

    /* add a quantifier, given as an integer value */
    addQuantifier(num)
    {
        quantifier = num;
    }

    /* add an ordinal, given as an integer value */
    addOrdinal(num)
    {
        ordinal = num;
    }

    /* add an exclusion list item */
    addExclusionItem(prod)
    {
        /* if we don't already have an exclusion list, create one */
        if (exclusions == nil)
            exclusions = [];

        /* create a new NounPhrase */
        local np = new NounPhrase(self, prod);

        /* add it to the exclusion list */
        exclusions += np;

        /* return the new noun phrase */
        return np;
    }

    /*
     *   Does this noun phrase refer to multiple objects structurally?
     *   This is true if any the matches used plural words, or the
     *   determiner is All, or we have a quantifier greater than 1.  
     */
    isMultiple()
    {
        return determiner == All
            || (quantifier != nil && quantifier > 1)
            || npMatches.indexWhich({ m: m.match & MatchPlural }) != nil;
    }

    /* 
     *   the Command list we're a part of (&dobjNPs, &iobjNPs, etc: the
     *   Command overrides this to the actual list property for a primary
     *   noun phrase, and for qualifiers such as possessives, this
     *   inherited version looks it up via the parent) 
     */
    role = (parent.role)

    /* the NounPhrase we qualify, if we're a possessive or locational */
    parent = nil

    /* the grammar production match object for this noun phrase */
    prod = nil

    /* 
     *   the grammar match for the core noun phrase; this is the part that
     *   names a single object, stripped of all qualifiers (such as
     *   possessives, articles, quantifiers, and locational phrases) 
     */
    coreProd = nil

    /* the literal tokens making up the noun phrase */
    tokens = []

    /* the pronoun, if any, as a Pronoun object */
    pronoun = nil

    /* the possessive qualifier, if any ("BOB'S box") */
    possQual = nil

    /* the locational qualifier phrase, if any ("the box ON THE SHELF") */
    locQual = nil

    /* 
     *   The locational qualifier relationship, as a LocType object.  (This
     *   is stored on the locational qualifier noun phrase itself, not on
     *   the underlying noun phrase it qualifies.)  
     */
    locType = nil

    /* the contents qualifier phrase, if any ("the bucket OF WATER") */
    contQual = nil

    /* the preposition of the contents qualifier */
    contPrep = nil

    /* the quantifier, if any, as a number: for "five books", this is 5 */
    quantifier = nil

    /* 
     *   The ordinal value, if any, as a number: for "the third one", this
     *   is 3.  This is intended for use in disambiguation replies, to let
     *   the user pick out an item by its position in the offered list.  
     */
    ordinal = nil

    /* the determiner, if any, as a Determiner object */
    determiner = nil

    /* 
     *   the exclusion list, if any (this is the list following EXCEPT or
     *   BUT in a phrase like ALL EXCEPT THE RED ONES) 
     */
    exclusions = nil

    /* the name list from the disambiguation query */
    disambigNameList = nil
;

/*
 *   TopicPhrase is a special kind of NounPhrase for topics (ASK ABOUT,
 *   TELL ABOUT, TALK ABOUT, LOOK UP, etc).  These phrases aren't resolved
 *   to game-world objects the way ordinary noun phrases are, but instead
 *   are resolved to conversation topic objects.  
 */
class TopicPhrase: NounPhrase
     /*
     *   Get the list of objects matching the vocabulary words in our noun
     *   phrase.  Populates our 'matches' property with a vector of matching
     *   objects.  This doesn't look at any of our qualifiers, or attempt
     *   to disambiguate contextually; it simply finds everything in scope
     *   that the noun phrase could refer to.  
     */
    matchVocab(cmd)
    {
        /* start with an empty vector */
        local v = new Vector(32);
        
        /* get the current scope list */
        //        local scope = World.scope;
        
        
        local scope = Q.topicScopeList;
        
        /* check what kind of phrase we have */
        if (pronoun != nil)
        {
            /* it's a pronoun - resolved based on the antecedent */
            addMatches(v, pronoun.resolve(), 0);
            
            /* if there are no antecedents, flag the error */
            if (v.length() == 0)
                throw new NoAntecedentError(self, pronoun);
            
            /* filter for in-scope objects (or reflexive placeholders) */
            v = v.subset(
                { m: m.obj.ofKind(Pronoun) || scope.find(m.obj) });
            
            /* if that leaves nothing, flag the error */
            if (v.length() == 0)
                throw new AntecedentScopeError(cmd, self, pronoun);
            
        }
        
        else
        {
            /* 
             *   It's a named object.  Our 'tokens' property is a list of the
             *   words in the noun phrase in the user input.  Match it against
             *   the objects in physical scope.
             */
             v.appendAll(matchNameScope(cmd, scope));
            
            /* 
             *   Create a dummy object to represent the literal text; we may
             *   need this even if there are other matches to ensure that a
             *   regular expression is matched on a TopicEntry.
             */
            local obj = new Topic(tokens.join(' ').trim());
            
            /* 
             *   Note that the dummy object has been newly created so it can defer to any
             *   user-defined topics when it comes to selecting the best match.
             */
            obj.newlyCreated = true;
            
            /* Wrap the dummy object in am NPMatch object */
            local lst = [obj];

            addMatches(v, lst, 1);
            
            npMatches = v;  
            
            cmd.madeTopic = true;
            

        }
        
        /* save the match list so far */
        npMatches = v;
        
        
        
        /* 
         *   if we have a possessive qualifier, apply it, but only if it is to be applied to a Thing
         *   (rather than a Topic)
         */
        if (possQual != nil && npMatches.indexWhich({x: x.obj.ofKind(Thing)}))
        {
            /* match vocabulary for the possessive phrase */
            possQual.matchVocabPoss(cmd);
            
            /* 
             *   apply the qualifier, filtering out things not owned by the
             *   object named in the qualifier
             */
            possQual.applyPossessive();
            
            /* if that empties our list, flag it */
            if (npMatches.length() == 0)
                throw new NoneInOwnerError(cmd, self, possQual);
            
            /* expand the error text to include the possessive qualifier */
            expandErrName(possQual);
        }
        
      
        
//        if(matches.length == 0)
        {        
           
        }
        
        
        local res = new ResolvedTopic(npMatches.mapAll({o: o.obj}).toList, tokens);
        
        res = new NPMatch(v[1].np, res, v[1].match);
        
        npMatches = new Vector([res]);
        
        
    }
    
    matchNameScope(cmd, scope)
    {
        /* set up a vector for the results */
        local v = new Vector(32);
        
        /*
         *   Run through the scope list and ask each object if it matches
         *   the noun phrase.  Keep the ones that match.  
         */
        foreach (local obj in scope)
        {
            /* ask this object if it matches */
            local match = obj.matchName(tokens);
            
            /* if it matches, include it in the results */
            if (match)
                v.append(new NPMatch(self, obj, match));
        }


        /* return the list */
        return v;
    }
    
    selectObjects(cmd)
    {
        filterResolveList(self, cmd, All);
    }
;

class ResolvedTopic: object
    construct(lst, toks)
    {
        /* 
         *   if our list of topics has more than one entry, sort it in ascending
         *   order of length of name. That's because the shorter the name, the
         *   closer it may be to what the player actually typed.
         */
        if(lst != nil && lst.length > 1)
            topicList = lst.sort(SortAsc, {a, b: a.name.length - b.name.length});
        else       
            topicList = lst;    
        tokens = toks;
    }    
    
    topicList = nil
    tokens = nil
    
    /* Get the object representing this ResolvedTopic's best match. */
    getBestMatch()
    {
        if(topicList == nil)
            return nil;
        
        /* 
         *   If possible, find an object that hasn't just been newly created by the parser as a
         *   fallback wrapper (because we'd prefer to use Thing or Topic defined by the user).
         */
        local top = topicList.valWhich({t:!t.newlyCreated});
        
        /*   
         *   If we find a user-defined topic, return that; otherwise simply return the first item in
         *   the list.
         */
        return top ?? topicList[1];
    }    
    
    getTopicText = tokens.join(' ').trim()
    theName = (topicList != nil ? topicList[1].theName : getTopicText)
    aName = (topicList != nil ? topicList[1].aName : getTopicText)
    name = (topicList != nil ? topicList[1].name : getTopicText)
    person = 3
;

/*
     *   LiteralPhrase is a special kind of NounPhrase for literals (TYPE,
     *   WRITE, SET TO, etc).  These phrases aren't resolved to game-world
     *   objects, but instead are just treated as literal text.  
 */
class LiteralPhrase: NounPhrase
    matchVocab(cmd)
    {
        local v = new Vector(2);
        
        /* Recreate the literal text */
        local litName = tokens.join(' ');
               
        /* Create a dummy object to represent the literal text */
        local obj = new LiteralObject(litName.trim());
        
        /* Wrap the dummy object in am NPMatch object */
        local lst = [obj];
        addMatches(v, lst, MatchNoApprox);
        
        npMatches = v;   
    }
    
    selectObjects(cmd)
    {
        /* do nothing; there's only one object */
    }
;

/* object to hold the result of a literal input */

class LiteralObject: object
    construct(name_)
    {
        name = name_;
    }
    
    name = nil
    theName = (name)
    person = 3
;
    
/*
 *   NumberPhrase is a special kind of NounPhrase for numeric literals
 *   (e.g., FOOTNOTE n).  These phrases aren't resolved to game-world
 *   objects, but are simply taken as numeric values. 
 */
class NumberPhrase: NounPhrase
     matchVocab(cmd)
    {
        local v = new Vector(2);
        
        /* Get the number just entered*/        
        local val = prod.numval;
               
        /* Create a dummy object to represent the literal text */
        local obj = new NumericObject(tokens, val);
        
        /* Wrap the dummy object in am NPMatch object */
        local lst = [obj];
        addMatches(v, lst, MatchNoApprox);
        
        npMatches = v;   
    }
    
    selectObjects(cmd)
    {
        /* do nothing; there's only one object */
    }
;

/* An object to hold a numerical value. */
class NumericObject: object
    construct(toks, val)
    {   
        numToks = toks;
        numVal = val;
    }
    
    numToks = nil
    numVal = nil
    numStr = (numToks.join(' '))
;
    

/* ------------------------------------------------------------------------ */
/*
 *   NPMatch is an object that describes one object matching a noun phrase.
 */
class NPMatch: object
    construct(np, obj, match)
    {
        /* save the NounPhrase, the object we matched, and the match flags */
        self.np = np;
        self.obj = obj;
        self.match = match;

        /* 
         *   set the name initially to the object name; the Command will
         *   replace this before execution with a name from the
         *   Distinguishers that's unique relative to the other objects in
         *   the list 
         */
        self.name = obj.name;

        /*
         *   Calculate the match strength for sorting purposes.
         *   
         *   The strength tells us how well the vocabulary matched the
         *   object.  Matches without truncation are stronger than those
         *   that include truncated words; likewise character
         *   approximation.  Matches that consist of entirely adjectives
         *   are weaker than those that contain nouns or plurals (for
         *   example, if we have a TOY CAR and a TOY CAR REMOTE CONTROL in
         *   scope, we'd consider CAR to be an unambiguous match to the TOY
         *   CAR, since the match to the REMOTE is weak by virtue of being
         *   all adjectives).
         *   
         *   The MatchXxx bit flags are arranged in arithmetic order of
         *   match strength, so the 'match' value basically equals the
         *   strength.  However, for the strength calculation, plurals and
         *   nouns are equivalent.  So the strength value is the match
         *   value with any plural flag replaced by the noun flag. 
         */
        self.strength = (match & ~MatchPlural)
            | (match & MatchPlural ? MatchNoun : 0);
    }

    /* the NounPhrase we matched */
    np = nil

    /* the matching object */
    obj = nil

    /* 
     *   the match flags - this is a combination of MatchXxx flags as
     *   returned from Mentionable.matchName()
     */
    match = 0

    /* the match strength, for sorting the match list */
    strength = 0

    /* the selection/disambiguation flags (SelXxx) */
    flags = 0

    /*
     *   Disambiguation score.  This is a number assigned by the action in
     *   scoreObjects().
     */
    score = 0

    /*
     *   The name, for announcement purposes.  This is filled in by the
     *   Command during execution.  The Command figures the name so that
     *   it's distinguished from all of the other objects in the same noun
     *   role in the command.  
     */
    name = ''
;


/* ------------------------------------------------------------------------ */
/*
 *   Our root class for grammar productions.  (A "production" represents a
 *   match to a syntax rule, as defined with a 'grammar' template.)
 *   
 *   The language module's grammar rules can define certain special
 *   properties on any production match object, and we'll find them in the
 *   course of building the command from the match tree:
 *   
 *   endOfSentence=true - define this on a production for a sentence-ending
 *   verb conjunction.  In English (and most Western languages), this can
 *   be used with rules that match punctuation marks like periods,
 *   exclamation points, and question marks, since these marks typically
 *   end a sentence.  The parser distinguishes between the grammar rules
 *   for the first clause in a sentence vs subsequent clauses.  It starts a
 *   new input line with the first-in-sentence rule, then uses the
 *   additional clause rule for each subsequent clause.  When a clause ends
 *   with a sentence-ending mark, though, we'll treat the next clause as a
 *   sentence opener again.  
 */
class Production: object
    /* get the original text of the command for this match */
    getText()
    {
        /* if we have no token list, return an empty string */
        if (tokenList == nil)
            return '';
        
        /* build the string based on my original token list */
        return cmdTokenizer.buildOrigText(getTokens());
    }

    /* get my original token list, in canonical tokenizer format */
    getTokens()
    {
        /* 
         *   return the subset of the full token list from my first token
         *   to my last token
         */
        return nilToList(tokenList).sublist(
            firstTokenIndex, lastTokenIndex - firstTokenIndex + 1);
    }

    /*
     *   Build the command for this production and its children.  By
     *   default, we'll simply traverse into our children.  
     */
    build(cmd, np)
    {
        /* if this is a sentence-ending mark, note it */
        if (endOfSentence)
            noteEndOfSentence(cmd, self);

        /* run through our list of matches */
        local info = grammarInfoForBuild();
        for (local i = 2, local len = info.length() ; i <= len ; ++i)
        {
            /* get the current match */
            local cur = info[i];

            /* process it based on its type */
            switch (typeOf(cur))
            {
            case TypeString:
                /* it's a literal token match item */
                visitLiteral(cmd, np, cur);
                break;

            case TypeObject:
                /* 
                 *   An object is a production sub-tree.  Set its parent
                 *   pointer to point back at us. 
                 */
                cur.parent = self;

                /* visit the production */
                visitProd(cmd, np, cur);
                break;
            }
        }

        /* 
         *   If there's a determiner, apply it the noun phrase.  Apply the
         *   determiner after building out the subtree, so that the parent
         *   determiner overrides any found in the subtree. 
         */
        if (determiner != nil)
            np.determiner = determiner;
    }

    /*
     *   Get the grammar match list for build() purposes.  By default, this
     *   simply returns the grammarInfo() results, which are automatically
     *   generated by the compiler to return a list of the "->prop" values from
     *   the matched grammar rule.  Some rules might want to modify that default
     *   value list, so we provide this routine as an override hook.
     */
    grammarInfoForBuild()
    {
        return grammarInfo();
    }
    
    
    /*
     *   Add a new NounPhrase item to the list under construction.  Certain
     *   productions are associated with specific functional slots in the
     *   abstract command - direct object, indirect object, EXCEPT list,
     *   etc.  This routine is for such production subclasses to override,
     *   to direct new noun phrases into the appropriate slot lists.  In a
     *   grammar, the functional role is typically at a higher level in the
     *   tree, with ordinary noun phrases plugged in underneath.
     *   
     *   Our default handling is to first check our nounPhraseRole
     *   property; if it's set, it tells us the role that this sub-tree
     *   plays in the predicate (direct object, indirect object,
     *   accessory).  We use that information to add the new NounPhrase to
     *   the Command list that we're building for our assigned role.
     *   
     *   If nounPhraseRole is nil, then we simply pass the request up to
     *   our parent.  Eventually we should reach a node encoding the
     *   function slot.  
     */
    addNounListItem(cmd, prod)
    {
        if (nounPhraseRole != nil)
            return cmd.addNounListItem(nounPhraseRole, prod);
        else
            return parent.addNounListItem(cmd, prod);
    }

    /* 
     *   Note an end-of-sentence marker.  We'll simply notify our parent by
     *   default. 
     */
    noteEndOfSentence(cmd, prod)
    {
        if (parent != nil)
            parent.noteEndOfSentence(cmd, prod);
    }

    /*
     *   The NounPhrase subclass to use for noun phrases within this
     *   sub-tree.  By default, we look to our parent; if we don't have a
     *   parent, we use the base NounPhrase class.
     *   
     *   Special phrase types (topics, literals, and numbers) have their
     *   own NounPhrase subclasses.  This is important because the
     *   resolution rules for these phrase types differ from the regular
     *   object resolution rules.  
     */
    npClass = (parent != nil ? parent.npClass : NounPhrase)

    /*
     *   My assigned noun phrase role, as a NounRole object.  This must be
     *   explicitly set for the top node in a noun slot (which can be a
     *   noun list production, a single noun production, a topic, etc).
     *   
     *   In a positional language grammar, the predicate production will
     *   mark its immediate child in each noun phrase slot by setting this
     *   according to the role that the sub-tree plays in the predicate
     *   grammar.  Non-positional languages that use grammatical case or
     *   other ways of encoding the role information must set this some
     *   other way.  
     */
    nounPhraseRole = nil

    /*
     *   Get our noun phrase role.  If we don't have a role defined
     *   directly, we'll inherit the role from our parent node. 
     */
    getNounPhraseRole()
    {
        return nounPhraseRole != nil
            ? nounPhraseRole : parent.nounPhraseRole;
    }

    /* 
     *   Visit a literal token child in our sub-tree.  This is called
     *   during the build process for each literal token in our child list.
     *   By default, we add the token to the command's current noun phrase.
     */
    visitLiteral(cmd, np, tok)
    {
        /* add the literal to the current noun phrase */
        if(np != nil)
           np.addLiteral(tok);
    }

    /* 
     *   Visit a production object in our list.  This is called during the
     *   build process for each production object in our child list.  By
     *   default, we simply build the child production recursively.  
     */
    visitProd(cmd, np, prod)
    {
        /* build out this production recursively */
        prod.build(cmd, np);
    }

    /*
     *   The determiner that this production applies to the noun phrase
     *   it's part of, as a Determiner object.  If this is non-nil, this
     *   Determiner will be set in the current NounPhrase when we visit
     *   this production in the build process.  
     */
    determiner = nil

    /* 
     *   My parent production.  The low-level GrammarRule mechanism doesn't
     *   set this up, so we set it up ourselves in the course of building
     *   out the tree.  In build(), just before we visit each
     *   sub-production, we set the sub-production's 'parent' property to
     *   point back to the parent production.  This property is therefore
     *   always set while we're traversing the child's tree, but won't
     *   necessarily be set yet if we're not currently working somewhere
     *   within the child's tree.  That means that you can always look at
     *   'parent' within your own build() routine or a child build()
     *   routine, but you can't necessarily look at it across the tree or
     *   within your own children.  
     */
    parent = nil

    /* 
     *   Find a parent matching a given test.  We'll scan up the parent
     *   tree, looking for the nearest parent p for which func(p) returns
     *   true, returning p.  If we can't find one, we return nil.  
     */
    findParent(func)
    {
        /* find the nearest parent that passes the callback test */
        local par;
        for (par = parent ; par != nil && !func(par) ; par = par.parent) ;

        /* return what we found */
        return par;
    }

    /* Is this production a child of the given production? */
    isChildOf(prod)
    {
        /* look up my parent tree for the given parent */
        for (local par = parent ; par != nil ; par = par.parent)
        {
            /* if this is the one we're looking for, we're a child */
            if (par == prod)
                return true;
        }

        /* didn't find it */
        return nil;
    }

    /*
     *   Find the action.  This finds the child of type VerbProduction,
     *   then retrieves the action from the verb production.  
     */
    findAction()
    {
        /* find the VerbProduction among our children */
        local vp = findChild(VerbProduction);

        /* return the action from the VerbProduction, if we found it */
        return (vp != nil ? vp.action : nil);
    }

    /*
     *   Find a child of a given class. 
     */
    findChild(cls)
    {
        /* if I'm of the desired class, we're done */
        if (ofKind(cls))
            return self;

        /* recursively scan my children */
        for (local gi = grammarInfo(), local i = 2, local len = gi.length() ;
             i <= len ; ++i)
        {
            /* try this child */
            local chi = gi[i].findChild(cls);
            if (chi != nil)
                return chi;
        }

        /* didn't find it */
        return nil;
    }
;

/*
 *   CommandProduction is a special Production subclass for the top-level
 *   grammar rule for the overall command. 
 *   
 *   Each instance of this type of production must define the following
 *   '->' properties in its syntax template:
 *   
 *   actor_ is the noun phrase giving the addressee of the command, if any.
 *   A command such as TELL ACTOR TO DO X or (using the long-standing IF
 *   convention) ACTOR, DO X addresses a command to an actor; i.e., it
 *   tells the actor to carry out the command, rather than the player's
 *   avatar.  A command that isn't addressed to an actor can leave actor_
 *   as nil.  
 *   
 *   cmd_ is the *first* predicate phrase (see below), in the desired order
 *   of execution.  For example, for "open the door and go north", cmd_
 *   should be set to the match tree for the "open the door" predicate.
 *   
 *   conj_ is any conjunction or punctuation ending the first predicate
 *   phrase.  This might be a period at the end of the sentence, or a word
 *   like 'and' or 'then' that can separate multiple commands.  This can be
 *   nil if there's no conjunction at all (such as when the whole command
 *   is just the first predicate).  The reason we need conj_ is that it
 *   tells us where any subsequent command on the same command line starts.
 *   If cmd2_ is not nil, we'll ignore conj_ and use cmd2_ instead for this
 *   purpose.
 *   
 *   cmd2_ is optional: it's the *second* predicate phrase.  If this is not
 *   nil, it tells the parser where to start parsing the next predicate on
 *   the same command line after finishing with the first one.  This is
 *   optional, even if the command line really does have more than one
 *   predicate, because the parser can use conj_ instead to infer where the
 *   second predicate must start.
 *   
 *   (It's probably intuitively obvious what "first predicate" means, but
 *   for the sake of translators, here's a more thorough analysis.  Some
 *   command productions can match more than one predicate phrase, but this
 *   is only for the sake of determining where the first one ends,
 *   syntactically.  The execution engine actually only carries out the
 *   first predicate matched for a given parse tree - it simply ignores any
 *   others in the same tree.  After we finish executing the first
 *   predicate from the match, we go back and re-parse the remaining text
 *   from scratch, as raw text; at that point, the next predicate in the
 *   text becomes the first predicate in the new parse tree and gets
 *   executed.  We repeat this until we run out of text.  So we do
 *   eventually execute everything the player types in - but not on the
 *   first parse; we have to do one parse per predicate.  We have to repeat
 *   the parsing because carrying out the first action could change the
 *   game state in such a way that we'll find a different match to the next
 *   predicate than we would have if we'd parsed everything up front.  By
 *   "first predicate phrase", then, we mean the one that gets executed
 *   first.  The point is to carry out the user's wishes as expressed in
 *   the command, so we want the first predicate we execute to be the one
 *   that the player *intends* to be carried out first; so by "first" we
 *   really mean the one that a speaker of the natural language would
 *   expect to be performed first, given the structure of the sentence and
 *   the rules of the language.  In English, this is easy: X THEN Y or X,Y
 *   or X AND Y all mean "first do X, then do Y" - the reading order is the
 *   same as the execution order.)  
 */
class CommandProduction: Production
    /* -> property: the match tree for the addressee, if any */
    actor_ = nil

    /*
     *   The grammatical person of the actor to whom we're giving orders.
     *   This is 2 for second person and 3 for third person.  (It's not
     *   meaningful to give orders in the first person.)
     *   
     *   In English (and probably most languages), commands of the form
     *   ACTOR, DO SOMETHING address ACTOR in the second person.  In
     *   contrast, TELL ACTOR TO DO SOMETHING gives orders to ACTOR, but in
     *   the third person.
     *   
     *   In the second-person form of giving orders, second-person pronouns
     *   (YOU, YOURSELF) within the command will refer back to the actor
     *   being addressed: BOB, EXAMINE YOURSELF tells Bob to look at Bob.
     *   In the indirect form, YOU refers to the player character: TELL BOB
     *   TO EXAMINE YOU tells Bob to look at the PC.
     *   
     *   The default is 2, since the long-standing IF convention is the
     *   ACTOR, DO SOMETHING format.  Override this (to 3) for TELL TO
     *   grammar rules.  
     */
    actorPerson = 2
    
    /* build the tree */
    build(cmd, np)
    {
        /* if we're giving orders, tell the command which person they're in */
        if (actor_ != nil)
            cmd.actorPerson = actorPerson;

        /* 
         *   if we have a second predicate or a conjunction, note where the
         *   second predicate starts 
         */
        if (cmd2_ != nil)
        {
            /* 
             *   we have a second predicate production, so the second
             *   predicate starts with the first token of that production 
             */
            cmd.nextTokens = tokenList.sublist(cmd2_.firstTokenIndex);
        }
        else if (conj_ != nil)
        {
            /* 
             *   we don't have an explicit second predicate production, but
             *   we do have a conjunction, so the second predicate must
             *   start at the next token after the conjunction 
             */
            cmd.nextTokens = tokenList.sublist(conj_.lastTokenIndex + 1);
        }

        /* do the normal work */
        inherited(cmd, np);
    }

    /* visit a production */
    visitProd(cmd, np, prod)
    {
        /* if this is the actor, create a NounPhrase for the actor role */
        if (prod == actor_)
            np = cmd.addNounListItem(ActorRole, prod);

        /*
         *   If this is the first predicate, actor, or conjunction, build
         *   it out as usual; otherwise ignore it.  We specifically don't
         *   want to build out any command processing for a second or
         *   subsequent predicate, because we only execute the first
         *   predicate in a parse tree.  
         */
        if (prod is in (cmd_, actor_, conj_))
        {
            /* expand the token extent to include this phrase */
            if (prod.lastTokenIndex > cmd.tokenLen)
                cmd.tokenLen = prod.lastTokenIndex;

            /* do the normal work */
            inherited(cmd, np, prod);
        }
    }

    /* note the end of the sentence */
    noteEndOfSentence(cmd, prod)
    {
        /* 
         *   if the production is within the conjunction, the command ends
         *   the sentence 
         */
        if (prod == conj_ || prod.isChildOf(conj_))
            cmd.endOfSentence = true;
    }
;

/*
 *   A NounRole is a internal parser object that provides information on a
 *   given noun role in a predicate.
 *   
 *   A noun role is one of the standard semantic roles that a noun phrase
 *   can play in a natural language predicate.  A predicate is a
 *   combination of an action and the objects that it applies to.  Any
 *   given verb has a set of assigned roles that need to be filled to make
 *   a complete thought.  (Sometimes the same verb word has multiple senses
 *   with different numbers of slots to fill, but you can think of the
 *   different senses as actually being different actions at some abstract
 *   level, which all happen to share the same verb word.)  For example,
 *   TAKE requires a noun phrase telling us which object is to be taken;
 *   this is called the direct object of the verb.  PUT X IN Y has a direct
 *   object (the thing to be put somewhere) and an indirect object (the
 *   place to put it).
 *   
 *   Natural languages use a fairly small number of these noun roles.  Most
 *   predicates in most languages have just one role: TAKE, DROP, OPEN,
 *   CLOSE.  We call this first-and-only noun role the direct object.  A
 *   few predicates have two roles: PUT IN, GIVE TO, UNLOCK WITH.  We call
 *   the second role the indirect object.  A very few predicates have three
 *   roles: TRADE BOB AN APPLE FOR AN ORANGE, PUT PLUTONIUM IN REACTOR WITH
 *   TONGS.  We call the third role the "accessory" object (which is
 *   something we made up - there doesn't seem to be an agreed-upon word
 *   among linguists for this role).  And it appears that there's simply no
 *   such thing as a "tetratransitive" verb in any natural human language,
 *   so we don't bother defining a fourth slot.
 *   
 *   (It would be easy for a game to add an object defining a fourth slot,
 *   analogous with these others, and use it to include a fourth noun
 *   phrase in the grammar for applicable verbs.  The rest of the parser
 *   will pick it up automatically if you do.  However, the practical
 *   utility of this seems minimal.  *Three*-noun verbs are incredibly rare
 *   in IF, in part because situations requiring them are rare, and in part
 *   because they're almost guaranteed to vex players and be panned as
 *   guess-the-syntax puzzles.  One can only imagine how a *four*-noun
 *   command would be received.)  
 */
class NounRole: object
    /* 
     *   The -> property slot in the predicate grammar that's assigned to
     *   this role.  This is the property that predicate grammar rules
     *   assign for the match tree for a noun phrase taking this role.
     */
    matchProp = nil

    /* the NounPhrase list property in the Command object for this role */
    npListProp = nil

    /* the object match list property in the Command object for this role */
    objListProp = nil

    /* the property in the Command for the *current* item being executed */
    objProp = nil

    /* the property in the Command for the current item's NPMatch */
    objMatchProp = nil

    /*
     *   Is this a predicate noun phrase role?  This is true for roles that
     *   serve as objects of a verb: direct object, indirect object,
     *   accessory.  This is nil for non-predicate roles, such as the
     *   addressee actor. 
     */
    isPredicate = true

    /* 
     *   the predicate match object property that gives the grammar rule
     *   for parsing a reply to a missing noun question for this role 
     */
    missingReplyProp = nil

    /* 
     *   name - this is an ID string that we use internally for embedding
     *   the role in things like verb template strings 
     */
    name = ''

    /*
     *   Internal sequence number.  This tells us the order in which this
     *   role appears in lists (including argument lists) when we store
     *   lists of roles.  
     */
    order = 1000

    /* class property: master list of all roles */
    all = []

    /* class property: master list of all predicate roles */
    allPredicate = []

    /* on construction, populate the various maps */
    construct()
    {
        /* add it to our master list of roles */
        NounRole.all += self;

        /* add it to the master list of predicate roles, if applicable */
        if (isPredicate)
            NounRole.allPredicate += self;
        
        /* keep the lists in sorted order */
        NounRole.all = NounRole.all.sort(SortAsc, { a, b: a.order - b.order });
        NounRole.allPredicate = NounRole.allPredicate.sort(
            SortAsc, { a, b: a.order - b.order });
    }
;

/*
 *   The DirectObject role is the role of the object being most directly
 *   acted upon in the command.  The is the only role in a verb that has
 *   only one object.  In a verb with two objects, this is the object most
 *   directly affected.  For example, UNLOCK DOOR WITH KEY directly acts
 *   upon the door, so the door is the direct object; the key isn't the
 *   direct object because it's merely a tool used to effect the change on
 *   the door.  
 */
DirectObject: NounRole
    matchProp = &dobjMatch
    npListProp = &dobjNPs
    objListProp = &dobjs
    objProp = &dobj
    objMatchProp = &dobjInfo
    missingReplyProp = &dobjReply
    curObjProp = &curDobj
    name = 'dobj'
    order = 1
;

/*
 *   The IndirectObject role is the role of a secondary object that is used
 *   in the command, but isn't the primary object being acted upon.  This
 *   is usually a tool (UNLOCK dobj WITH iobj), a destination (PUT dobj IN
 *   iobj), or a topic (ASK dobj ABOUT iobj). 
 */
IndirectObject: NounRole
    matchProp = &iobjMatch
    npListProp = &iobjNPs
    objListProp = &iobjs
    objProp = &iobj
    objMatchProp = &iobjInfo
    missingReplyProp = &iobjReply
    curObjProp = &curIobj
    name = 'iobj'
    order = 2
;

/*
 *   The AccessoryObject role is for a *third* object, beyond the direct
 *   and indirect objects, involved in the command.  This might be a peer
 *   to the indirect object in an exchange (TRADE dobj AN iobj FOR AN
 *   accessory), but the canonical IF use is as a tool in a two-object
 *   operation (PUT dobj IN iobj WITH accessory, WRITE dobj ON iobj WITH
 *   accessory).  
 */
AccessoryObject: NounRole
    matchProp = &accMatch
    npListProp = &accNPs
    objListProp = &accs
    objProp = &acc
    objMatchProp = &accInfo
    missingReplyProp = &accReply
    curObjProp = &curAobj
    name = 'acc'
    order = 3
;

/*
 *   ActorRole is a special role for the addressee of a command (BOB, GO
 *   NORTH, or TELL BOB TO GO NORTH).  This doesn't appear as part of a
 *   predicate structure, so there's no matchProp, but it is used within
 *   the Command.  
 */
ActorRole: NounRole
    npListProp = &actorNPs
    objListProp = &actors
    objProp = &actor
    isPredicate = nil
;


/*
 *   VerbProduction is a special Production subclass for verb (predicate)
 *   rules.  This production has special processing for building out the
 *   object phrases making up the verb.
 *   
 *   Each instance should have an 'action' property giving the Action
 *   object associated with the verb rule.  This is the Action that will be
 *   performed when the parser matches the command input to the rule.
 *   
 *   Some languages, such as English, have "positional" predicate grammars.
 *   This means that the position of a noun phrase in the sentence
 *   determines its role (direct object, indirect object, etc).  In the
 *   grammar for a positional language, each predicate rule simply needs to
 *   plug in a singleNoun or nounList production (as appropriate) in each
 *   noun phrase position, with its '->' property set to correspond to the
 *   role: ->dobjMatch for a direct object, ->iobjMatch for an indirect
 *   object, and ->accMatch for an accessory object.
 *   
 *   Some languages, such as German and Latin, identify the role of a noun
 *   phrase using grammatical case.  This means that the articles change
 *   form in the different roles, or that the nouns themselves are
 *   inflected (they have different forms, such as added suffixes)
 *   according to role.  Case languages tend to have flexible predicate
 *   word order, because the case markers tell you the role of each noun
 *   even if the nouns are rearranged.  For this reason, it can be tedious
 *   to write a grammar for a case language the way we do for English,
 *   where the word ordering for a given verb is so rigid that we can
 *   easily just write out each possible phrasing manually.  For a case
 *   language, you'll probably instead want to write a set of generic verb
 *   rules that cover *all* verbs (i.e., you leave the verb word itself as
 *   a sub-production) in all of the different word orders, and use the
 *   case tagging in the language to determine the role of each noun
 *   phrase.  For this style of grammar, the grammar must set the property
 *   nounPhraseRole in the top-level rule for each noun phrase case; set
 *   this to DirectObject, IndirectObject, AccessoryObject, etc., according
 *   to the role denoted by the case.
 *   
 *   Still other languages, such as Japanese, use particles (grammar
 *   function words) to denote the role of each noun phrase in the
 *   sentence.  This is similar to grammatical case, but the role
 *   information is encoded in separate words (the particles) rather than
 *   in noun affixes, so the nouns themselves aren't inflected.  You can
 *   handle this type of language roughly the same way you'd handle a case
 *   language.  Create generic rules that cover all verbs, then create a
 *   grammar rule for each particle-plus-noun structure.  In each
 *   particle-plus-noun phrase's top-level rule, set the nounPhraseRole
 *   property to the appropriate role object (DirectObject, etc).  
 */
class VerbProduction: Production
    /*
     *   The "priority" of this grammar rule.  This is a contributor to the
     *   Command priority - see Command.priority for an explanation of how
     *   that's used.
     *   
     *   The predicate priority is a small number, 0-99.  The default is
     *   50, which should apply to most normal, complete verb phrases.  For
     *   incomplete phrases (with a missing object, which will force the
     *   parser to assume a default or ask the player for the missing
     *   information), use 25.  Other values are for fine-tuning as needed
     *   in the individual grammar rules.  A higher value means higher
     *   priority.  
     */
    priority = 50

    /* 
     *   Do we want to consider this production to be active; we may want some
     *   VerbRules to be active only under certain circumstances.
     */
    isActive = true
    
    /* build the command */
    build(cmd, np)
    {
        /* set the action and the predicate phrase priority in the command */
        cmd.action = action;
        cmd.verbProd = self;
        cmd.predPriority = priority;
        cmd.predActive = isActive;;

        /* do the standard work */
        inherited(cmd, np);

        /* if we have a structurally empty slot, note it in the command */
        if (missingRole != nil)
            cmd.emptyNounRole(missingRole);
    }

    /*
     *   Visit a production during the build process.  If this is one of
     *   our noun phrase slots, we tell the command to add a new noun
     *   phrase of this type, and make it the current phrase; then we
     *   recursively build out this child to populate the new noun phrase.
     */
    visitProd(cmd, np, prod)
    {
        /* 
         *   If this is a special phrase slot, mark the child with its
         *   role.  This is necessary for positional languages, where the
         *   role of a noun phrase is determined by its position in the
         *   predicate.  Grammars for these languages use generic rules
         *   that apply to any noun phrases, so the match objects don't
         *   know what role they have until they find out their position in
         *   the parent grammar.  We're the parent grammar, so when we see
         *   one of these special positional markers, we need to pass the
         *   information down to the sub-tree here.  
         */
        local r;
        if ((r = NounRole.all.valWhich(
            {x: x.matchProp != nil && self.(x.matchProp) == prod})) != nil)
        {
            /* set the role in the sub-tree */
            prod.nounPhraseRole = r;

            /* start a new noun phrase for the role */
            np = prod.addNounListItem(cmd, prod);
        }

        /* 
         *   build out the child, in the context of the noun phrase we
         *   decided upon 
         */
        prod.build(cmd, np);
    }

    /*
     *   The parser calls answerMissing() when the player answers a query
     *   for a missing noun phrase in the last command.  There's nothing
     *   that needs to happen here, and by default we do nothing; this is
     *   purely advisory.  This routine gives the language module a chance
     *   to alter the command according to the reply, if necessary.  
     */
    answerMissing(cmd, np) { }
;

/*
 *   NounListProduction is a special Production subclass for lists
 *   including more than one noun.
 *   
 *   Each instance should have two '->' properties: np1_ and np2_.  These
 *   should be set to the match sub-tree for the first and second elements
 *   of the noun list (respectively).  Note that we assume there are only
 *   two elements in each list grammar item - this isn't because we want to
 *   limit noun lists to two elements, but rather because we assume that
 *   the grammars for longer lists will be constructed recursively out of
 *   two-element nodes: A, B, C, D becomes something along the lines of
 *   List(a, List(b, List(c, List(d)))).  
 */
class NounListProduction: Production
    /*
     *   Visit a production during the build process.  When parsing the
     *   second element, we'll add a new NounPhrase to the current slot's
     *   list.  
     */
    visitProd(cmd, np, prod)
    {
        /* if this is the second list item, add a new NounPhrase for it */
        if (prod == np2_)
            np = prod.addNounListItem(cmd, prod);

        /* for noun phrases, tell the noun phrase about the production */
        if (prod is in (np1_, np2_))
            np.prod = prod;

        /* do the normal work */
        inherited(cmd, np, prod);
    }
;

/*
 *   A BadListProduction is a Production subclass for a noun list written
 *   in a slot intended for a single noun only.  This isn't really a
 *   grammatical error, so the language grammar will probably want to
 *   include a rule for this.  However, it *is* a semantic error; rules
 *   that are written for single objects are written that way because we
 *   can't make sense of a list there.  For example, PUT BOOK IN BOX AND
 *   BAG would be nonsensical to us, because we can't put something in two
 *   places at once.  This class can be used for a grammar rule that parses
 *   a list where a single noun is required; we'll flag it with an
 *   explanatory error message for the user.  
 */
class BadListProduction: Production
    build(cmd, np)
    {
        /* mark the command with the list-in-single-slot error */
        cmd.badMulti = getNounPhraseRole();

        /* do the normal work */
        inherited(cmd, np);
    }
;

/*
 *   ExceptListProduction is a Production subclass for EXCEPT lists.  This
 *   is a slot in the grammar that holds a list of objects excepted from
 *   some set, as in ALL BUT THE RED BOOK or THE COINS EXCEPT THE PENNIES.
 */
class ExceptListProduction: Production
    /*
     *   Build this phrase.  Our sub-tree is a noun list that's to be
     *   excluded from the current noun phrase under construction, 'np';
     *   this exclusion list is a type of qualifier.  So, we (a) start an
     *   exception qualifier for 'np', (b) make that list the current noun
     *   phrase within our sub-tree, then (c) do the normal work to build
     *   out our sub-tree, but using the new context.  
     */
    build(cmd, np)
    {
        /* 
         *   remember the noun phrase that we qualify - this is simply the
         *   parent noun phrase, np 
         */
        qualifiedNP = np;

        /* 
         *   start an exclusion list for the noun phrase; make the first
         *   element of the new list the active noun phrase for our
         *   sub-tree 
         */
        np = np.addExclusionItem(self);

        /* do the normal work */
        inherited(cmd, np);
    }

    /*
     *   Add a noun list item.  List items within our sub-tree go into the
     *   exclusion list for the parent noun phrase that we qualify.  
     */
    addNounListItem(cmd, prod)
    {
        /* add a new noun phrase to the qualified NP's exclusion list */
        return qualifiedNP.addExclusionItem(prod);
    }

    /* the noun phrase we qualify */
    qualifiedNP = nil
;

/*
 *   CoreNounPhraseProduction is a Production subclass for the "core" noun
 *   phrase grammar for noun phrases with object vocabulary.  This is the
 *   part of the grammar that matches the basic name of an object, after
 *   all qualifiers (such as articles, possessives, and quantifiers) have
 *   already been dealt with.  This is the part of the phrase that contains
 *   the vocabulary words for game-world objects.
 *   
 *   This class is only needed for noun phrases with object vocabulary
 *   words.  It captures the unqualified core of the phrase as entered by
 *   the user, mostly for reiteration in error messages from the parser.
 *   It's not necessary to define rules of this class for noun phrases that
 *   don't have object vocabulary words (e.g., pronouns, ALL).  
 */
class CoreNounPhraseProduction: Production
    build(cmd, np)
    {
        /* note in the NounPhrase that this is the core noun phrase */
        np.coreProd = self;

        /* do the normal work */
        inherited(cmd, np);
    }
;

/*
 *   EmptyNounProduction is a Production subclass for a grammar rule that
 *   matches no tokens where a noun phrase would ordinarily go.  
 */
class EmptyNounProduction: Production
    build(cmd, np)
    {
        /* mark the noun phrase role as empty in the command */
        cmd.emptyNounRole(np.role);
    }
;

/*
 *   NumberNounProduction is a Production subclass for a number that serves
 *   as a direct, indirect, or accessory object.  
 */
class NumberNounProduction: Production
    /* we use the NumberPhrase subclass for a noun phrase entries */
    npClass = NumberPhrase
;

/*
 *   TopicNounProduction is a Production subclass for a topic that serves
 *   as a direct, indirect, or accessory object.  
 */
class TopicNounProduction: Production
    /* we use the TopicPhrase subclass for a topic phrase entry */
    npClass = TopicPhrase
;

/*
 *   LiteralNounProduction is a Production subclass for a literal phrase
 *   that serves as a direct, indirect, or accessory object. 
 */
class LiteralNounProduction: Production
    /* we use the LiteralPhrase subclass for a noun phrase entries */
    npClass = LiteralPhrase
;

/*
 *   PronounProduction is a Production subclass for pronoun phrases.
 *   Each instance should set the property 'pronoun' to a Pronoun object
 *   giving the pronoun role for the phrase.  
 */
class PronounProduction: Production
    /*
     *   Build the phrase.  We'll add our pronoun association to the
     *   current noun phrase.  (We'll also build out any sub-tree, although
     *   in nearly all cases a pronoun phrase is just a literal and won't
     *   have a sub-tree.) 
     */
    build(cmd, np)
    {
        /* set the pronoun association in the noun phrase */
        np.pronoun = pronoun;

        /* do the normal work */
        inherited(cmd, np);
    }
;

/*
 *   A PossessiveProduction is a production subclass for possessive
 *   qualifier phrases ("John's", "my").  When we build out this
 *   production's contribution to the command, we add a separate NounPhrase
 *   object for it, as a possessive qualifier to the current noun phrase.  
 */
class PossessiveProduction: Production
    /*
     *   Build the phrase.  We'll build out our sub-tree as normal, except
     *   that we'll assign its output to a new NounPhrase, which we attach
     *   as a possessive qualifier to the encompassing noun phrase under
     *   construction.  
     */
    build(cmd, np)
    {
        /* 
         *   create a new noun phrase to serve as a possessive qualifier to
         *   the current noun phrase 
         */
        np = np.addPossessive(self);

        /* if I have a pronoun, set it in the noun phrase */
        np.pronoun = pronoun;

        /* do the normal work in the context of the possessive qualifier */
        inherited(cmd, np);
    }
;

/*
 *   ContentsQualifierProduction is a subclass of Production for phrases
 *   that involve contents qualifiers, as in "the bucket of water".
 *   
 *   Each grammar rule of this type needs to define two special '->'
 *   associations in its template:
 *   
 *   cont_ is the contents qualifier.  This is also just an ordinary noun
 *   phrase.  This is the "water" part in "bucket of water".
 *   
 *   prep_ is the preposition giving the relationship. 
 */
class ContentsQualifierProduction: Production
    /*
     *   Visit a production.  When we process the contents qualifier
     *   phrase, we'll build out the sub-tree in the context of a new
     *   NounPhrase, which we attach as a contents qualifier to the
     *   encompassing noun phrase under construction.  
     */
    visitProd(cmd, np, prod)
    {
        /* 
         *   if this sub-production is the contents qualifier phrase,
         *   create a new locational qualifier for it 
         */
        if (prod == cont_)
            np = np.addContents(prep_.getText(), prod);

        /* do the normal work in the context of the noun phrase we set up */
        inherited(cmd, np, prod);
    }
;
    

/*
 *   LocationalProduction is a subclass of Production for phrases that
 *   involve locational qualifiers, as in "the book on the table".
 *   
 *   Each grammar rule of this type needs to define two special '->'
 *   associations in its template:
 *   
 *   cont_ is the locational qualifier.  This is also just an ordinary noun
 *   phrase.  This is the "the table" part in "the book on the table".
 *   
 *   prep_ is the preposition production.  This should be *or* contain a
 *   LocationTypeProduction match, which tells us the type of containment
 *   relationship specified by the grammar.  *Alternatively*, you can
 *   define locType directly on this production.  This specifies a LocType
 *   object giving the containment relationship.  
 */
class LocationalProduction: Production
    /*
     *   Visit a production.  When we process the locational qualifier
     *   phrase, we'll build out the sub-tree in the context of a new
     *   NounPhrase, which we attach as a locational qualifier to the
     *   encompassing noun phrase under construction.  
     */
    visitProd(cmd, np, prod)
    {
        /* 
         *   if this sub-production is the locational qualifier phrase,
         *   create a new locational qualifier for it 
         */
        if (prod == cont_)
        {
            /* add the location to the noun phrase */
            np = np.addLocation(locType, prod);

            /* 
             *   explicitly build out the preposition sub-tree in the
             *   context of the locational noun phrase - this ensures that
             *   the locType gets set for the locational rather than the
             *   base noun phrase 
             */
            if (prep_ != nil)
                prep_.build(cmd, np);
        }            

        /* 
         *   we already built the prep_ subtree explicitly in build(), so
         *   we can ignore it if we're hitting it again here 
         */
        if (prod == prep_)
            return;

        /* do the normal work in the context of the noun phrase we set up */
        inherited(cmd, np, prod);
    }

    /*
     *   Our location type.  This is a LocType object giving the location
     *   relationship specified by this locational phrase.  For languages
     *   that special locational phrases prepositionally, this will be set
     *   by the LocationPrepProduction in our sub-tree.  For languages that
     *   use case inflection to specify the type of relationship, this must
     *   be set by the noun phrase sub-tree instead.  
     */
    locType = nil
;

/*
 *   A LocationPrepProduction is a special Production type for phrases that
 *   encode the preposition of a locational phrase.  This is only needed in
 *   languages that use prepositional grammar to express location
 *   relationships.  For languages that use noun case inflection, the
 *   relationship will have to be inferred from the case grammar of the
 *   noun phrase (such as noun affixes or articles), and the noun phrase
 *   production will have to set the locType in the LocationalProduction.
 *   
 *   Set the locType property to the LocType object corresponding to the
 *   location relationship of the preposition.  
 */
class LocationPrepProduction: Production
    /* our location relationship type, as a LocType object */
    locType = nil

    /* 
     *   on building the production, set the locType in our
     *   LocationalProduction parent 
     */
    build(cmd, np)
    {
        /* set the location type on the noun phrase */
        np.locType = locType;
        
        /* do the normal work */
        inherited(cmd, np);
    }
;    

/*
 *   QuantifierProduction is a subclass of Production for phrases that add
 *   a number qualifier, as in "five books".
 *   
 *   Each grammar rule of this type needs to define a special '->quant_'
 *   association in its template, giving the quantity phrase production.
 *   This phrase must in turn provide a 'numval' property giving its
 *   numeric value. 
 *   
 *   Alternatively, this production can itself simply provide a 'numval'
 *   property with the correct number.  This is convenient for
 *   adjective-like qualifier phrases that imply a number without stating
 *   one directly, such as BOTH BOOKS.  
 */
class QuantifierProduction: Production
    /*
     *   Build out the subtree.  If we have a numval embedded in this
     *   production, we'll use it as the quantifier.  Otherwise, we'll
     *   expect to find a separate quant_ sub-production among our
     *   children, and that it provides the quantity.  
     */
    build(cmd, np)
    {
        /* if we have our own numval value, apply it as the quantifier */
        if (numval != nil)
            np.addQuantifier(numval);

        /* do the normal work */
        inherited(cmd, np);
    }

    /*
     *   Visit a production.  When we visit the quantifier phrase, we'll
     *   handle it specially: we'll add the quantifier value to the main
     *   noun phrase, and then we *won't* parse into the subtree.  There's
     *   no need to parse the quantifier subtree, as its entire meaning is
     *   captured in its numeric value.  Parsing into it is undesirable
     *   because that would add the numeric tokens to the noun phrase -
     *   they don't belong there, since their qualification is captured in
     *   the quantifier and shouldn't also be added as adjectives.  
     */
    visitProd(cmd, np, prod)
    {
        /* if this is the quantifier, handle it specially */
        if (prod == quant_)
        {
            /* add the quantifier to the noun phrase */
            np.addQuantifier(prod.numval);

            /* note that we explicitly DON'T parse into the subtree */
        }
        else
        {
            /* do the inherited work */
            inherited(cmd, np, prod);
        }
    }
;

/*
 *   OrdinalProduction is a subclass of Production for ordinal phrases
 *   ("first", "second", etc).  The match object must define a method
 *   ordval() that returns the integer value of the ordinal (1 for "first",
 *   2 for "second", etc).  
 */
class OrdinalProduction: Production
    build(cmd, np)
    {
        /* apply the ordinal value to the noun phrase */
        np.addOrdinal(ordval);

        /* 
         *   we don't want to build out the subtree, since we don't want to
         *   treat literals as vocabulary words for this type of phrase 
         */
    }
;

/*
 *   MiscWordListProduction is a subclass of Production for miscellaneous
 *   word list rules.  These are grammar rules of last resort, for matching
 *   text that's positionally where a noun phrase ought to be, but which
 *   doesn't match any of our other rules for constructing a valid noun
 *   phrase.  These rules let us still recognize the overall verb-phrase
 *   structure of a command, even though we can't make sense of what goes
 *   where the nouns ought to be.  
 */
class MiscWordListProduction: Production
    build(cmd, np)
    {
        /* tell the Command that it contains a misc word list */
        cmd.noteMiscWords(np);

        /* do the normal work */
        inherited(cmd, np);
    }
;

/*
 *   An OopsProduction is a subclass for the word list part of an OOPS
 *   command.  This must have a ->toks_ property that holds the sub-tree
 *   for the literal token list of the correction. 
 */
class OopsProduction: Production
    /* 
     *   Class method: apply the correction for an OOPS command to an
     *   original token list.
     */
    applyCorrection(prod, toks, typoIdx)
    {
        /* build the tree into an OopsCommand object */
        local cmd = new OopsCommand();
        prod.build(cmd, nil);
        
        /* If the player has already issues an OOPS command they don't need the OOPS tip. */
        oopsTip.makeShown();

        /* 
         *   splice the corrected tokens into the original token list,
         *   replacing the unknown word token, and return the result 
         */
        return toks.splice(typoIdx, 1, cmd.tokens...);
    }

    /* build the command */
    build(cmd, np)
    {
        /* add the token list of the correction to the command */
        cmd.tokens += toks_.getTokens();
    }
;

/*
 *   An OopsCommand is a fake Command object for building out an Oops tree.
 */
class OopsCommand: object
    /* the token list: this is filled in when we build the Oops nodes */
    tokens = []
;

/*
 *   DisambigProduction is a subclass of Production for the root of a
 *   disambiguation reply tree grammar. 
 */
class DisambigProduction: Production
    addNounListItem(cmd, prod)
    {
        /* 
         *   add the new item to the disambig reply list for the original
         *   noun phrase 
         */
        return cmd.addDisambigNP(prod);
    }
;

/*
 *   Production class for Yes-or-No phrases 
 */
property yesOrNoAnswer;
class YesOrNoProduction: Production
    build(cmd, np)
    {
        /* set the yes/no answer property in the Command */
        cmd.yesOrNoAnswer = answer;

        /* do the normal work */
        inherited(cmd, np);
    }
;

/* ------------------------------------------------------------------------ */
/*
 *   Base class for pronouns.  We represent each type of pronoun with an
 *   object, to abstract pronouns away from the vocabulary.
 *   
 *   The base library defines a set of pronouns that are common to most
 *   languages: It, Him, Her, Them, You, Y'all, Me, and Us, plus reflexive
 *   forms of It, Him, Her, and Them.  Some languages might not employ all
 *   of these (French, for example, has no neuter gender, so there's no
 *   equivalent of It), and some might need additional pronouns (e.g.,
 *   French needs a feminine third-person plural).  If a pronoun we define
 *   here has no equivalent in a given language, the language module should
 *   simply omit any grammar mentioning it.  If the language has pronouns
 *   that aren't in the basic set, the language module can provide
 *   definitions for its own additional Pronoun objects, along with the
 *   corresponding grammar rules.
 *   
 *   The library itself only directly references one pronoun object: You.
 *   The parser specifically references this pronoun because it binds to
 *   the addressee of a command, which has a special role in the parsing
 *   process.  Apart from You, though, the library's use of pronouns is
 *   directed by the grammar: if a given Pronoun doesn't appear in the
 *   grammar anywhere, the library will never use it.  (Other than in
 *   iterations over Pronoun instances, anyway; but these will be harmless
 *   because the parser is just trying to be inclusive.)  This means that
 *   language modules are free to ignore pronouns (other than You) from the
 *   standard set when they're not a good match for the language's needs.
 *   For example, if you need distinct Animate and Inanimate forms of Him
 *   and Her, you could simply define four new Pronoun objects for these
 *   forms, and use them in place of Him and Her throughout your grammar.  
 *   
 *   Note that these objects are NOT grammar rules or dictionary words.
 *   These are abstract objects representing the "binding" of the pronouns
 *   - basically the set of grammatical attributes (gender, number) that
 *   determine whether a given noun phrase is a valid antecedent for a
 *   given pronoun.  That's why we don't define separate Pronoun objects
 *   the different grammatical cases (nominative, accusative, dative, etc):
 *   case is a feature of the grammar, and we're one step removed from that
 *   here.  
 */
class Pronoun: object
    /*
     *   Resolve the pronoun during parsing.  The usual way of doing this
     *   is to return the list of antecedents we store as part of the
     *   pronoun object.  This lets each type of pronoun store an
     *   appropriate list of antecedents.
     *   
     *   For a reflexive pronoun, return the Pronoun object for the
     *   ordinary form of the pronoun.  This tells the parser that it needs
     *   to find a match for the pronoun within the command itself, rather
     *   than looking for an external antecedent.  Second person is
     *   inherently reflexive, in that it refers to the addressee(s), so
     *   this should return 'self' for a second-person pronoun.  
     */
    resolve() { return ante; }

    /* 
     *   The grammatical person of the pronoun.  Pronouns come in three
     *   persons: first (me, us), second (you), and third (her, them).  We
     *   represent these as 1, 2, and 3.  
     */
    person = 3

    /* 
     *   Set the antecedent(s) for future pronoun usage based on the
     *   objects mentioned in the current command input or narrative
     *   output.  'obj' can be a single antecedent object, or it can be a
     *   list.  Even a singular pronoun can have a list of antecedents:
     *   some commands have more than one noun phrase, and there's no way
     *   of knowing which one the user might want to refer to with a
     *   pronoun in a future command.  We can't know until we see the
     *   context of the future pronoun use.  For example, UNLOCK DOOR WITH
     *   KEY could be followed by OPEN IT, in which case IT is probably the
     *   door; or by DROP IT, in which case IT is probably the key.  The
     *   best thing to do is to save both the door and the key as possible
     *   antecedents, so that we can choose the most suitable object when
     *   we actually see a pronoun in a subsequent command.  
     */
    setAntecedents(obj){ ante = obj; }

    /*
     *   Does this pronoun match the given object or list of objects?  By
     *   default, we won't match lists, and we'll ask the object if it
     *   thinks we're a match.  
     */
    matchObj(obj)
    {
        return !obj.ofKind(Collection) && obj.matchPronoun(self);
    }

    /* my antecedent or list of antecedents */
    ante = []

    /* 
     *   the corresponding reflexive pronoun, if any - this is set up
     *   automatically during preinit 
     */
    reflexive = nil

    /* 
     *   Class property - list of all regular Pronoun objects.  (Note that
     *   this excludes the reflexive pronouns, because the ReflexivePronoun
     *   class has its own separate 'all' list for its instances.)  
     */
    all = []

    /* on initialization, add me to the master list of pronoun objects */
    construct()
    {
        /* get the nearest class that has a master list */
        local cl = hasProp(&all, PropDefGetClass);

        /* add me to my class's master list */
        cl.all += self;
    }
;

/* It - third-person neuter singular */
It: Pronoun
;

/* Her - third-person feminine singular */
Her: Pronoun
;

/* Him - third-person masculine singular */
Him: Pronoun
;

/* Them - third-person mixed-gender plural */
Them: Pronoun
    /* 
     *   Them is a plural, so it can match a list, as well as an individual
     *   object that matches Them 
     */
    matchObj(obj)
    {
        return obj.ofKind(Collection) || obj.matchPronoun(self);
    }
    
    plural = true
;

/* 
 *   You - the second-person singular.  YOU always binds to the addressee
 *   of the command: either the player character, or the actor being given
 *   orders via a construct like ACTOR, DO THIS.
 *   
 *   Binding to the PC is grammatically correct in a first-person
 *   narration, because the PC is the narrator's ME and therefore the
 *   player's YOU.  It's less so in a second-person game: the PC is the
 *   narrator's YOU, so the player's YOU ought to be the narrator.
 *   However, some players are literal-minded about second-person
 *   narration, so rather than reflecting the narrator's YOU into the
 *   player's ME, they simply say YOU too.  Fortunately, there's not any
 *   serious ambiguity here.  The narrator is typically not a game-world
 *   object, but is an entity that exists outside the game world, so it's
 *   off-limits for discussion in commands.  So YOU can't mean the
 *   narrator.  That means that if the player uses YOU at all, they must
 *   mean the PC.  
 */
You: Pronoun
    /* 
     *   The second-person pronoun binds to information contained within
     *   the command itself, namely the addressee of the command, so we
     *   need to resolve it using the parser's "late binding" scheme.  That
     *   is, we return 'self' to tell the parser that it needs to go back
     *   and resolve this pronoun after resolving other phrases.  
     */
    resolve() 
    { 
        /* 
         *   But if no other actor has been specified, 'YOU' must mean 'ME',
         *   i.e. the player character
         */
             
        if(now.command && now.command.actorNPs == [] && now.command.actorPerson == 2)
            return [now.player];
        
        return [self]; 
    }

    /* this is a second-person pronoun */
    person = 2
;

/*
 *   Y'all - the second-person plural.  ("Y'all" isn't exactly standard
 *   English, but it's as close as English comes to having a distinct
 *   plural You, and we had to call this *something*.)
 *   
 *   By default, we treat Y'all as a synonym for You, since there's rarely
 *   any reason in an IF context to distinguish them.  The main value in
 *   natural language is in group conversation, where it can be useful to
 *   clarify whether the speaker is addressing the whole group or just an
 *   individual.  In IF, though, this is never ambiguous: the addressee is
 *   either explicitly stated in the command, or it's the player character.
 *   The only thing we could do with a plural is check that the verb agrees
 *   in number, and chastise the player's sloppy grammar if not.  But that
 *   would be contrary to our general philosophy that we should be as lax
 *   as we can about the input grammar, to minimize the player's typing
 *   workload.  So our advice here is to implement a grammar rule for the
 *   various YOUs that treats all of the second-person pronoun forms as
 *   synonyms for the basic singular YOU.  
 */
Yall: Pronoun
    resolve() { return You.resolve(); }
    person = 2
;

/*
 *   Me - the first-person singular.  ME always binds to the player
 *   character.
 *   
 *   The discussion about the validity of binding YOU to the PC applies in
 *   mirror image here.  In a second-person game, the PC is the narrator's
 *   YOU and the player's ME; in a first-person game, she's the narrator's
 *   ME and the player's YOU.  But there is no game-world object for ME to
 *   bind to in commands in a first-person game - if anything, ME would be
 *   the player (not the player character, but the actual player), who is
 *   clearly not a game-world entity.  Since that's not meaningful, we can
 *   assume that a player talking about ME in a first-person game is being
 *   literal-minded and just using the same pronouns the narrator does, or
 *   that they're so accustomed to the second-person convention of most IF
 *   that they're saying ME out of habit.  In either case, the PC is the
 *   one they're talking about.  
 */
Me: Pronoun
    /* 
     *   the first person always resolves to the player character,
     *   regardless of context 
     */
    resolve() { return [libGlobal.playerChar]; }

    /* this is a first-person pronoun */
    person = 1
;

/* 
 *   Us - the first-person plural.  We throw this one in for relative
 *   completeness, but we simply treat it as a synonym for Me.  This could
 *   be useful in a game with a PC that represents a group of people (an
 *   adventuring party in a hack-n-slash game, say), or a royal personage.
 *   
 *   A more sophisticated use would be to allow the player to refer
 *   collectively to the PC and a group of accompanying NPCs.  The base
 *   library doesn't implement this because it doesn't define a way to
 *   identify such a group, but a game could add that capability.  Once
 *   you've defined what US means, you could make the pronoun US bind to
 *   that group simply by modifying the resolve() method here.  
 */
Us: Pronoun
    resolve() { return Me.resolve(); }
;


/*
 *   Base class for reflexive pronouns.  These are pronouns like "himself"
 *   that specifically refer to an antecedent in the same sentence, rather
 *   than to an earlier sentence: ASK BOB ABOUT HIMSELF is an inquiry about
 *   Bob, while ASK BOB ABOUT HIM refers to some male antecedent from an
 *   earlier statement.  
 *   
 *   Note that the first- and second-person reflexives are generally not
 *   needed in the parser.  (We define them here anyway, because they're
 *   useful for message generation.)  The third-person reflexive pronouns
 *   have distinct meanings in input from the corresponding ordinary
 *   pronouns, in that they refer to noun phrases within the same command
 *   rather than in earlier exchanges.  In contrast, the second-person
 *   pronouns have the same meaning in ordinary and reflexive forms, at
 *   least within the confines of the IF parser: EXAMINE ME and EXAMINE
 *   MYSELF mean the same thing in all typical IF command syntax.
 */
class ReflexivePronoun: Pronoun
    /* during construction, set the regular pronoun to point back at me */
    construct()
    {
        inherited();
        pronoun.reflexive = self;
    }

    /*
     *   A reflexive pronoun binds to another noun phrase contained in the
     *   same command, so we resolve using the parser's "late binding"
     *   scheme.  We invoke this by returning the ordinary (non-reflexive)
     *   pronoun object representing the attributes that we match; upon
     *   seeing this, the parser will know to come back to this pronoun
     *   after it's finished resolving earlier phrases, and look for the
     *   appropriate pronoun binding within those other phrases.  
     */
    resolve() { return pronoun; }

    /*
     *   Get the corresponding ordinary (non-reflexive) form of the
     *   pronoun.  For example, for HIMSELF we'd return HIM.  
     */
    pronoun = nil

    /* my grammatical person is the same as my underlying pronoun's */
    person = (pronoun.person)

    /* 
     *   Class property - list of all reflexive pronoun objects.  This
     *   keeps the reflexive pronouns in a separate list from the base
     *   Pronoun list.  
     */
    all = []
;

/* first-person singular reflexive */
Myself: ReflexivePronoun
    pronoun = Me
;

/* second-person singular reflexive */
Yourself: ReflexivePronoun
    pronoun = You
;

/* third-person singular neuter reflexive */
Itself: ReflexivePronoun
    pronoun = It
;

/* third-person singular feminine reflexive */
Herself: ReflexivePronoun
    pronoun = Her
;

/* third-person singular masculine reflexive */
Himself: ReflexivePronoun
    pronoun = Him
;

/* first-person plural reflexive */
Ourselves: ReflexivePronoun
    pronoun = Us
;

/* second-person plural reflexive */
Yourselves: ReflexivePronoun
    pronoun = Yall
;

/* third-person mixed-gender plural reflexive */
Themselves: ReflexivePronoun
    pronoun = Them
;


/* ------------------------------------------------------------------------ */
/*
 *   Determiners.  A determiner qualifies a noun phrase with information on
 *   how it relates to the objects it describes.  For example, "a book"
 *   refers to any book that's in scope for the discussion (in IF terms,
 *   this is usually any book that's physically present), while "the book"
 *   refers to some specific single book.
 *   
 *   Language modules can add determiners as needed.  For example, a
 *   language with grammatical gender would probably find gendered versions
 *   of Definite and Indefinite useful, to represent the use of gendered
 *   articles in input.
 */
class Determiner: object;

/* Unqualified mode ("book") */
Unqualified: Determiner;

/* Definite mode ("the book", "book", "both books", "the three books") */
Definite: Determiner;

/* Indefinite mode ("a book", "any book", "one of the books", three books") */
Indefinite: Determiner;

/* All ("the books", "all", "all of the books") */
All: Determiner;


/* ------------------------------------------------------------------------ */
/*
 *   ParseError is an Exception subclass for parsing errors. 
 */
class ParseError: Exception
    /*
     *   Display the error message
     */
    display() { "Unknown parsing error."; }

    /*
     *   Rank a spelling correction candidate for input that triggered this
     *   error on parsing.
     *   
     *   'toks' is the new token list, with the spelling correction
     *   applied; 'idx' is the index in the list of the corrected word.
     *   'dict' is the Dictionary used for parsing.
     *   
     *   Returns an integer value giving the ranking.  The ranking is used
     *   for sorting, so the scale is arbitrary - we simply take the
     *   highest ranking item.  The value 0 is special, though: it means
     *   that we should filter out the candidate and not consider it at
     *   all.  
     */
    rankCorrection(toks, idx, dict) { return 1; }

    /*
     *   Is this error allowed on a spelling correction candidate?  By
     *   default, this is nil, meaning that this error invalidates a
     *   correction candidate.  We mostly reject spelling "corrections"
     *   that result in errors because these are probably false positives:
     *   they probably replace a misspelled word with one that's in the
     *   dictionary but that's still wrong.  However, there are a few
     *   curable errors where it can make sense to keep a correction, such
     *   as an ambiguous noun phrase: that's so close to being a working
     *   command that we probably have a good correction.  
     */
    allowOnRespell = nil

    /*
     *   Is this a "curable" error?  A curable error is one that the user
     *   can fix by answering a question, such as "which one do you mean?"
     *   or "what do you want to unlock it with?"
     *   
     *   When we find more than one grammar match to an input string, the
     *   parser tries resolving each one, in order of the predicate match
     *   quality.  If one resolves without an error, the parser stops and
     *   uses that match.  But if *none* of the possible matches resolve
     *   without an error, the parser picks a match with a curable error
     *   over one with an incurable error.  
     */
    curable = nil

    /*
     *   Try curing this error with the user's answer to the error message.
     *   The parser calls this when (a) the PREVIOUS command resulted in
     *   this error, (b) this error is curable, and (c) the user typed
     *   something on the CURRENT command that didn't parse as a valid new
     *   command.  Since the new input doesn't look like a valid command,
     *   the parser calls this to determine if the input was instead meant
     *   as an answer to the question posed by the last error.
     *   
     *   If this new command is indeed a valid response to the error
     *   message, we return a CommandList with the "cured" version of the
     *   command.  This new command list should supplement the command with
     *   the new information provided by the reply.  If not, we simply
     *   return nil.  
     */
    tryCuring(toks, dict) { return nil; }

    /*
     *   The parsing "stage" of this error.  We can distinguish three
     *   levels of intelligibility as we work through the parsing process:
     *   (1) completely unintelligible, (2) valid verb structure, and (3)
     *   resolved noun phrases.  This property tells us which stage we
     *   finish in when we encounter an error of this type.
     */
    errStage = 1
;

/*
 *   The basic command-level parsing error.  This occurs when we can't find
 *   a grammar match to the overall command phrasing. 
 */
class NotUnderstoodError: ParseError
    display()
    {
        /*
         *   We couldn't parse a command.  This means that we were unable
         *   to find any grammar match for the input, so we basically have
         *   no idea what the player was trying to say.  
         */
        showMsg(not understood, 'I don\'t understand that command.');        
    }

    /* 
     *   This is a general verb syntax error, so our best candidates will
     *   words that are used in verb phrases.  The next best is a corrected
     *   word that's used in any GrammarRule, since the problem might
     *   actually be in some other structural part of the command phrase
     *   above the verb phrase (a conjunction, for example).  
     */
    rankCorrection(toks, idx, dict)
    {
        /* get the text of the token */
        local txt = getTokVal(toks[idx]);

        /* look up the word in the action vocabulary table */
        local w = actionDictionary.wordToAction[txt];
        if (w != nil)
        {
            /* get the highest spelling priority of the matching actions */
            local maxAct = w.maxVal({ a: a.spellingPriority });

            /* 
             *   Look for other words in the token list that are also in
             *   this words associated word list.  (For example, if the
             *   candidate is 'up', look for words like 'pick', 'go', or
             *   'look' that occur in the same verb rules with 'up'.) 
             */
            local xlst = actionDictionary.xwords[txt] - txt;
            local xbonus = (toks.indexWhich(
                { t: xlst.indexOf(getTokVal(t)) != nil }) != nil);

            /* 
             *   Give this a high rating, with the action priority and
             *   associated word bonuses to break ties.
             */
            return 200 + maxAct*2 + (xbonus ? 1 : 0);
        }

        /* okay, no predicate; how about any other GrammarRule word? */
        w = dict.findWord(txt);
        if (w.indexWhich(
            { x: typeOf(x) == TypeObject && x.ofKind(GrammarRule) }) != nil)
            return 100;

        /* 
         *   No luck on any of our preferences; give it our lowest rank.
         *   We still want to allow it to be considered, so give it a
         *   non-zero rank. 
         */
        return 1;
    }
;

/*
 *   An UnknownWordError points out a word that's not in the game's
 *   dictionary. 
 */
class UnknownWordError: ParseError
    construct(txt)
    {
        self.badWord = txt;
    }

    display()
    {
        /*
         *   The command contains a word that's not in the dictionary.
         *   This error is only used when the parser is set to admit to
         *   unknown words, and only when we fail to parse the command.
         *   (It's possible for a command to succeed even when it contains
         *   words that aren't in the dictionary, since objects and topics
         *   can sometimes match arbitrary input.)  
         */
        showMsg(unknown word, 'I don\'t know the word "{1}".', badWord);

    }

    /* the text of the unknown word */
    badWord = nil
;

/* 
 *   OopsError is the base class for errors in an OOPS command.
 */
class OopsError: ParseError
;

/*
 *   A CantOopsError means that the player typed OOPS when we don't have a
 *   previous command typo we can correct.  
 */
class CantOopsError: OopsError
    display()
    {
        /*
         *   The player typed an OOPS command, but we don't have anything
         *   from a past command that we can correct.  This means that
         *   either the last command succeeded, or that it simply didn't
         *   contain any non-dictionary words. 
         */
        showMsg(no oops now, 'Sorry, I\'m not sure what you\'re correcting.');
    }
;


/*
 *   A CommandError is an error in parsing that occurs within the build
 *   process for a Command object.  
 */
class CommandError: ParseError
    construct(cmd)
    {
        /* remember the command */
        self.cmd = cmd;
    }

    /* the Command object where the error occurred */
    cmd = nil

    /* 
     *   these errors occur once we have a valid predicate structure, so
     *   we're in stage 2 of the parsing when we encounter an error of this
     *   type 
     */
    errStage = 2
;

/*
 *   Rejected parsing structure.  There are certain structures that are
 *   hard to eliminate in the grammar, but which we don't want to accept
 *   semantically.  This error can be thrown when such a structure is
 *   encountered.  This effectively rules out a parse tree.  It's not a
 *   displayable error; the parser simply rules out these structures.  
 */
class RejectParseTreeError: CommandError
    display()
    {
        /* 
         *   users should never see this error - it should be handled
         *   internally to the library 
         */
        "\n(Internal: Parse tree rejected.)\n";
    }
;

/*
 *   Empty noun slot error.  This occurs when there are no noun phrases in
 *   a functional slot in the predicate (e.g., when the player types "TAKE"
 *   without a direct object).  
 */
class EmptyNounError: CommandError
    construct(cmd, role)
    {
        inherited(cmd);
        self.role = role;
    }

    /* our message is a missing noun query (e.g., "What do want to open?") */
    display()
    {
        askMissingNoun(cmd, role);
    }

    /*
     *   Try curing the error.  After a missing noun query, the player can
     *   respond with a simple noun phrase answering the question. 
     */
    tryCuring(toks, dict)
    {
        /* try parsing against the appropriate reply grammar */
        local lst = new CommandList(
            cmd.verbProd.missingRoleProd(role), toks, dict,
            new function(prod)
        {
            /* create a copy of the original command */
            local newCmd = cmd.clone();
            
            /* plug the new noun phrase tree into the empty role */
            newCmd.addNounProd(role, prod);
                        
            /* the new command is the mapped list entry */
            return newCmd;
        });

        /* accept curable resolutions as replies */
        lst.acceptCurable();

        /* return the list */
        return lst;
    }

    /* we can cure by asking the player for the missing noun phrase */
    curable = true
;



/*
 *   Noun phrase resolution error.  This is a special type of parsing error
 *   that indicates that the problem is with resolving a noun phrase to
 *   game-world objects.  
 */
class ResolutionError: ParseError
    construct(np)
    {
        /* do the normal work */
        inherited();
        
        /* save the noun phrase */
        self.np = np;

        /* note the error-display text of the noun phrase */
        self.txt = np.errName;
    }

    /* the NounPhrase object for the errant phrase, if available */
    np = nil

    /* the text of the errant phrase, if available */
    txt = nil

    /*
     *   For a noun resolution error, our best bet for a spelling
     *   correction would be a word associated with a game-world object.
     *   Only consider in-scope objects when making the correction, to
     *   avoid spurious corrections that give away information on objects
     *   the player has yet to encounter.  We'll also allow words that are
     *   used in non-predicate grammar productions, since we might have a
     *   structural noun phrase word (an article, pronoun, etc).  
     */
    rankCorrection(toks, idx, dict)
    {
        /* make a list consisting of the single changed word */
        local disList = [getTokVal(toks[idx])];

        /* look for an in-scope object association for the word */
        local m = 0;
        foreach (local obj in World.scope())
            m |= obj.matchNameDisambig(disList);

        /* 
         *   if we found any matches, give this the highest score; adjust
         *   slightly to prefer nouns, then adjectives, then plurals 
         */
        if (m != 0)
        {
            return ((m & MatchNoun) != 0 ? 102 :
                    (m & MatchAdj) != 0 ? 101 : 100);
        }

        /* check for non-predicate grammar words */
        local w = dict.findWord(getTokVal(toks[idx]))
            .subset({ x: typeOf(x) == TypeObject });

        if (w.indexWhich({ x: x.ofKind(GrammarRule) && !x.ofKind(predicate) })
            != nil)
            return 90;

        /* 
         *   it's not an in-scope object word or a structural word, so
         *   don't allow it, in case it refers to a yet-unseen object 
         */
        return 0;
    }
;

/*
 *   ActorResolutionError - this is for resolution errors that are in the
 *   context of what the target actor of the command (the addressee) can
 *   see.  These require the Command in addition to the noun phrase, since
 *   that provides the target actor information.  
 */
class ActorResolutionError: ResolutionError
    construct(cmd, np)
    {
        inherited(np);
        self.cmd = cmd;
    }

    /* the command that we were attempting to resolve */
    cmd = nil
;

/*
 *   No objects match the addressee of a command (BOB, GO NORTH or TELL BOB
 *   TO GO NORTH).  
 */
class UnmatchedActorError: ResolutionError
    display()
    {
        /*
         *   An actor phrase in a command (BOB, GO NORTH) didn't match any
         *   in-scope objects.  This doesn't necessarily mean that the
         *   phrase doesn't refer to any object anywhere in the game, just
         *   that it doesn't refer to anything in scope.  Since we didn't
         *   match anything, all we have is the text of the actor phrase
         *   from the player's input.  
         */
        showMsg(unmatched actor, '{I} {see} no {1} {here}.', txt);
    }
;

/*
 *   No objects match a noun phrase. 
 */
class UnmatchedNounError: ActorResolutionError
    display()
    {
        /*
         *   A noun phrase didn't match any in-scope objects.  This doesn't
         *   necessarily mean that the phrase doesn't refer to any object
         *   anywhere in the game, just that it doesn't refer to anything
         *   in scope.  Since we didn't find an object, all we have is the
         *   text of the noun phrase from the player's input.  
         */
        showMsg(unmatched noun, '{I} {see} no {2} {here}.', cmd, stripArticle(txt));
        
        oopsTip.showTip();
    }
;

/*
 *   Base class for resolution errors involving pronouns 
 */
class PronounError: ResolutionError
    construct(np, pro)
    {
        inherited(np);
        pronoun = pro;
    }

    /* the pronoun that caused the error, as a Pronoun object */
    pronoun = nil
;
        

/*
 *   No pronouns match a noun phrase. 
 */
class NoAntecedentError: PronounError
    display()
    {
        /*
         *   The player used a pronoun for which there's currently no
         *   antecedent.  
         */
        showMsg(no antecedent,
             'I\'m not sure what you mean by "{1}".', np.prod.getText());
    }
;


/*
 *   The antecedent of the pronoun is no longer in scope
 */
class AntecedentScopeError: PronounError
    construct(cmd, np, pro)
    {
        inherited(np, pro);
        self.cmd = cmd;
    }

    cmd = nil

    display()
    {
        /*
         *   The player used a pronoun that refers to an object that's no
         *   longer in scope. 
         */
        showMsg(antecedent out of scope,
             '{I} no longer {see} that {here}.', cmd);
    }
;


/*
 *   There aren't enough objects matching a noun phrase to satisfy a
 *   quantifier (e.g., TAKE FIVE COINS, but only three coins are present). 
 */
class InsufficientNounsError: ActorResolutionError
    display()
    { 
        
        if(cmd.matchedAll)
            
            /* 
             *   The player used ALL when there's nothing suitable for all to
             *   refer to.
             */
            showMsg(nothing suitable for all, 'There{\'s} nothing suitable for        
                ALL to refer to. ');
        
        else
            
            /*
             *   The player used a noun phrase that specifically calls for some
             *   number of objects (such as FIVE COINS or BOTH BOOKS), but there
             *   aren't enough of those objects present.
             */
            showMsg(not enough nouns,
                 '{I} {don\'t see} that many {2} {here}.', cmd, txt);       

    }
;

/*
 *   The owner in a possessive phrase doesn't have any of the objects
 *   named. 
 */
class NoneInOwnerError: ActorResolutionError
    construct(cmd, np, poss)
    {
        inherited(cmd, np);
        possQual = poss;
    }

    /* the possessive qualifier */
    possQual = nil

    display()
    {
        /* 
         *   if we have other than one possible owner, show the original
         *   text of the owner phrase, since we can't be sure which matched
         *   object was intended; otherwise show the name of the actual
         *   owner we matched 
         */
        if (possQual.npMatches.length() != 1)
        {
            /*
             *   The player used a possessive to qualify a noun phrase, and
             *   we matched multiple objects for the possessive phrase, but
             *   none of those owners actually owns anything in scope that
             *   matches the main noun phrase.  For example, the player
             *   entered THE GUARD'S SWORD, and there are two guards
             *   present, but neither of them has a sword (not that's in
             *   scope, anyway).  
             */
            showMsg(none in owners, 'No {2} {dummy}appear{s/ed} to have any {3}.',
                 cmd, possQual.prod.getText(), txt);
        }
        else
        {
            /*
             *   The player used a possessive to qualify a noun phrase, and
             *   we matched a single object for the possessive phrase, but
             *   that owner doesn't actually possess anything in scope that
             *   matches the main noun phrase.  For example, the player
             *   entered BOB'S WALLET, and Bob is indeed in scope, but Bob
             *   doesn't own a wallet (not one that's in scope, anyway).  
             */
            local obj = possQual.npMatches[1].obj;
            messageParams(obj);
            
            showMsg(none in owner, '{The subj obj} {doesn\'t appear[ed]} to have
                any {2}.',  cmd,  txt);
                      
        }
    }    
    
;

/*
 *   The location in a locational qualifier doesn't contain any of the
 *   objects named. 
 */
class NoneInLocationError: ActorResolutionError
    construct(cmd, np, loc)
    {
        inherited(cmd, np);
        locQual = loc;
    }

    /* the locational qualifier */
    locQual = nil
    
    display()
    {
        /* 
         *   if we have other than one possible location, show the original
         *   text of the locational phrase, since we can't be sure which
         *   matched object was intended; otherwise show the name of the
         *   actual location we matched 
         */
        if (locQual.npMatches.length() !=  1)
        {
            /*
             *   We have a locational qualifier, and we have multiple
             *   objects that match the location, but there's nothing in
             *   scope that matches the main noun phrase that's in any of
             *   those locations.  For example, the player typed THE BOX ON
             *   THE TABLE, and we have two tables in scope, but there's no
             *   box in scope that's on either of them.  
             */
            showMsg(none in locations,
                 '{I} {see} no {2} {3} any {4}.',
                 cmd, txt, locQual.locType.prep, locQual.prod.getText());
        }
        else
        {
            /*
             *   We have a locational qualifier, and we have exactly one
             *   object that matches the location, but there's nothing in
             *   scope that matches the main noun phrase that's in that
             *   location.  For example, the player typed THE BOX ON THE
             *   TABLE, and we have a table in scope, but there's no box on
             *   it. 
             */
            showMsg(none in location,
                 '{I} {see} no {2} {3} {the 4}.',
                 cmd, txt, locQual.locType.prep, locQual.npMatches[1].obj);
        }
    }
;

/*
 *   There are no objects matching this noun phrase name that have the
 *   contents mentioned in the contents qualifier. 
 */
class NoneWithContentsError: ActorResolutionError
    construct(cmd, np, cont)
    {
        inherited(cmd, np);
        contQual = cont;
    }

    /* the contents qualifier */
    contQual = nil

    display()
    {
        /* 
         *   if we have other than one possible contents object, show the
         *   original text of the contents phrase, since we can't be sure
         *   which matched object was intended; otherwise show the name of
         *   the object we matched 
         */
        if (contQual.npMatches.length() != 1)
        {
            /*
             *   We have a contents qualifier, and we have multiple objects
             *   in scope that match the contents phrase, but there's
             *   nothing in scope that matches the main noun phrase that
             *   actually contains any of the contents objects.  For
             *   example, the player typed THE BUCKET OF WATER, and we do
             *   have multiple "water" objects present, but none of them
             *   are inside buckets that are in scope.  
             */
            showMsg(none with contents in list,
                 '{I} {see} no {2} of {3}.',
                 cmd, txt, contQual.prod.getText());
        }
        else
        {
            /*
             *   We have a contents qualifier, and we have exactly one
             *   object in scope that matches the contents phrase, but
             *   there's nothing in scope that matches the main noun phrase
             *   that actually contains that object.  For example, the
             *   player typed THE BUCKET OF WATER, and we do have a "water"
             *   object present, but it's not inside anything called a
             *   bucket (not one that's in scope, anyway).  
             */
            showMsg(none with contents,
                 '{I} {see} no {2} of {3}.',
                 cmd, txt, contQual.npMatches[1].obj);
        }
    }
;

/*
 *   A noun phrase is ambiguous, so we'll have to ask for clarification.
 */
class AmbiguousError: ResolutionError
    construct(cmd, np, names)
    {
        inherited(np);
        self.cmd = cmd;
        self.nameList = names;
    }

    display()
    {
        /* ask the language-specific ambiguous noun question */
        askAmbiguous(cmd, np.role, nameList.mapAll({ n: n[1] }));     
        
    }

    /* 
     *   Accept spelling corrections that trigger an ambiguous noun error.
     *   If we find an ambiguous noun it means that we have valid overall
     *   verb syntax *and* we have noun phrases that match in-scope objects
     *   - in fact, they match too many objects.  This is pretty good
     *   evidence that the respelling is valid.  
     */
    allowOnRespell = true


    /* 
     *   this is a curable error, since the player can fix the problem by
     *   answering the disambiguation question 
     */
    curable = true

    /* 
     *   Try curing the error.  After an ambiguous noun error, the player
     *   can type a partial noun phrase that clarifies which object was
     *   intended: a distinguishing adjective, a locational phrase, a
     *   possessive, etc. 
     */
    tryCuring(toks, dict)
    {
        /* try parsing against the main disambiguation grammar */
        local lst = new CommandList(
            mainDisambigPhrase, toks, dict,
            new function(prod)
            {
                /* create a new copy of the Command to apply the change to */
                local newCmd = cmd.clone();

                /* add the reply to the new command */
                local dnp = newCmd.startDisambigReply(np, prod);

                /* build the reply tree */
                prod.build(newCmd, dnp);

                /* the mapping is the new command */
                return newCmd;
            });

        /* accept curable errors in the reply */
        lst.acceptCurable();

        /* return the list */
        return lst;
    }

    /* the original Command that we were trying to resolve */
    cmd = nil

    /* 
     *   The list of object names, with distinguisher information.  This is
     *   the same information returned from Distinguisher.getNames(). 
     */
    nameList = []
;

class AmbiguousMultiDefiniteError: UnmatchedNounError
    display()
    {
        showMsg(be more specific, 'I don\'t know which ones you mean.  
            Can you be more specific?');
    }

    /* 
     *   this is not really curable, but we need to say it is curable so that
     *   our custom message is displayed.  Would like to find a way to do this
     *   where curable=nil
     */
    curable = true
;


/*
 *   Ordinal out of range.  This occurs when the player replies to a
 *   disambiguation query with an ordinal that's out of the bounds of the
 *   offered list. 
 */
class OrdinalRangeError: ResolutionError
    construct(np, ordinal)
    {
        inherited(np);
        self.ordinal = ordinal;
    }

    display()
    {
        /*
         *   An ordinal reply to a disambiguation question is out of range.
         *   For example, we asked "Which do you mean, the red book or the
         *   blue book?", and the player answered THE THIRD ONE.  There are
         *   only two options, so THIRD is out of range.  
         */
        showMsg(ordinal out of range,
             'Sorry, I don\'t see what you\'re referring to.');
    }

    /* the ordinal, as an integer value (1=first, 2=second, etc) */
    ordinal = nil
;

class BadMultiError: ParseError
    display() 
    { 
        showMsg(multi not allowed, 'Sorry; multiple objects aren\'t allowed with
            that command.'); 
    }
;

/* ------------------------------------------------------------------------ */
/*
 *   A placeholder object for dictionary entries.  The Dictionary class
 *   stores a three-way association: word string, part-of-speech property,
 *   and object.  The object association is designed to allow the parser to
 *   come up with a list of objects that could match a given word, but the
 *   library doesn't use this feature.  We instead figure out the
 *   word-to-object association by directly asking the objects in scope if
 *   they're associated with a word.  We still need *something* to store as
 *   the object association for each word entry in the dictionary, though.
 *   That's where this object comes in: it's a dummy object that serves as
 *   the required object to associate with each word.
 *   
 *   A language module can ignore this and use the word-object-property
 *   association feature of the dictionary, if desired.
 */
dictionaryPlaceholder: object
;



/* Exception thrown by exit macro */
class ExitSignal: Exception
;

/* Exception thrown by abortImplicit macro */
class AbortImplicitSignal: Exception
;

/* Exception thrown by abort macro */
class AbortActionSignal: Exception
;

/* Exception thrown by exitAction macro */
class ExitActionSignal: Exception  
;

/* Exception thrown to terminate a command. */
class TerminateCommandException: Exception
;


/* 
 *   A SpecialVerb allows us to define grammar for verbs applying to only a handful of objects in
 *   our game, where we want the rarely used command to be translated into a common one, e.g. RIMG
 *   BELL -> PUSH BELL, which we could implement as:
 *
 *.  SpecialVerb 'ring' 'push' @doorbell
 */
class SpecialVerb: object
    /* 
     *   The word or words this SpecialVerb should match, e.g. 'ring'. Different forms can be listed
     *   separated by a vertical bar, e.g. 'cross|go across|walk across'
     */
    specVerb = ''
    
    /* 
     *   The verb words needed to trigger the action we want this SpecialVerb to perform, e.g.
     *   'push' or 'go through'
     */
    stdVerb = ''
    
    /* 
     *   The object ot objects we want this SpecialVerb to apply to. This can be a single object or
     *   class or list of objects and/or classes, but it should result only in a small number of
     *   matches.
     */
    matchObjs = nil
    
    /* 
     *   A Room, Region or list of Rooms and/or Regions where this SpecialVerb is applicable. Note
     *   we'd very rarely need to specify this since SpecialVerb already makes scope checks.
     */
    where = nil
    
    /*  A Scene or list of Scenes that must be happening for this SpecialVerb to apply. */
    during = nil
    
    /*  
     *   A condition that must be true for this SpecialVerb to apply. This cannot refer to the
     *   objects involved in the command (e.g. dobj or iobj) since these won't be known the first
     *   time the when condition is tested. For conditions involving the dobj, iobj, or aobj of a
     *   the current command, use objCheck() instead.
     */     
    when = true

    /* 
     *   A check that can be applied once the objects involved in the command are known, (e.g. to
     *   check whether dobj.isOpen). The method can return nil to reject the command at this stage,
     *   or else display a message to explain why it can't go ahead and then use abort to stop it.
     *   It's unlikely that this will be needed often.
     */
    objChecks(dobj, iobj, aobj)
    {
        return true;
    }
    
    /* 
     *   The priority we want to assign this SpecialVerb if the library needs to break a tie between
     *   two or more SpecialVerbs that might otherwise be matched after all other conditions have
     *   been applied. The default is 100. Other things being equal, the SpecialVerb with the
     *   higher/highest priority will be matched.
     */
    priority = 100
    
    /* 
     *   Our best guess at the direct object of the command this SpecialVerb will match before the
     *   objects of the command have been fully resolved.
     */
    tentativeDobj = nil
    
    /* 
     *   A list of the possible tentative direct objects of the command this SpecialVerb will match
     *   before the objects of the command have been fully resolved. This will be all the objects in
     *   scope that match our matchObjs property and the noun phrase the player apparently entered.
     */
    tentativeDobjList = []
    
    
    /* The verb phrase that's been matched to invoke this SpecialVerb. */
    verbPhrase = (specialVerbMgr.vWords.join())
    
    /* The remaining methods and properties of SpecialVerb are for internal library use. */

    /* 
     *   This method is called once the command has been resolved and we know the objects involved
     *   in it. lst is a list containing the action followed by the objects involved in the action,
     *   e.g. [action, dobj]. svPhrase is the special verb phrase that's been translated into
     *   another action, e.g. 'ring' or 'walk across'
     */     
    checkSV(lst, svPhrase)
    {
        /* The direct object of the command, which is the second element of lst. */
        obj = lst.elementAt(2);
        
        /* 
         *   If the direct object of the command does not not match any of the objects/classes
         *   listed in out matchObjs property, we fail the action at this stage.
         */
        if(!matchObjs.indexWhich({x:obj.ofKind(x)}))
           failCheck(svPhrase);
        
        /* Carry out the custom checks based on our where, when and during properties. */
        customChecks(lst);
    }
    
    /* 
     *   Display a message saying the command can't proceed and then stop it in its tracks.
     *   svPhrase is the command we matched, e.g. 'ring' or 'walk over'.
     */
    failCheck(svPhrase)
    {
        /* Display the failure message. */
        showFailureMsg(svPhrase);
        
        /* Abort the command. */
        abort;
    }
    
    /* Display our failure message. By default this is "You can't <<svPhrase>> that. */
    showFailureMsg(svPhrase)
    {
        showMsg(cant do that special, '{I} {can\'t} <<svPhrase>> {that dobj}. ');
    }
    
    /* Initialize (in fact preinitialize) this SpecialVerb */
    initSpec()
    {
        /* Make sure our matchObjs property contains a list. */
        matchObjs = valToList(matchObjs);
        
        /* 
         *   Ensure that specVerb is in lower case so that we can compare it with player input
         *   converted to lower case.
         */
        specVerb = specVerb.toLower();
        
        /* 
         *   Split our special verbs into a list, in case we have different options separated by a
         *   vertical bar.
         */
        local specVerbs = specVerb.split('|');
        
        /* 
         *   Then interate through every element in our special verb variants to add them to the
         *   special verbs Lookup table.
         */
        foreach(local s in specVerbs)
        {    
            /* 
             *   Split the grammar in variant s into a list of separate words, e.g. 'walk over' ->
             *   ['walk', 'over']
             */
            local sWords = s.split(' ');
            
            /* Add this SpecialVerb to the special verb table with sWords as the key/ */
            specialVerbMgr.addToTable(sWords, self); 
            
            /* 
             *   If the number of words in this variant is greater than the number of words
             *   encountered in any previous SpecialVerb that's been initialized, update the maximum
             *   length stored on specialVerbManager. We do this so SpecialVerbManager knows the
             *   maximum number of words it needs to look for when trying to match keys in its
             *   table.
             */             
            if(sWords.length > specialVerbMgr.maxKeyLen)
                specialVerbMgr.maxKeyLen = sWords.length;
        }       
    }
    
    /* Check whether this SpecialVerb matches its conditions. */
    npMatches(scope_, toks)
    {       
        /* 
         *   Start calculating our score for this match by making it our priority plus the result of
         *   looking for matching objects in scope.
         */        
        score = priority + vocabCheck(scope_, toks);
        
        /* Then carry out the custom checks, which may further adjust our score */
        return customChecks();
    }
 
    
    /* 
     *   Check how well any objects in scope that match our matchObjs also match the noun phrase we
     *   think the player entered.
     */
    vocabCheck(scope_, toks)
    {
        /* Cache a list of all the objects in scope for the current command. */
        scope_ = scope_.toList();
        
        /* Our verb phrase length is the number of words in specialVerbMgr's vWords list. */
        local vPhraseLen = specialVerbMgr.vWords.length();
        
        /* 
         *   The tokens that come after the verb phrase tokens potentially constitute our noun
         *   phrase tokens, which is what we'll want to match.
         */
        local nPhraseToks = toks.sublist(vPhraseLen + 1);
        
        /* 
         *   Check for a preposition in the noun phrase; this may mark the end of the noun phrase
         *   proper.
         */
        local prepTokPos = nPhraseToks.indexWhich({x: prepositions.find(x)});
        
        /*  
         *   If we found a preposition, truncate our nounPhrase token list to end just before the
         *   preposition.
         */
        if(prepTokPos)
            nPhraseToks = nPhraseToks.sublist(1, prepTokPos - 1);
        
        /* Remove any articles from the noun phrase before attempting to match. */        
        nPhraseToks = nPhraseToks.subset({x: articles.find(x) == nil});
        
        /* Make a note of whether we found a potentially suitable object in scope. */
        local scopeMatch = nil;
        
        /* 
         *   We'll keep a note of the best match score from the objects in scope that match our
         *   matchObjs.
         */
        local bestScore = 0;
        
        /* reset our tentativeDobj and tentativeDobjList */
        tentativeDobj = nil;
        tentativeDobjList = [];
        
        /* loop through every object in scope to find a match */
        foreach(local obj in matchObjs)
        {            
            /* We're looking for objects in scope that match one of our matchObjs */
            if(scope_.indexWhich({x: x.ofKind(obj)}))
            {
                /* Note that we have at least found a potential match in scope */
                scopeMatch = true;
                
                /* Obtain the vocab match score for the current obj. */
                local mScore = obj.matchName(nPhraseToks);
                
                if(mScore)
                {
                    /* If we have match, add obj to our list of tentative direct objects */
                    tentativeDobjList += obj;
                    
                    /* 
                     *   If our match score is greater than any we've found up to now, update the
                     *   bestScore to that match score and make obj our tentativeDobj.
                     */
                    if(mScore > bestScore)
                    {
                        bestScore = mScore;
                        
                        tentativeDobj = obj;
                    }
                }
            }
        }
            
        /* 
         *   If we haven't even found a suitable object in scope, return -500000 to note that we're
         *   a poor candidate for the best matching SpecialVerb; otherwise return 100 times out best
         *   vocab match score so that specialVerbMgr can prioritize the VerbRule that best matches
         *   a suitable object in scope.
         */
        return scopeMatch ? (bestScore * 100) : -500000;           
    }
    
    /* 
     *   This method is called twice, first when the specialVerbMgr is seeking the best SpecialVerb
     *   option to match, and the second once the objects of the revised command have been
     *   identified and the command is about to be executed. The first time round the lst parameter
     *   won't be supplied (so will be effectively nil); the second time it will be a list
     *   containing the action and its objects. The customChecks() method uses this simply to
     *   determine at which stage its being invoked. The first time its being asked to adjust the
     *   match score; the second time its being asked to check whether or not the proposed action
     *   should be allowed to proceed.
     */
    customChecks(lst?)
    {
        /* 
         *   If the Scenes module is present and our during property has been designed check whether
         *   one of the scenes in our during list is currently happening.
         */
        if(defined(sceneManager) && during && !(valToList(during).indexWhich({x: x.isHappening})))
        {
            /* 
             *   If not, return nil on the second invocation and deduct 100000 from our score on the
             *   first.
             */
            if(lst)
                return nil;
            else
                score -= 100000;
        }
        
        /* 
         *   Check whether the actor is located in one of the rooms or regions in our where list, if
         *   the where list has been defined.
         */
        if(where && !valToList(where).indexOf(now.actorRoom))
            /* 
             *   If not, return nil on the second invocation and deduct 100000 from our score on the
             *   first.
             */
        {
            if(lst)
                return nil;
            else
                score -= 100000;
        }
        
        /* Check whether our when condition has been met. */
        if(!when)
        {
            /* 
             *   If not, return nil on the second invocation and deduct 100000 from our score on the
             *   first.
             */
            if(lst)
                return nil;
            else
                score -= 100000;       
        }
        
        /* 
         *   On the second invocation, return the value of objAfterChecks(lst); on the first simply
         *   return true.
         */
        return lst ? objAfterChecks(lst) : true;
    }
        
    /* Checks involving the objects of the commmand, once we know them */
    objAfterChecks(lst)
    {
        /* 
         *   Call objChecks with the second, third, and fourth elements of lst as arguments; these
         *   correspond to the dobj, iobj and aobj of the command. Note that the elementAt(i) method
         *   simply returns nil if i is greater than the length of lst.
         */
        return objChecks(lst.elementAt(2), lst.elementAt(3), lst.elementAt(4));
    }
        
    /* Our adjusted priority after attempting a match. */
    score = 0
 
    /* Verb phrases we want to exclude from matching, e.g. 'pick up' if our specVerb is 'pick' */
    exclusions = []
    
    /* Check whether the command entered by the player matches an item in our exclusions list. */
    matchExclusions(tokWords)
    {
        
        /* Iterate over our list of exclusions to see if any match */
        foreach(local ex in exclusions)
        {
            /* Split the current exclusion into a list of words */
            local excWords = ex.split(' ');
            
            /* Start by assuming we'll find a match */
            local matched = true;
           
            /* Iterate through the words in our excWords list. */
            for(local i in 1..excWords.length)
            {
                /* 
                 *   If we've run out of words in our tokwords list or we find a word in one list
                 *   that differs from the corresponding word in the other list, then we don't
                 *   match, so we can note that the match has failed and stop comparing the two
                 *   lists.
                 */               
                if(i > tokWords.length() || tokWords[i] != excWords[i])
                {
                    matched = nil; 
                    break;                }
                
            }
            
            /* 
             *   If we didn't find a mismatch, then what the player entered matched our exclusions
             *   list, so we've found a match and can return true.
             */
            if(matched)
                return true;
        }
        
        /* 
         *   If we reach here then none of our exclusions match the player's input, so we return
         *   nil.
         */
        return nil;
    }
;


/* 
 *   The specialVerbMgr carries out various tasks needed for working with SpecialVerbs. In
 *   particular it preinitializes SpecialVerbs to add them to its Map, and is responsible
 *   for matching SpecialVerbs to player input and translating and checking actions appropriately.
 *   Its methods and properties are entirely intended for internal use by the library and shouldn't
 *   normally be invoked or changed in user game code.
 */
specialVerbMgr: PreinitObject
    findMatchingSV(toks)
    {
        /* Get a list of words in toks list */         
        local tokWords = toks.mapAll({t: t[1].toLower}); 
        
        /* Set up a variable to hold the list of SpecialVerbs we'll match. */
        local specs = nil; // new
        
        /* 
         *   Work down from the maximum key length (in terms of the number of words it contains) to
         *   1, so that a shorter key doesn't mask a longer one.
         */
        for(local klen in maxKeyLen .. 1 step -1)
        {
            /* Then key we're looking to match is the first klen elements of our tokWords list. */
            local ky = tokWords.sublist(1, klen);
            
            /* Obtain the SpecialVerbs that match that key. */
            specs = specTable[ky];
            
            /* Exclude any SpecialVerbs whose exclusion property matches our tokWords. */
            specs = valToList(specs).subset({x: !x.matchExclusions(tokWords)});
            
            /* 
             *   If we find any, store the key in our vWords property (the words in the player input
             *   we're just matching) and break out of the loop, since we won't need to keep
             *   looking.
             */
            if(valToList(specs).length > 0)
            {
                vWords = ky;
                break;
            }
        }
        
        /* If we don't find any we're done. */
        if(specs == nil || specs.length == 0)
            return nil;        
        
        /* Cache the player character's scope list. */
        local scope_ = Q.scopeList(now.player);
        
        /* Calculate each SpecialVerb's match score, based partly on what's in scope. */
        foreach(local s in specs)
            s.npMatches(scope_, tokWords);
        
        /* Sort the list in descending order of score. */
        local svmatches = specs.sort(true, {a, b: a.score  - b.score });
        
        /* Return the first one in the list, which should tbe the best match. */
        return svmatches[1];                                           
    }
    
    /* The verb words we're currently matching. */
    vWords = nil
    
    matchSV(toks)
    {
        /* Find the best SpecialVerb matching the tokens passed to us by the parser */
        local sv = findMatchingSV(toks);
        
        /* 
         *   If we've found one, update the parser's tokens accordingly, so they now contain the
         *   standard verb (stdVerb) we want to use in place of the special verb word.
         */
        if(sv)
        {              
            /* 
             *   We now need to add the rest of the toks back to the revised first one. We need to
             *   start from the next tok we just matched our special verb to.
             */
            local nToks = toks.sublist(vWords.length + 1);
            
            /* 
             *   Split the stdVerb into a list of words. Check its length. Update the first len toks
             *   with the list of words from stdVerb. Append nToks to the first stdVerb.length toks.
             */            
            local stdVerbWords = sv.stdVerb.split(' ');
            local stdVerbLen = stdVerbWords.length();
            local vToks = [];
            
            /* Create the toks for the new standard verb */
            for(local i in 1 .. stdVerbLen)
            {
                vToks = vToks.append([stdVerbWords[i], tokWord, stdVerbWords[i]]);                 
            }           
            
            /* Change toks to our new verb phrase plus the old noun phrase */
            toks = vToks + nToks;
            
            
            /* Make a note of the current SpecialVerb we're working with. */
            currentSV = sv;
            
        }
        
        /* Return the (possibly adjusted) list of tokens. */
        return toks;
    }
    
    /* 
     *   Call the checkSV() method on our currently active SpecialVerb, if we have one. Tbis is
     *   called by the current Command object just before invoking the relevant CommandRule for the
     *   command.
     */
    checkSV(lst)
    {
        try
        {
            /* 
             *   If have have a current SpecialVerb, invoke its checkSV method. lst is a list of
             *   objects involved in the action in the form [action, dobj, ...] while vWords
             *   contains the words making up the current SpecialVerb verb, e.g. ['ring'] or
             *   ['walk', 'across']
             */
            if(currentSV)
            {
                currentSV.checkSV(lst, vWords.join(' '));
                
                if(lst[1] == SpecialAction)
                    lst[1].specialPhrase = vWords.join(' ');
            }
        }
        finally
        {
            /* 
             *   Make sure we reset currentSV to nil, whatever happens in checkSV (which might well
             *   through an Exception such as abort to stop the action.
             */
            currentSV = nil;
        }
    }
    
    /* The SpecialVerb currently in use. */
    currentSV = nil
    
    /* Carry out our preinitialization. */
    execute()
    {
        /* Iterate over every object of the SpecialVerb class calling its initSpec() method. */
        for(local spec = firstObj(SpecialVerb); spec != nil; spec = nextObj(spec, SpecialVerb))
            spec.initSpec();               
    }

    /* 
     *   Add a SpecialVerb to our specTable; s is the key value containing the words that can invoke
     *   the SpecialVerb (e.g. ['ring'] or ['walk', 'across'] and spec is the matching SpecialVerb.
     */
    addToTable(s, spec)
    {
        /* Obtain the current value corresponding to the s key in specTable. */
        local specs = valToList(specTable[s]);
        
        /* Add spec to the list of SpecialVerbs it matches. */
        specTable[s] = specs + spec;
    }
    
    /* 
     *   Our Map containing lists of grammar tokens (e.g., ['ring'] or ['go', 'across']) as
     *   keys and a list of matching SpecialVerbs as values.
     */
    specTable = static new Map
    
       
    /* 
     *   The maximum number of words that can occur in a key to our specTable. This is calculated and
     *   stored here at preinit.
     */
    maxKeyLen = 0
;


/* 
 *   PreParser to strip punctuation from the start of the command line, since punctuation there is
 *   unlikely to be valid and may lead to run-time errors.
 */
InitialPunctPreparser:StringPreParser
    doParsing(str, which)
    {
        return str.findReplace(R'^<Punct>+', '');
        
    }    
;