-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathbasicparser.py
More file actions
1765 lines (1325 loc) · 59.2 KB
/
Copy pathbasicparser.py
File metadata and controls
1765 lines (1325 loc) · 59.2 KB
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
#! /usr/bin/python
# SPDX-License-Identifier: GPL-3.0-or-later
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from basictoken import BASICToken as Token
from flowsignal import FlowSignal
from sys import implementation
from os import uname
from time import sleep
import math
import random
try:
from pydos_ui import input
except:
pass
try:
from pydos_hw import sndPin as hwsndPin
from pydos_hw import Pydos_hw, quietSnd
sndPin = hwsndPin
except:
sndPin = None
if implementation.name.upper() == 'MICROPYTHON':
if sndPin:
from machine import PWM
from time import ticks_ms as monotonic
elif implementation.name.upper() == 'CIRCUITPYTHON':
from time import monotonic
if sndPin:
try: # temporary? until broadcom port supports pwmio
from pwmio import PWMOut
except:
sndPin = None
else:
try:
import winsound
except:
pass
from time import monotonic
import gc
gc.collect()
"""Implements a BASIC array, which may have up
to three dimensions of fixed size.
"""
class BASICArray:
def __init__(self, dimensions):
"""Initialises the object with the specified
number of dimensions. Maximum number of
dimensions is three
:param dimensions: List of array dimensions and their
corresponding sizes
"""
self.dims = min(3,len(dimensions))
if self.dims == 0:
raise SyntaxError("Zero dimensional array specified")
# Check for invalid sizes and ensure int
for i in range(self.dims):
if dimensions[i] < 0:
raise SyntaxError("Negative array size specified")
# Allow sizes like 1.0f, but not 1.1f
if int(dimensions[i]) != dimensions[i]:
raise SyntaxError("Fractional array size specified")
dimensions[i] = int(dimensions[i])
if self.dims == 1:
self.data = [None for x in range(dimensions[0])]
elif self.dims == 2:
self.data = [[None for x in range(dimensions[1])] for x in range(dimensions[0])]
else:
self.data = [[[None for x in range(dimensions[2])] for x in range(dimensions[1])] for x in range(dimensions[0])]
# def pretty_print(self):
# print(str(self.data))
"""Implements a BASIC parser that parses a single
statement when supplied.
"""
class BASICParser:
def __init__(self):
# Symbol table to hold variable names mapped
# to values
self.__symbol_table = {}
# Stack on which to store operands
# when evaluating expressions
self.__operand_stack = []
# List to hold contents of DATA statement
self.__data_values = []
# These values will be
# initialised on a per
# statement basis
self.__tokenlist = []
self.__tokenindex = None
# used to determine when to initalize extant loop variables
self.last_flowsignal = None
# Set to keep track of print column across multiple print statements
self.__prnt_column = 0
#file handle list
self.__file_handles = {}
self.__pwm = None
if implementation.name.upper() == 'MICROPYTHON':
if sndPin:
try:
self.__pwm = PWM(sndPin,freq=0)
except:
try:
self.__pwm = PWM(sndPin)
except:
pass
if 'duty_u16' in dir(self.__pwm):
self.__pwm.duty_u16(0)
elif 'duty' in dir(self.__pwm):
self.__pwm.duty(0)
def parse(self, tokenlist, line_number, cstmt_number, infile, tmpfile, datastmts):
"""Must be initialised with the list of
BTokens to be processed. These tokens
represent a BASIC statement without
its corresponding line number.
:param tokenlist: The tokenized program statement
:param line_number: The line number of the statement
:param cstmt_number: Which statement in a multistatment line
:return: The FlowSignal to indicate to the program
how to branch if necessary, None otherwise
"""
self.__tokenlist = tokenlist
self.__tokenindex = 0
# This block locates the index number of the first token in the statement
# referenced by che cstmt_number argument
indx = 0
colon_count = 0
if cstmt_number > 0:
for e in tokenlist:
if e.category == Token.COLON:
colon_count += 1
self.__tokenindex = indx + 1
indx += 1
if colon_count >= cstmt_number:
break
# Remember the line number to aid error reporting
self.__line_number = line_number
# Assign the first token
self.__token = self.__tokenlist[self.__tokenindex]
flow = self.__stmt(infile,tmpfile,datastmts)
# If the statement returns an EXECUTE flowsignal then it's a conditional
# and we need to parse the THEN or ELSE block depending on where the
# __ifstmt method left the current __tokenindex
if flow and (flow.ftype == FlowSignal.EXECUTE):
# Find the number of compound statements in the current
# conditional block (to an ELSE or end of line)
number_of_stmts = 1
for e in tokenlist[self.__tokenindex:]:
if e.category == Token.COLON:
number_of_stmts += 1
elif e.category == Token.ELSE:
break
recur_tokenindex = self.__tokenindex
self.__tokenindex = 0
for cstmtNo in range(0,number_of_stmts):
try:
#if True:
tmp_flow = self.parse(tokenlist[recur_tokenindex:],line_number,cstmtNo,infile,tmpfile,datastmts)
except RuntimeError as err:
raise RuntimeError(str(err))
if tmp_flow:
break
return tmp_flow
else:
return flow
def __advance(self):
"""Advances to the next token
"""
# Move to the next token
self.__tokenindex += 1
# Acquire the next token if there any left
if not self.__tokenindex >= len(self.__tokenlist):
self.__token = self.__tokenlist[self.__tokenindex]
def __consume(self, expected_category):
"""Consumes a token from the list
"""
if self.__token.category == expected_category:
self.__advance()
else:
raise RuntimeError('Expecting ' + Token.catnames[expected_category] +
' in line ' + str(self.__line_number))
def __stmt(self,infile,tmpfile,datastmts):
"""Parses a program statement
:return: The FlowSignal to indicate to the program
how to branch if necessary, None otherwise
"""
if self.__token.category in [Token.FOR, Token.IF, Token.NEXT,
Token.ON]:
return self.__compoundstmt()
else:
return self.__simplestmt(infile,tmpfile,datastmts)
def __simplestmt(self,infile,tmpfile,datastmts):
"""Parses a non-compound program statement
:return: The FlowSignal to indicate to the program
how to branch if necessary, None otherwise
"""
if self.__token.category == Token.NAME:
self.__assignmentstmt()
return None
elif self.__token.category == Token.PRINT:
self.__printstmt()
return None
elif self.__token.category == Token.LET:
self.__letstmt()
return None
elif self.__token.category == Token.GOTO:
return self.__gotostmt()
elif self.__token.category == Token.GOSUB:
return self.__gosubstmt()
elif self.__token.category == Token.RETURN:
return self.__returnstmt()
elif self.__token.category == Token.STOP:
return self.__stopstmt()
elif self.__token.category == Token.INPUT:
self.__inputstmt()
return None
elif self.__token.category == Token.DIM:
self.__dimstmt()
return None
elif self.__token.category == Token.RANDOMIZE:
self.__randomizestmt()
return None
elif self.__token.category == Token.DATA:
self.__datastmt()
return None
elif self.__token.category == Token.READ:
self.__readstmt(infile,tmpfile,datastmts)
return None
elif self.__token.category == Token.OPEN:
return self.__openstmt()
elif self.__token.category == Token.CLOSE:
self.__closestmt()
return None
elif self.__token.category == Token.FSEEK:
self.__fseekstmt()
return None
elif self.__token.category == Token.RESTORE:
self.__restorestmt(datastmts)
return None
elif self.__token.category == Token.SOUND:
self.__soundstmt()
return None
else:
# Ignore comments, but raise an error
# for anything else
if self.__token.category != Token.REM:
raise RuntimeError('Expecting program statement in line '
+ str(self.__line_number))
def __printstmt(self):
"""Parses a PRINT statement, causing
the value that is on top of the
operand stack to be printed on
the screen.
"""
self.__advance() # Advance past PRINT token
fileIO = False
if self.__token.category == Token.HASH:
fileIO = True
# Process the # keyword
self.__consume(Token.HASH)
# Acquire the file number
self.__expr()
filenum = self.__operand_stack.pop()
if self.__file_handles.get(filenum) == None:
raise RuntimeError("PRINT: file #"+str(filenum)+" not opened in line " + str(self.__line_number))
# Process the comma
if self.__tokenindex < len(self.__tokenlist) and self.__token.category != Token.COLON:
self.__consume(Token.COMMA)
# Check there are items to print
last_token_cat = None
if not self.__tokenindex >= len(self.__tokenlist) and self.__token.category != Token.COLON:
last_token_cat = self.__token.category
prntTab = (self.__token.category == Token.TAB)
self.__logexpr()
#if type(self.__operand_stack[-1]) == tuple and self.__operand_stack[-1][0] == "TAB":
if prntTab:
if self.__prnt_column >= len(self.__operand_stack[-1]):
if fileIO:
self.__file_handles[filenum].write("\n")
else:
print()
self.__prnt_column = 0
current_pr_column = len(self.__operand_stack[-1]) - self.__prnt_column
self.__prnt_column = len(self.__operand_stack.pop()) - 1
if current_pr_column > 1:
if fileIO:
self.__file_handles[filenum].write(" "*(current_pr_column-1))
else:
print(" "*(current_pr_column-1), end="")
else:
self.__prnt_column += len(str(self.__operand_stack[-1]))
if fileIO:
self.__file_handles[filenum].write('%s' %(self.__operand_stack.pop()))
else:
print(self.__operand_stack.pop(), end='')
while self.__token.category == Token.COMMA or self.__token.category == Token.SEMICOLON:
last_token_cat = self.__token.category
self.__advance()
prntTab = (self.__token.category == Token.TAB)
if not self.__tokenindex >= len(self.__tokenlist) and self.__token.category != Token.COLON:
last_token_cat = None
self.__logexpr()
#if type(self.__operand_stack[-1]) == tuple and self.__operand_stack[-1][0] == "TAB":
if prntTab:
if self.__prnt_column >= len(self.__operand_stack[-1]):
if fileIO:
self.__file_handles[filenum].write("\n")
else:
print()
self.__prnt_column = 0
current_pr_column = len(self.__operand_stack[-1]) - self.__prnt_column
if fileIO:
self.__file_handles[filenum].write(" "*(current_pr_column-1))
else:
print(" "*(current_pr_column-1), end="")
self.__prnt_column = len(self.__operand_stack.pop()) - 1
else:
self.__prnt_column += len(str(self.__operand_stack[-1]))
if fileIO:
self.__file_handles[filenum].write('%s' %(self.__operand_stack.pop()))
else:
print(self.__operand_stack.pop(), end='')
else:
break
# Final newline
if last_token_cat != Token.SEMICOLON:
if fileIO:
self.__file_handles[filenum].write("\n")
else:
print()
self.__prnt_column = 0
def __letstmt(self):
"""Parses a LET statement,
consuming the LET keyword.
"""
self.__advance() # Advance past the LET token
self.__assignmentstmt()
def __gotostmt(self):
"""Parses a GOTO statement
:return: A FlowSignal containing the target line number
of the GOTO
"""
self.__advance() # Advance past GOTO token
self.__expr()
# Set up and return the flow signal
return FlowSignal(ftarget=self.__operand_stack.pop())
def __gosubstmt(self):
"""Parses a GOSUB statement
:return: A FlowSignal containing the first line number
of the subroutine
"""
self.__advance() # Advance past GOSUB token
self.__expr()
# Set up and return the flow signal
return FlowSignal(ftarget=self.__operand_stack.pop(),
ftype=FlowSignal.GOSUB)
def __returnstmt(self):
"""Parses a RETURN statement"""
self.__advance() # Advance past RETURN token
# Set up and return the flow signal
return FlowSignal(ftype=FlowSignal.RETURN)
def __stopstmt(self):
"""Parses a STOP statement"""
self.__advance() # Advance past STOP token
for handles in self.__file_handles:
self.__file_handles[handles].close()
self.__file_handles.clear()
return FlowSignal(ftype=FlowSignal.STOP)
def __assignmentstmt(self):
"""Parses an assignment statement,
placing the corresponding
variable and its value in the symbol
table.
"""
left = self.__token.lexeme # Save lexeme of
# the current token
self.__advance()
if self.__token.category == Token.LEFTPAREN:
# We are assiging to an array
self.__arrayassignmentstmt(left)
else:
# We are assigning to a simple variable
self.__consume(Token.ASSIGNOP)
self.__logexpr()
# Check that we are using the right variable name format
right = self.__operand_stack.pop()
if left.endswith('$') and not isinstance(right, str):
raise SyntaxError('Syntax error: Attempt to assign non string to string variable' +
' in line ' + str(self.__line_number))
elif not left.endswith('$') and isinstance(right, str):
raise SyntaxError('Syntax error: Attempt to assign string to numeric variable' +
' in line ' + str(self.__line_number))
self.__symbol_table[left] = right
def __dimstmt(self):
"""Parses DIM statement and creates a symbol
table entry for an array of the specified
dimensions.
"""
self.__advance() # Advance past DIM keyword
# Extract the array name, append a suffix so
# that we can distinguish from simple variables
# in the symbol table
name = self.__token.lexeme + '_array'
self.__advance() # Advance past array name
self.__consume(Token.LEFTPAREN)
# Extract the dimensions
dimensions = []
if not self.__tokenindex >= len(self.__tokenlist):
self.__expr()
dimensions.append(self.__operand_stack.pop())
while self.__token.category == Token.COMMA:
self.__advance() # Advance past comma
self.__expr()
dimensions.append(self.__operand_stack.pop())
self.__consume(Token.RIGHTPAREN)
if len(dimensions) > 3:
raise SyntaxError("Maximum number of array dimensions is three " +
"in line " + str(self.__line_number))
self.__symbol_table[name] = BASICArray(dimensions)
def __arrayassignmentstmt(self, name):
"""Parses an assignment to an array variable
:param name: Array name
"""
self.__consume(Token.LEFTPAREN)
# Capture the index variables
# Extract the dimensions
indexvars = []
if not self.__tokenindex >= len(self.__tokenlist):
self.__expr()
indexvars.append(self.__operand_stack.pop())
while self.__token.category == Token.COMMA:
self.__advance() # Advance past comma
self.__expr()
indexvars.append(self.__operand_stack.pop())
try:
BASICarray = self.__symbol_table[name + '_array']
except KeyError:
raise KeyError('Array - ' + name + ' could not be found in line ' +
str(self.__line_number))
if BASICarray.dims != len(indexvars):
raise IndexError('Incorrect number of indices applied to array ' +
'in line ' + str(self.__line_number))
self.__consume(Token.RIGHTPAREN)
self.__consume(Token.ASSIGNOP)
self.__logexpr()
# Check that we are using the right variable name format
right = self.__operand_stack.pop()
if name.endswith('$') and not isinstance(right, str):
raise SyntaxError('Attempt to assign non string to string array' +
' in line ' + str(self.__line_number))
elif not name.endswith('$') and isinstance(right, str):
raise SyntaxError('Attempt to assign string to numeric array' +
' in line ' + str(self.__line_number))
# Assign to the specified array index
try:
if len(indexvars) == 1:
BASICarray.data[indexvars[0]-1] = right
elif len(indexvars) == 2:
BASICarray.data[indexvars[0]-1][indexvars[1]-1] = right
elif len(indexvars) == 3:
BASICarray.data[indexvars[0]-1][indexvars[1]-1][indexvars[2]-1] = right
except IndexError:
raise IndexError('Array index out of range in line ' +
str(self.__line_number))
def __openstmt(self):
"""Parses an open statement, opens the indicated file and
places the file handle into handle table
"""
self.__advance() # Advance past OPEN token
# Acquire the filename
self.__logexpr()
filename = self.__operand_stack.pop()
# Process the FOR keyword
self.__consume(Token.FOR)
if self.__token.lexeme == "INPUT":
accessMode = "r"
elif self.__token.lexeme == "APPEND":
accessMode = "r+"
elif self.__token.lexeme == "OUTPUT":
accessMode = "w+"
else:
raise SyntaxError('Invalid Open access mode in line ' + str(self.__line_number))
self.__advance() # Advance past acess type
if self.__token.lexeme != "AS":
raise SyntaxError('Expecting AS in line ' + str(self.__line_number))
self.__advance() # Advance past AS keyword
#if self.__token.category != Token.HASH:
#raise SyntaxError('Expecting (#filenum) in line ' + str(self.__line_number))
#self.__advance() # Advance past Hashmark (#)
# Process the # keyword
self.__consume(Token.HASH)
# Acquire the file number
self.__expr()
filenum = self.__operand_stack.pop()
branchOnError = False
if self.__token.category == Token.ELSE:
branchOnError = True
self.__advance() # Advance past ELSE
if self.__token.category == Token.GOTO:
self.__advance() # Advance past optional GOTO
self.__expr()
if self.__file_handles.get(filenum) != None:
if branchOnError:
return FlowSignal(ftarget=self.__operand_stack.pop())
else:
raise RuntimeError("File #",filenum," already opened in line " + str(self.__line_number))
try:
self.__file_handles[filenum] = open(filename,accessMode)
except:
if branchOnError:
return FlowSignal(ftarget=self.__operand_stack.pop())
else:
raise RuntimeError('File '+filename+' could not be opened in line ' + str(self.__line_number))
if accessMode == "r+":
try:
fileline = self.__file_handles[filenum].readline()
newlines = ""
for ichar in range(len(fileline)-1,-1,-1):
if fileline[ichar] not in ['\n','\r']:
break
newlines = fileline[ichar:]
except:
newlines = "\r\n"
self.__file_handles[filenum].seek(0)
filelen = 0
newlineAdj = len(newlines) - 1
for lines in self.__file_handles[filenum]:
filelen += len(lines)+newlineAdj
self.__file_handles[filenum].seek(filelen)
return None
def __closestmt(self):
"""Parses a close, closes the file and removes
the file handle from the handle table
"""
self.__advance() # Advance past CLOSE token
# Process the # keyword
self.__consume(Token.HASH)
# Acquire the file number
self.__expr()
filenum = self.__operand_stack.pop()
if self.__file_handles.get(filenum) == None:
raise RuntimeError("CLOSE: file #"+str(filenum)+" not opened in line " + str(self.__line_number))
self.__file_handles[filenum].close()
self.__file_handles.pop(filenum)
def __fseekstmt(self):
"""Parses an fseek statement, seeks the indicated file position
"""
self.__advance() # Advance past FSEEK token
# Process the # keyword
self.__consume(Token.HASH)
# Acquire the file number
self.__expr()
filenum = self.__operand_stack.pop()
if self.__file_handles.get(filenum) == None:
raise RuntimeError("FSEEK: file #"+str(filenum)+" not opened in line " + str(self.__line_number))
# Process the comma
self.__consume(Token.COMMA)
# Acquire the file position
self.__expr()
self.__file_handles[filenum].seek(self.__operand_stack.pop())
def __inputstmt(self):
"""Parses an input statement, extracts the input
from the user and places the values into the
symbol table
"""
self.__advance() # Advance past INPUT token
fileIO = False
if self.__token.category == Token.HASH:
fileIO = True
# Process the # keyword
self.__consume(Token.HASH)
# Acquire the file number
self.__expr()
filenum = self.__operand_stack.pop()
if self.__file_handles.get(filenum) == None:
raise RuntimeError("INPUT: file #"+str(filenum)+" not opened in line " + str(self.__line_number))
# Process the comma
self.__consume(Token.COMMA)
prompt = '? '
if self.__token.category == Token.STRING:
if fileIO:
raise SyntaxError('Input prompt specified for file I/O ' +
'in line ' + str(self.__line_number))
# Acquire the input prompt
self.__logexpr()
prompt = self.__operand_stack.pop()
self.__consume(Token.COMMA)
# Acquire the comma separated input variables
variables = []
if not self.__tokenindex >= len(self.__tokenlist):
if self.__token.category != Token.NAME:
raise ValueError('Expecting NAME in INPUT statement ' +
'in line ' + str(self.__line_number))
variables.append(self.__token.lexeme)
self.__advance() # Advance past variable
while self.__token.category == Token.COMMA:
self.__advance() # Advance past comma
variables.append(self.__token.lexeme)
self.__advance() # Advance past variable
# Gather input into the variables
if fileIO:
#inputvals = self.__file_handles[filenum].readline()[:(-2 if implementation.name.upper() ==
#'MICROPYTHON' else -1)].split(',', (len(variables)-1))
inputvals = ((self.__file_handles[filenum].readline().replace("\n","")).replace("\r","")).split(',', (len(variables)-1))
else:
# kfw inputvals = self.input_keyboard(prompt).split(',', (len(variables)-1))
inputvals = input(prompt).split(',', (len(variables)-1))
for variable in variables:
left = variable
try:
right = inputvals.pop(0)
if left.endswith('$'):
self.__symbol_table[left] = str(right)
elif not left.endswith('$'):
try:
self.__symbol_table[left] = int(right)
except ValueError:
raise ValueError('String input provided to a numeric variable ' +
'in line ' + str(self.__line_number))
except IndexError:
# No more input to process
pass
def __restorestmt(self,datastmts):
self.__advance() # Advance past RESTORE token
# Acquire the line number
self.__expr()
self.__data_values.clear()
datastmts.restore(self.__operand_stack.pop())
def __datastmt(self):
"""Parses a DATA statement"""
def __readstmt(self,infile,tmpfile,datastmts):
"""Parses a READ statement."""
self.__advance() # Advance past READ token
# Acquire the comma separated input variables
variables = []
if not self.__tokenindex >= len(self.__tokenlist):
variables.append(self.__token.lexeme)
self.__advance() # Advance past variable
while self.__token.category == Token.COMMA:
self.__advance() # Advance past comma
variables.append(self.__token.lexeme)
self.__advance() # Advance past variable
# Check that we have enough data values to fill the
# variables
#if len(variables) > len(self.__data_values):
#raise RuntimeError('Insufficient constants supplied to READ ' +
#'in line ' + str(self.__line_number))
# Gather input from the DATA statement into the variables
for variable in variables:
if len(self.__data_values) < 1:
self.__data_values = datastmts.readData(self.__line_number,infile,tmpfile)
left = variable
#right = readlist.pop(0)
right = self.__data_values.pop(0)
if left.endswith('$'):
# Python inserts quotes around input data
if isinstance(right, int):
raise ValueError('Non-string input provided to a string variable ' +
'in line ' + str(self.__line_number))
else:
self.__symbol_table[left] = right
elif not left.endswith('$'):
try:
#self.__symbol_table[left] = int(right)
self.__symbol_table[left] = right
except ValueError:
raise ValueError('String input provided to a numeric variable ' +
'in line ' + str(self.__line_number))
def __soundstmt(self):
"""Parses a SOUND statement"""
self.__advance() # Advance past SOUND token
# Acquire the comma separated values
self.__expr()
freq = self.__operand_stack.pop()
self.__consume(Token.COMMA)
self.__expr()
duration = self.__operand_stack.pop()
if self.__token.category == Token.COMMA:
self.__advance()
self.__expr()
volume = self.__operand_stack.pop()
else:
volume = 800
if implementation.name.upper() == 'MICROPYTHON':
if sndPin and self.__pwm:
self.__pwm.freq(freq)
if "duty_u16" in dir(self.__pwm):
self.__pwm.duty_u16(volume)
sleep(duration/18.2)
self.__pwm.duty_u16(0)
else:
self.__pwm.duty(int((volume/65535)*1023))
sleep(duration/18.2)
self.__pwm.duty(0)
elif implementation.name.upper() == 'CIRCUITPYTHON':
if sndPin:
try:
Pydos_hw.sndGPIO.deinit() # Workaround for ESP32-S2 GPIO issue
audioPin = PWMOut(sndPin, duty_cycle=volume, frequency=freq)
sleep(duration/18.2)
audioPin.deinit()
quietSnd() # Workaround for ESP32-S2 GPIO issue
except:
pass
else:
try:
winsound.Beep(freq,int(self.__operand_stack.pop()*1000/18.2))
except:
pass
def __expr(self):
"""Parses a numerical expression consisting
of two terms being added or subtracted,
leaving the result on the operand stack.
"""
self.__term() # Pushes value of left term
# onto top of stack
while self.__token.category in [Token.PLUS, Token.MINUS]:
savedcategory = self.__token.category
self.__advance()
self.__term() # Pushes value of right term
# onto top of stack
rightoperand = self.__operand_stack.pop()
leftoperand = self.__operand_stack.pop()
if savedcategory == Token.PLUS:
self.__operand_stack.append(leftoperand + rightoperand)
else:
self.__operand_stack.append(leftoperand - rightoperand)
def __term(self):
"""Parses a numerical expression consisting
of two factors being multiplied together,
leaving the result on the operand stack.
"""
self.__sign = 1 # Initialise sign to keep track of unary
# minuses
self.__factor() # Leaves value of term on top of stack
while self.__token.category in [Token.TIMES, Token.DIVIDE, Token.MODULO]:
savedcategory = self.__token.category
self.__advance()
self.__sign = 1 # Initialise sign
self.__factor() # Leaves value of term on top of stack
rightoperand = self.__operand_stack.pop()
leftoperand = self.__operand_stack.pop()
if savedcategory == Token.TIMES:
self.__operand_stack.append(leftoperand * rightoperand)
elif savedcategory == Token.DIVIDE:
self.__operand_stack.append(leftoperand / rightoperand)
else:
self.__operand_stack.append(leftoperand % rightoperand)
def __factor(self):
"""Evaluates a numerical expression
and leaves its value on top of the
operand stack.
"""
if self.__token.category == Token.PLUS:
self.__advance()