2012-01-27 6 views
1

모두,파이썬 PLY 파서 구문 오류

저는 매우 단순한 파서를 python PLY으로 작성하고 있습니다. 그것은 대부분은입니다.하지만 많은 입력 행에 대해 구문 오류 (yacc)가 표시됩니다.

tokens = ('VAR', 'NUMBER', 'CLOSE', 'JUNK') 

# Tokens 

t_VAR  = r'%[mM]\[' 
t_CLOSE = r'\]' 
t_JUNK = r'.' 

# Ignored characters 
t_ignore = " \t\r" 

def t_NUMBER(t): 
    r'\d+' 
    try: 
     t.value = int(t.value) 
    except ValueError: 
     print("Integer value too large %d", t.value) 
     t.value = 0 
    return 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 
lex.lex() 

# Parsing rules 

def p_statement(p): 
    '''statement : field''' 
    try: 
     print p[1] 
    except IndexError: 
     pass 

def p_trash(p): 
    '''statement : JUNK''' 
    pass 

def p_field(p): 
    '''field : VAR NUMBER CLOSE''' 
    #print p[1], p[2], p[3] 
    p[0] = p[2] 

def p_error(p): 
    print("Syntax error at '%s'" % repr(p)) #p.value) 

import ply.yacc as yacc 
yacc.yacc() 

샘플 용 : yacc.parse('.set %m[702] $substr($currentlength,2,$currentpg)') 출력으로서 제공한다 : 여기서 다소 쉽게 테스트 변성 렉서와 파서 코드이다

Syntax error at 'LexToken(JUNK,'s',1,1)' 
Syntax error at 'LexToken(JUNK,'$',1,13)' 

그것은 출력해야 702 만.

답변

2

최상위 규칙에는 단일 진술이 필요합니다. p_trash은 첫 번째 '와 일치합니다.' 명령.을 리턴하고 명령문이 계 속될 수 있도록하는 최상위 레벨 규칙이 없습니다. 당신이 뭔가를 할 수 있습니다 :

def p_junk(p): 
    '''statement | JUNK statement''' 

또한 같은 것을 할 (및 문의 목록 작성) 수 :

def p_statements(p): 
    '''statements | statement statements 
        | empty''' 
+0

오 뜨아를! 나는 그것이 잊어 버린 단순한 무언가라는 것을 알았다. –