calc.py (4479:61d3ed46e373) calc.py (6498:e21e9ab5fad0)
1# -----------------------------------------------------------------------------
2# calc.py
3#
4# A simple calculator with variables. This is from O'Reilly's
5# "Lex and Yacc", p. 63.
6#
7# This example uses unicode strings for tokens, docstrings, and input.
8# -----------------------------------------------------------------------------

--- 27 unchanged lines hidden (view full) ---

36 t.value = 0
37 return t
38
39t_ignore = u" \t"
40
41def t_newline(t):
42 ur'\n+'
43 t.lexer.lineno += t.value.count("\n")
1# -----------------------------------------------------------------------------
2# calc.py
3#
4# A simple calculator with variables. This is from O'Reilly's
5# "Lex and Yacc", p. 63.
6#
7# This example uses unicode strings for tokens, docstrings, and input.
8# -----------------------------------------------------------------------------

--- 27 unchanged lines hidden (view full) ---

36 t.value = 0
37 return t
38
39t_ignore = u" \t"
40
41def t_newline(t):
42 ur'\n+'
43 t.lexer.lineno += t.value.count("\n")
44
44
45def t_error(t):
46 print "Illegal character '%s'" % t.value[0]
47 t.lexer.skip(1)
45def t_error(t):
46 print "Illegal character '%s'" % t.value[0]
47 t.lexer.skip(1)
48
48
49# Build the lexer
50import ply.lex as lex
51lex.lex()
52
53# Parsing rules
54
55precedence = (
56 ('left','PLUS','MINUS'),

--- 38 unchanged lines hidden (view full) ---

95 'expression : NAME'
96 try:
97 p[0] = names[p[1]]
98 except LookupError:
99 print "Undefined name '%s'" % p[1]
100 p[0] = 0
101
102def p_error(p):
49# Build the lexer
50import ply.lex as lex
51lex.lex()
52
53# Parsing rules
54
55precedence = (
56 ('left','PLUS','MINUS'),

--- 38 unchanged lines hidden (view full) ---

95 'expression : NAME'
96 try:
97 p[0] = names[p[1]]
98 except LookupError:
99 print "Undefined name '%s'" % p[1]
100 p[0] = 0
101
102def p_error(p):
103 print "Syntax error at '%s'" % p.value
103 if p:
104 print "Syntax error at '%s'" % p.value
105 else:
106 print "Syntax error at EOF"
104
105import ply.yacc as yacc
106yacc.yacc()
107
108while 1:
109 try:
110 s = raw_input('calc > ')
111 except EOFError:
112 break
113 if not s: continue
114 yacc.parse(unicode(s))
107
108import ply.yacc as yacc
109yacc.yacc()
110
111while 1:
112 try:
113 s = raw_input('calc > ')
114 except EOFError:
115 break
116 if not s: continue
117 yacc.parse(unicode(s))