/
statements.py
2594 lines (2424 loc) · 116 KB
/
statements.py
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
"""
PC-BASIC - statements.py
Statement parser
(c) 2013, 2014, 2015, 2016 Rob Hagemans
This file is released under the GNU GPL version 3 or later.
"""
import os
from functools import partial
import logging
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
import string
from . import error
from . import fp
from . import ports
from . import print_and_input
from . import representation
from . import basictoken as tk
from . import util
from . import vartypes
class Statements(object):
""" BASIC statements. """
def __init__(self, parser):
""" Initialise statement context. """
self.parser = parser
self.session = parser.session
self._init_statements()
def _init_statements(self):
""" Initialise statements. """
self.statements = {
tk.END: self.exec_end,
tk.FOR: self.exec_for,
tk.NEXT: self.exec_next,
tk.DATA: self.exec_data,
tk.INPUT: self.exec_input,
tk.DIM: self.exec_dim,
tk.READ: self.exec_read,
tk.LET: self.exec_let,
tk.GOTO: self.exec_goto,
tk.RUN: self.exec_run,
tk.IF: self.exec_if,
tk.RESTORE: self.exec_restore,
tk.GOSUB: self.exec_gosub,
tk.RETURN: self.exec_return,
tk.REM: self.exec_rem,
tk.STOP: self.exec_stop,
tk.PRINT: self.exec_print,
tk.CLEAR: self.exec_clear,
tk.LIST: self.exec_list,
tk.NEW: self.exec_new,
tk.ON: self.exec_on,
tk.WAIT: self.exec_wait,
tk.DEF: self.exec_def,
tk.POKE: self.exec_poke,
tk.CONT: self.exec_cont,
tk.OUT: self.exec_out,
tk.LPRINT: self.exec_lprint,
tk.LLIST: self.exec_llist,
tk.WIDTH: self.exec_width,
tk.ELSE: self.exec_else,
tk.TRON: self.exec_tron,
tk.TROFF: self.exec_troff,
tk.SWAP: self.exec_swap,
tk.ERASE: self.exec_erase,
tk.EDIT: self.exec_edit,
tk.ERROR: self.exec_error,
tk.RESUME: self.exec_resume,
tk.DELETE: self.exec_delete,
tk.AUTO: self.exec_auto,
tk.RENUM: self.exec_renum,
tk.DEFSTR: partial(self.exec_deftype, typechar='$'),
tk.DEFINT: partial(self.exec_deftype, typechar='%'),
tk.DEFSNG: partial(self.exec_deftype, typechar='!'),
tk.DEFDBL: partial(self.exec_deftype, typechar='#'),
tk.LINE: self.exec_line,
tk.WHILE: self.exec_while,
tk.WEND: self.exec_wend,
tk.CALL: self.exec_call,
tk.WRITE: self.exec_write,
tk.OPTION: self.exec_option,
tk.RANDOMIZE: self.exec_randomize,
tk.OPEN: self.exec_open,
tk.CLOSE: self.exec_close,
tk.LOAD: self.exec_load,
tk.MERGE: self.exec_merge,
tk.SAVE: self.exec_save,
tk.COLOR: self.exec_color,
tk.CLS: self.exec_cls,
tk.MOTOR: self.exec_motor,
tk.BSAVE: self.exec_bsave,
tk.BLOAD: self.exec_bload,
tk.SOUND: self.exec_sound,
tk.BEEP: self.exec_beep,
tk.PSET: self.exec_pset,
tk.PRESET: self.exec_preset,
tk.SCREEN: self.exec_screen,
tk.KEY: self.exec_key,
tk.LOCATE: self.exec_locate,
tk.FILES: self.exec_files,
tk.FIELD: self.exec_field,
tk.SYSTEM: self.exec_system,
tk.NAME: self.exec_name,
tk.LSET: self.exec_lset,
tk.RSET: self.exec_rset,
tk.KILL: self.exec_kill,
tk.PUT: self.exec_put,
tk.GET: self.exec_get,
tk.RESET: self.exec_reset,
tk.COMMON: self.exec_common,
tk.CHAIN: self.exec_chain,
tk.DATE: self.exec_date,
tk.TIME: self.exec_time,
tk.PAINT: self.exec_paint,
tk.COM: self.exec_com,
tk.CIRCLE: self.exec_circle,
tk.DRAW: self.exec_draw,
tk.PLAY: self.exec_play,
tk.TIMER: self.exec_timer,
tk.IOCTL: self.exec_ioctl,
tk.CHDIR: self.exec_chdir,
tk.MKDIR: self.exec_mkdir,
tk.RMDIR: self.exec_rmdir,
tk.SHELL: self.exec_shell,
tk.ENVIRON: self.exec_environ,
tk.VIEW: self.exec_view,
tk.WINDOW: self.exec_window,
tk.PALETTE: self.exec_palette,
tk.LCOPY: self.exec_lcopy,
tk.CALLS: self.exec_calls,
tk.NOISE: self.exec_noise,
tk.PCOPY: self.exec_pcopy,
tk.TERM: self.exec_term,
tk.LOCK: self.exec_lock,
tk.UNLOCK: self.exec_unlock,
tk.MID: self.exec_mid,
tk.PEN: self.exec_pen,
tk.STRIG: self.exec_strig,
tk.DEBUG: self.exec_debug,
}
def __getstate__(self):
""" Pickle. """
pickle_dict = self.__dict__.copy()
# can't be pickled
pickle_dict['statements'] = None
return pickle_dict
def __setstate__(self, pickle_dict):
""" Unpickle. """
self.__dict__.update(pickle_dict)
self._init_statements()
def exec_system(self, ins):
""" SYSTEM: exit interpreter. """
# SYSTEM LAH does not execute
util.require(ins, tk.end_statement)
raise error.Exit()
def exec_tron(self, ins):
""" TRON: turn on line number tracing. """
self.parser.tron = True
# TRON LAH gives error, but TRON has been executed
util.require(ins, tk.end_statement)
def exec_troff(self, ins):
""" TROFF: turn off line number tracing. """
self.tron = False
util.require(ins, tk.end_statement)
def exec_rem(self, ins):
""" REM: comment. """
# skip the rest of the line, but parse numbers to avoid triggering EOL
util.skip_to(ins, tk.end_line)
def exec_lcopy(self, ins):
""" LCOPY: do nothing but check for syntax errors. """
# See e.g. http://shadowsshot.ho.ua/docs001.htm#LCOPY
if util.skip_white(ins) not in tk.end_statement:
util.range_check(0, 255, vartypes.pass_int_unpack(
self.parser.parse_expression(ins, self.session)))
util.require(ins, tk.end_statement)
def exec_motor(self, ins):
""" MOTOR: do nothing but check for syntax errors. """
self.exec_lcopy(ins)
def exec_debug(self, ins):
""" DEBUG: execute Python command. """
# this is not a GW-BASIC behaviour, but helps debugging.
# this is parsed like a REM by the tokeniser.
# rest of the line is considered to be a python statement
util.skip_white(ins)
debug_cmd = ''
while util.peek(ins) not in tk.end_line:
debug_cmd += ins.read(1)
self.session.debugger.debug_exec(debug_cmd)
def exec_term(self, ins):
""" TERM: load and run PCjr buitin terminal emulator program. """
try:
util.require(ins, tk.end_statement)
with self.session.files.open_native_or_basic(self.parser.term) as f:
self.session.program.load(f)
except EnvironmentError:
# on Tandy, raises Internal Error
raise error.RunError(error.INTERNAL_ERROR)
self.parser.clear_stacks_and_pointers()
self.session.clear()
self.parser.jump(None)
self.parser.error_handle_mode = False
self.parser.tron = False
##########################################################
# statements that require further qualification
def exec_def(self, ins):
""" DEF: select DEF FN, DEF USR, DEF SEG. """
c = util.skip_white(ins)
if util.read_if(ins, c, (tk.FN,)):
self.exec_def_fn(ins)
elif util.read_if(ins, c, (tk.USR,)):
self.exec_def_usr(ins)
# must be uppercase in tokenised form, otherwise syntax error
elif util.skip_white_read_if(ins, ('SEG',)):
self.exec_def_seg(ins)
else:
raise error.RunError(error.STX)
def exec_view(self, ins):
""" VIEW: select VIEW PRINT, VIEW (graphics). """
if util.skip_white_read_if(ins, (tk.PRINT,)):
self.exec_view_print(ins)
else:
self.exec_view_graph(ins)
def exec_line(self, ins):
""" LINE: select LINE INPUT, LINE (graphics). """
if util.skip_white_read_if(ins, (tk.INPUT,)):
self.exec_line_input(ins)
else:
self.exec_line_graph(ins)
def exec_get(self, ins):
""" GET: select GET (graphics), GET (files). """
if util.skip_white(ins) == '(':
self.exec_get_graph(ins)
else:
self.exec_get_file(ins)
def exec_put(self, ins):
""" PUT: select PUT (graphics), PUT (files). """
if util.skip_white(ins) == '(':
self.exec_put_graph(ins)
else:
self.exec_put_file(ins)
def exec_on(self, ins):
""" ON: select ON ERROR, ON KEY, ON TIMER, ON PLAY, ON COM, ON PEN, ON STRIG
or ON (jump statement). """
c = util.skip_white(ins)
if util.read_if(ins, c, (tk.ERROR,)):
self.exec_on_error(ins)
elif util.read_if(ins, c, (tk.KEY,)):
self.exec_on_key(ins)
elif c in ('\xFE', '\xFF'):
c = util.peek(ins, 2)
if util.read_if(ins, c, (tk.TIMER,)):
self.exec_on_timer(ins)
elif util.read_if(ins, c, (tk.PLAY,)):
self.exec_on_play(ins)
elif util.read_if(ins, c, (tk.COM,)):
self.exec_on_com(ins)
elif util.read_if(ins, c, (tk.PEN,)):
self.exec_on_pen(ins)
elif util.read_if(ins, c, (tk.STRIG,)):
self.exec_on_strig(ins)
else:
self.exec_on_jump(ins)
else:
self.exec_on_jump(ins)
##########################################################
# event switches (except PLAY) and event definitions
def exec_pen(self, ins):
""" PEN: switch on/off light pen event handling. """
if self.parser.events.pen.command(util.skip_white(ins)):
ins.read(1)
else:
raise error.RunError(error.STX)
util.require(ins, tk.end_statement)
def exec_strig(self, ins):
""" STRIG: switch on/off fire button event handling. """
d = util.skip_white(ins)
if d == '(':
# strig (n)
num = vartypes.pass_int_unpack(self.parser.parse_bracket(ins, self.session))
if num not in (0,2,4,6):
raise error.RunError(error.IFC)
if self.parser.events.strig[num//2].command(util.skip_white(ins)):
ins.read(1)
else:
raise error.RunError(error.STX)
elif d == tk.ON:
ins.read(1)
self.session.stick.switch(True)
elif d == tk.OFF:
ins.read(1)
self.session.stick.switch(False)
else:
raise error.RunError(error.STX)
util.require(ins, tk.end_statement)
def exec_com(self, ins):
""" COM: switch on/off serial port event handling. """
util.require(ins, ('(',))
num = vartypes.pass_int_unpack(self.parser.parse_bracket(ins, self.session))
util.range_check(1, 2, num)
if self.parser.events.com[num-1].command(util.skip_white(ins)):
ins.read(1)
else:
raise error.RunError(error.STX)
util.require(ins, tk.end_statement)
def exec_timer(self, ins):
""" TIMER: switch on/off timer event handling. """
if self.parser.events.timer.command(util.skip_white(ins)):
ins.read(1)
else:
raise error.RunError(error.STX)
util.require(ins, tk.end_statement)
def exec_key_events(self, ins):
""" KEY: switch on/off keyboard events. """
num = vartypes.pass_int_unpack(self.parser.parse_bracket(ins, self.session))
util.range_check(0, 255, num)
d = util.skip_white(ins)
# others are ignored
if num >= 1 and num <= 20:
if self.parser.events.key[num-1].command(d):
ins.read(1)
else:
raise error.RunError(error.STX)
def _parse_on_event(self, ins, bracket=True):
""" Helper function for ON event trap definitions. """
num = None
if bracket:
num = self.parser.parse_bracket(ins, self.session)
util.require_read(ins, (tk.GOSUB,))
jumpnum = util.parse_jumpnum(ins)
if jumpnum == 0:
jumpnum = None
elif jumpnum not in self.session.program.line_numbers:
raise error.RunError(error.UNDEFINED_LINE_NUMBER)
util.require(ins, tk.end_statement)
return num, jumpnum
def exec_on_key(self, ins):
""" ON KEY: define key event trapping. """
keynum, jumpnum = self._parse_on_event(ins)
keynum = vartypes.pass_int_unpack(keynum)
util.range_check(1, 20, keynum)
self.parser.events.key[keynum-1].set_jump(jumpnum)
def exec_on_timer(self, ins):
""" ON TIMER: define timer event trapping. """
timeval, jumpnum = self._parse_on_event(ins)
timeval = vartypes.pass_single(timeval)
period = fp.mul(fp.unpack(timeval), fp.Single.from_int(1000)).round_to_int()
self.parser.events.timer.set_trigger(period)
self.parser.events.timer.set_jump(jumpnum)
def exec_on_play(self, ins):
""" ON PLAY: define music event trapping. """
playval, jumpnum = self._parse_on_event(ins)
playval = vartypes.pass_int_unpack(playval)
self.parser.events.play.set_trigger(playval)
self.parser.events.play.set_jump(jumpnum)
def exec_on_pen(self, ins):
""" ON PEN: define light pen event trapping. """
_, jumpnum = self._parse_on_event(ins, bracket=False)
self.parser.events.pen.set_jump(jumpnum)
def exec_on_strig(self, ins):
""" ON STRIG: define fire button event trapping. """
strigval, jumpnum = self._parse_on_event(ins)
strigval = vartypes.pass_int_unpack(strigval)
## 0 -> [0][0] 2 -> [0][1] 4-> [1][0] 6 -> [1][1]
if strigval not in (0,2,4,6):
raise error.RunError(error.IFC)
self.parser.events.strig[strigval//2].set_jump(jumpnum)
def exec_on_com(self, ins):
""" ON COM: define serial port event trapping. """
keynum, jumpnum = self._parse_on_event(ins)
keynum = vartypes.pass_int_unpack(keynum)
util.range_check(1, 2, keynum)
self.parser.events.com[keynum-1].set_jump(jumpnum)
##########################################################
# sound
def exec_beep(self, ins):
""" BEEP: produce an alert sound or switch internal speaker on/off. """
# Tandy/PCjr BEEP ON, OFF
if self.parser.syntax in ('pcjr', 'tandy') and util.skip_white(ins) in (tk.ON, tk.OFF):
# this is ignored
#self.session.sound.beep_on = (ins.read(1) == tk.ON)
util.require(ins, tk.end_statement)
return
self.session.sound.beep()
# if a syntax error happens, we still beeped.
util.require(ins, tk.end_statement)
if self.session.sound.foreground:
self.session.sound.wait_music()
def exec_sound(self, ins):
""" SOUND: produce an arbitrary sound or switch external speaker on/off. """
# Tandy/PCjr SOUND ON, OFF
if self.parser.syntax in ('pcjr', 'tandy') and util.skip_white(ins) in (tk.ON, tk.OFF):
self.session.sound.sound_on = (ins.read(1) == tk.ON)
util.require(ins, tk.end_statement)
return
freq = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session))
util.require_read(ins, (',',))
dur = fp.unpack(vartypes.pass_single(self.parser.parse_expression(ins, self.session)))
if fp.Single.from_int(-65535).gt(dur) or dur.gt(fp.Single.from_int(65535)):
raise error.RunError(error.IFC)
# only look for args 3 and 4 if duration is > 0; otherwise those args are a syntax error (on tandy)
if dur.gt(fp.Single.zero):
if (util.skip_white_read_if(ins, (',',)) and (self.parser.syntax == 'tandy' or
(self.parser.syntax == 'pcjr' and self.session.sound.sound_on))):
volume = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session))
util.range_check(0, 15, volume)
if util.skip_white_read_if(ins, (',',)):
voice = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session))
util.range_check(0, 2, voice) # can't address noise channel here
else:
voice = 0
else:
volume, voice = 15, 0
util.require(ins, tk.end_statement)
if dur.is_zero():
self.session.sound.stop_all_sound()
return
# Tandy only allows frequencies below 37 (but plays them as 110 Hz)
if freq != 0:
util.range_check(-32768 if self.parser.syntax == 'tandy' else 37, 32767, freq) # 32767 is pause
# calculate duration in seconds
one_over_44 = fp.Single.from_bytes(bytearray('\x8c\x2e\x3a\x7b')) # 1/44 = 0.02272727248
dur_sec = dur.to_value()/18.2
if one_over_44.gt(dur):
# play indefinitely in background
self.session.sound.play_sound(freq, dur_sec, loop=True, voice=voice, volume=volume)
else:
self.session.sound.play_sound(freq, dur_sec, voice=voice, volume=volume)
if self.session.sound.foreground:
self.session.sound.wait_music()
def exec_play(self, ins):
""" PLAY: play sound sequence defined by a Music Macro Language string. """
# PLAY: event switch
if self.parser.events.play.command(util.skip_white(ins)):
ins.read(1)
util.require(ins, tk.end_statement)
else:
# retrieve Music Macro Language string
with self.session.strings:
mml0 = self.session.strings.copy(vartypes.pass_string(
self.parser.parse_expression(ins, self.session, allow_empty=True),
allow_empty=True))
mml1, mml2 = '', ''
if ((self.parser.syntax == 'tandy' or (self.parser.syntax == 'pcjr' and
self.session.sound.sound_on))
and util.skip_white_read_if(ins, (',',))):
with self.session.strings:
mml1 = self.session.strings.copy(vartypes.pass_string(
self.parser.parse_expression(ins, self.session, allow_empty=True),
allow_empty=True))
if util.skip_white_read_if(ins, (',',)):
with self.session.strings:
mml2 = self.session.strings.copy(vartypes.pass_string(
self.parser.parse_expression(ins, self.session, allow_empty=True),
allow_empty=True))
util.require(ins, tk.end_statement)
if not (mml0 or mml1 or mml2):
raise error.RunError(error.MISSING_OPERAND)
self.session.sound.play(self.session.memory, (mml0, mml1, mml2))
def exec_noise(self, ins):
""" NOISE: produce sound on the noise generator (Tandy/PCjr). """
if not self.session.sound.sound_on:
raise error.RunError(error.IFC)
source = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session))
util.require_read(ins, (',',))
volume = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session))
util.require_read(ins, (',',))
util.range_check(0, 7, source)
util.range_check(0, 15, volume)
dur = fp.unpack(vartypes.pass_single(self.parser.parse_expression(ins, self.session)))
if fp.Single.from_int(-65535).gt(dur) or dur.gt(fp.Single.from_int(65535)):
raise error.RunError(error.IFC)
util.require(ins, tk.end_statement)
one_over_44 = fp.Single.from_bytes(bytearray('\x8c\x2e\x3a\x7b')) # 1/44 = 0.02272727248
dur_sec = dur.to_value()/18.2
if one_over_44.gt(dur):
self.session.sound.play_noise(source, volume, dur_sec, loop=True)
else:
self.session.sound.play_noise(source, volume, dur_sec)
##########################################################
# machine emulation
def exec_poke(self, ins):
""" POKE: write to a memory location. Limited implementation. """
addr = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session), maxint=0xffff)
if self.session.program.protected and not self.parser.run_mode:
raise error.RunError(error.IFC)
util.require_read(ins, (',',))
val = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session))
util.range_check(0, 255, val)
self.session.all_memory.poke(addr, val)
util.require(ins, tk.end_statement)
def exec_def_seg(self, ins):
""" DEF SEG: set the current memory segment. """
# &hb800: text screen buffer; &h13d: data segment
if util.skip_white_read_if(ins, (tk.O_EQ,)):
# def_seg() accepts signed values
self.session.all_memory.def_seg(vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session), maxint=0xffff))
else:
self.session.all_memory.def_seg(self.session.memory.data_segment)
util.require(ins, tk.end_statement)
def exec_def_usr(self, ins):
""" DEF USR: Define a machine language function. Not implemented. """
util.require_read(ins, tk.digit)
util.require_read(ins, (tk.O_EQ,))
vartypes.pass_integer(self.parser.parse_expression(ins, self.session), maxint=0xffff)
util.require(ins, tk.end_statement)
logging.warning("DEF USR statement not implemented")
def exec_bload(self, ins):
""" BLOAD: load a file into a memory location. Limited implementation. """
if self.session.program.protected and not self.parser.run_mode:
raise error.RunError(error.IFC)
with self.session.strings:
name = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
# check if file exists, make some guesses (all uppercase, +.BAS) if not
offset = None
if util.skip_white_read_if(ins, (',',)):
offset = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session), maxint=0xffff)
if offset < 0:
offset += 0x10000
util.require(ins, tk.end_statement)
with self.session.files.open(0, name, filetype='M', mode='I') as f:
self.session.all_memory.bload(f, offset)
def exec_bsave(self, ins):
""" BSAVE: save a block of memory to a file. Limited implementation. """
if self.session.program.protected and not self.parser.run_mode:
raise error.RunError(error.IFC)
with self.session.strings:
name = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
# check if file exists, make some guesses (all uppercase, +.BAS) if not
util.require_read(ins, (',',))
offset = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session), maxint = 0xffff)
if offset < 0:
offset += 0x10000
util.require_read(ins, (',',))
length = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session), maxint = 0xffff)
if length < 0:
length += 0x10000
util.require(ins, tk.end_statement)
with self.session.files.open(0, name, filetype='M', mode='O',
seg=self.session.all_memory.segment,
offset=offset, length=length) as f:
self.session.all_memory.bsave(f, offset, length)
def exec_call(self, ins):
""" CALL: call an external procedure. Not implemented. """
addr_var = self.parser.parse_scalar(ins)
if addr_var[-1] == '$':
# type mismatch
raise error.RunError(error.TYPE_MISMATCH)
if util.skip_white_read_if(ins, ('(',)):
while True:
# if we wanted to call a function, we should distinguish varnames
# (passed by ref) from constants (passed by value) here.
self.parser.parse_expression(ins, self.session)
if not util.skip_white_read_if(ins, (',',)):
break
util.require_read(ins, (')',))
util.require(ins, tk.end_statement)
# ignore the statement
logging.warning("CALL or CALLS statement not implemented")
def exec_calls(self, ins):
""" CALLS: call an external procedure. Not implemented. """
self.exec_call(ins)
def exec_out(self, ins):
""" OUT: send a byte to a machine port. Limited implementation. """
addr = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session), maxint=0xffff)
util.require_read(ins, (',',))
val = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session))
util.range_check(0, 255, val)
self.session.machine.out(addr, val)
util.require(ins, tk.end_statement)
def exec_wait(self, ins):
""" WAIT: wait for a machine port. Limited implementation. """
addr = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session), maxint=0xffff)
util.require_read(ins, (',',))
ander = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session))
util.range_check(0, 255, ander)
xorer = 0
if util.skip_white_read_if(ins, (',',)):
xorer = vartypes.pass_int_unpack(self.parser.parse_expression(ins, self.session))
util.range_check(0, 255, xorer)
util.require(ins, tk.end_statement)
self.session.machine.wait(addr, ander, xorer)
##########################################################
# Disk
def exec_chdir(self, ins):
""" CHDIR: change working directory. """
with self.session.strings:
dev, path = self.session.devices.get_diskdevice_and_path(
self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session))))
dev.chdir(path)
util.require(ins, tk.end_statement)
def exec_mkdir(self, ins):
""" MKDIR: create directory. """
with self.session.strings:
dev, path = self.session.devices.get_diskdevice_and_path(
self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session))))
dev.mkdir(path)
util.require(ins, tk.end_statement)
def exec_rmdir(self, ins):
""" RMDIR: remove directory. """
with self.session.strings:
dev, path = self.session.devices.get_diskdevice_and_path(
self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session))))
dev.rmdir(path)
util.require(ins, tk.end_statement)
def exec_name(self, ins):
""" NAME: rename file or directory. """
with self.session.strings:
oldname = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
# AS is not a tokenised word
word = util.skip_white_read(ins) + ins.read(1)
if word.upper() != 'AS':
raise error.RunError(error.STX)
with self.session.strings:
newname = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
dev, oldpath = self.session.devices.get_diskdevice_and_path(oldname)
newdev, newpath = self.session.devices.get_diskdevice_and_path(newname)
# don't rename open files
dev.check_file_not_open(oldpath)
if dev != newdev:
raise error.RunError(error.RENAME_ACROSS_DISKS)
dev.rename(oldpath, newpath)
util.require(ins, tk.end_statement)
def exec_kill(self, ins):
""" KILL: remove file. """
with self.session.strings:
name = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
# don't delete open files
dev, path = self.session.devices.get_diskdevice_and_path(name)
dev.check_file_not_open(path)
dev.kill(path)
util.require(ins, tk.end_statement)
def exec_files(self, ins):
""" FILES: output directory listing. """
pathmask = ''
if util.skip_white(ins) not in tk.end_statement:
with self.session.strings:
pathmask = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
if not pathmask:
raise error.RunError(error.BAD_FILE_NAME)
dev, path = self.session.devices.get_diskdevice_and_path(pathmask)
dev.files(self.session.screen, path)
util.require(ins, tk.end_statement)
##########################################################
# OS
def exec_shell(self, ins):
""" SHELL: open OS shell and optionally execute command. """
# parse optional shell command
cmd = b''
if util.skip_white(ins) not in tk.end_statement:
with self.session.strings:
cmd = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
# no SHELL on PCjr.
if self.parser.syntax == 'pcjr':
raise error.RunError(error.IFC)
# force cursor visible in all cases
self.session.screen.cursor.show(True)
# sound stops playing and is forgotten
self.session.sound.stop_all_sound()
# no user events
with self.parser.events.suspend():
# run the os-specific shell
self.session.shell.launch(cmd)
# reset cursor visibility to its previous state
self.session.screen.cursor.reset_visibility()
util.require(ins, tk.end_statement)
def exec_environ(self, ins):
""" ENVIRON: set environment string. """
with self.session.strings:
envstr = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
eqs = envstr.find('=')
if eqs <= 0:
raise error.RunError(error.IFC)
envvar = str(envstr[:eqs])
val = str(envstr[eqs+1:])
os.environ[envvar] = val
util.require(ins, tk.end_statement)
def exec_time(self, ins):
""" TIME$: set time. """
util.require_read(ins, (tk.O_EQ,)) #time$=
# allowed formats: hh hh:mm hh:mm:ss where hh 0-23, mm 0-59, ss 0-59
with self.session.strings:
timestr = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
util.require(ins, tk.end_statement)
self.session.timer.set_time(timestr)
def exec_date(self, ins):
""" DATE$: set date. """
util.require_read(ins, (tk.O_EQ,)) # date$=
# allowed formats:
# mm/dd/yy or mm-dd-yy mm 0--12 dd 0--31 yy 80--00--77
# mm/dd/yyyy or mm-dd-yyyy yyyy 1980--2099
with self.session.strings:
datestr = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
util.require(ins, tk.end_statement)
self.session.timer.set_date(datestr)
##########################################################
# code
def _parse_line_range(self, ins):
""" Helper function: parse line number ranges. """
from_line = self._parse_jumpnum_or_dot(ins, allow_empty=True)
if util.skip_white_read_if(ins, (tk.O_MINUS,)):
to_line = self._parse_jumpnum_or_dot(ins, allow_empty=True)
else:
to_line = from_line
return (from_line, to_line)
def _parse_jumpnum_or_dot(self, ins, allow_empty=False, err=error.STX):
""" Helper function: parse jump target. """
c = util.skip_white_read(ins)
if c == tk.T_UINT:
return vartypes.integer_to_int_unsigned(vartypes.bytes_to_integer(ins.read(2)))
elif c == '.':
return self.session.program.last_stored
else:
if allow_empty:
ins.seek(-len(c), 1)
return None
raise error.RunError(err)
def exec_delete(self, ins):
""" DELETE: delete range of lines from program. """
from_line, to_line = self._parse_line_range(ins)
util.require(ins, tk.end_statement)
# throws back to direct mode
self.session.program.delete(from_line, to_line)
# clear all program stacks
self.parser.clear_stacks_and_pointers()
# clear all variables
self.session.clear()
def exec_edit(self, ins):
""" EDIT: output a program line and position cursor for editing. """
if util.skip_white(ins) in tk.end_statement:
# undefined line number
raise error.RunError(error.UNDEFINED_LINE_NUMBER)
from_line = self._parse_jumpnum_or_dot(ins, err=error.IFC)
if from_line is None or from_line not in self.session.program.line_numbers:
raise error.RunError(error.UNDEFINED_LINE_NUMBER)
util.require(ins, tk.end_statement, err=error.IFC)
# throws back to direct mode
# jump to end of direct line so execution stops
self.parser.set_pointer(False)
self.session.screen.cursor.reset_visibility()
# request edit prompt
self.session.edit_prompt = (from_line, None)
def exec_auto(self, ins):
""" AUTO: enter automatic line numbering mode. """
linenum = self._parse_jumpnum_or_dot(ins, allow_empty=True)
increment = None
if util.skip_white_read_if(ins, (',',)):
increment = util.parse_jumpnum(ins, allow_empty=True)
util.require(ins, tk.end_statement)
# reset linenum and increment on each call of AUTO (even in AUTO mode)
self.session.auto_linenum = linenum if linenum is not None else 10
self.session.auto_increment = increment if increment is not None else 10
# move program pointer to end
self.parser.set_pointer(False)
# continue input in AUTO mode
self.session.auto_mode = True
def exec_list(self, ins):
""" LIST: output program lines. """
from_line, to_line = self._parse_line_range(ins)
out = None
if util.skip_white_read_if(ins, (',',)):
with self.session.strings:
outname = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
out = self.session.files.open(0, outname, filetype='A', mode='O')
# ignore everything after file spec
util.skip_to(ins, tk.end_line)
util.require(ins, tk.end_statement)
lines = self.session.program.list_lines(from_line, to_line)
if out:
with out:
for l in lines:
out.write_line(l)
else:
for l in lines:
# flow of listing is visible on screen
# and interruptible
self.session.check_events()
# LIST on screen is slightly different from just writing
self.session.console.list_line(l)
# return to direct mode
self.parser.set_pointer(False)
def exec_llist(self, ins):
""" LLIST: output program lines to LPT1: """
from_line, to_line = self._parse_line_range(ins)
util.require(ins, tk.end_statement)
for l in self.session.program.list_lines(from_line, to_line):
self.session.devices.lpt1_file.write_line(l)
# return to direct mode
self.parser.set_pointer(False)
def exec_load(self, ins):
""" LOAD: load program from file. """
with self.session.strings:
name = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
# check if file exists, make some guesses (all uppercase, +.BAS) if not
comma = util.skip_white_read_if(ins, (',',))
if comma:
util.require_read(ins, 'R')
util.require(ins, tk.end_statement)
with self.session.files.open(0, name, filetype='ABP', mode='I') as f:
self.session.program.load(f)
# reset stacks
self.parser.clear_stacks_and_pointers()
# clear variables
self.session.clear()
if comma:
# in ,R mode, don't close files; run the program
self.parser.jump(None)
else:
self.session.files.close_all()
self.parser.tron = False
def exec_chain(self, ins):
""" CHAIN: load program and chain execution. """
if util.skip_white_read_if(ins, (tk.MERGE,)):
action = self.session.program.merge
else:
action = self.session.program.load
with self.session.strings:
name = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
jumpnum, common_all, delete_lines = None, False, None
if util.skip_white_read_if(ins, (',',)):
# check for an expression that indicates a line in the other self.session.program. This is not stored as a jumpnum (to avoid RENUM)
expr = self.parser.parse_expression(ins, self.session, allow_empty=True)
if expr is not None:
jumpnum = vartypes.pass_int_unpack(expr, maxint=0xffff)
# negative numbers will be two's complemented into a line number
if jumpnum < 0:
jumpnum = 0x10000 + jumpnum
if util.skip_white_read_if(ins, (',',)):
if util.skip_white_read_if(ins, ('ALL',)):
common_all = True
# CHAIN "file", , ALL, DELETE
if util.skip_white_read_if(ins, (',',)):
delete_lines = self._parse_delete_clause(ins)
else:
# CHAIN "file", , DELETE
delete_lines = self._parse_delete_clause(ins)
util.require(ins, tk.end_statement)
if self.session.program.protected and action == self.session.program.merge:
raise error.RunError(error.IFC)
with self.session.files.open(0, name, filetype='ABP', mode='I') as f:
if delete_lines:
# delete lines from existing code before merge (without MERGE, this is pointless)
self.session.program.delete(*delete_lines)
action(f)
# clear all program stacks
self.parser.clear_stacks_and_pointers()
# don't close files!
# RUN
self.parser.jump(jumpnum, err=error.IFC)
# preserve DEFtype on MERGE
self.session.clear(preserve_common=True, preserve_all=common_all, preserve_deftype=(action==self.session.program.merge))
def _parse_delete_clause(self, ins):
""" Helper function: parse the DELETE clause of a CHAIN statement. """
delete_lines = None
if util.skip_white_read_if(ins, (tk.DELETE,)):
from_line = util.parse_jumpnum(ins, allow_empty=True)
if util.skip_white_read_if(ins, (tk.O_MINUS,)):
to_line = util.parse_jumpnum(ins, allow_empty=True)
else:
to_line = from_line
# to_line must be specified and must be an existing line number
if not to_line or to_line not in self.session.program.line_numbers:
raise error.RunError(error.IFC)
delete_lines = (from_line, to_line)
# ignore rest if preceded by cmma
if util.skip_white_read_if(ins, (',',)):
util.skip_to(ins, tk.end_statement)
return delete_lines
def exec_save(self, ins):
""" SAVE: save program to a file. """
with self.session.strings:
name = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
mode = 'B'
if util.skip_white_read_if(ins, (',',)):
mode = util.skip_white_read(ins).upper()
if mode not in ('A', 'P'):
raise error.RunError(error.STX)
with self.session.files.open(0, name, filetype=mode, mode='O',
seg=self.session.memory.data_segment, offset=self.session.memory.code_start,
length=len(self.parser.program_code.getvalue())-1
) as f:
self.session.program.save(f)
util.require(ins, tk.end_statement)
def exec_merge(self, ins):
""" MERGE: merge lines from file into current program. """
with self.session.strings:
name = self.session.strings.copy(vartypes.pass_string(self.parser.parse_expression(ins, self.session)))
# check if file exists, make some guesses (all uppercase, +.BAS) if not
with self.session.files.open(0, name, filetype='A', mode='I') as f:
self.session.program.merge(f)
# clear all program stacks
self.parser.clear_stacks_and_pointers()
util.require(ins, tk.end_statement)
def exec_new(self, ins):
""" NEW: clear program from memory. """
self.parser.tron = False
# deletes the program currently in memory
self.session.program.erase()
# reset stacks
self.parser.clear_stacks_and_pointers()
# and clears all variables
self.session.clear()
self.parser.set_pointer(False)
def exec_renum(self, ins):
""" RENUM: renumber program line numbers. """
new, old, step = None, None, None
if util.skip_white(ins) not in tk.end_statement:
new = self._parse_jumpnum_or_dot(ins, allow_empty=True)
if util.skip_white_read_if(ins, (',',)):
old = self._parse_jumpnum_or_dot(ins, allow_empty=True)
if util.skip_white_read_if(ins, (',',)):
step = util.parse_jumpnum(ins, allow_empty=True) # returns -1 if empty
util.require(ins, tk.end_statement)
if step is not None and step < 1:
raise error.RunError(error.IFC)
old_to_new = self.session.program.renum(