1# -----------------------------------------------------------------------------
2# lex_object.py
3# -----------------------------------------------------------------------------
4import sys
5
6if ".." not in sys.path: sys.path.insert(0,"..")
7import ply.lex as lex
8
9class CalcLexer:
10    tokens = (
11        'NAME','NUMBER',
12        'PLUS','MINUS','TIMES','DIVIDE','EQUALS',
13        'LPAREN','RPAREN',
14        )
15
16    # Tokens
17
18    t_PLUS    = r'\+'
19    t_MINUS   = r'-'
20    t_TIMES   = r'\*'
21    t_DIVIDE  = r'/'
22    t_EQUALS  = r'='
23    t_LPAREN  = r'\('
24    t_RPAREN  = r'\)'
25    t_NAME    = r'[a-zA-Z_][a-zA-Z0-9_]*'
26
27    def t_NUMBER(self,t):
28        r'\d+'
29        try:
30            t.value = int(t.value)
31        except ValueError:
32            print("Integer value too large %s" % t.value)
33            t.value = 0
34        return t
35
36    t_ignore = " \t"
37
38    def t_newline(self,t):
39        r'\n+'
40        t.lineno += t.value.count("\n")
41
42    def t_error(self,t):
43        print("Illegal character '%s'" % t.value[0])
44        t.lexer.skip(1)
45
46
47calc = CalcLexer()
48
49# Build the lexer
50lex.lex(object=calc)
51lex.runmain(data="3+4")
52
53
54
55
56