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.

325 lines
10 KiB

  1. ## Lexer Implementation
  2. import re
  3. from .utils import Str, classify, get_regexp_width, Py36
  4. from .exceptions import UnexpectedCharacters, LexError
  5. class Pattern(object):
  6. def __init__(self, value, flags=()):
  7. self.value = value
  8. self.flags = frozenset(flags)
  9. def __repr__(self):
  10. return repr(self.to_regexp())
  11. # Pattern Hashing assumes all subclasses have a different priority!
  12. def __hash__(self):
  13. return hash((type(self), self.value, self.flags))
  14. def __eq__(self, other):
  15. return type(self) == type(other) and self.value == other.value and self.flags == other.flags
  16. def to_regexp(self):
  17. raise NotImplementedError()
  18. if Py36:
  19. # Python 3.6 changed syntax for flags in regular expression
  20. def _get_flags(self, value):
  21. for f in self.flags:
  22. value = ('(?%s:%s)' % (f, value))
  23. return value
  24. else:
  25. def _get_flags(self, value):
  26. for f in self.flags:
  27. value = ('(?%s)' % f) + value
  28. return value
  29. class PatternStr(Pattern):
  30. def to_regexp(self):
  31. return self._get_flags(re.escape(self.value))
  32. @property
  33. def min_width(self):
  34. return len(self.value)
  35. max_width = min_width
  36. class PatternRE(Pattern):
  37. def to_regexp(self):
  38. return self._get_flags(self.value)
  39. @property
  40. def min_width(self):
  41. return get_regexp_width(self.to_regexp())[0]
  42. @property
  43. def max_width(self):
  44. return get_regexp_width(self.to_regexp())[1]
  45. class TerminalDef(object):
  46. def __init__(self, name, pattern, priority=1):
  47. assert isinstance(pattern, Pattern), pattern
  48. self.name = name
  49. self.pattern = pattern
  50. self.priority = priority
  51. def __repr__(self):
  52. return '%s(%r, %r)' % (type(self).__name__, self.name, self.pattern)
  53. ###{standalone
  54. class Token(Str):
  55. __slots__ = ('type', 'pos_in_stream', 'value', 'line', 'column', 'end_line', 'end_column')
  56. def __new__(cls, type_, value, pos_in_stream=None, line=None, column=None):
  57. self = super(Token, cls).__new__(cls, value)
  58. self.type = type_
  59. self.pos_in_stream = pos_in_stream
  60. self.value = value
  61. self.line = line
  62. self.column = column
  63. self.end_line = None
  64. self.end_column = None
  65. return self
  66. @classmethod
  67. def new_borrow_pos(cls, type_, value, borrow_t):
  68. return cls(type_, value, borrow_t.pos_in_stream, line=borrow_t.line, column=borrow_t.column)
  69. def __reduce__(self):
  70. return (self.__class__, (self.type, self.value, self.pos_in_stream, self.line, self.column, ))
  71. def __repr__(self):
  72. return 'Token(%s, %r)' % (self.type, self.value)
  73. def __deepcopy__(self, memo):
  74. return Token(self.type, self.value, self.pos_in_stream, self.line, self.column)
  75. def __eq__(self, other):
  76. if isinstance(other, Token) and self.type != other.type:
  77. return False
  78. return Str.__eq__(self, other)
  79. __hash__ = Str.__hash__
  80. class LineCounter:
  81. def __init__(self):
  82. self.newline_char = '\n'
  83. self.char_pos = 0
  84. self.line = 1
  85. self.column = 1
  86. self.line_start_pos = 0
  87. def feed(self, token, test_newline=True):
  88. """Consume a token and calculate the new line & column.
  89. As an optional optimization, set test_newline=False is token doesn't contain a newline.
  90. """
  91. if test_newline:
  92. newlines = token.count(self.newline_char)
  93. if newlines:
  94. self.line += newlines
  95. self.line_start_pos = self.char_pos + token.rindex(self.newline_char) + 1
  96. self.char_pos += len(token)
  97. self.column = self.char_pos - self.line_start_pos + 1
  98. class _Lex:
  99. "Built to serve both Lexer and ContextualLexer"
  100. def __init__(self, lexer, state=None):
  101. self.lexer = lexer
  102. self.state = state
  103. def lex(self, stream, newline_types, ignore_types):
  104. newline_types = frozenset(newline_types)
  105. ignore_types = frozenset(ignore_types)
  106. line_ctr = LineCounter()
  107. while line_ctr.char_pos < len(stream):
  108. lexer = self.lexer
  109. for mre, type_from_index in lexer.mres:
  110. m = mre.match(stream, line_ctr.char_pos)
  111. if not m:
  112. continue
  113. t = None
  114. value = m.group(0)
  115. type_ = type_from_index[m.lastindex]
  116. if type_ not in ignore_types:
  117. t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  118. if t.type in lexer.callback:
  119. t = lexer.callback[t.type](t)
  120. yield t
  121. else:
  122. if type_ in lexer.callback:
  123. t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  124. lexer.callback[type_](t)
  125. line_ctr.feed(value, type_ in newline_types)
  126. if t:
  127. t.end_line = line_ctr.line
  128. t.end_column = line_ctr.column
  129. break
  130. else:
  131. raise UnexpectedCharacters(stream, line_ctr.char_pos, line_ctr.line, line_ctr.column, state=self.state)
  132. class UnlessCallback:
  133. def __init__(self, mres):
  134. self.mres = mres
  135. def __call__(self, t):
  136. for mre, type_from_index in self.mres:
  137. m = mre.match(t.value)
  138. if m:
  139. t.type = type_from_index[m.lastindex]
  140. break
  141. return t
  142. ###}
  143. def _create_unless(terminals):
  144. tokens_by_type = classify(terminals, lambda t: type(t.pattern))
  145. assert len(tokens_by_type) <= 2, tokens_by_type.keys()
  146. embedded_strs = set()
  147. callback = {}
  148. for retok in tokens_by_type.get(PatternRE, []):
  149. unless = [] # {}
  150. for strtok in tokens_by_type.get(PatternStr, []):
  151. if strtok.priority > retok.priority:
  152. continue
  153. s = strtok.pattern.value
  154. m = re.match(retok.pattern.to_regexp(), s)
  155. if m and m.group(0) == s:
  156. unless.append(strtok)
  157. if strtok.pattern.flags <= retok.pattern.flags:
  158. embedded_strs.add(strtok)
  159. if unless:
  160. callback[retok.name] = UnlessCallback(build_mres(unless, match_whole=True))
  161. terminals = [t for t in terminals if t not in embedded_strs]
  162. return terminals, callback
  163. def _build_mres(terminals, max_size, match_whole):
  164. # Python sets an unreasonable group limit (currently 100) in its re module
  165. # Worse, the only way to know we reached it is by catching an AssertionError!
  166. # This function recursively tries less and less groups until it's successful.
  167. postfix = '$' if match_whole else ''
  168. mres = []
  169. while terminals:
  170. try:
  171. mre = re.compile(u'|'.join(u'(?P<%s>%s)'%(t.name, t.pattern.to_regexp()+postfix) for t in terminals[:max_size]))
  172. except AssertionError: # Yes, this is what Python provides us.. :/
  173. return _build_mres(terminals, max_size//2, match_whole)
  174. # terms_from_name = {t.name: t for t in terminals[:max_size]}
  175. mres.append((mre, {i:n for n,i in mre.groupindex.items()} ))
  176. terminals = terminals[max_size:]
  177. return mres
  178. def build_mres(terminals, match_whole=False):
  179. return _build_mres(terminals, len(terminals), match_whole)
  180. def _regexp_has_newline(r):
  181. """Expressions that may indicate newlines in a regexp:
  182. - newlines (\n)
  183. - escaped newline (\\n)
  184. - anything but ([^...])
  185. - any-char (.) when the flag (?s) exists
  186. """
  187. return '\n' in r or '\\n' in r or '[^' in r or ('(?s' in r and '.' in r)
  188. class Lexer:
  189. """Lexer interface
  190. Method Signatures:
  191. lex(self, stream) -> Iterator[Token]
  192. set_parser_state(self, state) # Optional
  193. """
  194. set_parser_state = NotImplemented
  195. lex = NotImplemented
  196. class TraditionalLexer(Lexer):
  197. def __init__(self, terminals, ignore=(), user_callbacks={}):
  198. assert all(isinstance(t, TerminalDef) for t in terminals), terminals
  199. terminals = list(terminals)
  200. # Sanitization
  201. for t in terminals:
  202. try:
  203. re.compile(t.pattern.to_regexp())
  204. except:
  205. raise LexError("Cannot compile token %s: %s" % (t.name, t.pattern))
  206. if t.pattern.min_width == 0:
  207. raise LexError("Lexer does not allow zero-width terminals. (%s: %s)" % (t.name, t.pattern))
  208. assert set(ignore) <= {t.name for t in terminals}
  209. # Init
  210. self.newline_types = [t.name for t in terminals if _regexp_has_newline(t.pattern.to_regexp())]
  211. self.ignore_types = list(ignore)
  212. terminals.sort(key=lambda x:(-x.priority, -x.pattern.max_width, -len(x.pattern.value), x.name))
  213. terminals, self.callback = _create_unless(terminals)
  214. assert all(self.callback.values())
  215. for type_, f in user_callbacks.items():
  216. assert type_ not in self.callback
  217. self.callback[type_] = f
  218. self.terminals = terminals
  219. self.mres = build_mres(terminals)
  220. def lex(self, stream):
  221. return _Lex(self).lex(stream, self.newline_types, self.ignore_types)
  222. class ContextualLexer(Lexer):
  223. def __init__(self, terminals, states, ignore=(), always_accept=(), user_callbacks={}):
  224. tokens_by_name = {}
  225. for t in terminals:
  226. assert t.name not in tokens_by_name, t
  227. tokens_by_name[t.name] = t
  228. lexer_by_tokens = {}
  229. self.lexers = {}
  230. for state, accepts in states.items():
  231. key = frozenset(accepts)
  232. try:
  233. lexer = lexer_by_tokens[key]
  234. except KeyError:
  235. accepts = set(accepts) | set(ignore) | set(always_accept)
  236. state_tokens = [tokens_by_name[n] for n in accepts if n and n in tokens_by_name]
  237. lexer = TraditionalLexer(state_tokens, ignore=ignore, user_callbacks=user_callbacks)
  238. lexer_by_tokens[key] = lexer
  239. self.lexers[state] = lexer
  240. self.root_lexer = TraditionalLexer(terminals, ignore=ignore, user_callbacks=user_callbacks)
  241. self.set_parser_state(None) # Needs to be set on the outside
  242. def set_parser_state(self, state):
  243. self.parser_state = state
  244. def lex(self, stream):
  245. l = _Lex(self.lexers[self.parser_state], self.parser_state)
  246. for x in l.lex(stream, self.root_lexer.newline_types, self.root_lexer.ignore_types):
  247. yield x
  248. l.lexer = self.lexers[self.parser_state]
  249. l.state = self.parser_state