utils.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """General tools which don't depend on other parts of Parsimonious"""
  2. import ast
  3. class StrAndRepr(object):
  4. """Mix-in which gives the class the same __repr__ and __str__."""
  5. def __repr__(self):
  6. return self.__str__()
  7. def evaluate_string(string):
  8. """Piggyback on Python's string support so we can have backslash escaping
  9. and niceties like \n, \t, etc.
  10. This also supports:
  11. 1. b"strings", allowing grammars to parse bytestrings, in addition to str.
  12. 2. r"strings" to simplify regexes.
  13. """
  14. return ast.literal_eval(string)
  15. class Token(StrAndRepr):
  16. """A class to represent tokens, for use with TokenGrammars
  17. You will likely want to subclass this to hold additional information, like
  18. the characters that you lexed to create this token. Alternately, feel free
  19. to create your own class from scratch. The only contract is that tokens
  20. must have a ``type`` attr.
  21. """
  22. __slots__ = ['type']
  23. def __init__(self, type):
  24. self.type = type
  25. def __str__(self):
  26. return '<Token "%s">' % (self.type,)
  27. def __eq__(self, other):
  28. return self.type == other.type