File: yacc_error6.py

package info (click to toggle)
ply 3.9-1~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 1,344 kB
  • sloc: python: 10,171; perl: 62; makefile: 29; sh: 2
file content (80 lines) | stat: -rw-r--r-- 1,763 bytes parent folder | download | duplicates (12)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# -----------------------------------------------------------------------------
# yacc_error6.py
#
# Panic mode recovery test
# -----------------------------------------------------------------------------
import sys

if ".." not in sys.path: sys.path.insert(0,"..")
import ply.yacc as yacc

from calclex import tokens

# Parsing rules
precedence = (
    ('left','PLUS','MINUS'),
    ('left','TIMES','DIVIDE'),
    ('right','UMINUS'),
    )

def p_statements(t):
    'statements : statements statement'
    pass

def p_statements_1(t):
    'statements : statement'
    pass

def p_statement_assign(p):
    'statement : LPAREN NAME EQUALS expression RPAREN'
    print("%s=%s" % (p[2],p[4]))

def p_statement_expr(t):
    'statement : LPAREN expression RPAREN'
    print(t[1])

def p_expression_binop(t):
    '''expression : expression PLUS expression
                  | expression MINUS expression
                  | expression TIMES expression
                  | expression DIVIDE expression'''
    if t[2] == '+'  : t[0] = t[1] + t[3]
    elif t[2] == '-': t[0] = t[1] - t[3]
    elif t[2] == '*': t[0] = t[1] * t[3]
    elif t[2] == '/': t[0] = t[1] / t[3]

def p_expression_uminus(t):
    'expression : MINUS expression %prec UMINUS'
    t[0] = -t[2]

def p_expression_number(t):
    'expression : NUMBER'
    t[0] = t[1]

def p_error(p):
    if p:
        print("Line %d: Syntax error at '%s'" % (p.lineno, p.value))
    # Scan ahead looking for a name token
    while True:
        tok = parser.token()
        if not tok or tok.type == 'RPAREN':
            break
    if tok:
        parser.restart()
    return None

parser = yacc.yacc()
import calclex
calclex.lexer.lineno=1

parser.parse("""
(a = 3 + 4)
(b = 4 + * 5 - 6 + *)
(c = 10 + 11)
""")