This repository has been archived by the owner on Apr 17, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
zvm.js
3160 lines (2695 loc) · 92 KB
/
zvm.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
/*
ZVM - the ifvms.js Z-Machine (versions 5 and 8)
===============================================
Built: 2016-07-21
Copyright (c) 2011-2016 The ifvms.js team
MIT licenced
http://github.com/curiousdannii/ifvms.js
*/
/*
ZVM willfully ignores the standard in these ways:
Non-buffered output is not supported
Output streams 2 and 4 and input stream 1 are not supported
Saving tables is not supported (yet?)
No interpreter number or version is set
Any other non-standard behaviour should be considered a bug
*/
// Define our DEBUG constants
if (typeof DEBUG === 'undefined') {
DEBUG = true;
}
if (DEBUG) {
ZVM = true;
GVM = false;
}
// Wrap all of ZVM in a closure/namespace, and enable strict mode
var ZVM = (function () {
'use strict';
/*
Simple JavaScript Inheritance
=============================
By John Resig
Released into the public domain?
http://ejohn.org/blog/simple-javascript-inheritance/
Changes from Dannii: support toString in IE8
*/
/*
TODO:
Try copying properties
Stop using _super
*/
var Class = (function () {
var initializing = 0;
// Determine if functions can be serialized
var fnTest = /\b_super\b/;
var Class = function () {};
// Check whether for in will iterate toString
var iterate_toString, name;
for (name in { toString: 1 }) { iterate_toString = 1; }
// Create a new Class that inherits from this class
Class.subClass = function (prop) {
var _super = this.prototype,
proto,
name,
Klass;
var prop_toString = !/native code/.test('' + prop.toString) && prop.toString;
// Make the magical _super() function work
var make_super = function (name, fn) {
return function () {
var tmp = this._super,
ret;
// Add a new ._super() method that is the same method
// but on the super-class
this._super = _super[name];
// The method only need to be bound temporarily, so we
// remove it when we're done executing
ret = fn.apply(this, arguments);
this._super = tmp;
return ret;
};
};
// Instantiate a base class (but only create the instance,
// don't run the init constructor)
initializing = 1;
/* jshint newcap:false */ // require classes to begin with a capital
proto = new this();
/* jshint newcap:true */
initializing = 0;
// Copy the properties over onto the new prototype
for (name in prop) {
// Check if we're overwriting an existing function
proto[name] = typeof prop[name] === 'function' && typeof _super[name] === 'function' && fnTest.test(prop[name]) ?
make_super(name, prop[name]) :
prop[name];
}
// Handle toString in IE8
if (!iterate_toString && prop_toString) {
proto.toString = fnTest.test(prop_toString) ? make_super('toString', prop_toString) : prop_toString;
}
// The dummy class constructor
Klass = proto.init ? function () {
// All construction is actually done in the init method
if (!initializing) {
this.init.apply(this, arguments);
}
} : function () {};
// Populate our constructed prototype object
Klass.prototype = proto;
// Enforce the constructor to be what we expect
Klass.constructor = Klass;
// And make this class extendable
Klass.subClass = Class.subClass;
return Klass;
};
return Class;
})();
/*
Interchange File Format library
===============================
Copyright (c) 2008-2013 The ifvms.js team
BSD licenced
http://github.com/curiousdannii/ifvms.js
(Originally in Parchment)
*/
// Get a 32 bit number from a byte array, and vice versa
function num_from (s, offset) {
return s[offset] << 24 | s[offset + 1] << 16 | s[offset + 2] << 8 | s[offset + 3];
}
function num_to_word (n) {
return [(n >> 24) & 0xFF, (n >> 16) & 0xFF, (n >> 8) & 0xFF, n & 0xFF];
}
// Get a 4 byte string ID from a byte array, and vice versa
function text_from (s, offset) {
return String.fromCharCode(s[offset], s[offset + 1], s[offset + 2], s[offset + 3]);
}
function text_to_word (t) {
return [t.charCodeAt(0), t.charCodeAt(1), t.charCodeAt(2), t.charCodeAt(3)];
}
// IFF file class
// Parses an IFF file stored in a byte array
var IFF = Class.subClass({
// Parse a byte array or construct an empty IFF file
init: function parse_iff (data) {
this.type = '';
this.chunks = [];
if (data) {
// Check this is an IFF file
if (text_from(data, 0) !== 'FORM') {
throw new Error('Not an IFF file');
}
// Parse the file
this.type = text_from(data, 8);
var i = 12, l = data.length;
while (i < l) {
var chunk_length = num_from(data, i + 4);
if (chunk_length < 0 || (chunk_length + i) > l) {
// FIXME: do something sensible here
throw new Error('IFF: Chunk out of range');
}
this.chunks.push({
type: text_from(data, i),
offset: i,
data: data.slice(i + 8, i + 8 + chunk_length)
});
i += 8 + chunk_length;
if (chunk_length % 2) {
i++;
}
}
}
},
// Write out the IFF into a byte array
write: function write_iff () {
// Start with the IFF type
var out = text_to_word(this.type);
// Go through the chunks and write them out
for (var i = 0, l = this.chunks.length; i < l; i++) {
var chunk = this.chunks[i], data = chunk.data, len = data.length;
out = out.concat(text_to_word(chunk.type), num_to_word(len), data);
if (len % 2) {
out.push(0);
}
}
// Add the header and return
return text_to_word('FORM').concat(num_to_word(out.length), out);
}
});
// Expose the class and helper functions
IFF.num_from = num_from;
IFF.num_to_word = num_to_word;
IFF.text_from = text_from;
IFF.text_to_word = text_to_word;
/*
Common untility functions
=================================================
Copyright (c) 2013 The ifvms.js team
BSD licenced
http://github.com/curiousdannii/ifvms.js
*/
// Array.indexOf compatibility (Support: IE8)
if (![].indexOf) {
Array.prototype.indexOf = function (obj, fromIndex) {
for (var i = fromIndex || 0, l = this.length; i < l; i++) {
if (this[i] === obj) {
return i;
}
}
return -1;
};
}
// Bind, with compatiblity (Support: IE8)
function bind (func, obj) {
if (Function.prototype.bind) {
return func.bind(obj);
} else {
return function () {
func.apply(obj, [].slice.call(arguments));
};
}
}
// Utility to extend objects
function extend (old, add) {
for (var name in add) {
old[name] = add[name];
}
return old;
}
// Console dummy funcs
var console = typeof console !== 'undefined' ? console : {
log: function () {},
info: function () {},
warn: function () {}
};
// Utilities for 16-bit signed arithmetic
function U2S (value) {
return value << 16 >> 16;
}
function S2U (value) {
return value & 0xFFFF;
}
// Utility to convert from byte arrays to word arrays
function byte_to_word (array) {
var i = 0, l = array.length,
result = [];
while (i < l) {
result[i / 2] = array[i++] << 8 | array[i++];
}
return result;
}
// Perform some micro optimisations
function optimise (code) {
return code
// Sign conversions
.replace(/(e\.)?U2S\(([^(]+?)\)/g, '(($2)<<16>>16)')
.replace(/(e\.)?S2U\(([^(]+?)\)/g, '(($2)&65535)')
// Bytearray
.replace(/([\w.]+)\.getUint8\(([^(]+?)\)/g, '$1[$2]')
.replace(/([\w.]+)\.getUint16\(([^(]+?)\)/g, '($1[$2]<<8|$1[$2+1])');
}
// Optimise some functions of an obj, compiling several at once
function optimise_obj (obj, funcnames) {
var funcname, funcparts, newfuncs = [];
for (funcname in obj) {
if (funcnames.indexOf(funcname) >= 0) {
funcparts = /function\s*\(([^(]*)\)\s*\{([\s\S]+)\}/.exec('' + obj[funcname]);
if (DEBUG) {
newfuncs.push(funcname + ':function ' + funcname + '(' + funcparts[1] + '){' + optimise(funcparts[2]) + '}');
} else {
newfuncs.push(funcname + ':function(' + funcparts[1] + '){' + optimise(funcparts[2]) + '}');
}
}
}
extend(obj, eval('({' + newfuncs.join() + '})'));
}
if (DEBUG) {
// Debug flags
var debugflags = {},
get_debug_flags = function (data) {
data = data.split(',');
var i = 0;
while (i < data.length) {
debugflags[data[i++]] = 1;
}
};
if (typeof parchment !== 'undefined' && parchment.options && parchment.options.debug) {
get_debug_flags(parchment.options.debug);
}
} // ENDDEBUG
/*
ByteArray classes, using Typed Arrays if possible
=================================================
Copyright (c) 2011 The ifvms.js team
BSD licenced
http://github.com/curiousdannii/ifvms.js
*/
/*
Todo:
consider whether direct array access would help (what did i mean by this???)
is signed access needed?
add a system for guards, to run callbacks if certain addresses were written to
Needed for: @storew, @storeb, @output_stream?, @encode_text, @copy_table, @restore, @restore_undo
check whether returning the set values is bad for perf
consider generic funcs for set/get: get=Uint8(0), set=Uint8(0,0)
*/
if (DEBUG) {
console.log('bytearray.js: ' + (typeof DataView !== 'undefined' ? 'Native DataView' : 'Emulating DataView'));
}
// var native_bytearrays = DataView,
var native_bytearrays = 0,
ByteArray = native_bytearrays ?
// Converts the data to a buffer and then initiates a DataView on it
function (data) {
var buffer = new ArrayBuffer(data);
data = new DataView(buffer);
data.buffer = buffer;
return data;
} :
// Emulate DataView
function (data) {
// Copy the passed in array
data = data.slice();
if (ZVM) {
return extend(data, {
data: data,
getUint8: function (index) { return data[index]; },
getUint16: function (index) { return data[index] << 8 | data[index + 1]; },
getBuffer: function (start, length) { return data.slice(start, start + length); },
getBuffer16: function (start, length) { return byte_to_word(data.slice(start, start + length * 2)); },
setUint8: function (index, value) { return data[index] = value & 0xFF; },
setUint16: function (index, value) { data[index] = (value >> 8) & 0xFF; data[index + 1] = value & 0xFF; return value & 0xFFFF; },
setBuffer: function (index, buffer) {
var i = 0, l = buffer.length;
while (i < l) {
data[i + index] = buffer[i++];
}
}
});
} else if (GVM) {
}
};
/*
Abstract syntax trees for IF VMs
================================
Copyright (c) 2013 The ifvms.js team
BSD licenced
http://github.com/curiousdannii/ifvms.js
*/
/*
All AST nodes must use these functions, even constants
(An exception is made for branch addresses and text literals which remain as primitives)
toString() functions are used to generate JIT code
Aside from Variable is currently generic and could be used for Glulx too
TODO:
Use strict mode for new Function()?
When we can run through a whole game, test whether using common_func is faster (if its slower then not worth the file size saving)
Can we eliminate the Operand class?
Subclass Operand/Variable from Number?
Replace calls to args() with arguments.join()?
*/
// Generic/constant operand
// Value is a constant
var Operand = Class.subClass({
init: function (engine, value) {
this.e = engine;
this.v = value;
},
toString: function () {
return this.v;
},
// Convert an Operand into a signed operand
U2S: function () {
return U2S(this.v);
}
}),
// Variable operand
// Value is the variable number
// TODO: unrolling is needed -> retain immediate returns if optimisations are disabled
Variable = Operand.subClass({
// Get a value
toString: function () {
var variable = this.v;
// Indirect
if (this.indirect) {
return 'e.indirect(' + variable + ')';
}
// Stack
if (variable === 0) {
// If we've been passed a value we're setting a variable
return 's.pop()';
}
// Locals
if (--variable < 15) {
return 'l[' + variable + ']';
}
// Globals
return 'm.getUint16(' + (this.e.globals + (variable - 15) * 2) + ')';
},
// Store a value
store: function (value) {
var variable = this.v;
// Indirect variable
if (this.indirect) {
return 'e.indirect(' + variable + ',' + value + ')';
}
// BrancherStorers need the value
if (this.returnval) {
return 'e.variable(' + variable + ',' + value + ')';
}
// Stack
if (variable === 0) {
// If we've been passed a value we're setting a variable
return 's.push(' + value + ')';
}
// Locals
if (--variable < 15) {
return 'l[' + variable + ']=' + value;
}
// Globals
return 'm.setUint16(' + (this.e.globals + (variable - 15) * 2) + ',' + value + ')';
},
// Convert an Operand into a signed operand
U2S: function () {
return 'e.U2S(' + this + ')';
}
}),
// Generic opcode
// .func() must be set, which returns what .write() will actually return; it is passed the operands as its arguments
Opcode = Class.subClass({
init: function (engine, context, code, pc, next, operands) {
this.e = engine;
this.context = context;
this.code = code;
this.pc = pc;
this.labels = [ this.pc + '/' + this.code ];
this.next = next;
this.operands = operands;
// Post-init function (so that they don't all have to call _super)
if (this.post) {
this.post();
}
},
// Write out the opcode, passing .operands to .func(), with a JS comment of the pc/opcode
toString: function () {
return this.label() + (this.func ? this.func.apply(this, this.operands) : '');
},
// Return a string of the operands separated by commas
args: function (joiner) {
return this.operands.join(joiner);
},
// Generate a comment of the pc and code, possibly for more than one opcode
label: function () {
return '/* ' + this.labels.join() + ' */ ';
}
}),
// Stopping opcodes
Stopper = Opcode.subClass({
stopper: 1
}),
// Pausing opcodes (ie, set the pc at the end of the context)
Pauser = Stopper.subClass({
storer: 1,
post: function () {
this.storer = this.operands.pop();
this.origfunc = this.func;
this.func = this.newfunc;
},
newfunc: function () {
return 'e.pc=' + this.next + ';' + this.origfunc.apply(this, arguments);
}
}),
// Join multiple branchers together with varying logic conditions
BrancherLogic = Class.subClass({
init: function (ops, code) {
this.ops = ops || [];
this.code = code || '||';
},
toString: function () {
var i = 0,
ops = [],
op;
while (i < this.ops.length) {
op = this.ops[i++];
// Accept either Opcodes or further BrancherLogics
ops.push(
op.func ?
(op.iftrue ? '' : '!(') + op.func.apply(op, op.operands) + (op.iftrue ? '' : ')') :
op
);
}
return (this.invert ? '(!(' : '(') + ops.join(this.code) + (this.invert ? '))' : ')');
}
}),
// Branching opcodes
Brancher = Opcode.subClass({
// Flag for the disassembler
brancher: 1,
keyword: 'if',
// Process the branch result now
post: function () {
var result,
prev,
// Calculate the offset
brancher = this.operands.pop(),
offset = brancher[1];
this.iftrue = brancher[0];
// Process the offset
if (offset === 0 || offset === 1) {
result = 'e.ret(' + offset + ')';
} else {
offset += this.next - 2;
// Add this target to this context's list
this.context.targets.push(offset);
result = 'e.pc=' + offset;
}
this.result = result + ';return';
this.offset = offset;
this.cond = new BrancherLogic([this]);
if (DEBUG) {
// Stop if we must
if (debugflags.noidioms) {
return;
}
}
// Compare with previous statement
if (this.context.ops.length) {
prev = this.context.ops.pop();
// As long as no other opcodes have an offset property we can skip the instanceof check
if (/* prev instanceof Brancher && */ prev.offset === offset) {
// Goes to same offset so reuse the Brancher arrays
this.cond.ops.unshift(prev.cond);
this.labels = prev.labels;
this.labels.push(this.pc + '/' + this.code);
} else {
this.context.ops.push(prev);
}
}
},
// Write out the brancher
toString: function () {
var result = this.result;
// Account for Contexts
if (result instanceof Context) {
// Update the context to be a child of this context
if (DEBUG) {
result.context = this.context;
}
result = result + (result.stopper ? '; return' : '');
// Extra line breaks for multi-op results
if (this.result.ops.length > 1) {
result = '\n' + result + '\n';
if (DEBUG) {
result += this.context.spacer;
}
}
}
// Print out a label for all included branches and the branch itself
return this.label() + this.keyword + this.cond + ' {' + result + '}';
}
}),
// Brancher + Storer
BrancherStorer = Brancher.subClass({
storer: 1,
// Set aside the storer operand
post: function () {
this._super();
this.storer = this.operands.pop();
this.storer.returnval = 1;
// Replace the func
this.origfunc = this.func;
this.func = this.newfunc;
},
newfunc: function () {
return this.storer.store(this.origfunc.apply(this, arguments));
}
}),
// Storing opcodes
Storer = Opcode.subClass({
// Flag for the disassembler
storer: 1,
// Set aside the storer operand
post: function () {
this.storer = this.operands.pop();
},
// Write out the opcode, passing it to the storer (if there still is one)
toString: function () {
var data = this._super();
// If we still have a storer operand, use it
// Otherwise (if it's been removed due to optimisations) just return func()
return this.storer ? this.storer.store(data) : data;
}
}),
// Routine calling opcodes
Caller = Stopper.subClass({
// Fake a result variable
result: { v: -1 },
// Write out the opcode
toString: function () {
// TODO: Debug: include label if possible
return this.label() + 'e.call(' + this.operands.shift() + ',' + this.result.v + ',' + this.next + ',[' + this.args() + '])';
}
}),
// Routine calling opcodes, storing the result
CallerStorer = Caller.subClass({
// Flag for the disassembler
storer: 1,
post: function () {
// We can't let the storer be optimised away here
this.result = this.operands.pop();
}
}),
// A generic context (a routine, loop body etc)
Context = Class.subClass({
init: function (engine, pc) {
this.e = engine;
this.pc = pc;
this.pre = [];
this.ops = [];
this.post = [];
this.targets = []; // Branch targets
if (DEBUG) {
this.spacer = '';
}
},
toString: function () {
if (DEBUG) {
// Indent the spacer further if needed
if (this.context) { this.spacer = this.context.spacer + ' '; }
// DEBUG: Pretty print!
return this.pre.join('') + (this.ops.length > 1 ? this.spacer : '') + this.ops.join(';\n' + this.spacer) + this.post.join('');
} else {
// Return the code
return this.pre.join('') + this.ops.join(';') + this.post.join('');
}
}
}),
// A routine body
RoutineContext = Context.subClass({
toString: function () {
// TODO: Debug: If we have routine names, find this one's name
// Add in some extra vars and return
this.pre.unshift('var l=e.l,m=e.m,s=e.s;\n');
return this._super();
}
});
// Opcode builder
// Easily build a new opcode from a class
function opcode_builder (Class, func, flags) {
flags = flags || {};
if (func) {
/* if ( func.pop )
{
flags.str = func;
flags.func = common_func;
}
else
{ */
flags.func = func;
// }
}
return Class.subClass(flags);
}
// A common for opcodes which basically just need to provide texts
/* common_func = function()
{
var texts = this.str;
if ( texts.length == 2 )
{
return texts[0] + this.args() + texts[1];
}
}; */
/*
Inform idioms
=============
Copyright (c) 2011 The ifvms.js team
BSD licenced
http://github.com/curiousdannii/ifvms.js
*/
/*
TODO:
loops
doesn't work yet because of storers before the branch
Need loops where the condition is at the end -> do {} while ()
break (& continue?)
when opcodes are removed, if debug then add a comment
The @jump check isn't VM independant
*/
// Block if statements / while loops
function idiom_if_block (context, pc) {
var i = 0,
subcontext,
sublen,
brancher,
lastop,
secondlastop;
// This is only needed for pretty printing
if (DEBUG) {
// Update the contexts of new contexts
var update_contexts = function (ops, context) {
for (var i = 0; i < ops.length; i++) {
ops[i].context = context;
}
};
}
// First, find the branch opcode
// (-1 because we don't want to catch the very last opcode, not that it should ever branch to the following statement)
while (i < context.ops.length - 1) {
// As long as no other opcodes have an offset property we can skip the instanceof check
if (/* context.ops[i] instanceof Brancher && */ context.ops[i].offset === pc) {
// Sometimes Inform makes complex branches, where the only subcontext opcode would be a brancher itself
// Join the two branches into one
if (context.ops.length - i === 2 /* && context.ops[i + 1] instanceof Brancher */ && context.ops[i + 1].offset) {
lastop = context.ops.pop();
secondlastop = context.ops.pop();
// The first brancher must be inverted
secondlastop.cond.invert = !secondlastop.cond.invert;
// Make a new BrancherLogic to AND the old branchers together
lastop.cond = new BrancherLogic([secondlastop.cond, lastop.cond], '&&');
// Fix the labels and return the last opcode to the opcodes array
lastop.labels = secondlastop.labels.concat(lastop.labels);
context.ops.push(lastop);
return 1;
}
// Make a new Context to contain all of the following opcodes
subcontext = new Context(context.e, context.ops[i + 1].pc);
subcontext.ops = context.ops.slice(i + 1);
sublen = subcontext.ops.length - 1;
context.ops.length = i + 1;
// This is only needed for pretty printing
if (DEBUG) {
update_contexts(subcontext.ops, subcontext);
}
// Set that Context as the branch's target, and invert its condition
brancher = context.ops[i];
brancher.result = subcontext;
brancher.cond.invert = !brancher.cond.invert;
// Check if this is actually a loop
lastop = subcontext.ops[sublen];
if (lastop.code === 140 && (U2S(lastop.operands[0].v) + lastop.next - 2) === brancher.pc) {
brancher.keyword = 'while';
subcontext.ops.pop();
} else {
// Mark this subcontext as a stopper if its last opcode is
subcontext.stopper = lastop.stopper;
}
if (DEBUG) {
// Check whether this could be a very complex condition
var allbranches = 1;
for (i = 0; i < sublen + 1; i++) {
if (!(subcontext.ops[i] instanceof Brancher)) {
allbranches = 0;
}
}
if (allbranches === 1) {
console.info('Potential complex condition in ' + context.pc + ' at ' + brancher.pc);
}
}
// Return 1 to signal that we can continue past the stopper
return 1;
}
i++;
}
}
/* idiom_do_while = function( context )
{
}; */
/*
Quetzal Common Save-File Format
===============================
Copyright (c) 2013 The ifvms.js team
BSD licenced
http://github.com/curiousdannii/ifvms.js
*/
// A savefile
var Quetzal = IFF.subClass({
// Parse a Quetzal savefile, or make a blank one
init: function (bytes) {
this._super(bytes);
if (bytes) {
// Check this is a Quetzal savefile
if (this.type !== 'IFZS') {
throw new Error('Not a Quetzal savefile');
}
// Go through the chunks and extract the useful ones
for (var i = 0, l = this.chunks.length; i < l; i++) {
var type = this.chunks[i].type, data = this.chunks[i].data;
// Memory and stack chunks. Overwrites existing data if more than one of each is present!
if (type === 'CMem' || type === 'UMem') {
this.memory = data;
this.compressed = (type === 'CMem');
} else if (type === 'Stks') {
this.stacks = data;
}
// Story file data
else if (type === 'IFhd') {
this.release = data.slice(0, 2);
this.serial = data.slice(2, 8);
// The checksum isn't used, but if we throw it away we can't round-trip
this.checksum = data.slice(8, 10);
this.pc = data[10] << 16 | data[11] << 8 | data[12];
}
}
}
},
// Write out a savefile
write: function () {
// Reset the IFF type
this.type = 'IFZS';
// Format the IFhd chunk correctly
var pc = this.pc,
ifhd = this.release.concat(
this.serial,
this.checksum,
(pc >> 16) & 0xFF, (pc >> 8) & 0xFF, pc & 0xFF
);
// Add the chunks
this.chunks = [
{type: 'IFhd', data: ifhd},
{type: (this.compressed ? 'CMem' : 'UMem'), data: this.memory},
{type: 'Stks', data: this.stacks}
];
// Return the byte array
return this._super();
}
});
/*
Z-Machine UI
============
Copyright (c) 2013 The ifvms.js team
BSD licenced
http://github.com/curiousdannii/ifvms.js
*/
/*
Note: is used by both ZVM and Gnusto. In the case of Gnusto the engine is actually GnustoRunner.
The engine must have a StructIO modified env
*/
var ZVMUI = Class.subClass({
init: function (engine, headerbit) {
this.e = engine;
this.buffer = '';