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.

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