calclex.py 939 B

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