- 论坛徽章:
- 0
|
我发个Python的版本 基本上是翻译了楼主的C代码到python
#!/usr/bin/env python
import sys
class VM():
def __init__(self):
self.stack=[0 for i in range(256)]
self.stackLen=0;
self.pool=[ 0 for i in range(4096)]
self.pointer=0
self.currentInstructIndex=0
self.codeLen=0
self.code=''
def run(self,reader):
self.code=reader.read()
print "Run:",self.code
self.codeLen=len(self.code)
while self.currentInstructIndex<self.codeLen:
self.bfInterpreter(self.code[self.currentInstructIndex])
self.currentInstructIndex+=1
def dump(self,size=10):
pool=self.pool[:size]
stack=self.stack[:size]
print '============================================================================'
print 'pool',pool
print 'stack',stack
print 'CurrentInstructIndex:%d,%s'%(self.currentInstructIndex,self.code[self.currentInstructIndex])
def bfInterpreter(self,instruct):
if instruct=='+':
self.pool[self.pointer]+=1
elif instruct=='-':
self.pool[self.pointer]-=1
elif instruct=='>':
self.pointer+=1
elif instruct=='<':
self.pointer-=1
elif instruct=='.':
try:
sys.stdout.write(chr(self.pool[self.pointer]))
except:
print r"can't print:",self.pool[self.pointer]
elif instruct==',':
self.pool[self.pointer]=ord(sys.stdin.read())
elif instruct=='[':
if self.pool[self.pointer]!=0:
try:
self.stack[self.stackLen]=self.currentInstructIndex
self.stackLen+=1
except:
print self.stackLen
raise IndexError
else:
j=0;k=0
for k in range(self.currentInstructIndex,self.codeLen):
if self.code[k]=='[':
j+=1
if self.code[k]==']':
j-=1
if j==0:break
if j==0:
self.currentInstructIndex=k
else:
print 'Error'
return None
elif instruct==']':
self.stackLen-=1
self.currentInstructIndex=self.stack[self.stackLen]-1
if __name__=='__main__':
if len(sys.argv)<=1:
import StringIO
sample='++++++++++[>+++++++>++++++++++>+++>+\
<<<<-]>++.>+.+++++++..+++.>++.<<++++++++++++++\
+.>.+++.------.--------.>+.>.'
reader=StringIO.StringIO(sample)
else:
print 'Run file',sys.argv[1]
reader=open(sys.argv[1])
vm=VM()
vm.run(reader) |
[ 本帖最后由 zarra 于 2008-6-5 12:55 编辑 ] |
|