-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.js
1516 lines (1336 loc) · 50.4 KB
/
run.js
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
const TYPE_LARGE_CONSTANT = 0x0;
const TYPE_SMALL_CONSTANT = 0x1;
const TYPE_VARIABLE = 0x2;
const TYPE_OMITTED = 0x3;
const RELATION_PARENT = 0;
const RELATION_SIBLING = 1;
const RELATION_CHILD = 2;
function run(state, output, input, random) {
const instruction = decodeInstruction(state, state.pc);
if (!instruction.opcode) {
throw new Error(`invalid instruction at 0x${state.pc.toString(16)}`);
}
if (instruction.opcode.input && input == null) {
return 'yield';
}
if (instruction.opcode.op === 'quit') {
return 'quit';
}
const operands = instruction.operands.map(operand => operand.type === 'constant' ?
operand.value :
variableLoad(state, operand.value));
// debugInstruction(instruction, operands);
// debugZorkmid(state, instruction, operands);
state.pc = instruction.nextAddress;
return executeInstruction(state, instruction, operands, output, input, random);
}
function debugInstruction(instruction, operands) {
function opStr(operand, i) {
if (operand.type === 'constant') {
return `0x${operand.value.toString(16).padStart(4, 0)}`;
} else if (operand.value === 0) {
return 'ST' + (i != null ? `(0x${operands[i].toString(16)})` : '');
} else if (operand.value <= 0x0F) {
return `L${(operand.value - 1).toString(16)}` + (i != null ? `(0x${operands[i].toString(16)})` : '');
} else {
return `G${(operand.value - 0x0F).toString(16)}` + (i != null ? `(0x${operands[i].toString(16)})` : '');
}
}
let result = `0x${instruction.address.toString(16).padStart(4, '0')}: <`;
result += instruction.raw.map(byte => byte.toString(16).padStart(2, '0')).join(' ') + '> ';
if (!instruction.opcode) {
result += '[invalid opcode]';
} else {
if (instruction.opcode.store) {
result += `${opStr({ type: 'variable', value: instruction.resultVariable })} = `;
}
result += instruction.opcode.op + ' ';
result += instruction.operands.map(opStr).join(' ');
if (instruction.opcode.text) {
result += ` "${instruction.text}"`;
}
if (instruction.opcode.branch) {
if (instruction.branchOffset <= 1) {
result += ` ${instruction.branchIf}=>return ${instruction.branchOffset}`;
} else {
result += ` ${instruction.branchIf}=>0x${(instruction.nextAddress + instruction.branchOffset - 2).toString(16).padStart(4, 0)}`;
}
}
}
console.error(result);
}
function debugOperands(operands) {
console.error(' (' + operands.map(op => op && op.toString(16).padStart(4, 0)).join(' ') + ')');
}
function debugZorkmid(state, instruction, operands) {
function opStr(operand) {
if (typeof operand === 'number') {
return operand.toString(16).padStart(4, '0');
} else {
return operand;
}
}
console.error('<' +
instruction.address.toString(16).padStart(6, '0') + ' ' +
instruction.raw[0].toString(16).padStart(2, '0') + ' ' +
operands.length + ' ' +
opStr(operands.length > 0 ? operands[0] : 0) + ' ' +
opStr(operands.length > 1 ? operands[1] : 0) + ' ' +
opStr(operands.length > 2 ? operands[2] : 0) + ' ' +
opStr(operands.length > 3 ? operands[3] : 0) + '> | ' +
(state.stack[state.stack.length-1].stack.slice(-1)[0] || 0).toString(16).padStart(4, '0') + ' | ' +
(state.stack[state.stack.length-1].localVariables ? state.stack[state.stack.length-1].localVariables.map(l => l.toString(16).padStart(4, '0') + ' ').join('') : '')
);
}
function read16(buffer, address) {
return buffer[address] << 8 | buffer[address + 1];
}
function write16(buffer, address, value) {
buffer[address + 0] = (value >> 8) & 0xFF;
buffer[address + 1] = (value >> 0) & 0xFF;
}
function decodeDictionaryTable(state) {
let address = getDictionaryAddress(state);
const dictionary = {};
const wordSeparatorCount = state.memory[address++];
let wordSeparators = '';
for (let i = 0; i < wordSeparatorCount; ++i) {
wordSeparators += String.fromCharCode(state.memory[address++]);
}
const entryLength = state.memory[address++];
const entryCount = read16(state.memory, address);
address += 2;
const entries = [];
const textLength = getVersion(state) <= 3 ? 6 : 9;
const encodedTextLength = getVersion(state) <= 3 ? 4 : 6;
const dataLength = entryLength - encodedTextLength;
for (let i = 0; i < entryCount; ++i) {
const encodedText = state.memory.slice(address, address + encodedTextLength);
const data = state.memory.slice(address + encodedTextLength, address + encodedTextLength + dataLength);
entries.push({ number: i, encodedText, data, address });
address += encodedTextLength + dataLength;
}
return {
wordSeparators,
entries,
textLength,
encodedTextLength,
dataLength
};
}
function decodeText(state, address, isAbbreviation = false) {
const version = getVersion(state);
const alphabets = getAlphabets(state);
let text = '';
let alphabet = 0;
let shift = null;
let abbr = null;
let tenbit = null;
for (;;) {
const encoded = read16(state.memory, address);
address += 2;
// console.log('0x' + encoded.toString(16).padStart(4, '0') + ' 0b' + encoded.toString(2).padStart(16, '0'));
const zchars = [
(encoded >> 10) & 0x1F,
(encoded >> 5) & 0x1F,
(encoded >> 0) & 0x1F
];
zchars.forEach(c => {
if (abbr != null) {
const abbreviationAddress = 2 * read16(state.memory, getAbbreviationsTableAddress(state) + 2 * (abbr + c));
text += decodeText(state, abbreviationAddress, true).text;
abbr = null;
} else if (tenbit != null) {
if (tenbit === -1) {
tenbit = c;
} else {
text += String.fromCharCode(tenbit << 5 | c);
tenbit = null;
}
} else if (c === 0) {
text += ' ';
} else if (c === 1 && version === 1) {
text += '\n';
} else if (
(c === 1 && version === 2) ||
(c >= 1 && c <= 3 && version >= 3)
) {
if (isAbbreviation) {
throw new Error('abbreviation used from inside abbreviation');
}
abbr = 32*(c-1);
} else if (c === 2 && version <= 2) {
shift = (alphabet + 1) % 3;
} else if (c === 3 && version <= 2) {
shift = (alphabet + 2) % 3;
} else if (c === 4 && version <= 2) {
alphabet = (alphabet + 1) % 3;
} else if (c === 5 && version <= 2) {
alphabet = (alphabet + 2) % 3;
} else if (c === 4 && version >= 3) {
shift = 1;
} else if (c === 5 && version >= 3) {
shift = 2;
} else if (c >= 6) {
const a = shift != null ? shift : alphabet;
shift = null;
if (a === 2 && c === 6) {
tenbit = -1;
} else if (version <= 4 || getAlphabetTableAddress(state) === 0) {
const char = alphabets[a][c-6];
text += char;
} else {
const index = 26 * a + (c - 6);
text += String.fromCharCode(state.memory[getAlphabetTableAddress(state) + index]);
}
}
});
if (encoded & 0x8000) {
break;
}
}
return { text, nextAddress: address };
}
function encodeText(state, text) {
const alphabets = getAlphabets(state);
const version = getVersion(state);
const zchars = [];
const result = [];
text.split('').forEach(char => {
let index;
if (char === ' ') {
zchars.push(0);
} else if (char === '\0') {
zchars.push(5);
} else if ((index = alphabets[0].indexOf(char)) > -1) {
zchars.push(6 + index);
} else if ((index = alphabets[1].indexOf(char)) > -1) {
zchars.push(version <= 2 ? 2 : 4);
zchars.push(6 + index);
} else if ((index = alphabets[2].indexOf(char)) > -1) {
zchars.push(version <= 2 ? 3 : 5);
zchars.push(6 + index);
} else {
// could not encode character
return null;
}
});
for (let i = 0; i < zchars.length; i += 3) {
let value = (zchars[i] << 10) |
((i + 1 < zchars.length ? zchars[i + 1] : 5) << 5) |
((i + 2 < zchars.length ? zchars[i + 2] : 5) << 0) |
((i + 3 < zchars.length ? 0 : (1 << 15)));
result.push((value >> 8) & 0xFF);
result.push((value >> 0) & 0xFF);
}
return result;
}
function getVersion(state) {
return state.memory[0];
}
function getDictionaryAddress(state) {
return read16(state.memory, 0x08);
}
function getObjectTableAddress(state) {
return read16(state.memory, 0x0A);
}
function getGlobalTableAddress(state) {
return read16(state.memory, 0x0C);
}
function getAbbreviationsTableAddress(state) {
return read16(state.memory, 0x18);
}
function getRoutinesOffset(state) {
return read16(state.memory, 0x28);
}
function getStaticStringsOffset(state) {
return read16(state.memory, 0x2A);
}
function getAlphabetTableAddress(state) {
return read16(state.memory, 0x34);
}
function getAlphabets(state) {
return [
'abcdefghijklmnopqrstuvwxyz',
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
getVersion(state) === 1 ?
' 0123456789.,!?_#\'"/\\<-:()' :
' \n0123456789.,!?_#\'"/\\-:()'
];
}
function lookupOpcode(state, code, operandCount) {
return state.opcodeTable.find(entry =>
entry.code === code &&
entry.operandCount === operandCount);
}
function getDefaultPropertyData(state, propertyId) {
const version = getVersion(state);
const maxPropertyId = version <= 3 ? 32 : 64;
if (propertyId > maxPropertyId || propertyId < 1) {
throw new Error(`tried to read invalid default property id ${propertyId}`);
}
const base = getObjectTableAddress(state);
const address = base + 2 * (propertyId - 1);
return read16(state.memory, address);
}
function getObjectBase(state, objectId) {
const version = getVersion(state);
const maxObjectId = version <= 3 ? 255 : 65535;
if (objectId > maxObjectId || objectId < 1) {
throw new Error(`tried to find invalid object id ${objectId}`);
}
const maxPropertyId = version <= 3 ? 32 : 64;
const objectSize = version <= 3 ? 9 : 14;
return getObjectTableAddress(state) + 2 * (maxPropertyId - 1) + objectSize * (objectId - 1);
}
function getAttributeBase(state, objectId, attributeId) {
const version = getVersion(state);
const base = getObjectBase(state, objectId);
const maxAttributeId = version <= 3 ? 32 : 48;
if (attributeId >= maxAttributeId || attributeId < 0) {
throw new Error(`tried to find invalid attribute id ${attributeId}`);
}
const address = base + (attributeId >> 3);
const bit = 7 - (attributeId & 0x7);
return [address, bit];
}
function getObjectAttribute(state, objectId, attributeId) {
const [address, bit] = getAttributeBase(state, objectId, attributeId);
return !!(state.memory[address] & (1 << bit));
}
function setObjectAttribute(state, objectId, attributeId, value) {
const [address, bit] = getAttributeBase(state, objectId, attributeId);
if (value) {
state.memory[address] |= (1 << bit);
} else {
state.memory[address] &= ~(1 << bit);
}
}
function getObjectRelation(state, objectId, relationNumber) {
const version = getVersion(state);
const base = getObjectBase(state, objectId);
return version <= 3 ?
state.memory[base + 4 + relationNumber] :
read16(state.memory, base + 6 + 2 * relationNumber);
}
function setObjectRelation(state, objectId, relationNumber, relation) {
const version = getVersion(state);
const base = getObjectBase(state, objectId);
if (version <= 3) {
state.memory[base + 4 + relationNumber] = relation;
} else {
write16(state.memory, base + 6 + 2 * relationNumber, relation);
}
}
function moveObject(state, obj, dest) {
const parent = getObjectRelation(state, obj, RELATION_PARENT);
if (parent !== 0) {
const sibling = getObjectRelation(state, obj, RELATION_SIBLING);
let node = getObjectRelation(state, parent, RELATION_CHILD);
if (node === obj) {
setObjectRelation(state, parent, RELATION_CHILD, sibling);
} else {
let nodeSibling = getObjectRelation(state, node, RELATION_SIBLING);
while (nodeSibling !== obj) {
node = nodeSibling;
nodeSibling = getObjectRelation(state, node, RELATION_SIBLING);
}
setObjectRelation(state, node, RELATION_SIBLING, sibling);
}
}
if (dest !== 0) {
const destChild = getObjectRelation(state, dest, RELATION_CHILD);
setObjectRelation(state, obj, RELATION_SIBLING, destChild);
setObjectRelation(state, dest, RELATION_CHILD, obj);
} else {
setObjectRelation(state, obj, RELATION_SIBLING, 0);
}
setObjectRelation(state, obj, RELATION_PARENT, dest);
}
function getObjectPropertiesAddress(state, objectId) {
const version = getVersion(state);
const base = getObjectBase(state, objectId);
return read16(state.memory, base + (version <= 3 ? 7 : 12));
}
function setObjectPropertiesAddress(state, objectId, address) {
const version = getVersion(state);
const base = getObjectBase(state, objectId);
write16(state.memory, base + (version <= 3 ? 7 : 12), address);
}
function getObjectName(state, objectId) {
let address = getObjectPropertiesAddress(state, objectId);
return decodeText(state, address + 1).text;
}
function getObjectFirstPropertyAddress(state, objectId) {
let address = getObjectPropertiesAddress(state, objectId);
return address + 1 + 2 * (state.memory[address]);
}
function getPropertyNumber(state, address) {
if (state.memory[address] === 0) {
return 0;
} else if (getVersion(state) <= 3) {
return state.memory[address] & 0x1F;
} else {
return state.memory[address] & 0x3F;
}
}
function getPropertyDataAddress(state, address) {
if ((getVersion(state) <= 3) || !(state.memory[address] & 0x80)) {
return address + 1;
} else {
return address + 2;
}
}
function getPropertyDataLength(state, address) {
if (getVersion(state) <= 3) {
return 1 + (state.memory[address] >> 5);
} else if (state.memory[address] & 0x80) {
return (state.memory[address + 1] & 0x3F) || 64;
} else if (state.memory[address] & 0x40) {
return 2;
} else {
return 1;
}
}
function getObjectPropertyDataLengthFromDataAddress(state, address) {
address -= 1;
if (getVersion(state) <= 3) {
return 1 + (state.memory[address] >> 5);
} else if (state.memory[address] & 0x80) {
return (state.memory[address] & 0x3F) || 64;
} else if (state.memory[address] & 0x40) {
return 2;
} else {
return 1;
}
}
function getNextPropertyAddress(state, address) {
return getPropertyDataAddress(state, address) + getPropertyDataLength(state, address);
}
function getObjectPropertyAddress(state, objectId, propertyId) {
let address = getObjectFirstPropertyAddress(state, objectId);
let id = getPropertyNumber(state, address);
while (id > propertyId) {
address = getNextPropertyAddress(state, address);
id = getPropertyNumber(state, address);
}
if (id === propertyId) {
return address;
} else {
return 0;
}
}
function getObjectPropertyDataAddress(state, objectId, propertyId) {
const address = getObjectPropertyAddress(state, objectId, propertyId);
return address ? getPropertyDataAddress(state, address) : 0;
}
function getObjectPropertyData(state, objectId, propertyId) {
const address = getObjectPropertyAddress(state, objectId, propertyId);
if (!address) {
return null;
}
const dataAddress = getPropertyDataAddress(state, address);
const length = getPropertyDataLength(state, address);
return state.memory.slice(dataAddress, dataAddress + length);
}
function getObjectFirstPropertyNumber(state, objectId) {
const address = getObjectFirstPropertyAddress(state, objectId);
return getPropertyNumber(state, address);
}
function getObjectNextPropertyNumber(state, objectId, propertyId) {
const address = getObjectPropertyAddress(state, objectId, propertyId);
if (address === 0) {
throw new Error(`tried to get next prop for nonexistent prop ${propertyId} on object ${objectId}`);
}
const nextAddress = getNextPropertyAddress(state, address);
return getPropertyNumber(state, nextAddress);
}
function setObjectPropertyData(state, objectId, propertyId, value) {
const address = getObjectPropertyAddress(state, objectId, propertyId);
if (address === 0) {
throw new Error(`tried to set property data for nonexistent prop ${propertyId} on object ${objectId}`);
}
const dataAddress = getPropertyDataAddress(state, address);
const dataLength = getPropertyDataLength(state, address);
if (dataLength === 1) {
state.memory[dataAddress] = value & 0xFF;
} else {
write16(state.memory, dataAddress, value);
}
}
function parseText(state, text, textBufferAddress, parseTableAddress) {
let address = textBufferAddress;
const maxInputLength = state.memory[address++] - (getVersion(state) <= 4 ? 1 : 0);
text = text.slice(0, maxInputLength);
if (getVersion(state) >= 5) {
state.memory[address++] = text.length;
}
for (let i = 0; i < text.length; ++i) {
state.memory[address++] = text.charCodeAt(i);
}
if (getVersion(state) <= 4) {
state.memory[address++] = 0;
}
if (getVersion(state) <= 4 || parseTableAddress !== 0) {
const dictionary = decodeDictionaryTable(state);
const separatorRegex = new RegExp('([ ' + dictionary.wordSeparators.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '])');
let position = getVersion(state) <= 4 ? 1 : 2;
let words = text.split(separatorRegex);
words = words.map(text => {
const result = {
text: text.slice(0, dictionary.textLength).padEnd(dictionary.textLength, '\0'),
length: text.length,
position
};
position += text.length;
return result;
});
words = words.filter(word => /[^\0 ]/.test(word.text));
words.forEach(word => {
const encodedText = encodeText(state, word.text);
if (encodedText) {
word.entry = dictionary.entries.find(entry =>
entry.encodedText.every((c, i) => c === encodedText[i]));
}
});
address = parseTableAddress;
const maxParsedWords = state.memory[address++];
words = words.slice(0, maxParsedWords);
state.memory[address++] = words.length;
words.forEach(word => {
if (word.entry) {
write16(state.memory, address, word.entry.address);
address += 2;
} else {
state.memory[address++] = 0;
state.memory[address++] = 0;
}
state.memory[address++] = word.length;
state.memory[address++] = word.position;
});
}
}
function unpackAddress(state, op, packedAddress) {
if (getVersion(state) <= 3) {
return packedAddress * 2;
}
if (getVersion(state) <= 5) {
return packedAddress * 4;
}
if (getVersion(state) <= 7) {
if (op === 'print_paddr') {
return packedAddress * 4 + getStaticStringsOffset(state);
} else {
return packedAddress * 4 + getRoutinesOffset(state);
}
}
return packedAddress * 8;
}
function performBranch(state, offset) {
if (offset === 0) {
performReturn(state, 0);
} else if (offset === 1) {
performReturn(state, 1);
} else {
offset = new Int16Array([offset])[0];
state.pc = state.pc + offset - 2;
}
}
function performCall(state, op, packedAddress, args, resultVariable = null) {
let address = unpackAddress(state, op, packedAddress);
const localVariableCount = state.memory[address++];
const localVariables = [];
for (let i = 0; i < localVariableCount; ++i) {
let value;
if (getVersion(state) <= 4) {
value = read16(state.memory, address);
address += 2;
} else {
value = 0;
}
if (i < args.length) {
value = args[i];
}
localVariables.push(value);
}
const stackFrame = {
stack: [],
argumentCount: args.length,
localVariables,
resultVariable,
nextAddress: state.pc
};
state.stack.push(stackFrame);
state.pc = address;
}
function performReturn(state, value) {
const frame = state.stack.pop();
if (frame.resultVariable != null) {
variableStore(state, frame.resultVariable, value);
}
state.pc = frame.nextAddress;
}
function variableLoad(state, variable) {
if (variable === 0) {
const frame = state.stack[state.stack.length - 1];
if (frame.stack.length < 1) {
throw new Error('stack underflow');
}
return frame.stack.pop();
} else if (variable <= 0x0F) {
const frame = state.stack[state.stack.length - 1];
return frame.localVariables[variable - 1];
} else {
return read16(state.memory, getGlobalTableAddress(state) + 2 * (variable - 0x10));
}
}
function variableStore(state, variable, value) {
if (variable === 0) {
const frame = state.stack[state.stack.length - 1];
frame.stack.push(value);
} else if (variable <= 0x0F) {
const frame = state.stack[state.stack.length - 1];
frame.localVariables[variable - 1] = value;
} else {
write16(state.memory, getGlobalTableAddress(state) + 2 * (variable - 0x10), value);
}
}
function decodeInstruction(state, address) {
const startAddress = address;
const result = { address };
const opcodeByte = state.memory[address++];
const form =
(getVersion(state) >= 5 && opcodeByte === 0xBE) ? 'extended' :
(opcodeByte & 0xC0) === 0xC0 ? 'variable' :
(opcodeByte & 0xC0) === 0x80 ? 'short' :
'long';
const operandTypes = [];
switch (form) {
case 'short': {
const is0OP = ((opcodeByte & 0x30) === 0x30);
result.opcode = lookupOpcode(state, opcodeByte & 0x0F, is0OP ? '0OP' : '1OP');
if (!is0OP) {
operandTypes.push((opcodeByte >> 4) & 0x03);
}
} break;
case 'long': {
result.opcode = lookupOpcode(state, opcodeByte & 0x1F, '2OP');
operandTypes.push((opcodeByte & 0x40) ? TYPE_VARIABLE : TYPE_SMALL_CONSTANT);
operandTypes.push((opcodeByte & 0x20) ? TYPE_VARIABLE : TYPE_SMALL_CONSTANT);
} break;
case 'variable': {
result.opcode = lookupOpcode(state, opcodeByte & 0x1F, (opcodeByte & 0x20) ? 'VAR' : '2OP');
} break;
case 'extended': {
result.opcode = lookupOpcode(state, state.memory[address++], 'EXT');
} break;
}
if (form === 'variable' || form === 'extended') {
for (let shift = 6; shift >= 0; shift -= 2) {
const type = (state.memory[address] >> shift) & 0x3;
if (type == TYPE_OMITTED) {
break;
}
operandTypes.push(type);
}
++address;
if (operandTypes.length === 4 && result.opcode && (result.opcode.op === 'call_vs2' || result.opcode.op === 'call_vn2')) {
for (let shift = 6; shift >= 0; shift -= 2) {
const type = (state.memory[address] >> shift) & 0x3;
if (type == TYPE_OMITTED) {
break;
}
operandTypes.push(type);
}
++address;
}
}
result.operands = operandTypes.map(type => {
if (type === TYPE_LARGE_CONSTANT) {
const value = read16(state.memory, address);
address += 2;
return { type: 'constant', value };
} else if (type === TYPE_SMALL_CONSTANT) {
return { type: 'constant', value: state.memory[address++] };
} else {
return { type: 'variable', value: state.memory[address++] };
}
});
if (result.opcode && result.opcode.store) {
result.resultVariable = state.memory[address++];
}
if (result.opcode && result.opcode.branch) {
result.branchIf = !!(state.memory[address] & 0x80);
if (state.memory[address] & 0x40) {
result.branchOffset = state.memory[address++] & 0x3F;
// expand sign from 8 bits to 16 bits
if (result.branchOffset & 0x80) {
result.branchOffset |= 0xFF00;
}
} else {
result.branchOffset = (state.memory[address++] & 0x3F) << 8;
result.branchOffset |= state.memory[address++];
// expand sign from 14 bits to 16 bits
if (result.branchOffset & 0x2000) {
result.branchOffset |= 0xC000;
}
}
}
if (result.opcode && result.opcode.text) {
const { text, nextAddress } = decodeText(state, address);
result.text = text;
address = nextAddress;
}
result.nextAddress = address;
// for debugging purposes only
result.raw = state.memory.slice(startAddress, address);
return result;
}
function executeInstruction(state, instruction, operands, output, input, random) {
const op = instruction.opcode.op;
switch (op) {
case 'add': {
/* add
2OP:20 14 add a b -> (result)
Signed 16-bit addition. */
const value = (operands[0] + operands[1]) & 0xFFFF;
variableStore(state, instruction.resultVariable, value);
} break;
case 'and': {
/* and
2OP:9 9 and a b -> (result)
Bitwise AND. */
const value = operands[0] & operands[1];
variableStore(state, instruction.resultVariable, value);
} break;
case 'art_shift': {
/* art_shift
EXT:3 3 5/- art_shift number places -> (result)
Does an arithmetic shift of number by the given number of places, shifting left (i.e. increasing)
if places is positive, right if negative. In a right shift, the sign bit is preserved as well as being
shifted on down. (The alternative behaviour is log_shift.) */
const [number, places] = new Int16Array(operands);
let value;
if (places < 0) {
value = (number >> (-places)) & 0xFFFF;
} else {
value = (number << places) & 0xFFFF;
}
variableStore(state, instruction.resultVariable, value);
} break;
case 'call_1n': {
/* call_1n
1OP:143 F 5 call_1n routine
Executes routine() and throws away result. */
performCall(state, op, operands[0], []);
} break;
case 'call_1s': {
/* call_1s
1OP:136 8 4 call_1s routine -> (result)
Stores routine(). */
performCall(state, op, operands[0], [], instruction.resultVariable);
} break;
case 'call_2n': {
/* call_2n
2OP:26 1A 5 call_2n routine arg1
Executes routine(arg1) and throws away result. */
performCall(state, op, operands[0], [operands[1]]);
} break;
case 'call_2s': {
/* call_2s
2OP:25 19 4 call_2s routine arg1 -> (result)
Stores routine(arg1). */
performCall(state, op, operands[0], [operands[1]], instruction.resultVariable);
} break;
case 'call_vn': {
/* call_vn
VAR:249 19 5 call_vn routine ...up to 3 args...
Like call, but throws away result. */
const [packedAddress, ...args] = operands;
if (packedAddress !== 0) {
performCall(state, op, packedAddress, args);
}
} break;
case 'call':
case 'call_vs': {
/* call
VAR:224 0 1 call routine ...up to 3 args... -> (result)
The only call instruction in Version 3, Inform reads this as call_vs in higher versions: it calls the
routine with 0, 1, 2 or 3 arguments as supplied and stores the resulting return value. (When the
address 0 is called as a routine, nothing happens and the return value is false.) */
/* call_vs
VAR:224 0 4 call_vs routine ...up to 3 args... -> (result)
See call. */
const [packedAddress, ...args] = operands;
if (packedAddress === 0) {
variableStore(state, instruction.resultVariable, 0);
} else {
performCall(state, op, packedAddress, args, instruction.resultVariable);
}
} break;
case 'check_arg_count': {
/* check_arg_count
VAR:255 1F 5 check_arg_count argument-number
Branches if the given argument-number (counting from 1) has been provided by the routine call
to the current routine. (This allows routines in Versions 5 and later to distinguish between the
calls routine(1) and routine(1,0), which would otherwise be impossible to tell apart.) */
const count = state.stack[state.stack.length - 1].argumentCount;
const test = operands[0] === count;
if (test === instruction.branchIf) {
performBranch(state, instruction.branchOffset);
}
} break;
case 'clear_attr': {
/* clear_attr
2OP:12 C clear_attr object attribute
Make object not have the attribute numbered attribute. */
setObjectAttribute(state, operands[0], operands[1], false);
} break;
case 'dec': {
/* dec
1OP:134 6 dec (variable)
Decrement variable by 1. This is signed, so 0 decrements to -1. */
let value = variableLoad(state, operands[0]);
value = (value - 1) & 0xFFFF;
variableStore(state, operands[0], value);
} break;
case 'dec_chk': {
/* dec_chk
2OP:4 4 dec_chk (variable) value ?(label)
Decrement variable, and branch if it is now less than the given value. */
let value = variableLoad(state, operands[0]);
value = (value - 1) & 0xFFFF;
variableStore(state, operands[0], value);
let given = operands[1];
[value, given] = new Int16Array([value, given]);
const test = value < given;
if (test === instruction.branchIf) {
performBranch(state, instruction.branchOffset);
}
} break;
case 'div': {
/* div
2OP:23 17 div a b -> (result)
Signed 16-bit division. Division by zero should halt the interpreter with a suitable error message. */
const [a, b] = new Int16Array(operands);
const value = (a / b) & 0xFFFF;
variableStore(state, instruction.resultVariable, value);
} break;
case 'get_child': {
/* get_child
1OP:130 2 get_child object -> (result) ?(label)
Get first object contained in given object, branching if this exists, i.e. is not nothing (i.e., is not
0). */
const child = getObjectRelation(state, operands[0], RELATION_CHILD);
variableStore(state, instruction.resultVariable, child);
const test = child !== 0;
if (test === instruction.branchIf) {
performBranch(state, instruction.branchOffset);
}
} break;
case 'get_next_prop': {
/* get_next_prop
2OP:19 13 get_next_prop object property -> (result)
Gives the number of the next property provided by the quoted object. This may be zero, indicating
the end of the property list; if called with zero, it gives the first property number present. It is
illegal to try to find the next property of a property which does not exist, and an interpreter
should halt with an error message (if it can efficiently check this condition). */
const value = (operands[1] === 0) ?
getObjectFirstPropertyNumber(state, operands[0]) :
getObjectNextPropertyNumber(state, operands[0], operands[1]);
variableStore(state, instruction.resultVariable, value);
} break;
case 'get_parent': {
/* get_parent
1OP:131 3 get_parent object -> (result)
Get parent object (note that this has no "branch if exists" clause). */
const parent = getObjectRelation(state, operands[0], RELATION_PARENT);
variableStore(state, instruction.resultVariable, parent);
} break;
case 'get_prop': {
/* get_prop
2OP:17 11 get_prop object property -> (result)
Read property from object (resulting in the default value if it had no such declared property). If
the property has length 1, the value is only that byte. If it has length 2, the first two bytes of the
property are taken as a word value. It is illegal for the opcode to be used if the property has
length greater than 2, and the result is unspecified. */
const data = getObjectPropertyData(state, operands[0], operands[1]);
if (data) {
variableStore(state, instruction.resultVariable, data.length === 1 ?
data[0] :
read16(data, 0));
} else {
variableStore(state, instruction.resultVariable, getDefaultPropertyData(state, operands[1]));
}
} break;
case 'get_prop_addr': {
/* get_prop_addr
2OP:18 12 get_prop_addr object property -> (result)
Get the byte address (in dynamic memory) of the property data for the given object's property.
This must return 0 if the object hasn't got the property. */
const address = getObjectPropertyDataAddress(state, operands[0], operands[1]);
variableStore(state, instruction.resultVariable, address);