~crc_/retro-napia

retro-napia/napia.py -rw-r--r-- 12.0 KiB
2022e8a8 — crc factor out io; stubs for core-related instructions added 20 days ago
                                                                                
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
# ==============================================================
#
# crc & aec's          _
#    _ __   __ _ _ __ (_) __ _
#   | '_ \ / _` | '_ \| |/ _` | a multicore virtual computer
#   | | | | (_| | |_) | | (_| | 64kw RAM, 32-bit, Dual Stack
#   |_| |_|\__,_| .__/|_|\__,_|
#               |_|
#
# ==============================================================

import sys, time


DEBUG = False
BLOCK_PATH = 'napia.blocks'
IMAGE_PATH = 'napia.rom'

def int_32(val):
  if not -0x80000000 <= val <= 0x7fffffff:
    val = (val + 0x80000000) % 0x100000000 - 0x80000000
  return val


def read_block(memory, data):
  buffer = data.pop()
  block = data.pop()
  k=[]
  with open(BLOCK_PATH, 'rb') as f:
    f.seek(4096 * block)
    for i in range(1024):
      a,b,c,d=list(f.read(4))
      k.append(a+(b<<8)+(c<<16)+(d<<24))
  memory[buffer:buffer+1024] = k
  del k


def write_block(memory, data):
    buffer = data.pop()
    block = data.pop()
    with open(BLOCK_PATH, 'wb') as f:
      f.seek(4096 * block, 0)
      for i in memory[buffer:buffer + 1024]:
        f.write((i>>0)&0xff)
        f.write((i>>8)&0xff)
        f.write((i>>16)&0xff)
        f.write((i>>24)&0xff)


def save_image(memory):
  with open(IMAGE_PATH, 'wb') as f:
    for i in memory:
      f.write(bytearray([((i>>0)&0xff),((i>>8)&0xff), ((i>>16)&0xff),  ((i>>24)&0xff)]))

def read_image(memory):
  with open(IMAGE_PATH, 'rb') as f:
    for i in range(65536):
      a,b,c,d=list(f.read(4))
      memory[i] = a+(b<<8)+(c<<16)+(d<<24)


#for memhooks, run is executed first
#also. memhook gives full access to the napia instance
class io_base():
  def __init__(self):
    self.register = []
    self.memhook_query=None
    self.needs=[0,0]
    self.setup()
  def setup(self):
    pass
  def run(self, op, data, address):
    return data
  def memhook(self, napia):
    pass

class io_output(io_base):
  def setup(self):
    self.register = [0]
    self.needs = [1,0]
  def run(self,op,data,address):
    print(chr(data.pop()),end='')
    

class io_input(io_base):
  def setup(self):
    self.register = [1]
    self.needs = [0,1]
    self.grape = []
  def run(self,op,data,address):
    if not len(self.grape):
      self.grape = list(input())+['\n']
    l=self.grape[0]
    self.grape = self.grape[1:]
    data.push(ord(l))


class io_blocks(io_base):
  def setup(self):
    self.register = [2, 3]
    self.needs = [2, 0]
    self.memhook_query = True
    self.action = None
  def run(self,op,data,address):
    self.action = op,data
  def memhook(self, napia):
    if self.action[0] == 2:
      read_block(napia.memory,self.action[1])
    if self.action[0] == 3:
      write_block(napia.memory,self.action[1])
  
    
class io_napia_image(io_base):
  def setup(self):
    self.register = [4, 5]
    self.memhook_query=True
    self.op=0
  def run(self,op,data,address):
    self.op=op
  def memhook(self,napia):
    if self.op == 4:
      save_image(napia.memory)
    if self.op == 5:
      napia.reset()
      read_image(napia.memory)


class io_napia_state(io_base):
  def setup(self):
    self.register = [6, 7]
    self.needs = [0,2]
  def run(self, op, data, address):
    if op == 6:
      sys.exit()
    if op == 7:
      data.push(data.pointer)
      data.push(address.pointer)


class io_time(io_base):
  def setup(self):
    self.register = [8]
    self.needs = [0,1]
  def run(self, op, data, address):
    data.push(round(time.time()))





class stack(list):
  def __init__(self, size):
    self += [0]*size
    self.pointer = 0
  def push(self, a):
    self.pointer += 1
    self[self.pointer] = int_32(a)
  def pop(self):
    r = self[self.pointer]
    self[self.pointer] = 0
    self.pointer -= 1
    return r
  def reset(self):
    for i in range(len(self)):
      self[i]=0
    self.pointer = 0




class core():
  def __init__(self):
    self.registers = [0]*24
    self.data = stack(32)
    self.address = stack(256)
    self.ip = 0
  def reset(self):
    del self.registers, self.data, self.address, self.ip
    self.registers = [0]*24
    self.data = stack(32)
    self.address = stack(256)
    self.ip = 0


class napia():
  def __init__(self, extra_io=[]):
    self.cores = []
    for i in range(8):
      self.cores.append(core())
    self.active = [0]*8
    self.active[0]=1
    self.current_core = 0
    self.interrupt_core = core()
    self.solo_core = core()
    self.memory = stack(65536)
    self.ivt = [0]*129
    self.interrupts_active=True
    self.io_devices=[io_output(),io_input(), io_blocks(),io_napia_image(),io_napia_state(),io_time()]+extra_io
  def current(self):
    if self.current_core>=0:
      return self.cores[self.current_core]
    elif self.current_core==-1:
      return self.interrupt_core
    elif self.current_core==-2:
      return self.solo_core
    raise Exception(self.current_core)
  def patch_memory(self, stuff={}):
    for i in stuff:
      l=i
      for o in stuff[i]:
        self.memory[l] = o
        l += 1
  
  def reset(self):
    id=0
    for i in self.cores:
      i.reset()
      self.active[id]=0
    self.active[0]=1
    self.current_core = 0
    self.current().ip-=1 # compensate_for_the_ip_jump
    self.memory.reset()
    self.ivt = [0]*129
    self.interrupts_active=True
    self.io_devices[1].grape = []
  
  
  def push(self,a):
    self.current().data.push(a)
  def pop(self):
    return self.current().data.pop()
  
  def stack_check(self, t,g, diff):
    if self.interrupts_active:
      p=self.current().data.pointer
      if p<t or p<0:
        self.current().data.reset()
        self.interrupt(1)
        return True
      elif ((p+g)-t)>31 or p>31:
        self.current().data.reset()
        self.interrupt(2)
        return True
      elif self.current().address.pointer+diff<0:
        self.interrupt(3)
        return True
      elif self.current().address.pointer+diff>255:
        self.interrupt(4)
        return True
      else:
        return False
    else:
      return False
        
  
  def interrupt(self, i):
    if self.interrupts_active:
      if self.ivt[i]:
        self.interrupts_active=0
        prev = self.current_core
        self.current_core = -1
        self.current().reset()
        self.current().ip=self.ivt[i]
        self.current().address.push(0)
        while self.current().address.pointer:
          if self.current().ip>65535:
            raise
          bundle=self.memory[self.current().ip]
          self.process_bundle(bundle)
          self.current().ip += 1
        self.current_core = prev
        self.interrupts_active=1
  
  def no(self):#0
    pass
  def li(self):#1
    self.current().ip+=1
    self.push(self.memory[self.current().ip])
  def du(self):#2
    m=self.pop()
    self.push(m)
    self.push(m)
  def dr(self):#3
    self.current().data.pop()
  def sw(self):#4
    a=self.pop()
    b=self.pop()
    self.push(a)
    self.push(b)
  def pu(self):#5
    self.current().address.push(self.pop())
  def po(self):#6
    self.push(self.current().address.pop())
  def ju(self):#7
    self.current().ip = self.pop()-1
  def ca(self):#8
    self.current().address.push(self.current().ip)
    self.current().ip = self.pop()-1
  def cc(self):#9
    a = self.pop()
    b = self.pop()
    if b == 0:
      pass
    else:
      self.current().address.push(self.current().ip)
      self.current().ip = a-1
  def cj(self):#10
    a = self.pop()
    b = self.pop()
    if b == 0:
      pass
    else:
      self.current().ip = a-1
  def re(self):#11
    self.current().ip = self.current().address.pop()
  def eq(self):#12
    a=self.pop()
    b=self.pop()
    self.push(-(b==a))
  def ne(self):#13
    a=self.pop()
    b=self.pop()
    self.push(-(b!=a))
  def lt(self):#14
    a=self.pop()
    b=self.pop()
    self.push(-(b<a))
  def gt(self):#15
    a=self.pop()
    b=self.pop()
    self.push(-(b>a))
  def fe(self):#16
    self.push(self.memory[self.pop()])
  def st(self):#17
    a = self.pop()
    v = self.pop()
    self.memory[a]=v
  def ad(self):#18
    a=self.pop()
    b=self.pop()
    self.push(b+a)
  def su(self):#19
    a=self.pop()
    b=self.pop()
    self.push(b-a)
  def mu(self):#20
    a=self.pop()
    b=self.pop()
    self.push(b*a)
  def di(self):#21
    a=self.pop()
    b=self.pop()
    if a != 0:
      self.push(b%a)
      self.push(b//a)
    else:
      self.interrupt(6)
  def an(self):#22
    a=self.pop()
    b=self.pop()
    self.push(b & a)
  def OR(self):#23
    a=self.pop()
    b=self.pop()
    self.push(b | a)
  def xo(self):#24
    a=self.pop()
    b=self.pop()
    self.push(b ^ a)
  def sl(self):#25
    a=self.pop()
    b=self.pop()
    self.push(b<<a)
  def sr(self):#26
    a=self.pop()
    b=self.pop()
    self.push(b>>a)
  def cp(self):#27
    l=self.pop()
    d=self.pop()
    s=self.pop()
    self.push(-(self.memory[d:d+l]==self.memory[s:s+l]))
  def cy(self):#28
    l=self.pop()
    d=self.pop()
    s=self.pop()
    self.memory[d:d+l]=self.memory[s:s+l]
  def io(self):#29
    op = self.pop()
    for i in self.io_devices:
      if op in i.register:
        if not self.stack_check(i.needs[0],i.needs[1],0):
          i.run(op,self.current().data,self.current().address)
          if i.memhook_query:
            i.memhook(self)
  def ic(self):#30
    a=self.pop()
    self.active[a] = 0
    self.cores[a].reset()
  def ac(self):#31
    a=self.pop()
    self.active[a]=1
    self.cores[a].ip=self.pop()
  def pc(self):#32
    self.active[self.pop()]=0
  def sc(self):#33
    self.active[self.pop()]=1
  def rr(self):#34
    k=self.pop()
    self.push(self.current().registers[k])
  def wr(self):#35
    a = self.pop()
    b = self.pop()
    self.current().registers[a]=b
  def mx(self):#36
    to=self.pop()
    prev=self.current_core
    o=self.current().data
    self.current_core = -2
    self.current().data=o
    self.current().reset()
    self.current().ip=to
    self.current().address.push(0)
    while self.current().address.pointer:
      if self.current().ip>65535:
        raise
      bundle=self.memory[self.current().ip]
      self.process_bundle(bundle)
      self.current().ip += 1
    n=self.current().data
    self.current_core=prev
    self.current().data=n
  def sv(self):#37
    a=self.pop()
    b=self.pop()
    self.ivt[a] = b
  def ti(self):#38
    self.interrupt(self.pop())
  def si(self):#39
    self.interrupts_active=True
  def hi(self):#40
    self.interrupts_active=False
  
  
  def process_instruction(self, instr):
    #  nolidudrswpu pojucacccj reeqneltgtfestadsumudianorxoslsrcpcyioicacpcscrrwrmxsvtisihi
    t=[0,0,1,1,2,1, 0,1,1,2,2, 0,2,2,2,2,1,2,2,2,2,2,2,2,2,2,2,3,3,1,1,2,1,1,1,2,1,2,1,0,0]
    g=[0,1,2,0,2,0, 1,0,0,0,0, 0,1,1,1,1,1,0,1,1,1,2,1,1,1,1,1,1,0,0,0,0,0,0,1,0,0,0,0,0,0]
    a=[0,0,0,0,0,1,-1,0,1,0,1,-1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    ips = [
      self.no, self.li, self.du, self.dr, self.sw, self.pu, 
      self.po, self.ju, self.ca, self.cc, self.cj, self.re, 
      self.eq, self.ne, self.lt, self.gt, self.fe, self.st, 
      self.ad, self.su, self.mu, self.di, self.an, self.OR, 
      self.xo, self.sl, self.sr, self.cp, self.cy, self.io,
      self.ic, self.ac, self.pc, self.sc, self.rr, self.wr, 
      self.mx, self.sv, self.ti, self.si, self.hi]
    if instr:
      if DEBUG:
        print(f'  instr:{str(ips[instr])[20:22]} ip:{self.current().ip} sp:{self.current().data.pointer}/{self.current().address.pointer} tos:{self.current().data[self.current().data.pointer]} core:{self.current_core}')
      if not self.stack_check(t[instr],g[instr],a[instr]):
        ips[instr]()
  
  def process_bundle(self, bundle):
    self.process_instruction((bundle>>0)&0xff)
    self.process_instruction((bundle>>8)&0xff)
    self.process_instruction((bundle>>16)&0xff)
    self.process_instruction((bundle>>24)&0xff)
    self.interrupt(0)
  
  def run(self):
    while 1:
      if self.current().ip>65535:
        return
      bundle=self.memory[self.current().ip]
      self.process_bundle(bundle)
      self.current().ip+=1
      self.current_core+=1
      if self.current_core >= len(self.cores):
        self.current_core=0
      while not self.active[self.current_core]:
        self.current_core+=1
        if self.current_core >= len(self.cores):
          self.current_core=0
      
  

a=napia()
read_image(a.memory)
a.run()