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