2012年5月4日金曜日

bf処理系、pythonでevalバージョン

このエントリーをブックマークに追加 このエントリーを含むはてなブックマーク
標記のバージョン。だいぶさっぱりしている。bfからpythonへのトランスレータなんですよね。 どの言語で書いてもトランスレータであるほうが楽。もっともbfからCとかだとgccが必要ですが。
import sys


source = sys.stdin.read()  

data = [0 for i in range(30000)]
L = {     
  "data" : data,
  "stdout" : sys.stdout,
  "idx" :0,
}

G ={}

mapping = {
  '>':  "idx+=1",
  '<':  "idx-=1",
  '+':  "data[idx]+=1",
  '-':  "data[idx]-=1",
  '.':  "stdout.write(chr(data[idx]))",
  ',':  " #not implemented ",
  '[':  "while data[idx]:",
  ']':  "False",
}


py = []
indent = ''
for c in source:
  o = mapping.get(c, '');
  py.append(indent + o + ' # ' + c +'\n')
  if c=='[':
    indent += '  '
  elif c == ']':
    indent = indent[:-2]
  else:
    pass
  #if c=='[':
  #  py.append(indent + 'print idx' + '\n')

p = ''.join(py)

#print len(data)
#for line, k in enumerate(p.split('\n')):
#  print '%4d: %s'%(line, k)
exec p in G, L
    

0 件のコメント: