ValueError: столкнулся с $ end, где это не ожидалось - RPLY Parsing - PullRequest
0 голосов
/ 15 декабря 2018

Я пытаюсь создать парсер для базового интерпретируемого языка.

Когда я запускаю свою программу, я получаю следующую ошибку:

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?

...