如何修复python中的ply语法错误?

omqzjyyz  于 2021-09-29  发布在  Java
关注(0)|答案(0)|浏览(208)

我最近了解了ply python模块,并对它感兴趣。现在我正在尝试实现类似brainfuck的东西,但即使在最初阶段,我也有无法修复的bug。作为对下面代码的响应,解析器给出以下行:

yacc: Syntax error at line 1, token=OUT

我试过很多录音选项,但都没用。也许你会在这段代码中发现错误?提前感谢您的帮助。

tokens = (
'ADD', 'OUT', 'IN',
'SEMI', 'INT',
'LPAREN','RPAREN',
)

# Tokens

t_ADD = r'add'
t_OUT = r'out'
t_IN = r'in'
t_LPAREN  = r'\('
t_RPAREN  = r'\)'
t_SEMI = r';'

def t_INT(t):
    r'[-]?\d+'
    try:
       t.value = int(t.value)
    except ValueError:
       print("Integer value too large %d", t.value)
       t.value = 0
    return t

# Ignored characters

t_ignore = " \t"

def t_newline(t):
    r'\n+'
    t.lexer.lineno += t.value.count("\n")

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer

import ply.lex as lex
lexer = lex.lex()

ceils = [0] * 10
i = 0

# Parsing rules

def p_add_command(t):
    '''expr : ADD SEMI
        | ADD INT SEMI'''
    if len(t) == 3:
        ceils[i] += 1
    else:
        ceils[i] += t[2]
    t[0] = ceils[i]

def p_out_command(t):
    '''expr : OUT SEMI
        | OUT INT SEMI'''
    if len(t) == 3:
        print(ceils[i])
    else:
        print(t[2])
t[0] = ceils[i]

def p_in_command(t):
    """expr : IN SEMI
        | IN INT SEMI"""
    try:
        if len(t) == 3:
            temp = input()
            ceils[i] = int(temp)
        else:
            ceils[i] = t[2]
    except ValueError:
        print(f'Invalid integer: {temp}!')
    t[0] = ceils[i]

def p_expression_group(t):
    'expr : LPAREN expr RPAREN'
    t[0] = t[2]

def p_expression_number(t):
    'expr : INT'
    t[0] = t[1]

import ply.yacc as yacc
parser = yacc.yacc()

s = """add; out;"""
parser.parse(s)

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题