-
Notifications
You must be signed in to change notification settings - Fork 2
/
esotope-aheui
executable file
·385 lines (338 loc) · 11.8 KB
/
esotope-aheui
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
#!/usr/bin/env python
#
# Esotope Aheui Interpreter, revision 6
# Copyright (c) 2005, 2010, Kang Seonghoon.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import sys
class AheuiStack(list):
def push(self, value):
self.append(value)
def pop(self):
if len(self): return list.pop(self)
return None
def dup(self):
if len(self): self.append(self[-1])
def swap(self):
if len(self) > 1:
self[-1], self[-2] = self[-2], self[-1]
class AheuiQueue(AheuiStack):
def pop(self):
if len(self): return list.pop(self, 0)
return None
class AheuiPort(AheuiStack):
def push(self, value):
pass
def pop(self):
return None
class AheuiIO(object):
def __init__(self, encoding='utf-8'):
self.encoding = encoding
def getunicode(self):
buf = ''
while 1:
char = sys.stdin.read(1)
if char == '':
return -1
buf += char
try:
return ord(buf.decode(self.encoding))
except UnicodeError, e:
# if we may clear out this error by reading more buffer, ignore for now
if not ('end of data' in e.reason or 'incomplete' in e.reason):
return None
def getunichar(self):
char = self.getunicode()
if char is None:
return u'\ufffd' # U+FFFD: Replacement Character
elif char < 0:
return u''
else:
return unichr(char)
def getchar(self):
char = self.getunicode()
if char is None:
return 0xfffd
elif char == 13:
return 10
else:
return char
def getint(self):
str = u' '
char = u'0'
sign = 1
while str and not str.isdigit():
if str == u'-':
sign = -sign
elif str != u'+':
sign = 1
str = self.getunichar()
while char.isdigit():
char = self.getunichar()
str += char
return sign * int(str[:-1])
def putint(self, value):
sys.stdout.write(unicode(value).encode(self.encoding))
def putchar(self, value):
try:
sys.stdout.write(unichr(value).encode(self.encoding))
except:
sys.stdout.write('[U+%04X]' % value)
class AheuiCode(object):
def __init__(self, code):
if not isinstance(code, unicode):
code = str(code).encode('utf-8')
self.space = []
self.sizex = self.sizey = 0
for line in code.splitlines():
if len(line) > self.sizex:
self.sizex = len(line)
self.sizey += 1
self.space.append(map(self.split, line))
if self.sizex == 0:
self.sizex = 1
if self.sizey == 0:
self.sizey = 1
def __getitem__(self, index):
x, y = index
try:
return self.space[y][x]
except IndexError:
return ()
def split(self, char):
if u'\uac00' <= char <= u'\ud7a3':
code = ord(char) - 0xac00
return (code/588, (code/28)%21, code%28)
else:
return ()
split = classmethod(split)
################################################################################
class AheuiInterpreter(object):
MINSTACKSIZE = [0, 0, 2, 2, 2, 2, 1, 0, 1, 0, 1, 0, 2, 0, 1, 0, 2, 2, 0]
FINALVALUE = [0, 2, 4, 4, 2, 5, 5, 3, 5, 7, 9, 9, 7, 9, 9,
8, 4, 4, 6, 2, 4, 1, 3, 4, 3, 4, 4, 3]
def __init__(self, code, io=None):
self.code = code
self.io = io
self.ready = False
def init(self):
self.x = 0
self.y = 0
if self.code[self.x, self.y] == ():
# move down if the first character is not a hangeul at all
self.dx = 0
self.dy = 1
else:
self.dx = 1
self.dy = 0
self.ready = True
self.finished = False
self.stacks = []
for i in xrange(28):
if i == 21:
self.stacks.append(AheuiQueue())
elif i == 27:
self.stacks.append(AheuiPort())
else:
self.stacks.append(AheuiStack())
self.current = self.stacks[0]
def get_delta(self, code, dx, dy):
if code == 0: return (1, 0)
elif code == 2: return (2, 0)
elif code == 4: return (-1, 0)
elif code == 6: return (-2, 0)
elif code == 8: return (0, -1)
elif code == 12: return (0, -2)
elif code == 13: return (0, 1)
elif code == 17: return (0, 2)
elif code == 18: return (dx, -dy)
elif code == 19: return (-dx, -dy)
elif code == 20: return (-dx, dy)
else: return (dx, dy)
def next_cell(self, x, y, dx, dy, sizex, sizey):
x += dx
if x >= sizex:
x = x % dx
elif x < 0:
x = sizex - (sizex - x) % dx
y += dy
if y >= sizey:
y = y % dy
elif y < 0:
y = sizey - (sizey - y) % dy
return x, y
def step(self):
char = self.code[self.x, self.y]
if char != ():
a, b, c = char
self.dx, self.dy = self.get_delta(b, self.dx, self.dy)
if len(self.current) < self.MINSTACKSIZE[a]:
self.dx = -self.dx
self.dy = -self.dy
elif a == 2: # div
x = self.current.pop()
y = self.current.pop()
if x != 0:
self.current.push(y // x)
else:
self.current.push(0)
elif a == 3: # add
x = self.current.pop()
y = self.current.pop()
self.current.push(y + x)
elif a == 4: # mul
x = self.current.pop()
y = self.current.pop()
self.current.push(y * x)
elif a == 5: # mod
x = self.current.pop()
y = self.current.pop()
if x != 0:
self.current.push(y % x)
else:
self.current.push(0)
elif a == 6: # pop
x = self.current.pop()
if c == 21:
self.io.putint(x)
elif c == 27:
self.io.putchar(x)
elif a == 7: # push
if c == 21:
x = self.io.getint()
elif c == 27:
x = self.io.getchar()
else:
x = self.FINALVALUE[c]
self.current.push(x)
elif a == 8: # dup
self.current.dup()
elif a == 9: # sel
self.current = self.stacks[c]
elif a == 10: # mov
x = self.current.pop()
self.stacks[c].push(x)
elif a == 12: # ge
x = self.current.pop()
y = self.current.pop()
if y >= x:
self.current.push(1)
else:
self.current.push(0)
elif a == 14: # if
if self.current.pop() == 0:
self.dx = -self.dx
self.dy = -self.dy
elif a == 16: # sub
x = self.current.pop()
y = self.current.pop()
self.current.push(y - x)
elif a == 17: # swap
self.current.swap()
elif a == 18: # halt
self.finished = True
self.x, self.y = self.next_cell(self.x, self.y, self.dx, self.dy,
self.code.sizex, self.code.sizey)
def execute(self):
self.init()
while not self.finished:
self.step()
exitcode = self.current.pop()
if exitcode is None: exitcode = 0
return exitcode
get_delta = classmethod(get_delta)
next_cell = classmethod(next_cell)
################################################################################
def version(apppath):
print >>sys.stderr, 'Esotope Aheui Interpreter revision 6'
print >>sys.stderr, 'Copyright (c) 2005, 2010, Kang Seonghoon.'
return 0
def help(apppath):
version(apppath)
print >>sys.stderr
print >>sys.stderr, 'Usage: %s [options] <filename> [<param>]' % apppath
print >>sys.stderr
print >>sys.stderr, '--help, -h Prints help message.'
print >>sys.stderr, '--version, -V Prints version information.'
print >>sys.stderr, '--skip-blankline, -x Skips leading blank lines.'
print >>sys.stderr, '--fileencoding, -e Set the encoding of source code. (default "utf-8")'
print >>sys.stderr, '--ioencoding, -E Set the encoding for input/output.'
print >>sys.stderr
print >>sys.stderr, 'See more information about esotope at:'
print >>sys.stderr, ' https://mearie.org/projects/esotope/aheui'
return 0
def main(argv):
import getopt, locale
try:
opts, args = getopt.getopt(argv[1:], 'hVe:E:x',
['help', 'version', 'fileencoding=', 'ioencoding=', 'charset=',
'skip-blankline'])
except getopt.GetoptError:
return help(argv[0])
fencoding = 'utf-8'
ioencoding = locale.getdefaultlocale()[1]
skipblanklines = False
for opt, arg in opts:
if opt in ('-h', '--help'):
return help(argv[0])
elif opt in ('-V', '--version'):
return version(argv[0])
elif opt in ('-e', '--fileencoding', '--charset'):
if opt == '--charset':
print 'Warning: --charset option is deprecated. use --fileencoding.'
fencoding = arg
elif opt in ('-x', '--skip-blankline'):
skipblanklines = True
elif opt in ('-E', '--ioencoding'):
ioencoding = arg
if len(args) == 0:
version(argv[0])
print >>sys.stderr
print >>sys.stderr, 'Type "%s --help" for help.' % argv[0]
return 1
# encoding fix
if fencoding == 'euc-kr': fencoding = 'cp949'
if ioencoding == 'euc-kr': ioencoding = 'cp949'
filename = args[0]
param = args[1:]
try:
if filename == '-':
data = sys.stdin.read()
else:
data = file(filename).read()
except IOError:
print 'Cannot read file: %s' % filename
return 1
try:
data = data.decode(fencoding)
except LookupError:
print 'There is no encoding named "%s".' % fencoding
return 1
except UnicodeDecodeError:
print 'Unicode decode error!'
return 1
if skipblanklines:
data = data.lstrip('\r\n')
code = AheuiCode(data)
io = AheuiIO(ioencoding)
interpreter = AheuiInterpreter(code, io)
return interpreter.execute()
if __name__ == '__main__':
sys.exit(main(sys.argv))