2

我正在尝试为 c 语言编写一个解析器,它能够处理表达式、赋值、if-else 和 while 循环。

这是我的规则:

表达式 -> 表达式 op 表达式
表达式 -> ID
表达式 -> NUMBER
语句 -> ID ASSIGN 表达式
语句 -> IF 表达式 THEN 语句
语句 -> WHILE 表达式 THEN 语句

大写字母中的所有内容都是令牌(终端符号)

解析字符串“while h<=0 then t=1”时,似乎将“h”视为表达式(使用规则表达式->ID)。因此,“WHILE 表达式 THEN 语句”中的表达式变为“h”。显然,我希望它考虑“h<=0”作为表达式(使用规则表达式 -> 表达式 op 表达式)。我如何确保发生这种情况?

4

1 回答 1

1

Building on the previous post where you were asking about the ply.lex module, the snippet below seems like a partial implementation of a c-like grammar. I haven't used ply much, but one of the tricks seems to be that you need to define the grammar rules in the correct order.

tokens   = [ 'ID', 'NUMBER', 'LESSEQUAL', 'ASSIGN' ]
reserved = {
    'while' : 'WHILE',
    'then'  : 'THEN',
    'if'    : 'IF'
}
tokens += reserved.values()

t_ignore    = ' \t'
t_NUMBER    = r'\d+'
t_LESSEQUAL = r'<='
t_ASSIGN    = r'\='

def t_ID(t):
    r'[a-zA-Z_][a-zA-Z0-9_]*'
    if t.value in reserved:
        t.type = reserved[ t.value ]
    return t

def t_error(t):
    print 'Illegal character'
    t.lexer.skip(1)

def p_statement_assign(p):
    'statement : ID ASSIGN expression'
    p[0] = ('assign', p[1], p[3] )

def p_statement_if(p):
    'statement : IF expression THEN statement'
    p[0] = ('if', p[2], p[4] )

def p_statement_while(p):
    'statement : WHILE expression THEN statement'
    p[0] = ('while', p[2], p[4] )

def p_expression_simple(p):
    '''expression : ID
                  | NUMBER'''
    p[0] = p[1]

def p_expression_cmp(p):
    'expression : expression LESSEQUAL expression'
    p[0] = ( '<=', p[1], p[3] )

import ply.lex as lex
import ply.yacc as yacc
lexer = lex.lex()
parser = yacc.yacc()
inp = 'while h<=0 then t=1'
res = parser.parse(inp)
print res

Output from the snippet is:

('while', ('<=', 'h', '0'), ('assign', 't', '1'))
于 2011-02-18T23:49:12.380 回答