PLY的LALR语法详细解释

首先还是先给出本次可以运行的程序。


###################################################

tokens = ['ID', 'FLOAT', 'INT'] 

literals = ['=', '.', '<', '+', '-', '*', '/', '(', ')']

t_ignore = " "

#t_ID = r'[a-zA-Z_][a-zA-Z_0-9]*'
def t_ID(t):
    r'[a-zA-Z_][a-zA-Z_0-9]*'
    print('t_ID', t.value)
    return t

def t_FLOAT(t):
    r'\d+\.\d+'
    t.value = float(t.value)
    print('t_FLOAT', t.value)
    return t

def t_INT(t):
    r'\d+'
    t.value = int(t.value)
    print('t_INT', t.value)
    return t

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

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

# Build the lexer
import ply.lex as lex
myLex = lex.lex()

###################################################
# dictionary of ids
ids = {}

# Parsing rules
precedence = (
    ('left', '+', '-'),
    ('left', '*', '/'),
    ('right', 'UMINUS'),
)

###   statement   ###
def p_statement_assign(p):
    'statement : ID "=" expression'
    ids[p[1]] = p[3]
    for i in range(len(p)):
        print('p_statement_assign', 'pos', i, 'value', p[i])

###   statement   ###
def p_statement_expr(p):
    'statement : expression'
    print(p[1])
    for i in range(len(p)):
        print('p_statement_expr', 'pos', i, 'value', p[i])

###   expression   ###
def p_expression_plus(p):
    '''expression : expression '+' expression'''
    p[0] = p[1] + p[3]
    for i in range(len(p)):
        print('p_expression_plus', 'pos', i, 'value', p[i])

###   expression   ###
def p_expression_minus(p):
    '''expression : expression '-' expression'''
    p[0] = p[1] - p[3]
    for i in range(len(p)):
        print('p_expression_minus', 'pos', i, 'value', p[i])

###   expression   ###
def p_expression_times(p):
    '''expression : expression '*&
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值