-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnative.py
372 lines (302 loc) · 12.7 KB
/
native.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
import os
from expr import ExprVisitor
import time
import asyncio
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from error import RuntimeError
from tokens import Token
from callable import HootCallable, HootClass, HootInstance
def is_numberable(value):
try:
float(value)
except ValueError:
return False
return True
class StringInstance(HootInstance):
def __init__(self, elements: str, error_token: Token):
super().__init__(HootClass("String", None, {}))
self.error_token = error_token
self.elements = list(str(elements))
def get(self, name: Token):
elements = self.elements
if name.lexeme == "at":
class At(HootCallable):
def arity(self, interpreter, arguments):
return 1
def call(self, interpreter, arguments, error_token: Token):
arg = arguments[0]
if not is_numberable(arg):
raise RuntimeError(
error_token, f"'at' only accepts a number index. Got '{arg}'.")
index = int(arg)
if arg > len(elements) - 1:
raise RuntimeError(
error_token, f"'at' out of bounds error.")
return elements[index]
return At()
elif name.lexeme == "alter":
class Alter(HootCallable):
def arity(self, interpreter, arguments):
return 2
def call(self, interpreter, arguments, error_token: Token):
arg = arguments[0]
to = arguments[1]
if not is_numberable(arg):
raise RuntimeError(
error_token, f"'alter' only accepts a number index. Got '{arg}'.")
index = int(arg)
if arg > len(elements) - 1:
raise RuntimeError(
error_token, f"'at' out of bounds error.")
elements[index] = str(to)
return Alter()
elif name.lexeme == "length":
class Length(HootCallable):
def arity(self, interpreter, arguments):
return 0
def call(self, interpreter, arguments, error_token: Token):
return len(elements)
return Length()
else:
raise RuntimeError(
self.error_token, f"Can't call '{name.lexeme}' on a string.")
def __repr__(self):
return ''.join(self.elements)
class MapInstance(HootInstance):
def __init__(self):
super().__init__(HootClass("Map", None, {}))
self.store = {}
def get(self, name: Token):
store = self.store
if name.lexeme == "get":
class Get(HootCallable):
def arity(self, interpreter, arguments):
return 1
def call(self, interpreter, arguments, error_token: Token):
arg = arguments[0]
return store.get(arg, None)
return Get()
elif name.lexeme == "set":
class Set(HootCallable):
def arity(self, interpreter, arguments):
return 2
def call(self, interpreter, arguments, error_token: Token):
arg = arguments[0]
to = arguments[1]
store[arg] = to
return Set()
else:
raise RuntimeError(
name, f"Can't call '{name.lexeme}' on a map.")
def items(self):
return self.store.items()
def __repr__(self):
return str(self.store)
class Input(HootCallable):
def arity(self, interpreter, arguments):
return 1
def call(self, interpreter, arguments, error_token: Token):
return StringInstance(input(arguments[0]), error_token)
def __repr__(self):
return "<native fn>"
class Read(HootCallable):
def arity(self, interpreter, arguments):
return 2
def call(self, interpreter, arguments, error_token: Token):
def blocking_read():
try:
with open(arguments[0], "r") as f:
return f.read()
except Exception as err:
interpreter.hoot.error(
error_token, f"Error reading '{arguments[0]}'. Caught error: {err}")
return None
async def main():
loop = asyncio.get_running_loop()
with ThreadPoolExecutor() as pool:
data = await loop.run_in_executor(
pool, blocking_read)
arguments[1].call(
interpreter, [StringInstance(data, error_token)], error_token)
asyncio.create_task(main())
def __repr__(self):
return "<native fn>"
class Write(HootCallable):
def arity(self, interpreter, arguments):
return 4
def call(self, interpreter, arguments, error_token: Token):
def blocking_write():
try:
with open(arguments[0], arguments[1]) as f:
f.write(arguments[2])
# wait for file write
# https://stackoverflow.com/a/3857543
os.fsync(f.fileno())
except Exception as err:
interpreter.hoot.error(
error_token, f"Error writing '{arguments[0]}'. Caught error: {err}")
return None
async def main():
loop = asyncio.get_running_loop()
with ThreadPoolExecutor() as pool:
await loop.run_in_executor(
pool, blocking_write)
if arguments[3]:
arguments[3].call(interpreter, [], error_token)
asyncio.create_task(main())
with open(arguments[0], arguments[1]) as f:
f.write(arguments[2])
def __repr__(self):
return "<native fn>"
class Clock(HootCallable):
def arity(self, interpreter, arguments):
return 0
def call(self, interpreter, arguments, error_token: Token):
return time.time()
def __repr__(self):
return "<native fn>"
class Delay(HootCallable):
def arity(self, interpreter, arguments):
return 2
def call(self, interpreter, arguments, error_token: Token):
async def sleeper():
await asyncio.sleep(arguments[0] / 1000)
try:
arguments[1].call(interpreter, [], error_token)
except Exception as err:
interpreter.hoot.error(
error_token, f"Error in delay callback '{arguments[1]}'. Caught error: {err}")
return False
asyncio.create_task(sleeper())
def __repr__(self):
return "<native fn>"
class Request(HootCallable):
def arity(self, interpreter, arguments):
return 5
def call(self, interpreter, arguments, error_token: Token):
url, data, headers, method, callback = arguments
if headers == None:
headers = {}
def return_response():
try:
request = urllib.request.Request(
url, data, headers, method=method)
response = urllib.request.urlopen(request)
except Exception as err:
interpreter.hoot.error(
error_token, f"Error requesting '{url}'. Caught error: {err}")
return False
return {
"headers": dict(response.info()),
"body": response.read(),
}
@asyncio.coroutine
def read_page():
loop = asyncio.get_event_loop()
data = yield from loop.run_in_executor(None, lambda: return_response())
if data == False:
return
instance = HootInstance(HootClass("Response", None, {}))
headers = MapInstance()
for k, v in data["headers"].items():
headers.store[k] = v
instance.fields = {
"body": StringInstance(data["body"].decode("utf-8", errors="ignore"), error_token),
"headers": headers,
}
callback.call(interpreter, [instance], error_token)
asyncio.create_task(read_page())
def __repr__(self):
return "<native fn>"
class StringDataType(HootCallable):
def arity(self, interpreter, arguments):
return 1
def call(self, interpreter, arguments, error_token: Token):
return StringInstance(arguments[0], error_token)
def __repr__(self):
return "<native fn>"
class ListDataType(HootCallable):
def arity(self, interpreter, arguments):
return -1
def call(self, interpreter, arguments, error_token: Token):
class ListInstance(HootInstance):
def __init__(self, elements: list):
super().__init__(HootClass("List", None, {}))
self.elements = elements
def get(self, name: Token):
elements = self.elements
if name.lexeme == "at":
class At(HootCallable):
def arity(self, interpreter, arguments):
return 1
def call(self, interpreter, arguments, error_token: Token):
arg = arguments[0]
if not is_numberable(arg):
raise RuntimeError(
error_token, f"'at' only accepts a number index. Got '{arg}'.")
index = int(arg)
if arg > len(elements) - 1:
print(arg, len(elements))
raise RuntimeError(
error_token, f"'at' out of bounds error.")
return elements[index]
return At()
elif name.lexeme == "alter":
class Alter(HootCallable):
def arity(self, interpreter, arguments):
return 2
def call(self, interpreter, arguments, error_token: Token):
arg = arguments[0]
if not is_numberable(arg):
raise RuntimeError(
error_token, f"'alter' only accepts a number index. Got '{arg}'.")
index = int(arg)
if arg > len(elements) - 1:
print(arg, len(elements))
raise RuntimeError(
error_token, f"'at' out of bounds error.")
to = float(arguments[1])
elements[index] = to
return Alter()
elif name.lexeme == "length":
class Length(HootCallable):
def arity(self, interpreter, arguments):
return 0
def call(self, interpreter, arguments, error_token: Token):
return float(len(elements))
return Length()
elif name.lexeme == "push":
class Push(HootCallable):
def arity(self, interpreter, arguments):
return 1
def call(self, interpreter, arguments, error_token: Token):
arg = arguments[0]
if not is_numberable(arg):
raise RuntimeError(
error_token, f"'alter' only accepts numbers. Got '{arg}'.")
index = int(arg)
elements.append(index)
return Push()
elif name.lexeme == "pop":
class Pop(HootCallable):
def arity(self, interpreter, arguments):
return 0
def call(self, interpreter, arguments, error_token: Token):
return elements.pop()
return Pop()
else:
raise RuntimeError(
error_token, f"Can't call '{name.lexeme}' on a list.")
def __repr__(self):
return str(self.elements)
return ListInstance(arguments)
def __repr__(self):
return "<native fn>"
class MapDataType(HootCallable):
def arity(self, interpreter, arguments):
return 0
def call(self, interpreter, arguments, error_token: Token):
return MapInstance()
def __repr__(self):
return "<native fn>"