Actions.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. #=======================================================================
  2. #
  3. # Python Lexical Analyser
  4. #
  5. # Actions for use in token specifications
  6. #
  7. #=======================================================================
  8. class Action(object):
  9. def perform(self, token_stream, text):
  10. pass # abstract
  11. def same_as(self, other):
  12. return self is other
  13. class Return(Action):
  14. """
  15. Internal Plex action which causes |value| to
  16. be returned as the value of the associated token
  17. """
  18. def __init__(self, value):
  19. self.value = value
  20. def perform(self, token_stream, text):
  21. return self.value
  22. def same_as(self, other):
  23. return isinstance(other, Return) and self.value == other.value
  24. def __repr__(self):
  25. return "Return(%s)" % repr(self.value)
  26. class Call(Action):
  27. """
  28. Internal Plex action which causes a function to be called.
  29. """
  30. def __init__(self, function):
  31. self.function = function
  32. def perform(self, token_stream, text):
  33. return self.function(token_stream, text)
  34. def __repr__(self):
  35. return "Call(%s)" % self.function.__name__
  36. def same_as(self, other):
  37. return isinstance(other, Call) and self.function is other.function
  38. class Begin(Action):
  39. """
  40. Begin(state_name) is a Plex action which causes the Scanner to
  41. enter the state |state_name|. See the docstring of Plex.Lexicon
  42. for more information.
  43. """
  44. def __init__(self, state_name):
  45. self.state_name = state_name
  46. def perform(self, token_stream, text):
  47. token_stream.begin(self.state_name)
  48. def __repr__(self):
  49. return "Begin(%s)" % self.state_name
  50. def same_as(self, other):
  51. return isinstance(other, Begin) and self.state_name == other.state_name
  52. class Ignore(Action):
  53. """
  54. IGNORE is a Plex action which causes its associated token
  55. to be ignored. See the docstring of Plex.Lexicon for more
  56. information.
  57. """
  58. def perform(self, token_stream, text):
  59. return None
  60. def __repr__(self):
  61. return "IGNORE"
  62. IGNORE = Ignore()
  63. #IGNORE.__doc__ = Ignore.__doc__
  64. class Text(Action):
  65. """
  66. TEXT is a Plex action which causes the text of a token to
  67. be returned as the value of the token. See the docstring of
  68. Plex.Lexicon for more information.
  69. """
  70. def perform(self, token_stream, text):
  71. return text
  72. def __repr__(self):
  73. return "TEXT"
  74. TEXT = Text()
  75. #TEXT.__doc__ = Text.__doc__