-
Notifications
You must be signed in to change notification settings - Fork 2
/
eg_basic.py
256 lines (221 loc) · 6.46 KB
/
eg_basic.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
"""
BASIC interpreter, inspired by Tiny BASIC.
"""
import bisect, operator, sys
from parson import Grammar, alter
def chat():
print "I am Puny Basic. Enter 'bye' to dismiss me."
while True:
try: text = raw_input('> ').strip()
except EOFError: break
if text == 'bye': break
try: basic.command(text)
except Exception as e:
# TODO: put the current line# in the prompt instead, if any;
# should work nicely with a resumable STOP statement
print e, ('' if pc is None else 'at line %d' % lines[pc][0])
grammar = Grammar(r"""
command : /(\d+)/ :int /(.*)/ /$/ :set_line
| "run" /$/ :run
| "new" /$/ :new
| "load" /(\S+)/ /$/ :load
| "save" /(\S+)/ /$/ :save
| stmt
| /$/.
stmt : "print" printing /$/ :next
| '?' printing /$/ :next
| "input" id /$/ :input :next
| "goto" exp /$/ :goto
| "if" relexp "then" exp /$/ :if_goto
| "gosub" exp /$/ :gosub
| "return" /$/ :return_
| "end" /$/ :end
| "list" /$/ :list :next
| "rem" /.*/ /$/ :next
| "let"? id '=' exp /$/ :store :next.
printing : (display writes)?.
writes : ';' printing
| ',' :space printing
| :newline.
display ~: exp :write
| '"' [qchar :write]* '"' FNORD.
qchar ~: /"(")/ # Two consecutive double-quotes mean '"'.
| /([^"])/. # Any other character just means itself.
relexp : exp ( '<>' exp :ne
| '<=' exp :le
| '<' exp :lt
| '=' exp :eq
| '>=' exp :ge
| '>' exp :gt
)?.
exp : exp1 ( '+' exp1 :add
| '-' exp1 :sub
)*.
exp1 : exp2 ( '*' exp2 :mul
| '/' exp2 :idiv
)*.
exp2 : primary ('^' exp2 :pow)?.
primary : '-' exp1 :neg
| /(\d+)/ :int
| id :fetch
| '(' exp ')'.
id : /([a-z])/. # TODO: longer names, screening out reserved words
FNORD ~: /\s*/.
""")
lines = [] # A sorted array of (line_number, source_line) pairs.
pc = None # The program counter: an index into lines[], or None.
return_stack = [] # A stack of line numbers of GOSUBs in progress.
env = {} # Current variable values.
def run():
reset()
go()
def reset():
global pc
pc = 0 if lines else None
return_stack[:] = []
env.clear()
def go():
global pc
while pc is not None: # TODO: check for stopped, instead
_, line = lines[pc]
pc, = basic.stmt(line)
def new():
lines[:] = []
reset()
def load(filename):
with open(filename) as f:
new()
for line in f:
basic.command(line)
def save(filename):
with open(filename, 'w') as f:
for pair in lines:
f.write('%d %s\n' % pair)
def listing():
for n, line in lines:
print n, line
def find(n): # The slice of lines[] including line n, or where to insert it.
i = bisect.bisect(lines, (n, ''))
return slice(i, i+1 if i < len(lines) and lines[i][0] == n else i)
def set_line(n, text):
lines[find(n)] = [(n, text)] if text else []
def goto(n):
sl = find(n)
if sl.start == sl.stop: raise Exception("Missing line", n)
return sl.start
def if_goto(flag, n):
return goto(n) if flag else next_line(pc)
def next_line(a_pc):
return None if a_pc in (None, len(lines)-1) else a_pc+1
def gosub(n):
target = goto(n)
return_stack.append(lines[pc][0])
return target
def return_():
return next_line(goto(return_stack.pop()))
# Parson's default meaning for a function appearing in a grammar is a
# semantic action returning one value. In this Basic we do some actions
# only for effect: this wraps those actions to produce no values.
def for_effect(fn):
def fn_for_effect(*args):
fn(*args)
return ()
return alter(fn_for_effect)
basic = grammar(
fetch = env.__getitem__,
store = for_effect(env.__setitem__),
input = for_effect(lambda var: env.__setitem__(var, int(raw_input()))),
set_line = for_effect(set_line),
goto = goto,
if_goto = if_goto,
gosub = gosub,
return_ = return_,
eq = operator.eq,
ne = operator.ne,
lt = operator.lt,
le = operator.le,
ge = operator.ge,
gt = operator.gt,
add = operator.add,
sub = operator.sub,
mul = operator.mul,
idiv = operator.idiv,
pow = operator.pow,
neg = operator.neg,
end = lambda: None,
list = for_effect(listing),
run = for_effect(run),
next = lambda: next_line(pc),
new = for_effect(new),
load = for_effect(load),
save = for_effect(save),
write = for_effect(lambda x: sys.stdout.write(str(x))),
space = for_effect(lambda: sys.stdout.write(' ')),
newline = for_effect(lambda: sys.stdout.write('\n')),
)
if __name__ == '__main__':
chat()
## basic.command('100 print "hello"')
#. ()
## lines
#. [(100, 'print "hello"')]
## basic.command('100 print "goodbye"')
#. ()
## lines
#. [(100, 'print "goodbye"')]
## basic.command('99 print 42,')
#. ()
## lines
#. [(99, 'print 42,'), (100, 'print "goodbye"')]
## basic.command('run')
#. 42 goodbye
#. ()
## basic.command('print')
#. (None,)
## basic.command('let x = 5')
#. (None,)
## basic.command('print x*x')
#. 25
#. (None,)
## basic.command('print 2+2; -5, "hi"')
#. 4-5 hi
#. (None,)
## basic.command('? 42 * (5-3) + -2^2')
#. 80
#. (None,)
## basic.command('print 2^3^2, ')
#. 512
#. (None,)
## basic.command('print 5-3-1')
#. 1
#. (None,)
## basic.command('print 3/2')
#. 1
#. (None,)
## basic.command('new')
#. ()
## basic.command('load countdown.bas')
#. ()
## basic.command('list')
#. 10 let a = 10
#. 20 if a < 0 then 60
#. 30 print a
#. 40 a = a - 1
#. 50 goto 20
#. 60 print "Blast off!"
#. 70 end
#. (None,)
## basic.command('run')
#. 10
#. 9
#. 8
#. 7
#. 6
#. 5
#. 4
#. 3
#. 2
#. 1
#. 0
#. Blast off!
#. ()