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.

256 lines
8.6 KiB

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