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

/*
 *   ************************************************************************
 *   debug.hxn: this module defines a
 *   number of commands that can be used for debugging purposes.
 */


/* We only include any of the code in this module in debug builds */
#ifdef __DEBUG

DebugCtl: object
    /*
     *   Debug mode options.  Each debug function has an associated ID key,
     *   which is just a string identifying it.  This is a lookup table
     *   that keeps a true/nil value for each key, saying whether the
     *   function is enabled or disabled.  This lets the developer turn
     *   debugging displays on and off individually, so that you don't have
     *   to look at piles of debug output not relevant to the task you're
     *   currently working on.  
     */
    enabled = static (new Map(32, 64))

    /* list of all debugging options */
    all = ['spelling', 'messages', 'actions', 'rules']

    /* show the current status */
    status()
    {
        "Debugging options:\n";
        local opts = all.sort(SortAsc);
        foreach (local opt in opts)
            "\t<<opt>> = <<enabled[opt] ? 'on' : 'off'>>\n";
    }
    
    /* Map used to avoid duplicate debug message reports */
    messageIDs = static (new Map(32, 64))    
;

/*
 *   Debug options.  This is the general verb for performing various
 *   debugging operations while running the game.  The Debug Action parses
 *   the options string to carry out the command.  
 */
verb Debug 'debug' literalDobj:
    verbPhrase = 'debug/debugging'
    missingQ = 'which debug option do you want to set'
;

/* The Debug Action with various options */
action Debug: SystemAction
    execAction(cmd)
    {
        now.action.literal = cmd.dobj.name.toLower;
        switch(now.literal)
        {       
        case 'status':
            DebugCtl.status();
            break;
        case 'off':
        case 'stop':    
            foreach(local opt in DebugCtl.all)
                DebugCtl.enabled[opt] = nil;
            DebugCtl.status();
            break;
        default:
            if(DebugCtl.all.indexOf(now.literal))
            {
                DebugCtl.enabled[now.literal] = !DebugCtl.enabled[now.literal];
                DebugCtl.status();               
            }
            else                
                "That is not a valid option. The valid DEBUG options are DEBUG
                MESSAGES, DEBUG SPELLING, DEBUG ACTIONS, DEBUG RULES,
                DEBUG OFF or DEBUG STOP (to turn off all options) or
                just DEBUG by itself to break into the debugger. ";
            break;
        }
        
    }
;

/* DEBUG without any options simply breaks into the debugger */
action DebugI: SystemAction
    execAction(cmd)
    {
        /* if the debugger is present, break into it */
        if (debugTrace(DebugTraceCheck))
            debugTrace(DebugTraceBreak);
        else
            showMsg(debugger not present, 'Debugger not present. ');
    }
;

verb DebugI 'debug':
    verbPhrase = 'debug/debugging'
    missingQ = 'which debug option do you want to set'
;

/* 
 *   The actionTab object holds a table providing the names (as strings)
 *   corresponding to the various Action objects, for use with the DEBUG ACTIONS
 *   option.
 */
actionTab: PreinitObject
    
    /* 
     *   To return the string val corresponding to the Action val, simply look
     *   it up in out ctab table
     */
    symbolToVal(val)
    {
        return ctab[val];        
    }
    
    /* A Map of Actions and their corresponding string names */
    ctab = [* -> '???']
        
    execute()
    {
        /* 
         *   Populate our ctab table by going through the global symbol table at
         *   preinit and storing the value and associated name of every Action
         *   object.
         */
        globalSymbols().forEachAssoc( new function(key, value)
        {
            if(typeOf(value) == TypeObject && value.ofKind(Action))
                ctab[value] = key;
        });
    }
;

/* 
 *   The Purloin Action allows a game author to take any object in the game
 *   while testing
 */
action Purloin(dobj): TAction    
    againRepeatsParse = true
    
    /* The PURLOIN action requires universal scope */
    addExtraScopeItems(whichRole?)
    {
        makeScopeUniversal();
    }
    beforeAction() { }
    afterAction() { }
    turnSequence() { }
    
    /* The Purloin action should work even on a hidden item  */
    unhides = true
;    

/* 
 *   The GONEAR action allows the game author to move the player character to
 *   anywhere on the map, while testing.
 */
action GoNear(dobj): TAction   
    againRepeatsParse = true
    
    /* The GONEAR action requires universal scope */
    addExtraScopeItems(whichRole?)
    {
        makeScopeUniversal();
    }  
    beforeAction() { }
    afterAction() { }
    turnSequence() { }
    
    /* The GoNear action should work even on a hidden item  */
    unhides = true
;

/*  
 *   The FIAT LUX Action can be used to light up the player character (thus
 *   bringing light to a dark location). Repeating the FIAT LUX action removes
 *   the light from the player character
 */
action FiatLux: IAction
    execAction(cmd)
    {
        now.player.isLit = !now.player.isLit;
        showMsg(fiat lux, '{I} suddenly {1} glowing. ', now.player.isLit ? 'start'
             :  'stop' );
    }
    
    beforeAction() { }    
    turnSequence() { }
;

/* The EVALUATE action allows any expression to be evaluated */
action Evaluate: LiteralAction
    
    /* 
     *   Do we want to use Compiler.compile rather than Compiler.eval()? By default we do since this
     *   circumvents a bug in some Linux interpreters.
     */
    
    useCompile = true
    
    exec(cmd)
    {
        try
        {
            /* 
             *   Try using the Compiler object to evaluate the expression
             *   contained in the name property of the direct object of this
             *   command (i.e. the string literal it was executed upon).
             */
            local res;
            local str = stripQuotesFrom(cmd.dobj.name);
            
            if(useCompile)
            {
                local func = Compiler.compile(str);
                res = func();
            }
            else           
               res = Compiler.eval(str);
            
            if(typeOf(res) == TypeEnum)
            {
                local str = enumTabObj.enumTab[res];
                if(str) res = str;
            }
            
            /* Display a string version of the result */
            say(toString(res));
        }
        /* 
         *   If the attempt to evaluate the expression caused a compiler error,
         *   display the exception message.
         */
        catch (CompilerException cex)
        {           
            cex.displayException();
        }
        
        /* 
         *   If the attempt to evaluate the expression caused any other kind of
         *   error, display the exception message.
         */
        catch (Exception ex)
        {
            ex.displayException();
        }
        
    }
    includeInUndo = true
    afterAction() {}
    beforeAction() { }    
    turnSequence() { }
;

/* An object to store class and object names */
symTab: PreinitObject
    symbolToVal(val)
    {
        return ctab[val];        
    }
    
    ctab = [* -> '???']
    
    /* 
     *   Store a string equivalent of the name of every identifier defined in the
     *   game (and the library)
     */
    execute()
    {
        globalSymbols().forEachAssoc( new function(key, value)
        {
//            if(typeOf(value) == TypeObject && value.isClass)
//                ctab[value] = key;
//            
//            if(typeOf(value) == TypeObject && (value.ofKind(Region)))               
//                ctab[value] = key;
//            
//            if(defined(Actor) && typeOf(value) == TypeObject &&
//               (value.ofKind(ActorState) || value.ofKind(AgendaItem)))
//                ctab[value] = key;
            ctab[value] = key;
        });
    }
;


/* Take a string and return the object whose programmatic name it refers to */
symToVal(val)
{    
    return globalSymbols()[val];      
}
    
/* Take a value and return the string representation of its programmatic name */
valToSym(val)
{
    local str;
    switch(typeOf(val))
    {
    case TypeString:        
        return val;
    case TypeInt:
        return toString(val);
    case TypeObject:
        str = symTab.ctab[val]; 
        if(str == '???' && val.hasProp(&name)) str = val.name;
        return str;
        
    case TypeEnum:
        local enumStr = enumTabObj.enumTab[val];
        if(enumStr) return enumStr;    
        /* Fallthrough deliberate */
    case TypeProp:  
        return symTab.ctab[val]; 
//        return str;   
    case TypeNil:
        return 'nil';
    case TypeTrue:
        return 'true';
    case TypeList:
        str = '[';
        for(local cur in val, local i=1, local len=val.length;; i++)
        {
            str += valToSym(cur);
            if(i < len)
                str += ', ';            
        }
        str += ']';
        return str;
        
    }
    
    return '?';
}


/* 
 *   Provide ProgramObject with an objToString() method so that the EVALUATE
 *   command can display some kind of name of the object via the toString()
 *   function
 */
modify ProgramObject
    objToString()
    {
        /* If this object is a class, return the name of the class */
        if(isClass)
            return symTab.symbolToVal(self);
        
        local str = '';
        
        /* 
         *   If the object has a name property, start the string with this
         *   object's name
         */
        if(name != nil)
            str = name + ' ';
        /* 
         *   Otherwise if we have an identifier for this object stored in our
         *   symbol table, use that
         */
        else if(symTab.symbolToVal(self) != '???')
            str = symTab.symbolToVal(self) + ' ';
        
        /*  Append this object's superclass list in parentheses*/
        str  += '(' + superclasses + ')';
        
        /*  Return the result */
        return str;
    }
    
;


/*
 *   To use this facility, define Test objects like so:
 *
 *. foo: Test
 *.    testName = 'foo'
 *.    testList =
 *.    [
 *.        'x me',
 *.        'i'
 *.    ]
 *. ;
 *
 *. bar: Test
 *.     testName = 'bar'
 *.     testList =
 *.     [
 *.         'look',
 *.         'listen'
 *.     ]
 *. ;
 *
 *. allTests: Test
 *.     testName = 'all'
 *.     testList =
 *.     [
 *.         'test foo',
 *.         'test bar'
 *.     ]
 *   ;
 *
 *   Alternatively,  use the template structure to create your test objects more
 *   conveniently:
 *
 *.  someTest: Test 'foo' ['x me', 'i'];
 *
 *   Unless you're planning to refer to the Test object in some other part of
 *   your code, you can save a bit of typing by making it an anonymous object:
 *
 *. Test 'foo' ['x me', 'i'];
 *
 */


/*
 *   Assertion-based testing
 *   assertPlayerInRoom room: Fails test when not in room; does nothing otherwise
 *   assertPlayerHasItem item(s): Fails test/script when not in possession
 *   assertPlayerLacksItem item(s): Fails test/script when in possession
 *   assertPlayerRoomHasItem item(s): Fails test/script when not in possession
 *   assertPlayerRoomLacksItem item(s): Fails test/script when in possession
 *   assertMsg text: Fails if text is not within prior text output messages; clears after
 *                   and, by default, before each non-assert message
 *   assertMsgClear: Clears assertMsg buffer
 *
 * 
 *   Usage:
 *
 *   test <name>
 *   testall [nostop]
 *   list tests [fully|sorted]
 *
 *
 *   Usage:
 *
 *   test <name>
 *   testall
 *   list tests [fully|sorted]
 *
 */

/////////////////////////////////////
// Mitch's assertion extensions
///////////////////////////////////


/*
 *   Every Thing in the game, for the testing commands that go through all of
 *   them.
 */

everything: object
    lst()
    {
        local obj = firstObj(Thing);
        
        /* Create a vector to store our results. */
        local vec = new Vector;
        
        /* Go through every Thing in the game and add it to our vector. */
        do
        {
            vec.append(obj);
            obj = nextObj(obj, Thing);
        } while (obj!= nil);
        
        lst = vec.toList();
        return lst;
    }
    
;

action AssertPlayerInRoom: SystemAction
    
    /* For this action to work all known rooms also need to be in scope */
    addExtraScopeItems(whichRole?)
    {
        scopeList = scopeList.appendUnique(everything.lst().subset({x:
            x.ofKind(Room)}));
    }

    execAction(cmd)
    {
        if (now.actor.isPlayerChar && now.room != now.dobj) {
            allNewTests.fail('Expected player in room "<<now.dobj>>" but was located in "<<now.room>>"
                instead');
        }
        else
            allNewTests.succeed();
    }  
;

verb AssertPlayerInRoom 'assertPlayerInRoom' singleDobj:
	verbPhrase = 'assertPlayerInRoom (what)'
    missingQ = 'what room is player supposed to be in'
;

///////////////////////////////////////////////

action AssertPlayerHasItem: SystemAction
    
    /* For this action to work all known rooms also need to be in scope */
    addExtraScopeItems(whichRole?)
    {
        scopeList = scopeList.appendUnique(everything.lst());
    }

	execAction(cmd)
	{       
        if(now.dobj.ofKind(Fixture) || now.dobj.ofKind(Immovable) || now.dobj.ofKind(Decoration)) {
            allNewTests.fail('INVALID: Can never have item "<<now.dobj>>"!<.p>');
        }
		else if (now.actor.isPlayerChar && !now.dobj.isIn(now.actor)) {
            allNewTests.fail('Expected player to have item \"<<now.dobj>>\" but does not!');
		}
        else
            allNewTests.succeed();
	}
;

verb AssertPlayerHasItem 'assertPlayerHasItem' singleDobj:
	verbPhrase = 'assertPlayerHasItem (what)'
    missingQ = 'what item is player supposed to have in possession'
;

///////////////////////////////////////////////

action AssertPlayerLacksItem: SystemAction
    
    /* For this action to work all known rooms also need to be in scope */
    addExtraScopeItems(whichRole?)
    {
        scopeList = scopeList.appendUnique(everything.lst());
    }

	execAction(cmd)
	{       
        if(now.dobj.ofKind(Fixture) || now.dobj.ofKind(Immovable) || now.dobj.ofKind(Decoration)) {
            allNewTests.fail('INVALID: Can never have item "<<now.dobj>>"!');
        }
		else if (now.actor.isPlayerChar && now.dobj.isIn(now.actor)) {
            allNewTests.fail('Expected player to NOT have item \"<<now.dobj>>\" but
                does!');
		}
        else
            allNewTests.succeed();
	}
;

verb AssertPlayerLacksItem 'assertPlayerLacksItem' singleDobj:
	verbPhrase = 'assertPlayerLacksItem (what)'
    missingQ = 'what item is player NOT supposed to have in possession'
;

///////////////////////////////////////////////

action AssertPlayerRoomHasItem: SystemAction
    
    /* For this action to work all known rooms also need to be in scope */
    addExtraScopeItems(whichRole?)
    {
        scopeList = scopeList.appendUnique(everything.lst());
    }
       
    execAction(cmd)
    {
        if (now.actor.isPlayerChar && !now.dobj.isIn(now.actor.getOutermostRoom)) 
        {
            allNewTests.fail('Expected player\'s room to have item \"<<now.dobj>>\" but does not!');
        }
        else
            allNewTests.succeed();
    }
    
;

verb AssertPlayerRoomHasItem 'assertPlayerRoomHasItem' singleDobj:
	verbPhrase = 'assertPlayerRoomHasItem (what)'
    missingQ = 'what item is player\'s room supposed to contain'
;

///////////////////////////////////////////////

action AssertPlayerRoomLacksItem: SystemAction
    
    /* For this action to work all known rooms also need to be in scope */
    addExtraScopeItems(whichRole?)
    {
        scopeList = scopeList.appendUnique(everything.lst());
    }
        
    execAction(cmd)
    {
        if (now.actor.isPlayerChar && now.dobj.isIn(now.actor.getOutermostRoom)) {
            allNewTests.fail('Expected player\'s room not to have item \"<<now.dobj>>\" but
                it does!');
        }
        else
            allNewTests.succeed();
    }
;

verb AssertPlayerRoomLacksItem 'assertPlayerRoomLacksItem' singleDobj:
	verbPhrase = 'assertPlayerRoomLacksItem (what)'
    missingQ = 'what item should not be in player\'s room'
;

///////////////////////////////////////////////

action Assert: SystemAction
    exec(cmd)
    {
        /* Recreate the literal text */
        local f = now.commandTokens.sublist(2);
        local expr = f.join('');
        local msg = 'assert FAILED';
        local res = nil;
        expr = stripQuotesFrom(expr);
//        "Expr:<<expr>>:\n";
        try
        {
            /* 
             *   Try using the Compiler object to evaluate the expression
             *   contained in the name property of the direct object of this
             *   command (i.e. the string literal it was executed upon).
             */
            
            res = Compiler.eval(expr);
        }
        /* 
         *   If the attempt to evaluate the expression caused a compiler error,
         *   display the exception message.
         */
        catch (CompilerException cex)
        {           
            msg += ' with compiler exception';
        }
        
        /* 
         *   If the attempt to evaluate the expression caused any other kind of
         *   error, display the exception message.
         */
        catch (Exception ex)
        {
            msg += ' with unknown exception';
        }
        
        if(res == nil) {
            msg += ': <<expr>>';
            allNewTests.fail(msg);
        } else {
            // if do not clear this out, it processes the next token
            cmd.nextTokens = [];
            allNewTests.succeed();
        }
    }
;


verb Assert 'assert' literalDobj:
    verbPhrase = 'assert (expression)'
    missingQ = 'what expression should be true'
;

///////////////////////////////////////////////

action AssertMsgClear: SystemAction
    exec(cmd)
    {
        "Done.\n";
        allNewTests.lastMsg = '';
    }
;

verb AssertMsgClear 'assertMsgClear':
    verbPhrase = 'assertMsgClear'
;

///////////////////////////////////////////////

action AssertMsg: SystemAction
    exec(cmd)
    {
        local f = now.commandTokens.sublist(2);
        local expr = f.join(' ').toLower();
        local fnd = allNewTests.lastMsg.toLower();

        if(fnd == nil) {
            allNewTests.fail('No message to check for "<<expr>>"');
        }
        else if(!fnd.find(expr)) {
            local msg = 'Message string mismatch:\n  found "<<fnd>>"\n';
            msg += '  expected "<<expr>>"';
            allNewTests.fail(msg);
        }
        else
            allNewTests.succeed();

        // message is CLEARED after testing so you don't stumble upon old messages
        allNewTests.lastMsg = '';
    }
;

verb AssertMsg 'assertMsg' literalDobj:
    verbPhrase = 'assertMsg (expression)'
    missingQ = 'what expression should be true'
;

///////////////////////////////////////////////
///////////////////////////////////////////////

/* 
 * An overhaul of the Test object, to make it work
 * and provide needed functionality for actually ASSERTing if something is correct
 * Moreover, the Test did not work and had issues with "leftovers" where each subsequent
 * test depended upon the results of the previous test!
 * 
 *
 *.  Test 'foo' ['x me', 'i', 'wear uniform'] [uniform] @location;
 *
 *   Would cause the uniform to be moved into the player character's inventory
 *   and then the commands X ME and then I and WEAR UNIFORM to be executed in
 *   response to TEST FOO.  Both the location and the inventory entries are optional
 */

class Test: object
    /* The name of this test */
    testName = 'nil'
    
    /* The list commands to be executed when running this test. */
    testList = [ 'z' ]
    
    /*   
     *   The objects to move into the player character's inventory before
     *   running the test script.
     */
    testHolding = []    // objects to move
    
    /* 
     *   The location to move the player character to before running the test
     *   script
     */
    location = nil
    
    /*  
     *   Flag: do we want to report on what items were added to inventory? By
     *   default we do.
     */
    reportHolding = true
	
    /* 
     *   Flag: Do we want to report any change of location by looking around in
     *   the new one? By default we will.
     */
    reportMove = true
    
    /*
     *   Restore game to where it was before this test.  
     *   The default value is nil.
     */   
    restoreStartStateAfterTest = nil
    
    /*
     *   If you need to restart the game BEFORE running the test
     *   activity and values
     */   
    restartBeforeTest = nil
    
    /*
     *   By default, we want to clear out the message buffer before each non-assert
     *   command, but you can change that for each test
     */   
    clearAssertBufferBeforeCmd = true

    /////////////////////
    
    /* Move everything in the testHolding list into the actor's inventory */
    getHolding()
    {
        foreach (local x in testHolding) {
            x.moveInto(now.actor);
            x.isHidden = nil;   // otherwise cannot see or interact with it

        }
        
        /* 
         *   If we want to report on the effect of moving additional items into
         *   the player character's inventory, and if we specified any items to
         *   move, report that the actor is now holding those items.
         */
        if(reportHolding && testHolding.length > 0)
            showMsg(debug test now holding, '{I} {am} {now} holding {1}.\n',
                 makeListStr(testHolding, &theName));
    }

    /* 
     *   Run this test by passing the commands into a script file to replay
     */
    run()
    {        
        "====================================\n";
        "Test: \"<<testName>>\"\n";

        if(restartBeforeTest) {
            local hld = allNewTests.savedState();
            if(allNewTests.restoregame(&restartSaveFile) == nil) {
                allNewTests.isTesting = nil;    // failed so quit the test
                return;
            }
            allNewTests.restoreState(hld);
        }

        /* we save the entire game at this point by default to restore it */
        if(restoreStartStateAfterTest)
            allNewTests.savegame(&revertSaveFile); // save the current state

        /* 
         *   If a location is specified, first move the actor into that
         *   location.
         */
        if (location && now.player.location != location)
        {
            now.player.moveInto(location);	
            
            /* If we want to report the move, show the new room description */
            if(reportMove)
                now.player.getOutermostRoom.lookAroundWithin();
        }
        
        /*   Move any required objects into the actor's inventory */
        getHolding();

        /* Export a file to use */
        local txt;
        local temp = new TemporaryFile();
        local f = File.openTextFile(temp, FileAccessWrite, 'ascii');

        local testVec = new Vector(testList);

        /*   Preparse and execute each command in the list */
        local linecnt = 0;
        testVec.forEach(new function(x)  {
            local c = x.trim();
            f.writeFile('><<c>>\n');
            ++linecnt;
        });
        f.closeFile();
        allNewTests.isTesting = true;
        setScriptFile(temp,ScriptFileNonstop);
        do
        {
            /* Display score notifications if the score module is included. */
            if(defined(scoreNotifier) && scoreNotifier.checkNotification())
                ;
            
            /* run any PromptDaemons if the events module is included */
            if(defined(eventManager) && eventManager.executePrompt())
                ;
        
            try
            {
                /* Output a paragraph break */
                "<.p>";
                
                /* Read a new command from the keyboard. */
                "<.inputline>";
                showCommandPrompt();
                txt = inputManager.getInputLine();
                "<./inputline>\n";   
                
                if(clearAssertBufferBeforeCmd && !txt.startsWith('assert'))
                    allNewTests.lastMsg = '';
                
                
                /* Pass the command through all our StringPreParsers */
                txt = StringPreParser.runAll(txt, Parser.rmcType());
                
                /* 
                 *   If the txt is now nil, a StringPreParser has fully dealt with
                 *   the command, so go back and prompt for another one.
                 */        
                if(txt == nil)
                    continue;
                
                /* Parse and execute the command. */
                Parser.parse(txt);
            }
            catch(TerminateCommandException tce)
            {
                
            }
            
            /* Update the status line. */
            statusLine.showStatusLine();
 
        } while (--linecnt > 0 && allNewTests.isTesting);

        if(restoreStartStateAfterTest) {

            local hld = allNewTests.savedState();
            allNewTests.restoregame(&revertSaveFile); // restore the saved state
            allNewTests.restoreState(hld);
        }
        // this means an error happened so this script needs to go away
        if(!allNewTests.isTesting)
            setScriptFile(nil);
        temp.deleteFile();
    }
    
    /* 
     *   The test all command will run tests in ascending order of their test order. By default we
     *   use the sourceTextOrder.
     */
    testOrder = sourceTextOrder
;
    
/*
 *   The 'list tests' and 'list tests fully' commands can be used to list your
 *   test scripts from within the running game.
 */   
action GListTests: SystemAction
    execAction(cmd)
    {
        if(allNewTests.lst.length == 0)
        {
            showMsg(no test scripts, 'There are no test scripts defined in this
                game. ');
            exit;
        }

        local fully = cmd.verbProd.fully;
        local sorted = cmd.verbProd.sorted;
        
        local testlist = allNewTests.lst;
        if(sorted) {
            testlist = testlist.sort(nil, { a, b: a.testName.compareTo(b.testName) });
        }
        
        foreach(local testObj in testlist)
        {
            "<<testObj.testName>>: ";
            if(fully)               
            {
                foreach(local txt in testObj.testList)
                    "<<txt>>/";
                "\n";
            } else {
                "restoreAfter=<<yesNo(testObj.restoreStartStateAfterTest)>>, ";
                "firstRestart=<<yesNo(testObj.restartBeforeTest)>>, ";
                "clearAssertBuff=<<yesNo(testObj.clearAssertBufferBeforeCmd)>>\n";
            }
        }
    }
    
    yesNo(bval) { return bval? 'yes' : 'no'; }
;

verb GListTests ('list' | 'l') 'tests' (| 'fully' -> fully | 'sorted' -> sorted):
    verbPhrase = 'list/listing test scripts'
;

/*
 *   The 'test X' command can be used with any Test object defined in the source
 *   code:
 */
action GTest: LiteralAction
    /* 
     *   We override exec() rather than execAction() here, since we want to skip
     *   all the normal turn sequence routines such as before and after
     *   notifications and advancing the turn count.
     */
    exec(cmd)
    {
        local target = cmd.dobj.name.toLower();
        local script = allNewTests.valWhich({x: x.testName.toLower == target});
        if (script) {
            allNewTests.totasserts = 0;
            allNewTests.fasserts = 0;
            script.run();
        }
        else
            showMsg(test sequence not found, 'Test sequence not found. ');
    }
    
    /* Do nothing after the main action */
    afterAction() { }
      
    turnSequence() { }
;

verb GTest 'test' literalDobj:
    verbPhrase = 'test/testing (what)'
    missingQ = 'which sequence do you want to test'
;


////////////////////////////////////////////////

action TestAll: SystemAction
    execAction(cmd)
    {
        if(allNewTests.lst.length == 0)
        {
            showMsg(no test scripts, 'There are no test scripts defined in this
                game. ');
            exit;
        }

        allNewTests.totasserts = 0;
        allNewTests.fasserts = 0;        
        
        local testenostop = cmd.verbProd.testnostop;
        local defstop = allNewTests.stopOnFail; // what it was
        if(testenostop)
            allNewTests.stopOnFail = nil;
        local cntr = 0;

        foreach(local testObj in allNewTests.lst)
        {
            ++cntr;
            testObj.run();
            if(allNewTests.stopOnFail && !allNewTests.isTesting)  // Houston, we have a problem
                break;
            allNewTests.isTesting = nil;
        }
        if(testenostop)
            allNewTests.stopOnFail = defstop;   // restore prior setting

        "===========================\n";
        "===========================\n";
        "Total tests: \ \ \ \ \ <<cntr>>\n";
        "Total asserts: \ \ <<allNewTests.totasserts>>\n";
        "Failed asserts: <<allNewTests.fasserts>>\n";
        "===========================<.p>";
    }
;

verb TestAll 'testall' (| 'nostop' -> testnostop):
    verbPhrase = 'testall test scripts'
;


////////////////////////////////////////////////

/* 
 *   The allTests object contains a list of Test objects for listing via the
 *   LIST TESTS command, and for finding the test that corresponds to a
 *   particular testName.
 */
allNewTests: object
    
    // when set (the default), quit testing when failed assertion encountered
    stopOnFail = true
    
   lst()
   {
      if (lst_ == nil)
         initLst();
      return lst_;
   }

    initLst()
    {
        lst_ = new Vector(100);
        local obj = firstObj(Test);
        while (obj != nil)
        {
            lst_.append(obj);
            obj = nextObj(obj, Test);
        }
        lst_ = lst_.toList().sort(SortAsc, {x, y: x.testOrder - y.testOrder});
    }

   valWhich(cond)
   {
      return lst().valWhich(cond);
   }
    
    isTesting = nil     // indicator to print() about copying outcome here as well
    // last message(s) to copy here; reset before each non-test cmd or after assertMsg
    lastMsg = ''
    
    // counter of failed asserts and total asserts
    totasserts = 0
    fasserts = 0

    setLastMsg(msg) {
        msg = msg.specialsToText().trim();
        msg = msg.findReplace('\n',' ',ReplaceAll);
        msg = msg.findReplace('\b',' ',ReplaceAll).trim();
        // solves situation of multiple-multiple spaces
        while(msg.find('  ') != nil)
            msg = msg.findReplace('  ',' ',ReplaceAll);
        lastMsg += ' <<msg>>';  // just keep concantenating with space between
    }
    
    fail(msg) {
        ++totasserts;
        ++fasserts;
        isTesting = nil;        // signals the end of THIS test
        "<.p>###  <<msg>><.p>";
    }
    
    succeed(msg?) {
        if(msg == nil || msg == '')
            msg = 'Valid!';     // need to say something
        ++totasserts;
        "<<msg>><.p>";
    }

    // when undo() happens, it reverts all values to what they were prior to savepoint!
    savedState() { return [totasserts,fasserts,isTesting,restartSaveFile,revertSaveFile]; }
    restoreState(lst) {
        totasserts = lst[1];
        fasserts = lst[2];
        isTesting = lst[3];
        restartSaveFile = lst[4];
        revertSaveFile = lst[5];        
    }

    restartSaveFile = nil       // this gets created at the start of the game
    revertSaveFile = nil        // and this gets created during testing
    
//    init() { savegame(&restartSaveFile); }
    
    // exit with error if game cannot be saved
    savegame(fprop) {
        // only want to create temp file once per property per game
        local f = self.(fprop);
        
        if(f == nil)
            f = new TemporaryFile();
        try {
            saveGame(f);
        }
        catch (StorageServerError sse)
        {
            /* the save failed due to a storage server problem - explain */           
            showMsg(save failed on server, '<.parser>Failed, because of a problem
                accessing the storage server:
                <<makeSentence(sse.errMsg)>><./parser>');

            /* done */
            return;
        }
        catch (RuntimeError err)
        {
            /* the save failed - mention the problem */
            showMsg(save failed, '<.parser>Failed; your computer might be running
                low on disk space, or you might not have the necessary
                permissions to write this file.<./parser>');            
            
            /* done */
            return;
        }
        self.(fprop) = f;    // it worked
    }
   
    // return true if restored game ok, else nil
    restoregame(fprop) {
        if(self.(fprop) == nil) {
            "<.p>### No save file created!<.p>";
            return nil;
        }
        try
        {
            /* restore the file */
            restoreGame(self.(fprop));
        }
        catch (StorageServerError sse)
        {
            /* failed due to a storage server error - explain the problem */
            showMsg(restore failed on server,'<.parser>Failed, because of a problem
                accessing the storage server:
                <<makeSentence(sse.errMsg)>><./parser>');            

            /* indicate failure */
            return nil;
        }
        catch (RuntimeError err)
        {
            /* failed - check the error to see what went wrong */
            switch(err.errno_)
            {
            case 1201:
                /* not a saved state file */
                showMsg(restore invalid file, '<.parser>Failed: this is not a valid
                    saved position file.<./parser> ');                
                break;
                
            case 1202:
                /* saved by different game or different version */
                showMsg(restore invalid match, '<.parser>Failed: the file was not
                    saved by this story (or was saved by an incompatible version
                    of the story).<./parser> ');               
                break;
                
            case 1207:
                /* corrupted saved state file */
                showMsg(restore corrupted file, '<.parser>Failed: this saved state
                    file appears to be corrupted.  This can occur if the file
                    was modified by another program, or the file was copied
                    between computers in a non-binary transfer mode, or the
                    physical media storing the file were damaged.<./parser> ');                
                break;
                
            default:
                /* some other failure */
                showMsg(restore failed, '<.parser>Failed: the position could not be
                    restored.<./parser>');                
                break;
            }

            /* indicate failure */
            return nil;
        }
               
        /* set the appropriate restore-action code */
        PostRestoreObject.restoreCode = 2;  // user restore

        /* notify all PostRestoreObject instances */
        PostRestoreObject.classExec();

        /* Ensure the current actor is defined. */
        libGlobal.curActor = now.actor ?? now.player;
        
        return true;
    }
   
    lst_ = nil  // the tests that are found
;

/* Modification to allow assert to test for the presence of particular strings in game output. */
modify aioSay(txt)
{
    if(allNewTests.isTesting)
    {       
        allNewTests.setLastMsg(txt);        
    }
    
    replaced(txt);
}

/* Create a save file at game startup to allow a Test to restore before running. */
testInit: InitObject
   testRestart = true
   execute()
   {
      if(testRestart)
          allNewTests.savegame(&restartSaveFile);
   }
;


/*
 *   KSTATE (debugging only): what the player character knows of a thing,
 *   anywhere in the game: whether they have seen it, examined it, know of
 *   it (familiar), and so know it (known: seen or familiar).
 */
action KnowledgeState(dobj): TAction
    addExtraScopeItems(role) { makeScopeUniversal(); }
    turnSequence() { }

    /*
     *   Said by the action itself, for any object, without a handler on
     *   Thing (which is defined after this file).
     */
    execResolvedAction()
    {
        local obj = curDobj;
        local yn = {v: v ? 'yes' : 'no'};
        "<<obj.theName>>: seen <<yn(obj.seen)>>, examined <<yn(obj.examined)>>,
        familiar <<yn(obj.familiar)>>, known
        <<yn(now.player.knowsAbout(obj))>>. ";
        return true;
    }
;

verb KnowledgeState 'kstate' singleDobj:
    verbPhrase = 'kstate/kstating (what)'
    missingQ = 'what do you want to know the state of'
;



#endif // __DEBUG