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.

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