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.

234 lines
8.1 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. mres = build_mres(strs, match_whole=True)
  40. def unless_callback(t):
  41. # if t in strs:
  42. # t.type = strs[t]
  43. for mre, type_from_index in mres:
  44. m = mre.match(t.value)
  45. if m:
  46. value = m.group(0)
  47. t.type = type_from_index[m.lastindex]
  48. return t
  49. return unless_callback
  50. def _create_unless(tokens):
  51. tokens_by_type = classify(tokens, lambda t: type(t.pattern))
  52. assert len(tokens_by_type) <= 2, tokens_by_type.keys()
  53. embedded_strs = set()
  54. callback = {}
  55. for retok in tokens_by_type.get(PatternRE, []):
  56. unless = [] # {}
  57. for strtok in tokens_by_type.get(PatternStr, []):
  58. s = strtok.pattern.value
  59. m = re.match(retok.pattern.value, s)
  60. if m and m.group(0) == s:
  61. embedded_strs.add(strtok.name)
  62. #unless[s] = strtok.name
  63. unless.append(strtok)
  64. if unless:
  65. callback[retok.name] = _create_unless_callback(unless)
  66. tokens = [t for t in tokens if t.name not in embedded_strs]
  67. return tokens, callback
  68. def _build_mres(tokens, max_size, match_whole):
  69. # Python sets an unreasonable group limit (currently 100) in its re module
  70. # Worse, the only way to know we reached it is by catching an AssertionError!
  71. # This function recursively tries less and less groups until it's successful.
  72. postfix = '$' if match_whole else ''
  73. mres = []
  74. while tokens:
  75. try:
  76. mre = re.compile(u'|'.join(u'(?P<%s>%s)'%(t.name, t.pattern.to_regexp()) for t in tokens[:max_size])+postfix)
  77. except AssertionError: # Yes, this is what Python provides us.. :/
  78. return _build_mres(tokens, max_size//2, match_whole)
  79. mres.append((mre, {i:n for n,i in mre.groupindex.items()} ))
  80. tokens = tokens[max_size:]
  81. return mres
  82. def build_mres(tokens, match_whole=False):
  83. return _build_mres(tokens, len(tokens), match_whole)
  84. class Lexer(object):
  85. def __init__(self, tokens, ignore=()):
  86. assert all(isinstance(t, TokenDef) for t in tokens), tokens
  87. self.ignore = ignore
  88. self.newline_char = '\n'
  89. tokens = list(tokens)
  90. # Sanitization
  91. for t in tokens:
  92. try:
  93. re.compile(t.pattern.to_regexp())
  94. except:
  95. raise LexError("Cannot compile token %s: %s" % (t.name, t.pattern))
  96. width = sre_parse.parse(t.pattern.to_regexp()).getwidth()
  97. if width[0] == 0:
  98. raise LexError("Lexer does not allow zero-width tokens. (%s: %s)" % (t.name, t.pattern))
  99. token_names = {t.name for t in tokens}
  100. for t in ignore:
  101. if t not in token_names:
  102. raise LexError("Token '%s' was marked to ignore but it is not defined!" % t)
  103. # Init
  104. self.newline_types = [t.name for t in tokens if _regexp_has_newline(t.pattern.to_regexp())]
  105. self.ignore_types = [t for t in ignore]
  106. tokens, self.callback = _create_unless(tokens)
  107. assert all(self.callback.values())
  108. tokens.sort(key=lambda x:(x.pattern.priority, len(x.pattern.value)), reverse=True)
  109. self.tokens = tokens
  110. self.mres = build_mres(tokens)
  111. def lex(self, stream):
  112. lex_pos = 0
  113. line = 1
  114. col_start_pos = 0
  115. newline_types = list(self.newline_types)
  116. ignore_types = list(self.ignore_types)
  117. while True:
  118. for mre, type_from_index in self.mres:
  119. m = mre.match(stream, lex_pos)
  120. if m:
  121. value = m.group(0)
  122. type_ = type_from_index[m.lastindex]
  123. if type_ not in ignore_types:
  124. t = Token(type_, value, lex_pos, line, lex_pos - col_start_pos)
  125. if t.type in self.callback:
  126. t = self.callback[t.type](t)
  127. yield t
  128. if type_ in newline_types:
  129. newlines = value.count(self.newline_char)
  130. if newlines:
  131. line += newlines
  132. col_start_pos = lex_pos + value.rindex(self.newline_char)
  133. lex_pos += len(value)
  134. break
  135. else:
  136. if lex_pos < len(stream):
  137. raise UnexpectedInput(stream, lex_pos, line, lex_pos - col_start_pos)
  138. break
  139. class ContextualLexer:
  140. def __init__(self, tokens, states, ignore=(), always_accept=()):
  141. tokens_by_name = {}
  142. for t in tokens:
  143. assert t.name not in tokens_by_name, t
  144. tokens_by_name[t.name] = t
  145. lexer_by_tokens = {}
  146. self.lexers = {}
  147. for state, accepts in states.items():
  148. key = frozenset(accepts)
  149. try:
  150. lexer = lexer_by_tokens[key]
  151. except KeyError:
  152. accepts = set(accepts) | set(ignore) | set(always_accept)
  153. state_tokens = [tokens_by_name[n] for n in accepts if is_terminal(n) and n!='$end']
  154. lexer = Lexer(state_tokens, ignore=ignore)
  155. lexer_by_tokens[key] = lexer
  156. self.lexers[state] = lexer
  157. self.root_lexer = Lexer(tokens, ignore=ignore)
  158. self.set_parser_state(None) # Needs to be set on the outside
  159. def set_parser_state(self, state):
  160. self.parser_state = state
  161. def lex(self, stream):
  162. lex_pos = 0
  163. line = 1
  164. col_start_pos = 0
  165. newline_types = list(self.root_lexer.newline_types)
  166. ignore_types = list(self.root_lexer.ignore_types)
  167. while True:
  168. lexer = self.lexers[self.parser_state]
  169. for mre, type_from_index in lexer.mres:
  170. m = mre.match(stream, lex_pos)
  171. if m:
  172. value = m.group(0)
  173. type_ = type_from_index[m.lastindex]
  174. if type_ not in ignore_types:
  175. t = Token(type_, value, lex_pos, line, lex_pos - col_start_pos)
  176. if t.type in lexer.callback:
  177. t = lexer.callback[t.type](t)
  178. yield t
  179. if type_ in newline_types:
  180. newlines = value.count(lexer.newline_char)
  181. if newlines:
  182. line += newlines
  183. col_start_pos = lex_pos + value.rindex(lexer.newline_char)
  184. lex_pos += len(value)
  185. break
  186. else:
  187. if lex_pos < len(stream):
  188. print("Allowed tokens:", lexer.tokens)
  189. raise UnexpectedInput(stream, lex_pos, line, lex_pos - col_start_pos)
  190. break