大数跨境

构建一个简单的编译器系类教程.Part 2

构建一个简单的编译器系类教程.Part 2 Python程序员
2016-02-23
0
导读:Python部落组织翻译,禁止转载,欢迎转发在《The 5 Elements of Effective Th


Python部落组织翻译,禁止转载,欢迎转发


在《The 5 Elements of Effective Thinking》一书中,作者 Burger 和 Starbird 分享了一个他们观察Tony Plog(一位国际著名的小号演奏家)的故事,指导一个大师班完成小号演奏。 学生们首先演奏复杂的乐句,而且演奏的非常棒。然后他们被要求演奏非常基本的、简单的音节。 但效果很不理想,这些音节相较于之前的复杂乐句听起来是那么幼稚。然后,老师也演奏了一遍和刚才同样的音节,但听起来截然不同,一丝也不感觉幼稚。 前后的反差,令人震撼。Tony 解释道,对单音节演奏的充分掌握,能够使你更好的掌控复杂曲目的演奏。教训很明确 -  取得精湛技巧不能忽视对嘴简单、基本思想的把我。
       

故事中的教训显然不仅适用于音乐领域,也适用于软件开发。这个故事很好的警醒着我们,不要忽视复杂工作背后简单的、基本思想,即使有时感觉关注那些是退步的表现。精通一个工具或框架固然重要,更重要的是掌握框架背后的原理。拉尔夫·瓦尔多·爱默生说过:


“如果你只学习方法,你就只是单纯的会这个方法。但是如果你学习背后的原则思想,你可以设计你自己的方法。”


基于这一点,让我们再次深入研究解释器和编译器。
今天我将展现给你一个基于 Part 1 计算器的新版本,它有如下特性:
1. 处理输入字符串中的空白字符
2. 处理输入的多位整数
3. 处理减法运算


这是新版计算器的源码,可以完成上述三个新功能:


# Token types
# EOF (end-of-file) token is used to indicate that
# there is no more input left for lexical analysis
INTEGER, PLUS, MINUS, EOF = 'INTEGER', 'PLUS', 'MINUS', 'EOF'
 
 
class Token(object):
    def __init__(self, type, value):
        # token type: INTEGER, PLUS, MINUS, or EOF
        self.type = type
        # token value: non-negative integer value, '+', '-', or None
        self.value = value
 
    def __str__(self):
        """String representation of the class instance.
 
        Examples:
            Token(INTEGER, 3)
            Token(PLUS '+')
        """
        return 'Token({type}, {value})'.format(
            type=self.type,
            value=repr(self.value)
        )
 
    def __repr__(self):
        return self.__str__()
 
 
class Interpreter(object):
    def __init__(self, text):
        # client string input, e.g. "3 + 5", "12 - 5", etc
        self.text = text
        # self.pos is an index into self.text
        self.pos = 0
        # current token instance
        self.current_token = None
        self.current_char = self.text[self.pos]
 
    def error(self):
        raise Exception('Error parsing input')
 
    def advance(self):
        """Advance the 'pos' pointer and set the 'current_char' variable."""
        self.pos += 1
        if self.pos > len(self.text) - 1:
            self.current_char = None  # Indicates end of input
        else:
            self.current_char = self.text[self.pos]
 
    def skip_whitespace(self):
        while self.current_char is not None and self.current_char.isspace():
            self.advance()
 
    def integer(self):
        """Return a (multidigit) integer consumed from the input."""
        result = ''
        while self.current_char is not None and self.current_char.isdigit():
            result += self.current_char
            self.advance()
        return int(result)
 
    def get_next_token(self):
        """Lexical analyzer (also known as scanner or tokenizer)
 
        This method is responsible for breaking a sentence
        apart into tokens.
        """
        while self.current_char is not None:
 
            if self.current_char.isspace():
                self.skip_whitespace()
                continue
 
            if self.current_char.isdigit():
                return Token(INTEGER, self.integer())
 
            if self.current_char == '+':
                self.advance()
                return Token(PLUS, '+')
 
            if self.current_char == '-':
                self.advance()
                return Token(MINUS, '-')
 
            self.error()
 
        return Token(EOF, None)
 
    def eat(self, token_type):
        # compare the current token type with the passed token
        # type and if they match then "eat" the current token
        # and assign the next token to the self.current_token,
        # otherwise raise an exception.
        if self.current_token.type == token_type:
            self.current_token = self.get_next_token()
        else:
            self.error()
 
    def expr(self):
        """Parser / Interpreter
 
        expr -> INTEGER PLUS INTEGER
        expr -> INTEGER MINUS INTEGER
        """
        # set current token to the first token taken from the input
        self.current_token = self.get_next_token()
 
        # we expect the current token to be an integer
        left = self.current_token
        self.eat(INTEGER)
 
        # we expect the current token to be either a '+' or '-'
        op = self.current_token
        if op.type == PLUS:
            self.eat(PLUS)
        else:
            self.eat(MINUS)
 
        # we expect the current token to be an integer
        right = self.current_token
        self.eat(INTEGER)
        # after the above call the self.current_token is set to
        # EOF token
 
        # at this point either the INTEGER PLUS INTEGER or
        # the INTEGER MINUS INTEGER sequence of tokens
        # has been successfully found and the method can just
        # return the result of adding or subtracting two integers,
        # thus effectively interpreting client input
        if op.type == PLUS:
            result = left.value + right.value
        else:
            result = left.value - right.value
        return result
 
 
def main():
    while True:
        try:
            # To run under Python3 replace 'raw_input' call
            # with 'input'
            text = raw_input('calc> ')
        except EOFError:
            break
        if not text:
            continue
        interpreter = Interpreter(text)
        result = interpreter.expr()
        print(result)
 
 
if __name__ == '__main__':
    main()


将以上代码保存到calc2.py文件或直接从 GitHub下载它。试一下吧,亲眼看看它是否按预期运行:它可以处理输入字符串中的空白字;它可以接受多位的整数,既可以做加法运算也可以做减法运算。


这是我的笔记本中运行的例子:


$ python calc2.py
calc> 27 + 3
30
calc> 27 - 7
20
calc>


跟 Part 1 相比,主要的代码变动如下:
1. 对 get_next_token 方法进行了略微的修改。 pos 指针递增的逻辑单独抽离成独立的方法。
2. 添加了两个新方法: skip_whitespace 方法用来处理空格字符,自动忽略, integer 方法用来处理输入中的多位整数。
3. 对expr 方法做了修改,现在可以同时识别 INTEGER -> MINUS -> INTEGER 结构的表达式和 INTEGER -> PLUS -> INTEGER 结构的表达式。通过对这个两中表达式的成功识别,来处理加法和减法运算。
       

在第1部分,您了解了两个重要的概念,即token (令牌)和 lexical analyzer(词法分析程序)。今天我想谈谈lexemes(语义)、parsing(解析)、parsers(解析器)。
       

你已经知道了tokens(令牌)。但为了让我完成令牌的讨论我需要提到lexemes(语义)。语义是什么?语义是一个字符序列,组成了一个token (令牌)。在接下来的图片你可以看到一些关于token (令牌)和示例lexemes(语义)的例子,希望它能让你明确它们之间的关系:
现在,记住我们的朋友expr方法?我说过这是一个算术表达式的解释操作实际上发生的地方。但是在此之前,你要解释一个表达式,首先需要识别出这个表达式短语的类型。例如,它可能是加法或减法表达式。这就是expr方法本质上完成的功能:它发现从get_next_token方法中拿到的token的结构,然后解释识别结构的类型,产生对应的算术表达式的结果。
       

识别令牌短语表达式结构的过程被称为parsing(解析)。解释器或编译器执行这一工作的部分成为parser(解析器)。
       

现在你知道interpreter (解释器)中parsing(解析)和interpreting(翻译)的过程都发生在expr方法中, expr方法首先尝试parse(解析) Token流中INTEGER -> PLUS ->INTEGER 或者 INTEGER -> MINUS -> INTEGER短语,在成功parse(解析)其中的一个短语后,方法计算并返回加法或减法的运算结果给调用者。
下面又是练习的时间:

1. 扩展计算机功能:处理两个数的乘法
2. 扩展计算机功能:处理两个数的除法
3. 修改代码,实现处理表达式中包含任意数量的加法或减法,例如,“9 - 5 + 3 + 11”


检验一下对本文的理解:
1. 什么是 lexeme(语义)?
2. 处理识别token流中短语类型的过程叫什么名字?
3. 解释器(编译器) 中处理 parsing(解析)的部分叫什么名字?


好的,这就是今天的全部内容,下一篇文章,我们一起来扩展你的算法,让他实现更多算法。


英文原文:https://ruslanspivak.com/lsbasi-part2/

译者:cg2580

【声明】内容源于网络
0
0
Python程序员
1234
内容 2525
粉丝 0
Python程序员 1234
总阅读0
粉丝0
内容2.5k