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.

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