ValueError:遇到了意外的$ end-RPLY解析

时间:2018-12-15 06:09:23

标签: python python-3.x parsing lexer

我正在尝试为基本的解释语言创建解析器。

运行程序时,出现以下错误:

ValueError: Ran into a $end where it wasn't expected

这是我的main.py

from lexer import Lexer #imported from the lexer file
from parser_class_file import ParserClass
import time

#the actual code
text_input = "print(4 - 2);"


#creating the lexer object from my lexer file
lexer = Lexer().get_lexer()

#'lexs' the text_input
tokens = lexer.lex(text_input)

#prints all the tokens in the object
for token in tokens:
print(token)

time.sleep(1)
pg = ParserClass()
pg.parse_()
parser_object = pg.get_parser()
parser_object.parse(tokens)

以上代码的最后一行是问题说明。

这里是parse_class_file.py

"""Generating the parser"""
from rply import ParserGenerator
from ast import *

class ParserClass():

    def __init__(self):
        self.pg = ParserGenerator(
        #TOKENS ACCEPTED BY THE PARSER
        tokens=['NUMBER', 'PRINT', 'OPEN_PAREN', 'CLOSE_PAREN','SEMI_COLON', 'SUM', 'SUB', '$end']
    )

def parse_(self):
    @self.pg.production('program : PRINT OPEN_PAREN expression CLOSE_PAREN SEMI_COLON $end')
    def program(p):
        return Print(p[2]) #why the p[2]

    @self.pg.production('expression : expression SUM expression')
    @self.pg.production('expression : expression SUB expression')
    def expression(p):
        left = p[0]
        right = p[2]
        operator = p[1]

        if operator.gettokentype() == 'SUM':
            return Sum(left, right)
        elif operator.gettokentype() == 'SUB':
            return Sub(left, right)

    @self.pg.production('expression : NUMBER')
    def number(p):
        return Number(p[0].value)

    @self.pg.production('expression : expression $end')
    def end(p):
        print(p[3])

    @self.pg.error
    def error_handle(token):
        raise ValueError("Ran into a %s where it wasn't expected" % token.gettokentype())

def get_parser(self):
    return self.pg.build()

raise ValueError("Ran into a %s where it wasn't expected" % token.gettokentype())行是此文件中的问题说明。

我忽略了lexer和ast文件,因为它们似乎与错误无关。

如何解决错误并解决$end令牌的存在?

0 个答案:

没有答案