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