PLY函数声明的解析错误

时间:2017-04-25 18:52:11

标签: python ply

我试图在python中解析以下源语言

print("hello")

我在PLY中所做的是以下

import ply
import yacc

tokens =('LPAREN','RPAREN','STRING','PRINT')
reserved ={
('print': 'PRINT')
}

t_LPAREN ='\('
t_RPREN = '\)'
t_STRING = r'\".*?\"'

t_ignore = " \t"

def p_print(p):
  'statement : print LPAREN STRING RPAREN'
  print(p[3])
def p_error(p):
  print("Syntax error at %s"%p.value)
lex.lex()
yacc.yacc()
s ='print("Hello")'
yacc.parse(s)

我原以为会打印Hello。但我得到错误

  

'print'的语法错误

任何人都可以帮我解决我的错误吗? 感谢

1 个答案:

答案 0 :(得分:1)

以下是您的代码中所有内容的列表:

  1. 导入语句。您没有错过正确导入模块。我不确定你是怎么做到的,但导入这些模块的正确方法是

    import ply.lex as lex
    import ply.yacc as yacc
    
  2. 指定了PRINT令牌,但没有为其定义规则。像这样定义规则:

    t_PRINT = r'print'
    
  3. print语句的语法规则应指定令牌名称,而不是令牌匹配的名称。

    def p_print(p):
      r'statement : PRINT LPAREN STRING RPAREN'
      ...
    
  4. 删除reserved结构,似乎没有用处。

  5. 修正这些错误后,我们有:

    import ply.lex as lex
    import ply.yacc as yacc
    
    tokens =('LPAREN','RPAREN','STRING','PRINT')
    
    t_LPAREN ='\('
    t_RPAREN = '\)'
    t_STRING = r'\".*?\"'
    t_PRINT = r'print'
    t_ignore = " \t"
    
    def p_print(p):
      'statement : PRINT LPAREN STRING RPAREN'
      print(p[3])
    
    def p_error(p):
      print("Syntax error at %s"%p.value)
    
    lex.lex()
    yacc.yacc()
    s ='print("Hello")'
    yacc.parse(s)
    

    输出:

    WARNING: No t_error rule is defined
    "Hello"
    

    现在可以,但是为更大的程序定义t_error规则。

相关问题