ValueError:遇到了$end,在那里不需要RPLY解析

2024-04-25 16:49:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为一种基本的解释语言创建一个解析器。你知道吗

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

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令牌的存在?你知道吗


Tags: thefromimportselftokenparserreturndef