Path: blob/main/third_party/ply/test/lex_object.py
6169 views
# -----------------------------------------------------------------------------1# lex_object.py2# -----------------------------------------------------------------------------3import sys45if ".." not in sys.path: sys.path.insert(0,"..")6import ply.lex as lex78class CalcLexer:9tokens = (10'NAME','NUMBER',11'PLUS','MINUS','TIMES','DIVIDE','EQUALS',12'LPAREN','RPAREN',13)1415# Tokens1617t_PLUS = r'\+'18t_MINUS = r'-'19t_TIMES = r'\*'20t_DIVIDE = r'/'21t_EQUALS = r'='22t_LPAREN = r'\('23t_RPAREN = r'\)'24t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'2526def t_NUMBER(self,t):27r'\d+'28try:29t.value = int(t.value)30except ValueError:31print("Integer value too large %s" % t.value)32t.value = 033return t3435t_ignore = " \t"3637def t_newline(self,t):38r'\n+'39t.lineno += t.value.count("\n")4041def t_error(self,t):42print("Illegal character '%s'" % t.value[0])43t.lexer.skip(1)444546calc = CalcLexer()4748# Build the lexer49lex.lex(object=calc)50lex.runmain(data="3+4")51525354555657