This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
2.7 KiB

  1. from .utils import Serialize
  2. class Symbol(Serialize):
  3. is_term = NotImplemented
  4. def __init__(self, name):
  5. self.name = name
  6. def __eq__(self, other):
  7. assert isinstance(other, Symbol), other
  8. return self.is_term == other.is_term and self.name == other.name
  9. def __ne__(self, other):
  10. return not (self == other)
  11. def __hash__(self):
  12. return hash(self.name)
  13. def __repr__(self):
  14. return '%s(%r)' % (type(self).__name__, self.name)
  15. fullrepr = property(__repr__)
  16. class Terminal(Symbol):
  17. __serialize_fields__ = 'name', 'filter_out'
  18. is_term = True
  19. def __init__(self, name, filter_out=False):
  20. self.name = name
  21. self.filter_out = filter_out
  22. @property
  23. def fullrepr(self):
  24. return '%s(%r, %r)' % (type(self).__name__, self.name, self.filter_out)
  25. class NonTerminal(Symbol):
  26. __serialize_fields__ = 'name',
  27. is_term = False
  28. class Rule(Serialize):
  29. """
  30. origin : a symbol
  31. expansion : a list of symbols
  32. order : index of this expansion amongst all rules of the same name
  33. """
  34. __slots__ = ('origin', 'expansion', 'alias', 'options', 'order', '_hash')
  35. __serialize_fields__ = 'origin', 'expansion', 'order', 'alias', 'options'
  36. __serialize_namespace__ = lambda: (Terminal, NonTerminal, RuleOptions)
  37. def __init__(self, origin, expansion, order=0, alias=None, options=None):
  38. self.origin = origin
  39. self.expansion = expansion
  40. self.alias = alias
  41. self.order = order
  42. self.options = options
  43. self._hash = hash((self.origin, tuple(self.expansion)))
  44. def _deserialize(self):
  45. self._hash = hash((self.origin, tuple(self.expansion)))
  46. def __str__(self):
  47. return '<%s : %s>' % (self.origin.name, ' '.join(x.name for x in self.expansion))
  48. def __repr__(self):
  49. return 'Rule(%r, %r, %r, %r)' % (self.origin, self.expansion, self.alias, self.options)
  50. def __hash__(self):
  51. return self._hash
  52. def __eq__(self, other):
  53. if not isinstance(other, Rule):
  54. return False
  55. return self.origin == other.origin and self.expansion == other.expansion
  56. class RuleOptions(Serialize):
  57. __serialize_fields__ = 'keep_all_tokens', 'expand1', 'priority', 'empty_indices'
  58. def __init__(self, keep_all_tokens=False, expand1=False, priority=None, empty_indices=()):
  59. self.keep_all_tokens = keep_all_tokens
  60. self.expand1 = expand1
  61. self.priority = priority
  62. self.empty_indices = empty_indices
  63. def __repr__(self):
  64. return 'RuleOptions(%r, %r, %r)' % (
  65. self.keep_all_tokens,
  66. self.expand1,
  67. self.priority,
  68. )