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.

222 lines
7.8 KiB

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