forked from micropython/micropython-lib
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaiorepl.py
325 lines (296 loc) · 12.1 KB
/
aiorepl.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
# MIT license; Copyright (c) 2022 Jim Mussared
importmicropython
frommicropythonimportconst
importre
importsys
importtime
importasyncio
# Import statement (needs to be global, and does not return).
_RE_IMPORT=re.compile("^import ([^ ]+)( as ([^ ]+))?")
_RE_FROM_IMPORT=re.compile("^from [^ ]+ import ([^ ]+)( as ([^ ]+))?")
# Global variable assignment.
_RE_GLOBAL=re.compile("^([a-zA-Z0-9_]+) ?=[^=]")
# General assignment expression or import statement (does not return a value).
_RE_ASSIGN=re.compile("[^=]=[^=]")
# Command hist (One reserved slot for the current command).
_HISTORY_LIMIT=const(5+1)
CHAR_CTRL_A=const(1)
CHAR_CTRL_B=const(2)
CHAR_CTRL_C=const(3)
CHAR_CTRL_D=const(4)
CHAR_CTRL_E=const(5)
asyncdefexecute(code, g, s):
ifnotcode.strip():
return
try:
if"await "incode:
# Execute the code snippet in an async context.
ifm:=_RE_IMPORT.match(code) or_RE_FROM_IMPORT.match(code):
code="global {}\n {}".format(m.group(3) orm.group(1), code)
elifm:=_RE_GLOBAL.match(code):
code="global {}\n {}".format(m.group(1), code)
elifnot_RE_ASSIGN.search(code):
code="return {}".format(code)
code="""
import asyncio
async def __code():
{}
__exec_task = asyncio.create_task(__code())
""".format(code)
asyncdefkbd_intr_task(exec_task, s):
whileTrue:
iford(awaits.read(1)) ==CHAR_CTRL_C:
exec_task.cancel()
return
l= {"__exec_task": None}
exec(code, g, l)
exec_task=l["__exec_task"]
# Concurrently wait for either Ctrl-C from the stream or task
# completion.
intr_task=asyncio.create_task(kbd_intr_task(exec_task, s))
try:
try:
returnawaitexec_task
exceptasyncio.CancelledError:
pass
finally:
intr_task.cancel()
try:
awaitintr_task
exceptasyncio.CancelledError:
pass
else:
# Excute code snippet directly.
try:
try:
micropython.kbd_intr(3)
try:
returneval(code, g)
exceptSyntaxError:
# Maybe an assignment, try with exec.
returnexec(code, g)
exceptKeyboardInterrupt:
pass
finally:
micropython.kbd_intr(-1)
exceptExceptionaserr:
print("{}: {}".format(type(err).__name__, err))
# REPL task. Invoke this with an optional mutable globals dict.
asyncdeftask(g=None, prompt="--> "):
print("Starting asyncio REPL...")
ifgisNone:
g=__import__("__main__").__dict__
try:
micropython.kbd_intr(-1)
s=asyncio.StreamReader(sys.stdin)
# clear = True
hist= [None] *_HISTORY_LIMIT
hist_i=0# Index of most recent entry.
hist_n=0# Number of history entries.
c=0# ord of most recent character.
t=0# timestamp of most recent character.
whileTrue:
hist_b=0# How far back in the history are we currently.
sys.stdout.write(prompt)
cmd: str=""
paste=False
curs=0# cursor offset from end of cmd buffer
whileTrue:
b=awaits.read(1)
pc=c# save previous character
c=ord(b)
pt=t# save previous time
t=time.ticks_ms()
ifc<0x20orc>0x7E:
ifc==0x0A:
# LF
ifpaste:
sys.stdout.write(b)
cmd+=b
continue
# If the previous character was also LF, and was less
# than 20 ms ago, this was likely due to CRLF->LFLF
# conversion, so ignore this linefeed.
ifpc==0x0Aandtime.ticks_diff(t, pt) <20:
continue
ifcurs:
# move cursor to end of the line
sys.stdout.write("\x1B[{}C".format(curs))
curs=0
sys.stdout.write("\n")
ifcmd:
# Push current command.
hist[hist_i] =cmd
# Increase history length if possible, and rotate ring forward.
hist_n=min(_HISTORY_LIMIT-1, hist_n+1)
hist_i= (hist_i+1) %_HISTORY_LIMIT
result=awaitexecute(cmd, g, s)
ifresultisnotNone:
sys.stdout.write(repr(result))
sys.stdout.write("\n")
break
elifc==0x08orc==0x7F:
# Backspace.
ifcmd:
ifcurs:
cmd="".join((cmd[: -curs-1], cmd[-curs:]))
sys.stdout.write(
"\x08\x1B[K"
) # move cursor back, erase to end of line
sys.stdout.write(cmd[-curs:]) # redraw line
sys.stdout.write("\x1B[{}D".format(curs)) # reset cursor location
else:
cmd=cmd[:-1]
sys.stdout.write("\x08\x08")
elifc==CHAR_CTRL_A:
awaitraw_repl(s, g)
break
elifc==CHAR_CTRL_B:
continue
elifc==CHAR_CTRL_C:
ifpaste:
break
sys.stdout.write("\n")
break
elifc==CHAR_CTRL_D:
ifpaste:
result=awaitexecute(cmd, g, s)
ifresultisnotNone:
sys.stdout.write(repr(result))
sys.stdout.write("\n")
break
sys.stdout.write("\n")
# Shutdown asyncio.
asyncio.new_event_loop()
return
elifc==CHAR_CTRL_E:
sys.stdout.write("paste mode; Ctrl-C to cancel, Ctrl-D to finish\n===\n")
paste=True
elifc==0x1B:
# Start of escape sequence.
key=awaits.read(2)
ifkeyin ("[A", "[B"): # up, down
# Stash the current command.
hist[(hist_i-hist_b) %_HISTORY_LIMIT] =cmd
# Clear current command.
b="\x08"*len(cmd)
sys.stdout.write(b)
sys.stdout.write(" "*len(cmd))
sys.stdout.write(b)
# Go backwards or forwards in the history.
ifkey=="[A":
hist_b=min(hist_n, hist_b+1)
else:
hist_b=max(0, hist_b-1)
# Update current command.
cmd=hist[(hist_i-hist_b) %_HISTORY_LIMIT]
sys.stdout.write(cmd)
elifkey=="[D": # left
ifcurs<len(cmd) -1:
curs+=1
sys.stdout.write("\x1B")
sys.stdout.write(key)
elifkey=="[C": # right
ifcurs:
curs-=1
sys.stdout.write("\x1B")
sys.stdout.write(key)
elifkey=="[H": # home
pcurs=curs
curs=len(cmd)
sys.stdout.write("\x1B[{}D".format(curs-pcurs)) # move cursor left
elifkey=="[F": # end
pcurs=curs
curs=0
sys.stdout.write("\x1B[{}C".format(pcurs)) # move cursor right
else:
# sys.stdout.write("\\x")
# sys.stdout.write(hex(c))
pass
else:
ifcurs:
# inserting into middle of line
cmd="".join((cmd[:-curs], b, cmd[-curs:]))
sys.stdout.write(cmd[-curs-1 :]) # redraw line to end
sys.stdout.write("\x1B[{}D".format(curs)) # reset cursor location
else:
sys.stdout.write(b)
cmd+=b
finally:
micropython.kbd_intr(3)
asyncdefraw_paste(s, g, window=512):
sys.stdout.write("R\x01") # supported
sys.stdout.write(bytearray([window&0xFF, window>>8, 0x01]).decode())
eof=False
idx=0
buff=bytearray(window)
file=b""
whilenoteof:
foridxinrange(window):
b=awaits.read(1)
c=ord(b)
ifc==CHAR_CTRL_Corc==CHAR_CTRL_D:
# end of file
sys.stdout.write(chr(CHAR_CTRL_D))
ifc==CHAR_CTRL_C:
raiseKeyboardInterrupt
file+=buff[:idx]
eof=True
break
buff[idx] =c
ifnoteof:
file+=buff
sys.stdout.write("\x01") # indicate window available to host
returnfile
asyncdefraw_repl(s: asyncio.StreamReader, g: dict):
heading="raw REPL; CTRL-B to exit\n"
line=""
sys.stdout.write(heading)
whileTrue:
line=""
sys.stdout.write(">")
whileTrue:
b=awaits.read(1)
c=ord(b)
ifc==CHAR_CTRL_A:
rline=line
line=""
iflen(rline) ==2andord(rline[0]) ==CHAR_CTRL_E:
ifrline[1] =="A":
line=awaitraw_paste(s, g)
break
else:
# reset raw REPL
sys.stdout.write(heading)
sys.stdout.write(">")
continue
elifc==CHAR_CTRL_B:
# exit raw REPL
sys.stdout.write("\n")
return0
elifc==CHAR_CTRL_C:
# clear line
line=""
elifc==CHAR_CTRL_D:
# entry finished
# indicate reception of command
sys.stdout.write("OK")
break
else:
# let through any other raw 8-bit value
line+=b
iflen(line) ==0:
# Normally used to trigger soft-reset but stay in raw mode.
# Fake it for aiorepl / mpremote.
sys.stdout.write("Ignored: soft reboot\n")
sys.stdout.write(heading)
try:
result=exec(line, g)
ifresultisnotNone:
sys.stdout.write(repr(result))
sys.stdout.write(chr(CHAR_CTRL_D))
exceptExceptionasex:
print(line)
sys.stdout.write(chr(CHAR_CTRL_D))
sys.print_exception(ex, sys.stdout)
sys.stdout.write(chr(CHAR_CTRL_D))