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.

260 lines
8.7 KiB

  1. ## Lexer Implementation
  2. import re
  3. from .utils import Str, classify
  4. from .common import is_terminal, PatternStr, PatternRE, TokenDef
  5. ###{standalone
  6. class LexError(Exception):
  7. pass
  8. class UnexpectedInput(LexError):
  9. def __init__(self, seq, lex_pos, line, column, allowed=None, considered_rules=None):
  10. context = seq[lex_pos:lex_pos+5]
  11. message = "No token defined for: '%s' in %r at line %d col %d" % (seq[lex_pos], context, line, column)
  12. if allowed:
  13. message += '\n\nExpecting: %s\n' % allowed
  14. super(UnexpectedInput, self).__init__(message)
  15. self.line = line
  16. self.column = column
  17. self.context = context
  18. self.allowed = allowed
  19. self.considered_rules = considered_rules
  20. class Token(Str):
  21. __slots__ = ('type', 'pos_in_stream', 'value', 'line', 'column', 'end_line', 'end_column')
  22. def __new__(cls, type_, value, pos_in_stream=None, line=None, column=None):
  23. self = super(Token, cls).__new__(cls, value)
  24. self.type = type_
  25. self.pos_in_stream = pos_in_stream
  26. self.value = value
  27. self.line = line
  28. self.column = column
  29. self.end_line = None
  30. self.end_column = None
  31. return self
  32. @classmethod
  33. def new_borrow_pos(cls, type_, value, borrow_t):
  34. return cls(type_, value, borrow_t.pos_in_stream, line=borrow_t.line, column=borrow_t.column)
  35. def __reduce__(self):
  36. return (self.__class__, (self.type, self.value, self.pos_in_stream, self.line, self.column, ))
  37. def __repr__(self):
  38. return 'Token(%s, %r)' % (self.type, self.value)
  39. def __deepcopy__(self, memo):
  40. return Token(self.type, self.value, self.pos_in_stream, self.line, self.column)
  41. def __eq__(self, other):
  42. if isinstance(other, Token) and self.type != other.type:
  43. return False
  44. return Str.__eq__(self, other)
  45. __hash__ = Str.__hash__
  46. class LineCounter:
  47. def __init__(self):
  48. self.newline_char = '\n'
  49. self.char_pos = 0
  50. self.line = 1
  51. self.column = 1
  52. self.line_start_pos = 0
  53. def feed(self, token, test_newline=True):
  54. """Consume a token and calculate the new line & column.
  55. As an optional optimization, set test_newline=False is token doesn't contain a newline.
  56. """
  57. if test_newline:
  58. newlines = token.count(self.newline_char)
  59. if newlines:
  60. self.line += newlines
  61. self.line_start_pos = self.char_pos + token.rindex(self.newline_char) + 1
  62. self.char_pos += len(token)
  63. self.column = self.char_pos - self.line_start_pos + 1
  64. class _Lex:
  65. "Built to serve both Lexer and ContextualLexer"
  66. def __init__(self, lexer):
  67. self.lexer = lexer
  68. def lex(self, stream, newline_types, ignore_types):
  69. newline_types = list(newline_types)
  70. ignore_types = list(ignore_types)
  71. line_ctr = LineCounter()
  72. t = None
  73. while True:
  74. lexer = self.lexer
  75. for mre, type_from_index in lexer.mres:
  76. m = mre.match(stream, line_ctr.char_pos)
  77. if m:
  78. value = m.group(0)
  79. type_ = type_from_index[m.lastindex]
  80. if type_ not in ignore_types:
  81. t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  82. if t.type in lexer.callback:
  83. t = lexer.callback[t.type](t)
  84. yield t
  85. else:
  86. if type_ in lexer.callback:
  87. t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  88. lexer.callback[type_](t)
  89. line_ctr.feed(value, type_ in newline_types)
  90. if t:
  91. t.end_line = line_ctr.line
  92. t.end_column = line_ctr.column
  93. break
  94. else:
  95. if line_ctr.char_pos < len(stream):
  96. raise UnexpectedInput(stream, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  97. break
  98. class UnlessCallback:
  99. def __init__(self, mres):
  100. self.mres = mres
  101. def __call__(self, t):
  102. for mre, type_from_index in self.mres:
  103. m = mre.match(t.value)
  104. if m:
  105. value = m.group(0)
  106. t.type = type_from_index[m.lastindex]
  107. break
  108. return t
  109. ###}
  110. def _create_unless(tokens):
  111. tokens_by_type = classify(tokens, lambda t: type(t.pattern))
  112. assert len(tokens_by_type) <= 2, tokens_by_type.keys()
  113. embedded_strs = set()
  114. callback = {}
  115. for retok in tokens_by_type.get(PatternRE, []):
  116. unless = [] # {}
  117. for strtok in tokens_by_type.get(PatternStr, []):
  118. if strtok.priority > retok.priority:
  119. continue
  120. s = strtok.pattern.value
  121. m = re.match(retok.pattern.to_regexp(), s)
  122. if m and m.group(0) == s:
  123. unless.append(strtok)
  124. if strtok.pattern.flags <= retok.pattern.flags:
  125. embedded_strs.add(strtok)
  126. if unless:
  127. callback[retok.name] = UnlessCallback(build_mres(unless, match_whole=True))
  128. tokens = [t for t in tokens if t not in embedded_strs]
  129. return tokens, callback
  130. def _build_mres(tokens, max_size, match_whole):
  131. # Python sets an unreasonable group limit (currently 100) in its re module
  132. # Worse, the only way to know we reached it is by catching an AssertionError!
  133. # This function recursively tries less and less groups until it's successful.
  134. postfix = '$' if match_whole else ''
  135. mres = []
  136. while tokens:
  137. try:
  138. mre = re.compile(u'|'.join(u'(?P<%s>%s)'%(t.name, t.pattern.to_regexp()+postfix) for t in tokens[:max_size]))
  139. except AssertionError: # Yes, this is what Python provides us.. :/
  140. return _build_mres(tokens, max_size//2, match_whole)
  141. mres.append((mre, {i:n for n,i in mre.groupindex.items()} ))
  142. tokens = tokens[max_size:]
  143. return mres
  144. def build_mres(tokens, match_whole=False):
  145. return _build_mres(tokens, len(tokens), match_whole)
  146. def _regexp_has_newline(r):
  147. return '\n' in r or '\\n' in r or ('(?s' in r and '.' in r)
  148. class Lexer:
  149. def __init__(self, tokens, ignore=(), user_callbacks={}):
  150. assert all(isinstance(t, TokenDef) for t in tokens), tokens
  151. tokens = list(tokens)
  152. # Sanitization
  153. for t in tokens:
  154. try:
  155. re.compile(t.pattern.to_regexp())
  156. except:
  157. raise LexError("Cannot compile token %s: %s" % (t.name, t.pattern))
  158. if t.pattern.min_width == 0:
  159. raise LexError("Lexer does not allow zero-width tokens. (%s: %s)" % (t.name, t.pattern))
  160. assert set(ignore) <= {t.name for t in tokens}
  161. # Init
  162. self.newline_types = [t.name for t in tokens if _regexp_has_newline(t.pattern.to_regexp())]
  163. self.ignore_types = list(ignore)
  164. tokens.sort(key=lambda x:(-x.priority, -x.pattern.max_width, -len(x.pattern.value), x.name))
  165. tokens, self.callback = _create_unless(tokens)
  166. assert all(self.callback.values())
  167. for type_, f in user_callbacks.items():
  168. assert type_ not in self.callback
  169. self.callback[type_] = f
  170. self.tokens = tokens
  171. self.mres = build_mres(tokens)
  172. def lex(self, stream):
  173. return _Lex(self).lex(stream, self.newline_types, self.ignore_types)
  174. class ContextualLexer:
  175. def __init__(self, tokens, states, ignore=(), always_accept=(), user_callbacks={}):
  176. tokens_by_name = {}
  177. for t in tokens:
  178. assert t.name not in tokens_by_name, t
  179. tokens_by_name[t.name] = t
  180. lexer_by_tokens = {}
  181. self.lexers = {}
  182. for state, accepts in states.items():
  183. key = frozenset(accepts)
  184. try:
  185. lexer = lexer_by_tokens[key]
  186. except KeyError:
  187. accepts = set(accepts) | set(ignore) | set(always_accept)
  188. state_tokens = [tokens_by_name[n] for n in accepts if n and n in tokens_by_name]
  189. lexer = Lexer(state_tokens, ignore=ignore, user_callbacks=user_callbacks)
  190. lexer_by_tokens[key] = lexer
  191. self.lexers[state] = lexer
  192. self.root_lexer = Lexer(tokens, ignore=ignore, user_callbacks=user_callbacks)
  193. self.set_parser_state(None) # Needs to be set on the outside
  194. def set_parser_state(self, state):
  195. self.parser_state = state
  196. def lex(self, stream):
  197. l = _Lex(self.lexers[self.parser_state])
  198. for x in l.lex(stream, self.root_lexer.newline_types, self.root_lexer.ignore_types):
  199. yield x
  200. l.lexer = self.lexers[self.parser_state]