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.

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