PLY认为我实现变量后数学表达式是语法错误

2024-06-25 23:45:39 发布

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

我一直在玩弄PLY,在得到示例后,我决定应该实现变量。这是很好的工作,但现在任何数学表达式,没有分配到一个变量似乎抛出一个语法错误(不是python语法错误,而是我的语言中的语法错误)。例如:

calc> a = 5
Name: a
Number: 5
Assigning variable a to 5
{'a': 5}
calc> 6 + 1
Number: 6
SYNTACTIC ERROR: line: 1 position: 0 Syntax error: 6
Number: 1
{'a': 5}

我注意到,我把数字语法函数放在变量赋值的函数之上,然后变量中断,计算工作。在

Lexer:

^{pr2}$

解析器:

import ply.yacc as yacc

from langlex import tokens

import colorama
colorama.init()

variables = {}

def p_assignment(p):
    "assignment : NAME EQUALS expression"
    print "Assigning variable", p[1], "to", p[3]
    variables[p[1]] = p[3]

def p_expression_plus(p):
    "expression : expression PLUS term"
    p[0] = p[1] + p[3]

def p_expression_minus(p):
    "expression : expression MINUS term"
    p[0] = p[1] - p[3]

def p_expression_term(p):
    "expression : term"
    p[0] = p[1]

def p_expression_name(p):
    "expression : NAME"
    p[0] = variables[p[1]]

def p_term_times(p):
    "term : term MULTIPLY factor"
    p[0] = p[1] * p[3]

def p_term_div(p):
    "term : term DIVIDE factor"
    p[0] = p[1] / p[3]

def p_term_factor(p):
    "term : factor"
    p[0] = p[1]

def p_factor_expr(p):
    "factor : LBRACKET expression RBRACKET"
    p[0] = p[2]

def p_factor_num(p):
    "factor : NUMBER"
    p[0] = p[1]

def p_error(p):
    if(p):
        print colorama.Fore.RED + "SYNTACTIC ERROR: line:", p.lexer.lineno, "position:", p.lexpos, "Syntax error:", p.value, colorama.Fore.RESET
    else:
        print colorama.Fore.RED + "SYNTACTIC ERROR: Unknown syntax error" + colorama.Fore.RESET

parser = yacc.yacc()

while True:
    s = raw_input("calc> ")

    if not(s):
        continue
    result = parser.parse(s)

    if(result):
        print result

    print variables

Tags: numberdefcalcerrorvariablescoloramaprintexpression
1条回答
网友
1楼 · 发布于 2024-06-25 23:45:39

在创建p_assignment时,您创建了一个新的起始语法符号。从文件中:

The first rule defined in the yacc specification determines the starting grammar symbol. Whenever the starting rule is reduced by the parser and no more input is available, parsing stops and the final value is returned.

http://www.dabeaz.com/ply/ply.html#ply_nn24

这意味着,对于你的语法来说,唯一允许输入的句子是赋值:

$ python p_o.py 
Generating LALR tables
calc> a=1
Name: a
Number: 1
Assigning variable a to 1
{'a': 1}
calc> a
Name: a
SYNTACTIC ERROR: Unknown syntax error
{'a': 1}
calc> 1
Number: 1
SYNTACTIC ERROR: line: 1 position: 0 Syntax error: 1 
{'a': 1}

所以,我们需要一个起始语法符号,通过某种途径,解析为表达式。我选择添加一个statement非终结符作为起始语法符号:

^{pr2}$
$ python p_1.py 
Generating LALR tables
calc> a=1
Name: a
Number: 1
Assigning variable a to 1
{'a': 1}
calc> a
Name: a
1
{'a': 1}
calc> 1
Number: 1
1
{'a': 1}
calc> 

相关问题 更多 >