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.

350 lines
9.8 KiB

  1. import unicodedata
  2. import os
  3. from functools import reduce
  4. from collections import deque
  5. ###{standalone
  6. import sys, re
  7. import logging
  8. logger = logging.getLogger("lark")
  9. logger.addHandler(logging.StreamHandler())
  10. # Set to highest level, since we have some warnings amongst the code
  11. # By default, we should not output any log messages
  12. logger.setLevel(logging.CRITICAL)
  13. if sys.version_info[0]>2:
  14. from abc import ABC, abstractmethod
  15. else:
  16. from abc import ABCMeta, abstractmethod
  17. class ABC(object): # Provide Python27 compatibility
  18. __slots__ = ()
  19. __metclass__ = ABCMeta
  20. Py36 = (sys.version_info[:2] >= (3, 6))
  21. NO_VALUE = object()
  22. def classify(seq, key=None, value=None):
  23. d = {}
  24. for item in seq:
  25. k = key(item) if (key is not None) else item
  26. v = value(item) if (value is not None) else item
  27. if k in d:
  28. d[k].append(v)
  29. else:
  30. d[k] = [v]
  31. return d
  32. def _deserialize(data, namespace, memo):
  33. if isinstance(data, dict):
  34. if '__type__' in data: # Object
  35. class_ = namespace[data['__type__']]
  36. return class_.deserialize(data, memo)
  37. elif '@' in data:
  38. return memo[data['@']]
  39. return {key:_deserialize(value, namespace, memo) for key, value in data.items()}
  40. elif isinstance(data, list):
  41. return [_deserialize(value, namespace, memo) for value in data]
  42. return data
  43. class Serialize(object):
  44. """Safe-ish serialization interface that doesn't rely on Pickle
  45. Attributes:
  46. __serialize_fields__ (List[str]): Fields (aka attributes) to serialize.
  47. __serialize_namespace__ (list): List of classes that deserialization is allowed to instantiate.
  48. Should include all field types that aren't builtin types.
  49. """
  50. def memo_serialize(self, types_to_memoize):
  51. memo = SerializeMemoizer(types_to_memoize)
  52. return self.serialize(memo), memo.serialize()
  53. def serialize(self, memo=None):
  54. if memo and memo.in_types(self):
  55. return {'@': memo.memoized.get(self)}
  56. fields = getattr(self, '__serialize_fields__')
  57. res = {f: _serialize(getattr(self, f), memo) for f in fields}
  58. res['__type__'] = type(self).__name__
  59. postprocess = getattr(self, '_serialize', None)
  60. if postprocess:
  61. postprocess(res, memo)
  62. return res
  63. @classmethod
  64. def deserialize(cls, data, memo):
  65. namespace = getattr(cls, '__serialize_namespace__', {})
  66. namespace = {c.__name__:c for c in namespace}
  67. fields = getattr(cls, '__serialize_fields__')
  68. if '@' in data:
  69. return memo[data['@']]
  70. inst = cls.__new__(cls)
  71. for f in fields:
  72. try:
  73. setattr(inst, f, _deserialize(data[f], namespace, memo))
  74. except KeyError as e:
  75. raise KeyError("Cannot find key for class", cls, e)
  76. postprocess = getattr(inst, '_deserialize', None)
  77. if postprocess:
  78. postprocess()
  79. return inst
  80. class SerializeMemoizer(Serialize):
  81. "A version of serialize that memoizes objects to reduce space"
  82. __serialize_fields__ = 'memoized',
  83. def __init__(self, types_to_memoize):
  84. self.types_to_memoize = tuple(types_to_memoize)
  85. self.memoized = Enumerator()
  86. def in_types(self, value):
  87. return isinstance(value, self.types_to_memoize)
  88. def serialize(self):
  89. return _serialize(self.memoized.reversed(), None)
  90. @classmethod
  91. def deserialize(cls, data, namespace, memo):
  92. return _deserialize(data, namespace, memo)
  93. try:
  94. STRING_TYPE = basestring
  95. except NameError: # Python 3
  96. STRING_TYPE = str
  97. import types
  98. from functools import wraps, partial
  99. from contextlib import contextmanager
  100. Str = type(u'')
  101. try:
  102. classtype = types.ClassType # Python2
  103. except AttributeError:
  104. classtype = type # Python3
  105. def smart_decorator(f, create_decorator):
  106. if isinstance(f, types.FunctionType):
  107. return wraps(f)(create_decorator(f, True))
  108. elif isinstance(f, (classtype, type, types.BuiltinFunctionType)):
  109. return wraps(f)(create_decorator(f, False))
  110. elif isinstance(f, types.MethodType):
  111. return wraps(f)(create_decorator(f.__func__, True))
  112. elif isinstance(f, partial):
  113. # wraps does not work for partials in 2.7: https://bugs.python.org/issue3445
  114. return wraps(f.func)(create_decorator(lambda *args, **kw: f(*args[1:], **kw), True))
  115. else:
  116. return create_decorator(f.__func__.__call__, True)
  117. try:
  118. import regex
  119. except ImportError:
  120. regex = None
  121. import sre_parse
  122. import sre_constants
  123. categ_pattern = re.compile(r'\\p{[A-Za-z_]+}')
  124. def get_regexp_width(expr):
  125. if regex:
  126. # Since `sre_parse` cannot deal with Unicode categories of the form `\p{Mn}`, we replace these with
  127. # a simple letter, which makes no difference as we are only trying to get the possible lengths of the regex
  128. # match here below.
  129. regexp_final = re.sub(categ_pattern, 'A', expr)
  130. else:
  131. if re.search(categ_pattern, expr):
  132. raise ImportError('`regex` module must be installed in order to use Unicode categories.', expr)
  133. regexp_final = expr
  134. try:
  135. return [int(x) for x in sre_parse.parse(regexp_final).getwidth()]
  136. except sre_constants.error:
  137. raise ValueError(expr)
  138. ###}
  139. _ID_START = 'Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Mn', 'Mc', 'Pc'
  140. _ID_CONTINUE = _ID_START + ('Nd', 'Nl',)
  141. def _test_unicode_category(s, categories):
  142. if len(s) != 1:
  143. return all(_test_unicode_category(char, categories) for char in s)
  144. return s == '_' or unicodedata.category(s) in categories
  145. def is_id_continue(s):
  146. """
  147. Checks if all characters in `s` are alphanumeric characters (Unicode standard, so diacritics, indian vowels, non-latin
  148. numbers, etc. all pass). Synonymous with a Python `ID_CONTINUE` identifier. See PEP 3131 for details.
  149. """
  150. return _test_unicode_category(s, _ID_CONTINUE)
  151. def is_id_start(s):
  152. """
  153. Checks if all characters in `s` are alphabetic characters (Unicode standard, so diacritics, indian vowels, non-latin
  154. numbers, etc. all pass). Synonymous with a Python `ID_START` identifier. See PEP 3131 for details.
  155. """
  156. return _test_unicode_category(s, _ID_START)
  157. def dedup_list(l):
  158. """Given a list (l) will removing duplicates from the list,
  159. preserving the original order of the list. Assumes that
  160. the list entries are hashable."""
  161. dedup = set()
  162. return [x for x in l if not (x in dedup or dedup.add(x))]
  163. try:
  164. from contextlib import suppress # Python 3
  165. except ImportError:
  166. @contextmanager
  167. def suppress(*excs):
  168. '''Catch and dismiss the provided exception
  169. >>> x = 'hello'
  170. >>> with suppress(IndexError):
  171. ... x = x[10]
  172. >>> x
  173. 'hello'
  174. '''
  175. try:
  176. yield
  177. except excs:
  178. pass
  179. try:
  180. compare = cmp
  181. except NameError:
  182. def compare(a, b):
  183. if a == b:
  184. return 0
  185. elif a > b:
  186. return 1
  187. return -1
  188. class Enumerator(Serialize):
  189. def __init__(self):
  190. self.enums = {}
  191. def get(self, item):
  192. if item not in self.enums:
  193. self.enums[item] = len(self.enums)
  194. return self.enums[item]
  195. def __len__(self):
  196. return len(self.enums)
  197. def reversed(self):
  198. r = {v: k for k, v in self.enums.items()}
  199. assert len(r) == len(self.enums)
  200. return r
  201. def combine_alternatives(lists):
  202. """
  203. Accepts a list of alternatives, and enumerates all their possible concatinations.
  204. Examples:
  205. >>> combine_alternatives([range(2), [4,5]])
  206. [[0, 4], [0, 5], [1, 4], [1, 5]]
  207. >>> combine_alternatives(["abc", "xy", '$'])
  208. [['a', 'x', '$'], ['a', 'y', '$'], ['b', 'x', '$'], ['b', 'y', '$'], ['c', 'x', '$'], ['c', 'y', '$']]
  209. >>> combine_alternatives([])
  210. [[]]
  211. """
  212. if not lists:
  213. return [[]]
  214. assert all(l for l in lists), lists
  215. init = [[x] for x in lists[0]]
  216. return reduce(lambda a,b: [i+[j] for i in a for j in b], lists[1:], init)
  217. class FS:
  218. open = open
  219. exists = os.path.exists
  220. def isascii(s):
  221. """ str.isascii only exists in python3.7+ """
  222. try:
  223. return s.isascii()
  224. except AttributeError:
  225. try:
  226. s.encode('ascii')
  227. return True
  228. except (UnicodeDecodeError, UnicodeEncodeError):
  229. return False
  230. class fzset(frozenset):
  231. def __repr__(self):
  232. return '{%s}' % ', '.join(map(repr, self))
  233. def classify_bool(seq, pred):
  234. true_elems = []
  235. false_elems = []
  236. for elem in seq:
  237. if pred(elem):
  238. true_elems.append(elem)
  239. else:
  240. false_elems.append(elem)
  241. return true_elems, false_elems
  242. def bfs(initial, expand):
  243. open_q = deque(list(initial))
  244. visited = set(open_q)
  245. while open_q:
  246. node = open_q.popleft()
  247. yield node
  248. for next_node in expand(node):
  249. if next_node not in visited:
  250. visited.add(next_node)
  251. open_q.append(next_node)
  252. def bfs_all_unique(initial, expand):
  253. "bfs, but doesn't keep track of visited (aka seen), because there can be no repetitions"
  254. open_q = deque(list(initial))
  255. while open_q:
  256. node = open_q.popleft()
  257. yield node
  258. open_q += expand(node)
  259. def _serialize(value, memo):
  260. if isinstance(value, Serialize):
  261. return value.serialize(memo)
  262. elif isinstance(value, list):
  263. return [_serialize(elem, memo) for elem in value]
  264. elif isinstance(value, frozenset):
  265. return list(value) # TODO reversible?
  266. elif isinstance(value, dict):
  267. return {key:_serialize(elem, memo) for key, elem in value.items()}
  268. # assert value is None or isinstance(value, (int, float, str, tuple)), value
  269. return value