Pythonからの単純なインタプリタを構築します.01
6587 ワード
やあ!
このブログシリーズでは、プログラミング言語、インタプリタ、パーサー、コンパイラ、および仮想マシンを構築しようとする私の試みにおいて、私が気に入っているかどうかはわかりません.どのような質問のための'なぜ'答えは常に'理由はないですかを除くなぜPython?Pythonは、言語自体との戦いよりも問題に焦点を当てることができます. なぜ錆がないのか?さびは、それに対して戦っている間、脱毛を引き起こしています. なぜCではないのか?それはあなたの手で何度も爆発します.あなたはあなたの手を失う. 私が書くコードが慣用的でないならば、あなたのためにtastefullを無視してください.
さあ始めましょう.
このブログシリーズでは、プログラミング言語、インタプリタ、パーサー、コンパイラ、および仮想マシンを構築しようとする私の試みにおいて、私が気に入っているかどうかはわかりません.どのような質問のための'なぜ'答えは常に'理由はないですかを除く
さあ始めましょう.
class Interpreter:
def __init__(self):
pass
def run(self,code):
for xs in code:
self.eval(xs)
# This is our magic function. It evauates xs parameter
# according to its first element and calls appropriate
# member function and passes the parameter to that function.
# If xs is not a list then returns xs itself:
def eval(self,xs):
if isinstance(xs,list):
return self.__getattribute__(xs[0])(xs)
return xs
# Our first function (or opcode) is Print. If last item
# is a comma it doesn't print newline:
def Print(self,xs):
if len(xs)==1:
print()
return
l=len(xs)-1
for i,x in enumerate(xs[1:]):
e=self.eval(x)
if i<l-1:
print(e,end="")
else:
if e!=",":
print(e)
else:
print(e,end="")
# This is AST (Abstract Syntax Tree) generated by
# parser. Consisting of recursive lists
# (No, not lisp :P )
code=[
["Print","Hello World!","Sky is blue"],
["Print",1,","],
["Print",2,","],
["Print",3],
["Print","a"],
["Print","b"],
["Print"],
["Print","c"],
]
interpreter=Interpreter()
interpreter.run(code)
出力はHello World!Sky is blue
1,2,3
a
b
c
フォローミーオンReference
この問題について(Pythonからの単純なインタプリタを構築します.01), 我々は、より多くの情報をここで見つけました https://dev.to/smadev/lets-build-a-simple-interpreter-from-scratch-in-python-pt-01-2ejfテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol