语句解析
刚才跳过了parse这一条语句,这里我们回头来看,这里的代码比较集中,主要是在parser.py这个文件里面,由于这个模块其具有较强的独立性,所以有时候可以单独拿出来添加一些输入输出,这样便于理解他的机制。
def parse(fn, filedata=None):
"""
Parses a Ren'Py script contained within the file `fn`.
Returns a list of AST objects representing the statements that were found
at the top level of the file.
If `filedata` is given, it should be a unicode string giving the file
contents.
"""
renpy.game.exception_info = 'While parsing ' + fn + '.'
try:
lines = list_logical_lines(fn, filedata)
nested = group_logical_lines(lines)
except ParseError, e:
parse_errors.append(e.message)
return None
l = Lexer(nested)
rv = parse_block(l)
if parse_errors:
return None
return rv
其实其中主要有四个步骤:
list_logical_lines: 列举文件中的所有逻辑行,之所以叫逻辑行是为了与物理行区别,比如遇到有“\”换行符或者是在括号中的语句,一个逻辑行就有可能由多个物理行组成。这里返回的结果就是<文件名,逻辑行数,语句内容>这样的集合。
group_logical_lines:把上一步的逻辑行列表分块,Ren'py继承了Python的“用缩进来表示代码块”的思想,所以需要构建代码块之间的包含关系<文件名,逻辑行数,[代码块里的语句]>。
构建Lexer对象: 然后根据代码块的关系构建一个Lexer词法分析器。
parse_block:借助Lexer对象解析语句。
Lexer对象包含了之前分块的逻辑行,它本身是有状态的,状态就是当前的逻辑行,由于Lexer对象方法太多,我们先来看最开始的一部分:
class Lexer(object):
"""
The lexer that is used to lex script files. This works on the idea
that we want to lex each line in a block individually, and use
sub-lexers to lex sub-blocks.
"""
def __init__(self, block, init=False):
# Are we underneath an init block?
self.init = init
self.block = block
self.eob = False
self.line = -1
# These are set by advance.
self.filename = ""
self.text = ""
self.number = 0
self.subblock = [ ]
self.pos = 0
self.word_ca