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
import hexad;


/*
 *   **************************************************************************
 *   commandRule.hxn
 */

/*  
 *   A Redirector is an object that can redirect one action to another via a
 *   doInstead wrapper method that provides a common interface. Subclasses are
 *   responsible for implementing the redirect method.
 *
 *   We begin this module by defining the Redirector class, since
 *   Redirector is the base class for CommandRule.
 */
class Redirector: object
    
    /*
     *   doInstead() turns the current action into altAction with the objects
     *   specified in args, and executes altAction as a replacement for the
     *   current action, which is then done, as with replaceAction(): what
     *   would have followed it (its report, say) does not happen. So
     *   goInstead(north), in a handler, is going north and nothing else.
     */
    doInstead(altAction, [args])
    {
        doOtherAction(true, altAction, args...);
        exit;
    }
    
    /* 
     *   doNested() executes altAction with the objects specified in args,
     *   executing altAction as part of the current action.
     */
    doNested(altAction, [args])
    {
        doOtherAction(nil, altAction, args...);
    }
    
    /* 
     *   Execute altAction on the objects specified in the args parameter. If
     *   isReplacement is true make altAction a replacement for the current
     *   action.
     */
    doOtherAction(isReplacement, altAction, [args])
    {
        
        /* Extract our dobj and our iobj from the args parameter. */
        local dobj = args.elementAt(1);
        local iobj = args.elementAt(2);    
        local aobj = args.elementAt(3);
        
        /* 
         *   If the action involves a Literal argument and one of the arguments
         *   is supplied as a single-quoted string, wrap it in a LiteralObject
         *   before passing it.
         */
        if(altAction.ofKind(LiteralAction) || altAction.ofKind(LiteralTAction)
           || aobj != nil)
        {
            if(typeOf(dobj) == TypeString)
                dobj = new LiteralObject(dobj);
            if(typeOf(iobj) == TypeString)
                iobj = new LiteralObject(iobj);
            if(typeOf(aobj) == TypeString)
                aobj = new LiteralObject(aobj);
        }
        
        /*  
         *   If the action involves a Topic object and one of the arguments is
         *   supplied as a single-quoted string, wrap it in a Topic before using
         *   it.
         */                
        if(altAction.ofKind(TopicAction) || altAction.ofKind(TopicTAction)
           || aobj != nil)
        {
            if(typeOf(dobj) == TypeString)
                dobj = new Topic(dobj);
            if(typeOf(iobj) == TypeString)
                iobj = new Topic(iobj);
            if(typeOf(aobj) == TypeString)
                aobj = new Topic(aobj);
        }
        
        /*   
         *   If the action is a TopicTAction check that the appropriate object
         *   (usually but not necessarily the indirect object) has been passed
         *   as a ResolvedTopic; if not, wrap it in a new Resolved Topic object.
         */
        if(altAction.ofKind(TopicTAction))
        {
            if(altAction.topicIsGrammaticalIobj && !iobj.ofKind(ResolvedTopic))
                iobj = new ResolvedTopic([iobj], iobj.name.split(' '));
            
            if(!altAction.topicIsGrammaticalIobj && !dobj.ofKind(ResolvedTopic))
                dobj = new ResolvedTopic([dobj], dobj.name.split(' '));
            
//            if(!altAction.topicIsGrammaticalAobj && !aobj.ofKind(ResolvedTopic))
//                dobj = new ResolvedTopic([aobj], aobj.name.split(' '));
        }
        
        
               
        /*  
         *   If the new action is of a kind that requires two objects, call the
         *   redirect method with both objects
         */
        if(altAction.ofKind(TIAction) || altAction.ofKind(LiteralTAction) ||
           altAction.ofKind(TopicTAction))
        {
            redirect(now.command, altAction, dobj: dobj, iobj: iobj, aobj: aobj,
                     isReplacement: isReplacement);
            return;
        }
        
        /*   
         *   If the action is a TopicAction check that its object has been
         *   passed as a ResolvedTopic; if not, wrap it in a new Resolved Topic
         *   object.
         */
        if(altAction.ofKind(TopicAction) && !dobj.ofKind(ResolvedTopic))
        {
            dobj = new ResolvedTopic([dobj], dobj.name.split(' '));
        }
        
        /*  
         *   If the new action requires a single object, call redirect with the
         *   direct object.
         */
        if(altAction.ofKind(TAction) || altAction.ofKind(LiteralAction) ||
           altAction == Go || altAction.ofKind(TopicAction))
        {
            redirect(now.command, altAction, dobj: dobj, isReplacement:
                     isReplacement);
            return;
        }      
        
        /*  
         *   Otherwise call redirect with the new action alone (it's some form
         *   of intransitive action).
         */
        redirect(now.command, altAction, isReplacement: isReplacement);
    }
    
    /* Ask for a missing literal and retry action with the literal in role. */
    askMissingLiteral(action, role = IndirectObject)
    {
        local obj;
        
        if(objOfKind(now.dobj,Thing))
            obj = now.dobj;
        else if(objOfKind(now.iobj, Thing))
            obj = now.iobj;  
        
        /* Ask for the missing literal */
        askMissingLiteralQ(action, role);
        "<.p>";
        
        /* Read a new command from the keyboard. */        
        local txt = readCommandLine();       
        
        if(role == IndirectObject 
           && action.ofKind(LiteralTAction) || action.ofKind(TopicTAction))
        {           
            doInstead(action, obj, txt);           
        }
        
        if(role == DirectObject)
        {
            if(action.ofKind(LiteralAction) || action.ofKind(TopicAction))
                doInstead(action, txt);
            
            if(action.ofKind(LiteralTAction) || action.ofKind(TopicTAction))
                doInstead(action, txt, obj);
        }
    }
    
;


/* ------------------------------------------------------------------------ */
/*
 *   A CommandRule is a command handler for a specific action acting on particular
 *   objects under a given set of conditions.  We use these for all of the
 *   levels of customization in command handling.
 *   
 *   CommandRule objects are inherently static.  All CommandRule objects should be
 *   defined at compile time; they're not designed to be created
 *   dynamically during execution.  Rather than creating and removing CommandRule
 *   objects as conditions in the game change, use the CommandRule conditions to
 *   define when a given CommandRule is active and when it's dormant.  
 */
class CommandRule: Redirector
    /*
     *   The command that the object handles.  This is a string describing
     *   the action and object combination that this handler recognizes.
     *   
     *   The command string specifies a verb and its objects, generally
     *   using the same verb phrase syntax that a player would use to enter
     *   a command to the game.  The exact verb syntax is up to the
     *   language library to define; for English, we replicate the same
     *   verb phrases used to parse command input.
     *   
     *   The verb phrase syntax is generally the same as for regular player
     *   commands, but the noun syntax is different.  Each noun is written
     *   as the SOURCE CODE name of a game object or class.  That is, not a
     *   noun-and-adjective phrase as the player would type it, but the
     *   program symbol name as it appears in the source code.  If you use
     *   a class name, the command matches any object of the class.  For
     *   example, to handle putting any treasure in any container:
     *   
     *.    cmd = 'put Treasure in Container'
     *   
     *   You can match multiple objects or classes in a single noun slot
     *   (and you can freely mix objects and classes).  For example, to
     *   handle putting any treasure or magic item in a container:
     *   
     *.    cmd = 'put Treasure|Magical in Container'
     *   
     *   You can't use the '|' syntax with verbs, because the verb syntax
     *   covers the entire phrase.  You can match multiple verbs by writing
     *   out the entire phrasing for each verb, separating each phrase with
     *   a semicolon:
     *   
     *.    cmd = 'take skull; put skull in Thing'
     *   
     *   You can also write a command that matches ANY verb, by using "*"
     *   as the verb.  You can follow the "*" with any number of objects;
     *   the first is the direct object, the second is the indirect, and
     *   the third is the accessory.  This phrasing will match any verb
     *   that matches the given objects AND the given number of objects.
     *   For example, '* Thing' will match any verb with a direct object
     *   that's of class Thing, but it won't match verbs without any
     *   objects or verbs with an indirect object.  Using "*" as a noun
     *   will match any object as well as no object at all.  So to write a
     *   handler for every possible command, you'd write:
     *   
     *.    cmd = '* * * *'
     *   
     *   That is, match any verb, with or without any direct object,
     *   indirect object, and accessory object.  
     */
    cmd = ''

    /*
     *   The priority of this handler.  You can use this when it's
     *   necessary to override the default precedence order, which is
     *   figured according to the specialization rules described below.
     *   
     *   Most of the time, you shouldn't need to set a priority manually.
     *   If you don't, the library determines the precedence automatically
     *   according to the degree of specialization.  However, the way the
     *   library figures specialization is a heuristic, so it's not always
     *   right.  In cases where the heuristic produces the wrong results,
     *   you can bypass the rules by setting a priority manually.  A manual
     *   priority takes precedence over all of the standard rules.
     *   
     *   Our basic approach is to process CommandRules in order from most specific
     *   to most general.  This creates a natural hierarchy of handlers
     *   where more specific rules override the generic, default handlers.
     *   Here are the degrees of specialization, in order of importance:
     *   
     *   1. A CommandRule with a higher 'priority' value takes precedence over one
     *   with a lower value. 
     *   
     *   2. A CommandRule with a 'when' condition is more specific than a CommandRule
     *   without one.  A 'when' condition means that the CommandRule is designed
     *   to operate only at specific times, so it's inherently more
     *   specialized than one that always operates.
     *   
     *   3. A CommandRule with a 'where' condition is more specific than a CommandRule
     *   without one.  A 'where' condition means that the CommandRule only applies
     *   to a limited geographical area.
     *   
     *   4. A CommandRule that matches a particular Action is more specific than
     *   one that matches any Action.
     *   
     *   5. If two CommandRule commands are for the same Action, the CommandRule that
     *   matches a more specialized subclass (or just a single object
     *   instance) for a noun phrase is more specific than one that matches
     *   a base class for the same noun phrase.  For example, 'take
     *   Container' is more specific than 'take Thing', because Container
     *   is a subclass of Thing, and 'take backpack' (where the 'backpack'
     *   is a Container) is more specific than either.  This type of
     *   specialization applies in the canonical object role order: direct
     *   object, indirect object, accessory.  For example, we consider 'put
     *   Container in Thing' to be more specific than 'put Thing in
     *   Container', because we look at the direct object by itself before
     *   we even consider the indirect object.  This rule only applies when
     *   the Action is the same: 'put Thing in Container' and 'open Door'
     *   are equal for the purposes of this rule.
     *   
     *   It's important to understand that each degree of specialization is
     *   considered independently of the others, in the order above.  For
     *   example, if you have a CommandRule with just a 'when' condition, and
     *   another with only a 'where' condition, the one with the 'when'
     *   condition has higher priority.  This is because we look at the
     *   presence of a 'when' condition first, before even considering
     *   whether there's a 'where' condition.
     *   
     *   The library has no way to gauge the specificity of a 'when' or
     *   'where' condition, so there's no finer-grained priority to the
     *   conditions than simply their presence or absence.
     *   
     *   If two CommandRules have the same priority based on the rules above, the
     *   one that's defined LATER in the source code has priority.  This
     *   means that CommandRules defined in the game take priority over library
     *   definitions.  
     */
    priority = 100

    /*
     *   Execute the command. 
     */
    
    /* 
     *   ECSE ADDED a curCmd parameter (the command being added) to give the CommandRule
     *   access to what it's meant to be acting on, together with a default
     *   handling (execute the action associated with the current command).
     */
    exec(curCmd)
    {        
        /*
         *   If the command specifies a direction, check that the direction is
         *   valid for the actor's location. This will rule out meaningless
         *   commands like THROW BALL PORT, GO AFT or PUSH TROLLEY STARBOARD
         *   when we're not aboard a vessel.
         */
        if(curCmd.verbProd && curCmd.verbProd.dirMatch != nil)
            checkDirection(curCmd);
	
        /*   
         *   Temporarily set now.dobj and now.iobj to the dobj and iobj of the curCmd
         *   so that they're available to be passed as parameters
         */        
        now.action.curDobj = curCmd.dobj;
        now.action.curIobj = curCmd.iobj;
        now.action.curAobj = curCmd.acc;
        
        /* 
         *   If the command is an action to be carried out by the player
         *   character, execute the action in the normal manner.
         */
        if(curCmd.actor == now.player)
        {
            /* 
             *   If our execAction() method is going to handle the action in
             *   some non-standard way, instead of simply stopping it or
             *   replacing it with another one, we need to perform some
             *   housekeeping to ensure everything works properly.
             */
            if(handleAction)
            {
                /* 
                 *   If we specified an object on the handleAction property,
                 *   it's the action we're going to simulate. We don't need to
                 *   specify a different action if we're notionally handling the
                 *   one we've just matched.
                 */
                if(propType(&handleAction) == TypeObject)
                {
                    /* 
                     *   Change the current action to the one we're notionally
                     *   handling.
                     */
                    libGlobal.curAction = handleAction;
                    
                    /*  
                     *   Set the objects of the new now.action in case we need them
                     */
                    now.action.curDobj = curCmd.dobj;
                    now.action.curIobj = curCmd.iobj;
                    now.action.curAobj = curCmd.acc;
                }
                   
                /* Send the beforeAction notifications. */                
                now.action.beforeAction();                
                
            }
            
            execAction(curCmd); 
        }
        
        /* 
         *   If the command is directed to another actor (or object) let the
         *   actor or object in question handle it.
         */
        else
            curCmd.actor.handleCommand(curCmd.action);
    }
    
    /* 
     *   If this CommandRule is handling a complete action (instead of stopping one or
     *   replacing it with another) this should either be true (if it's the same
     *   action that we've matched) or some other action (if that's the one
     *   we're simulating and it's not the one we matched).
     */
    handleAction = nil
    
    /* 
     *   We separate out execAction() as a separate method from exec() so that
     *   custom CommandRules can readily override this for the player character while
     *   leaving commands directed to other actors (or objects) to be handle by
     *   their handleCommand() method.     */
    
    execAction(curCmd)
    {
        /* 
         *   Our default behavior is to let the current action handle the
         *   command.
         */
        curCmd.action.exec(curCmd);
    }
    
    /* 
     *   Check whether the direction associatated with this command is valid for
     *   the actor's current location.
     */
    checkDirection(curCmd)
    {
        local dirn = curCmd.verbProd.dirMatch.dir;
        local loc = curCmd.actor.getOutermostRoom();
        
        /* 
         *   Rule out a command involving a shipboard direction where shipboard
         *   directions aren't allowed.
         */
        if(dirn.ofKind(ShipboardDirection) && !loc.allowShipboardDirections())
        {
            showMsg(no shipboard directions, 'Shipboard directions {plural} {have}
                no meaning {here}. ');
            abort;
        }
        
        
        /*
         *   Rule out a command involving a compass direction where compass
         *   directions aren't allowed.
         */
        if(dirn.ofKind(CompassDirection) && !loc.allowCompassDirections)
        {
            showMsg(no compass directions, 'Compass directions {plural} {have}
                no meaning {here}, ');
            abort;
        }
        
        /* 
         *   Set the direction property of the current Command's association
         *   Action object to the direction determined by its
         *   verbProd.dirMatch.dir property in case the game author tries to use
         *   action.direction to get at the direction entered.
         */
        curCmd.action.direction = dirn;
        
    }
    
    /* 
     *   Utility method that can be called from execAction() to redirect the
     *   command to a new action with the same (or new) objects. This will
     *   normally be called via the doInstead()/doNested() interface defined on
     *   our Redirector superclass.
     */    
    redirect(curCmd, altAction, dobj: = 0, iobj: = 0, aobj: = 0,
             isReplacement: = true)
    {
        
        /* 
         *   We use a default value of 0 for the dobj and iobj parameters to
         *   mean 'keep the current value' so that we can explicitly pass nil
         *   values if we want to.
         */             
        dobj = dobj == 0 ? curCmd.dobj : dobj;
        iobj = iobj == 0 ? curCmd.iobj : iobj;
        aobj = iobj == 0 ? curCmd.acc : aobj;
        
        /* 
         *   Get the current command to change its current action to altAction
         *   performed on dobj and iobj. Note that this will change now.action to
         *   altAction.
         */
        curCmd.changeAction(altAction, dobj, iobj, aobj);
        
        /* Execute the command on our new action. */
        now.action.exec(curCmd);
    }
    
    /* 
     *   Set this property to true for this CommandRule to match only if the wording
     *   corresponds (and not just the action). At the moment the check is
     *   only on the first word of the command, but this may usually be enough
     */
    
    strict = nil
    
    /*  
     *   Flag, do we want to ignore (i.e. not report) an error in the
     *   construction of this CommandRule. We may want to do this when the error is
     *   simply due to the exclusion of a module like extras.hxn
     */
    ignoreError = nil
;

/* Define isHappening as a property in case the scenes module is not included */
property isHappening;

/* ------------------------------------------------------------------------ */
/*
 *   A CommandRuleCmd is a helper object that stores a single command match
 *   template for a CommandRule object.  A given CommandRule can match multiple commands;
 *   each match is represented by one of these objects.  
 */
class CommandRuleCmd: object
    /* construction */
    construct(d, c)
    {
        commandRule = d;
        cmd = c;
    }

    /* the CommandRule I'm associated with */
    commandRule = nil

    /* 
     *   The parsed command template.  This is a list consisting of the
     *   Action we match plus the objects or classes we match for the noun
     *   phrases, in the canonical order (direct object, indirect object,
     *   accessory).  The action can also be the Action class itself, to
     *   indicate that we match all actions.  We only match a command with
     *   the same number of noun phrases as in the template.  
     */
    cmd = []

    /*
     *   My global sequence number.  During initialization, we set this to
     *   reflect our position in the global list of CommandRuleCmd objects after
     *   the list is sorted into priority order.  This makes it easy to
     *   sort a new list of CommandRuleCmd objects into the original priority
     *   order.  
     */
    seqno = 0

    /*
     *   Class member: the master table of CommandRuleCmd objects.  The library
     *   builds this automatically during preinitialization.  This is a
     *   lookup table indexed by Action.  Each Action entry has a list of
     *   CommandRuleCmd objects associated with that Action.  Note that the
     *   generic all-verb handlers are listed under Action.  
     */
    commandRuleTab = nil

    /*
     *   Class method: Get a list of CommandRule objects matching the given
     *   command.  'cmdLst' is the command's action and object list in
     *   canonical format: [action, dobj, iobj, accessory].  
     */
    findCommandRules(cmdLst)
    {
        /* 
         *   Start with a list of the CommandRuleCmd objects that could *possibly*
         *   match this command.  This includes all of the CommandRuleCmds listed
         *   in the master table under the command's action, plus all of
         *   the wildcard "any action" CommandRuleCmds, which are listed in the
         *   table under Action.  
         */
        local lst = nilToList(commandRuleTab[cmdLst[1]])
            + nilToList(commandRuleTab[Action]);

        /* keep only the elements that match the command's objects */
        lst = lst.subset({ d: d.matchCmd(cmdLst) });
        
        /* 
         *   keep only the elements whose where and when conditions don't
         *   exclude them.
         */
        
        lst = lst.subset({ d: d.matchConditions() } );

        /* sort the combined list into the original priority order */
        lst = lst.sort(SortAsc, { a, b: a.seqno - b.seqno });

        /* pull out the list of CommandRules that the CommandRuleCmds map to */
        lst = lst.mapAll({ d: d.commandRule });

        /* 
         *   It's conceivable that a given CommandRule is listed more than once,
         *   since the same CommandRule could have more than one matching command
         *   template.  In such cases we'd still only want to process each
         *   CommandRule once, so eliminate any duplicates. 
         */
        lst = lst.getUnique();

        /* return the result */
        return lst;
    }

    /*
     *   Check for a match to a command list.  'cmdLst' is the command
     *   object list in canonical format: [action, dobj, iobj, ...].  This
     *   routine determines if our CommandRule is a handler for the given command.
     */
    matchCmd(cmdLst)
    {
        /*
         *   The first element of the template is the action.  For the
         *   template to match, the Command's action must either exactly
         *   match the template action, or it must be an instance of the
         *   template action class.  
         */
        if (cmdLst[1] != cmd[1] && !cmdLst[1].ofKind(cmd[1]))
            return nil;

        /*   
         *   If the strict property is set we want the command rule to match not only
         *   the command but the wording of the command, or rather, at least the
         *   first word, so that, for example, 'go through junk' would not be
         *   treated as matching 'walk through junk' (in English idiom the first
         *   but not the second might be treated as meaning 'search junk').
         */
           
        
        if (now.command != nil && commandRule.strict && now.command.verbProd && now.command.verbProd.tokenList !=
            nil)
        {
            local cmdToks = now.command.verbProd.tokenList.mapAll( {x:
                getTokVal(x) });
            local commandRuleToks = commandRule.cmd.split(' ');
            
            if(cmdToks[1] != commandRuleToks[1])
                return nil;        
        }
        
        /* 
         *   The rest of the template is the list of noun roles, in
         *   canonical order (direct object, indirect object, accessory).
         *   The Command must have the same number of objects, and each
         *   object in the Command must match the corresponding template
         *   object or be an instance of the template object class.
         *   (There's one special case: if the template object is nil, we
         *   match anything.)
         *   
         *   First, check that we have the same number of objects.  
         */
        if (cmdLst.length() != cmd.length())
            return nil;

        /* now check each object */
        for (local i = 2, local len = cmd.length() ; i <= len ; ++i)
        {
            /* get the object from the Command and template */
            local cobj = cmdLst[i];
            local tobj = cmd[i];

            /* 
             *   if the template object is non-nil, we have to match the
             *   object or class 
             */
            if (tobj != nil && cobj != tobj && !cobj.ofKind(tobj) 
                && cobj.lexicalParent != tobj)
                return nil;
        }

        /* everything matches, so this Command matches this template */
        return true;
    }

    /*
     *   Get the processing priority sorting order relative to another
     *   CommandRuleCmd.  (See CommandRule.priority for a discussion of the priority
     *   rules.)
     */
    compareTo(other)
    {
        local p, a, b;
        
        /* the explicitly priority takes precedence over all other rules */
        if (commandRule.priority != other.commandRule.priority)
            return commandRule.priority - other.commandRule.priority;

        /* a 'when' has priority over no 'when' */
        p = commandRule.hasProp(&when);
        if (p != other.commandRule.hasProp(&when))
            return p ? 1 : -1;

        /* a 'where' has priority over no 'where' */
        p = commandRule.hasProp(&where);
        if (p != other.commandRule.hasProp(&where))
            return p ? 1 : -1;

         /* a 'who' has priority over no 'where' */
        p = commandRule.hasProp(&who);
        if (p != other.commandRule.hasProp(&who))
            return p ? 1 : -1;
        
        /* a 'during' has priority over no 'during' */
        p = commandRule.hasProp(&during);
            if (p != other.commandRule.hasProp(&during))
            return p ? 1 : -1;
        
        /* get each command's Action */
        a = cmd[1];
        b = other.cmd[1];
        
        /* 
         *   a 'direction' has priority over no 'direction' for a Travel
         *   command.
         */        
        if(a == Travel)
        {
            p = commandRule.hasProp(&direction);
            if (p != other.commandRule.hasProp(&direction))
                return p ? 1 : -1;
        }

        /* 
         *   if one is a specific Action and the other is the generic
         *   'Action' class (a wildcard that matches all actions), the
         *   specific action takes precedence 
         */
        if (a != Action && b == Action)
            return 1;
        if (a == Action && b != Action)
            return -1;

        /* if the actions are the same, compare the objects */
        if (a == b && cmd.length() == other.cmd.length())
        {
            /* 
             *   Check each object role in turn, in canonical order.  The
             *   first one where the precedence differs determines the
             *   overall precedence. 
             */
            for (local i = 2 ; i < cmd.length() ; ++i)
            {
                /* get the two objects */
                a = cmd[i];
                b = other.cmd[i];

                /* 
                 *   if one is a subclass of the other, the subclass takes
                 *   precedence because it's more specialized
                 */
                if (a == nil || b == nil)
                {
                    if (a != nil)
                        return 1;
                    if (b != nil)
                        return -1;
                }
                else
                {
                    if (a.ofKind(b))
                        return 1;
                    if (b.ofKind(a))
                        return -1;
                }
            }
        }

        /* 
         *   Failing all else, go by the relative location of the source
         *   code definitions: the definition that appears later in the
         *   source code takes precedence.  If the two are defined in
         *   different modules, the one in the later module takes
         *   precedence.  
         */
        if (commandRule.sourceTextGroup != other.commandRule.sourceTextGroup)
            return commandRule.sourceTextGroup.sourceTextGroupOrder
            - other.commandRule.sourceTextGroup.sourceTextGroupOrder;

        /* they're in the same module, so the later one takes precedence */
        return commandRule.sourceTextOrder - other.commandRule.sourceTextOrder;
    }
    
    /* Check whether a CommandRule matches its where, when, who and during conditions. */    
    matchConditions()    
    {
        /* first check the where condition, if there is one. */
        if(commandRule.hasProp(&where))
        {
            local whereLst = valToList(commandRule.where);
                                    
            /* 
             *   if we can't match any item in the where list to the player
             *   char's current location, we don't meet the where condition, so
             *   return nil
             */
            if(whereLst.indexWhich( {loc: now.player.isIn(loc)}) == nil)
                return nil;
        }
        
        /* 
         *   Interpret 'when' as simply a routine that returns true or nil
         *   according to some condition defined by the author; so we simply
         *   test whether command rule.when returns nil if the property is defined.
         */        
        if(commandRule.hasProp(&when) && commandRule.when() == nil)
            return nil;       
        
         /* check the who condition, if there is one. */
        if(commandRule.hasProp(&who))
        {
            local whoLst = valToList(commandRule.who);
                        
            
            /* 
             *   If we can't match any item in the who list to the current
             *   actor, we don't meet the who condition, so return nil
             */
            if(whoLst.indexOf(now.command.actor) == nil)
                return nil;
        }
        
        
        /* 
         *   if we're using the scene manager and a during condition is
         *   specified, test whether the scene is currently happening.
         */        
        if(defined(sceneManager) && commandRule.hasProp(&during))
        {
            local duringList = valToList(commandRule.during);
            
            if(duringList.indexWhich({s: s.isHappening}) == nil)
                return nil;
        }
        
        /* 
         *   If the command is a travel action and a direction has been
         *   specified, check that we match the direction.
         */
        if(commandRule.hasProp(&direction) && cmd[1] is in (Travel,
            PushTravelDir, ThrowDir))
            return valToList(commandRule.direction).indexOf(
                now.command.verbProd.dirMatch.dir) != nil;
        
        /* 
         *   If we haven't failed any of the conditions, we're okay to match, so
         *   return true.
         */
        return true;
    }
;



/* ------------------------------------------------------------------------ */
/*
 *   A CommandRuleParser is a helper object we use during initialization for
 *   parsing CommandRule 'cmd' strings and turning them into action description
 *   lists.  The language-specific library creates these for us based on
 *   the language grammar.
 *   
 *   These objects are only used during initialization, since they're only
 *   needed to set up the internal representation of a CommandRule command
 *   template string.  During normal play we only need that internal
 *   representation.  
 */
class CommandRuleParser: object
    /*
     *   Construction.  The language library should create one of these
     *   objects for each verb phrasing it wants to define for use in
     *   writing CommandRule 'cmd' strings.  
     */
    construct(action, v, pat, roles)
    {
        action_ = action;
        verb_ = v;
        pat_ = new Regex('<space>*' + pat + '<space>*$');
        roles_ = roles;
    }

    /* The Action object for the verb. */
    action_ = nil

    /* 
     *   The main verb word.  This is simply the first word of the verb's
     *   token list.  This is essentially a hash, to reduce the number of
     *   regular expressions we have to test individually.  This saves us a
     *   lot of compute time, since it's very quick to pull out the first
     *   word and get a list of the small set of rules with the same first
     *   word.  We then test each of those potential matches by doing the
     *   full regular expression comparison.  
     */
    verb_ = nil

    /* 
     *   The regular expression for the verb rule.  The verb initializer
     *   sets this up to contain the literal text of the verb rule's
     *   literal tokens, and to substitute a parenthesized group wildcard
     *   pattern for each noun slot.  For example, for English, a Give To
     *   rule might look like 'give (.+) to (.+)'.  
     */
    pat_ = nil

    /* 
     *   The list of object roles.  This is a list of NounRole objects.
     *   The list entries correspond positionally to the parenthesized
     *   groups in the regular expression string, so roles_[1] is the noun
     *   role for the first parenthesized group, roles_[2] is the noun role
     *   for the second group, and so on.  
     */
    roles_ = []
;


/* ------------------------------------------------------------------------ */
/*
 *   CommandRuleParser Table.  This stores a lookup table of CommandRuleParser objects,
 *   indexed by the first word (the verb) of the command template.  
 */
class CommandRuleParserTable: object
    /* add a parser to the table */
    addParser(p)
    {
        /* get the verb from the parser */
        local v = p.verb_;

        /* make sure there's a list at the verb entry */
        if (ptab[v] == nil)
            ptab[v] = [];

        /* add this parser to the list for its verb */
        ptab[v] += p;
    }

    /* get the list of parsers for a given verb word */
    getParsers(v)
    {
        /* look up the list */
        local lst = ptab[v];

        /* return the list, or an empty list if the verb is unknown */
        return (lst != nil ? lst : []);
    }

    /* the lookup table */
    ptab = perInstance(new Map(64, 128))
;

/*
 *   Initialize the CommandRule objects.  This parses each CommandRule's command string
 *   to generate a list of command templates.  
 */
commandRulePreinit: PreinitObject
    execute()
    {              
               
        /* initialize the CommandRuleParser objects */
        local ptab = new CommandRuleParserTable();
        initCommandRuleParsers(ptab);

        /* get the global symbols */
        local gtab = globalSymbols();

        /* get the predicate noun phrase list */
        local roles = NounRole.allPredicate;

        /* 
         *   Add the special "any verb" wildcard verbs.  Add one for each
         *   subset of the roles list.  (The role subsets are always
         *   cumulative, because we don't ever have a later role without
         *   also including all of the earlier roles.  E.g., if a verb
         *   takes an indirect object, it must take a direct object as
         *   well.)  
         */
        local pat = '<star>';
        local npat = ' (<alphanum|_|vbar|star>+)';
        for (local i = 0 ; i <= roles.length() ; ++i, pat += npat)
        {
            ptab.addParser(new CommandRuleParser(
                Action, '*', pat, roles.sublist(1, i)));
        }
        
        /* set up an empty list of command template (CommandRuleCmd) objects */
        local tlst = new Vector(100);

        /* call the language-specific parser for each CommandRule's command string */
        forEachInstance(CommandRule, new function(d)
        {
            /* get the string to parse */
            local c = d.cmd;

            /* 
             *   split it into commands - a given CommandRule might match multiple
             *   commands 
             */
            local clst = c.split(';');
  
                        
            /* process each command */
            foreach (c in clst)
            {
                /* check for direction names in the command */
                local tokList = c.split(R'<space|vbar>');
                
                foreach(local tok in tokList)
                {
                    local dir = Direction.nameTab[tok];
                    if(dir != nil)
                    {                        
                        d.direction = valToList(d.direction) + dir;
                    }
                }
                
                /* pull out the first word of the command */
                regexMatch(R'<space>*(<alphanum|star>+)', c);

                /* match it against each template with the same first word */
                local found = nil;
                foreach (local p in ptab.getParsers(regexGroup(1)[3]))
                {
                    /* if we match this item's template, this is the one */
                    if (regexMatch(p.pat_, c))
                    {
                        /* 
                         *   It matches.  Set up the initial action template
                         *   with just the action. 
                         */
                        local tpl = [p.action_];
                        
                        /* 
                         *   Add each noun slot.  Note that we need to add
                         *   the nouns in the canonical order: dobj, iobj,
                         *   accessory.  This might differ from the order
                         *   of the noun phrases in the verb; for example,
                         *   Give To in English can be phrased as "give
                         *   dobj to iobj" or as "give iobj dobj" - the
                         *   second form uses the reverse of the canonical
                         *   order.  We must always use the canonical
                         *   ordering for the template, regardless of how
                         *   the verb is phrased.  
                         */
                        foreach (local r in roles)
                        {
                            /* 
                             *   find this role in the template list order
                             *   - this tells us which parenthesized group
                             *   it matches in the regular expression for
                             *   the verb template 
                             */
                            local idx = p.roles_.indexOf(r);
                            
                            /* 
                             *   If the role isn't in the verb, we're done.
                             *   A verb with an indirect object always has
                             *   a direct object, and a verb with an
                             *   accessory always has direct and indirect
                             *   objects, so if this role isn't in the
                             *   verb's list, we know there are no more
                             *   roles to find.  
                             */
                            if (idx == nil)
                                break;
                            
                            /* get the regular expression match */
                            local n = regexGroup(idx)[3];

                            /* add it to the template list */
                            tpl += n;
                        }

                        /* expand "noun|noun" constructions */
                        expandNounLists(gtab, d, tlst, tpl, 2);

                        /* we found a match, so we can stop looking */
                        found = true;
                        break;
                    }
                }

                /* if we didn't a match, note the error */
                if (!found && d.ignoreError == nil)
                {
                    "Error in the command phrase of a CommandRule \"<<d.cmd>>\": this
                    command syntax doesn't match any known verb grammar.";
                }
            }
        });

        /* sort the CommandRuleCmd list by descending precedence */
        tlst.sort(SortDesc, { a, b: a.compareTo(b) });

        /* build the master table of CommandRuleCmd objects */
        local dtab = CommandRuleCmd.commandRuleTab = new Map(64, 128);
        local seqno = 1;
        foreach (local d in tlst)
        {
            /* 
             *   Set this item's global sequence number.  This lets us
             *   quickly sort into the original priority order when we
             *   combine two lists. 
             */
            d.seqno = seqno++;

            /* get this item's Action - it's the first template item */
            local action = d.cmd[1];

            /* make sure this entry has a list */
            if (dtab[action] == nil)
                dtab[action] = [];

            /* add this item to this action entry's list */
            dtab[action] += d;
        }
    }

    /*
     *   Expand an initial template list.  This takes a list of the form
     *   [action, 'a|b|c', 'd|e|f'], and converts it into multiple lists
     *   with an individual noun in each slot.  
     */
    expandNounLists(gtab, d, tlst, tpl, idx)
    {
        /* 
         *   if we've run out of slots, we have a fully expanded template,
         *   so simply add the current template to the results and return 
         */
        if (idx > tpl.length())
        {
            tlst.append(new CommandRuleCmd(d, tpl));
            return;
        }

        /* process the list of elements for the current item */
        foreach (local item in tpl[idx].split('|'))
        {
            /* look up the object name in the symbol table */
            local obj = gtab[item];

            /* if we didn't find it, note the error */
            if (obj == nil && item != '*')
            {
                /* explain the problem */
                if(!d.ignoreError)
                    "Error in the command phrase of a CommandRule \"<<d.cmd>>\": the word \"<<
                      item>>\" is not a known object or class name.
                    Each noun must be the source code name of an object
                    or class.\n";

                /* abort processing this template */
                return;
            }

            /* build the simplified list with the current single item */
            local stpl = tpl;
            stpl[idx] = obj;

            /* recursively process the rest of the list */
            expandNounLists(gtab, d, tlst, stpl, idx + 1);
        }
    }
    
    
;

/* 
 *   Define four DefaultCommandRules that between them will match any command unless a
 *   more specialized CommandRule intervenes. This allows most commands to be executed
 *   by the appropriate action.
 */

default4CommandRule: CommandRule
    cmd = '* * * *'
;

default3CommandRule: CommandRule
    cmd = '* * *'
;

default2CommandRule: CommandRule
    cmd = '* *'
;

default1CommandRule: CommandRule
    cmd = '*'
;