This repo contains code to mirror other repos. It also contains the code that is getting mirrored.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

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