手机版
你好,游客 登录 注册
背景:
阅读新闻

用Python写语言的解释器

[日期:2012-05-27] 来源:Linux社区  作者:zzljlu [字体:大 中 小]
运行演示——从文件获得程序
还是前面那个y = x + x2的程序,首先我需要为两个输入参数(x, x2)给定值,如果没有为其赋值,那么它们的值默认为0。另外,我们还可以查看程序的内部表示结构,以及简单调试(就查看其他环境变量的值)。其演示结果如下:
  1. ======================================================  
  2. *Metafor 1.0, Welecome to Metafor shell environment. *  
  3. *Author: Zhu zhaolong(zzljlu@gmail.com)              *  
  4. ======================================================  
  5.   
  6. Metafor> 2 3  
  7. 5  
  8. Metafor> 5 6  
  9. 11  
  10. Metafor> code  
  11. [['setf', 'y', 'x'],  
  12.  ['labeled_exp', 'B', ['con_goto', 'A', 'x2']],  
  13.  ['goto', 'E'],  
  14.  ['labeled_exp', 'A', ['dec', 'x2']],  
  15.  ['inc', 'y'],  
  16.  ['goto', 'B']]  
  17. >>> ========================================== RESTART ==========================================  
  18. >>>   
  19. ======================================================  
  20. *Metafor 1.0, Welecome to Metafor shell environment. *  
  21. *Author: Zhu zhaolong(zzljlu@gmail.com)              *  
  22. ======================================================  
  23.   
  24. Metafor> 234 5  
  25. 239  
  26. Metafor> debug  
  27. debug> x  
  28. 234  
  29. debug> x2  
  30. 0  
  31. debug> y  
  32. 239  
  33. debug> exit  
  34. >>>   
运行演示——从终端用户直接输入原语言程序
我写了一个简单的repl交互环境,这样我们可以方便的测试简单的原语言程序,例如下面给出了一个y =  x + 1的程序,示例如下:
  1. >>> repl()  
  2. ======================================================  
  3. *Metafor 1.0, Welecome to Metafor shell environment. *  
  4. *Author: Zhu zhaolong(zzljlu@gmail.com)              *  
  5. ======================================================  
  6.   
  7.   
  8.   
  9. Input your program:  
  10. x = x + 1  
  11. y = x  
  12.   
  13. inputs> 5  
  14. =>6  
  15.   
  16.   
  17. Input your program:  
全部代码
在这里我贴出所有Python代码:
  1. """ Metafor: meta fortran, is a small language used in 
  2. "Computabilit and Complexity" course in Jilin University. 
  3.  
  4. @Author: Zhu Zhaolong(zzljlu@gmail.com) 
  5. @Date: 2011.12.25 
  6.  
  7.  
  8. 1. Metafor has five instructions: 
  9.  
  10. name instruction description 
  11.  
  12. inc: x = x + 1, Increase by 1 the value of the variable x. 
  13. dec: x = x - 1, If the value of x is 0, leave it unchanged; otherwise 
  14.                 decrease by 1 the value of x. 
  15. con_goto: TO A IF x != 0, If the value of x is nonzero, perform the instruction 
  16.                           with the label A next; otherwise proceed to the next 
  17.                           instruction in the list. 
  18. goto: TO A, Perform the instruction with the label A next. 
  19. setf: y = x, Change the value variable y to the value of variable x. 
  20.  
  21. 2. Some specification: 
  22.  
  23. (1) Input variables are represented as: 
  24. x1, x2, x3, ... 
  25.  
  26. (2) Local variables are represented as: 
  27. z1, z2, z3, ... 
  28.  
  29. (3) Output variable is represented as: 
  30. y 
  31.  
  32. note: the num 1 is often omitted(i.e., x stands for x1 and z stands 
  33. for z1). 
  34.  
  35. 3. Labeled instructions: 
  36.  
  37. Instructions may or may not have labels. When an instruction is labeled, 
  38. the label is written to its left in square brackets. For example, 
  39.  
  40. [B] Z = Z - l 
  41.  
  42. 4. A smaple program: 
  43.  
  44. "Program to compute y = x1+ x2" 
  45.  
  46.     y = x1 
  47. [B] TO A IF x2 != 0 
  48.     TO E 
  49. [A] x2 = x2 - 1 
  50.     y = y + 1 
  51.     TO B 
  52.  
  53. 4. For more information, please refer to 《可计算性与计算复杂性》, 
  54. 周长林、李占山著. 
  55.  
  56. """  
  57. ###========================================================   
  58. import re  
  59. from pprint import pprint  
  60.   
  61. ###===========================parse========================   
  62. def parse(program):  
  63.     return [read(e) for e in program]  
  64.   
  65. def read(s):  
  66.     """Read a metafor insctruction from a string. and change 
  67.     it to internal represtation."""  
  68.     return read_from(tokenize(s))  
  69.   
  70. def tokenize(s):  
  71.     "Convert a string into alist of tokens."  
  72.     return s.split()  
  73.   
  74. def read_from(tokens):  
  75.     "Read an exp from a sequence of tokens."  
  76.     if len(tokens) == 0:  
  77.         raise SyntaxError("uncexpected EOF while reading.")  
  78.   
  79.     if is_setf(tokens):  
  80.         return make_setf(tokens[0], tokens[2])  
  81.     elif is_inc(tokens):  
  82.         return make_inc(tokens[0])  
  83.     elif is_dec(tokens):  
  84.         return make_dec(tokens[0])  
  85.     elif is_goto(tokens):  
  86.         return make_goto(tokens[1])  
  87.     elif is_con_goto(tokens):  
  88.         return make_con_goto(tokens[1], tokens[3])  
  89.     elif is_labeled_exp(tokens):  
  90.         return make_labeled_exp(get_label(tokens[0]), read_from(tokens[1:]))  
  91.     else:  
  92.         raise SyntaxError("unexpected instructions: %s" % " ".join(tokens))  
  93.   
  94.   
  95. #=======================================================   
  96.   
  97. def is_variable(token):  
  98.     if token.startswith("x") or \  
  99.        token.startswith("z") or \  
  100.        token == "y":  
  101.         return True  
  102.     else:  
  103.         return False  
  104.   
  105. def get_label(token):  
  106.     "Token is like [A1]. we want get A1."  
  107.     return token.replace('[', '').replace(']', '')  
  108.   
  109. ## setf       
  110. def is_setf(tokens):  
  111.     if tokens[1] == "=" and len(tokens) == 3:  
  112.         if is_variable(tokens[0]) and is_variable(tokens[2]):  
  113.             return True  
  114.         else:  
  115.             raise SyntaxError("unexpected setf instruction: %s" % " ".join(tokens))  
  116.     else:  
  117.         return False  
  118.   
  119. def make_setf(des_var, src_var):  
  120.     return ["setf", des_var, src_var]  
  121.   
  122. ## inc    
  123. def is_inc(tokens):  
  124.     if len(tokens) == 5 and tokens[1] == "=" \  
  125.        and tokens[3] == "+" and tokens[4] == "1":  
  126.         if tokens[0] == tokens[2] and is_variable(tokens[0]):  
  127.             return True  
  128.         else:  
  129.             raise SyntaxError("unexpected inc instruction: %s" % " ".join(tokens))  
  130.     else:  
  131.         return False  
  132. def make_inc(var):  
  133.     return ["inc", var]  
  134.   
  135. ## dec   
  136. def is_dec(tokens):  
  137.     if len(tokens) == 5 and tokens[1] == "=" \  
  138.        and tokens[3] == "-" and tokens[4] == "1":  
  139.         if tokens[0] == tokens[2] and is_variable(tokens[0]):  
  140.             return True  
  141.         else:  
  142.             raise SyntaxError("unexpected dec instruction: %s" % " ".join(tokens))  
  143.     else:  
  144.         return False  
  145. def make_dec(var):  
  146.     return ["dec", var]  
  147.   
  148. ## goto   
  149. def is_goto(tokens):  
  150.     if len(tokens) == 2 and tokens[0] == "TO":  
  151.         return True  
  152.     else:  
  153.         return False  
  154.   
  155. def make_goto(lable):  
  156.     return ["goto", lable]  
  157.   
  158. ## con_goto   
  159. def is_con_goto(tokens):  
  160.     if len(tokens) == 6 and tokens[0] == "TO" \  
  161.        and tokens[2] == "IF" and is_variable(tokens[3]) \  
  162.        and tokens[4] == "!=" and tokens[5] == "0":  
  163.         return True  
  164.     else:  
  165.         return False  
  166.   
  167. def make_con_goto(lable, var):  
  168.     return ["con_goto", lable, var]  
  169.   
  170. ## labeled exp   
  171. def is_labeled_exp(tokens):  
  172.     return tokens[0].startswith('[')  
  173.   
  174. def make_labeled_exp(label, exp):  
  175.     return ["labeled_exp", label, exp]  
  176.   
  177.   
  178. ###==========================CodeSeg======================   
  179.   
  180. def is_label(s):  
  181.     return s == "labeled_exp"  
  182.           
  183. class CodeSeg:  
  184.     """ To store internal instructions (exps). 
  185.     N : the number of instructions. 
  186.     exps: the list of instructions. 
  187.     label_2_exps: a dict of {'label': num} pairs."""  
  188.       
  189.     def __init__(self, exps):  
  190.         self.N = len(exps)  
  191.         self.exps = []  
  192.         self.label_2_exp={}  
  193.         for (i, e) in enumerate(exps):  
  194.             if is_label(e[0]):  
  195.                 (_, label, exp) = e  
  196.                 self.label_2_exp[label] = i  
  197.                 self.exps.append(exp)  
  198.             else:  
  199.                 self.exps.append(e)  
  200.   
  201.     def get_instruction_num(self, label):  
  202.         "Return instruction num with the label."  
  203.         if label in self.label_2_exp.keys():  
  204.             return self.label_2_exp[label]  
  205.         # IF there is no instruction with that label,   
  206.         # return a instruction num that doesn't exit.   
  207.         else:   
  208.             return self.N  
  209.   
  210.     def get_instruction(self, pc):  
  211.         return self.exps[pc]  
  212.       
  213.           
  214. ###=============================Env======================   
  215.   
  216. class Env():  
  217.     "An enviromnet: a dict of {'var': val} paris, var's default value is 0."  
  218.     def __init__(self, args):  
  219.         self.pairs = {}  
  220.         for (i, v) in enumerate(args):  
  221.             if i == 0:  
  222.                 self.pairs['x'] = int(v)  
  223.             else:  
  224.                 self.pairs['x'+str(i+1)] = int(v)  
  225.   
  226.     def get_v(self, var):  
  227.         if var in self.pairs.keys():  
  228.             return self.pairs[var]  
  229.         else:  
  230.             return 0  
  231.           
  232.     def set_v(self, var, value):  
  233.         self.pairs[var] = value  
  234.   
  235. ###=========================mainloop=======================   
  236.   
  237. def mainloop(codeseg, env):  
  238.     "pc refers to the current instruction."   
  239.     pc = 0  
  240.     while pc < codeseg.N:  
  241.         e = codeseg.get_instruction(pc)  
  242.         if e[0] == 'inc':  
  243.             (_, v) = e  
  244.             env.set_v(v, env.get_v(v) + 1)  
  245.             pc += 1  
  246.         elif e[0] == 'dec':  
  247.             (_, v) = e  
  248.             env.set_v(v, max(env.get_v(v) - 1, 0))  
  249.             pc += 1  
  250.         elif e[0] == 'setf':  
  251.             (_, x, y) = e  
  252.             env.set_v(x, env.get_v(y))  
  253.             pc += 1  
  254.         elif e[0] == 'goto':  
  255.             (_, label) = e  
  256.             pc = codeseg.get_instruction_num(label)  
  257.         elif e[0] == "con_goto":  
  258.             (_, label, var) = e  
  259.             val = env.get_v(var)  
  260.             if val != 0:  
  261.                 pc = codeseg.get_instruction_num(label)  
  262.             else:  
  263.                 pc += 1  
  264.         else:  
  265.             raise SyntaxError("unexpected instructions: %s" % " ".join(e))  
  266.     return env.get_v('y')  
  267.   
  268. ###========================repl================================   
  269.   
  270. def repl(input_prompt='inputs> '):  
  271.     "A prompt-read-eval-print loop."  
  272.     print_info()  
  273.     while True:  
  274.         program = get_prog_from_shell()  
  275.         if program == []:  
  276.             return "Return successfully!"  
  277.         codes = CodeSeg(parse(program))  
  278.         inputs = raw_input(input_prompt)  
  279.         env = Env(inputs.split())  
  280.         print("=>" + str(mainloop(codes, env)))  
  281.               
  282.   
  283. def get_prog_from_shell():  
  284.     program = []  
  285.     exp = raw_input("\n\nInput your program:\n")  
  286.     while exp:  
  287.         program.append(exp)  
  288.         exp = raw_input()  
  289.     return program  
  290.   
  291. def print_info():  
  292.     print("======================================================\n"  
  293.           "*Metafor 1.0, Welecome to Metafor shell environment. *\n"  
  294.           "*Author: Zhu zhaolong(zzljlu@gmail.com)              *\n"  
  295.           "======================================================\n")  
  296.   
  297. ###========================run=============================   
  298.   
  299. def run(filepath, prompt='Metafor> '):  
  300.     "This function can run Metafor program from file."  
  301.     print_info()  
  302.     program = get_prog_from_file(filepath)  
  303.     parsed_prog = parse(program)  
  304.     codes = CodeSeg(parsed_prog)  
  305.   
  306.     inputs = raw_input(prompt)  
  307.     while True:  
  308.         env = Env(inputs.split())  
  309.         print(mainloop(codes, env))  
  310.           
  311.         inputs = raw_input(prompt)  
  312.         if inputs == "exit":  
  313.             return "Return successfully!"  
  314.         if inputs == "debug":  
  315.             while True:  
  316.                 var = raw_input('debug> ')  
  317.                 if var == "exit":  
  318.                     return None  
  319.                 print(env.get_v(var))  
  320.         if inputs == "code":  
  321.             pprint(parsed_prog)  
  322.             return None  
  323.   
  324. def get_prog_from_file(filepath):  
  325.     f = open(filepath, "r")  
  326.     program = f.readlines()  
  327.     f.close()  
  328.   
  329.     return program  
  330.   
  331. ###===========================test==================================   
  332.   
  333. # y = x + x2   
  334. test_file_1 = "metafor_test.mf"  
  335. # y = 2 * x   
  336. test_file_2 = "metafor_test2.mf"  
  337.   
  338. if __name__ == "__main__":   
  339.     run(test_file_1)  
  340.    
  341.         
linux
相关资讯       Python教程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款