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.

366 lines
12 KiB

  1. ## Lexer Implementation
  2. import re
  3. from .utils import Str, classify, get_regexp_width, Py36, Serialize
  4. from .exceptions import UnexpectedCharacters, LexError
  5. class Pattern(Serialize):
  6. __serialize_fields__ = 'value', 'flags'
  7. def __init__(self, value, flags=()):
  8. self.value = value
  9. self.flags = frozenset(flags)
  10. def __repr__(self):
  11. return repr(self.to_regexp())
  12. # Pattern Hashing assumes all subclasses have a different priority!
  13. def __hash__(self):
  14. return hash((type(self), self.value, self.flags))
  15. def __eq__(self, other):
  16. return type(self) == type(other) and self.value == other.value and self.flags == other.flags
  17. def to_regexp(self):
  18. raise NotImplementedError()
  19. if Py36:
  20. # Python 3.6 changed syntax for flags in regular expression
  21. def _get_flags(self, value):
  22. for f in self.flags:
  23. value = ('(?%s:%s)' % (f, value))
  24. return value
  25. else:
  26. def _get_flags(self, value):
  27. for f in self.flags:
  28. value = ('(?%s)' % f) + value
  29. return value
  30. class PatternStr(Pattern):
  31. def to_regexp(self):
  32. return self._get_flags(re.escape(self.value))
  33. @property
  34. def min_width(self):
  35. return len(self.value)
  36. max_width = min_width
  37. class PatternRE(Pattern):
  38. def to_regexp(self):
  39. return self._get_flags(self.value)
  40. @property
  41. def min_width(self):
  42. return get_regexp_width(self.to_regexp())[0]
  43. @property
  44. def max_width(self):
  45. return get_regexp_width(self.to_regexp())[1]
  46. class TerminalDef(Serialize):
  47. __serialize_fields__ = 'name', 'pattern', 'priority'
  48. __serialize_namespace__ = lambda: (PatternStr, PatternRE)
  49. def __init__(self, name, pattern, priority=1):
  50. assert isinstance(pattern, Pattern), pattern
  51. self.name = name
  52. self.pattern = pattern
  53. self.priority = priority
  54. def __repr__(self):
  55. return '%s(%r, %r)' % (type(self).__name__, self.name, self.pattern)
  56. ###{standalone
  57. class Token(Str):
  58. __slots__ = ('type', 'pos_in_stream', 'value', 'line', 'column', 'end_line', 'end_column')
  59. def __new__(cls, type_, value, pos_in_stream=None, line=None, column=None, end_line=None, end_column=None):
  60. try:
  61. self = super(Token, cls).__new__(cls, value)
  62. except UnicodeDecodeError:
  63. value = value.decode('latin1')
  64. self = super(Token, cls).__new__(cls, value)
  65. self.type = type_
  66. self.pos_in_stream = pos_in_stream
  67. self.value = value
  68. self.line = line
  69. self.column = column
  70. self.end_line = end_line
  71. self.end_column = end_column
  72. return self
  73. @classmethod
  74. def new_borrow_pos(cls, type_, value, borrow_t):
  75. return cls(type_, value, borrow_t.pos_in_stream, borrow_t.line, borrow_t.column, borrow_t.end_line, borrow_t.end_column)
  76. def __reduce__(self):
  77. return (self.__class__, (self.type, self.value, self.pos_in_stream, self.line, self.column, ))
  78. def __repr__(self):
  79. return 'Token(%s, %r)' % (self.type, self.value)
  80. def __deepcopy__(self, memo):
  81. return Token(self.type, self.value, self.pos_in_stream, self.line, self.column)
  82. def __eq__(self, other):
  83. if isinstance(other, Token) and self.type != other.type:
  84. return False
  85. return Str.__eq__(self, other)
  86. __hash__ = Str.__hash__
  87. class LineCounter:
  88. def __init__(self):
  89. self.newline_char = '\n'
  90. self.char_pos = 0
  91. self.line = 1
  92. self.column = 1
  93. self.line_start_pos = 0
  94. def feed(self, token, test_newline=True):
  95. """Consume a token and calculate the new line & column.
  96. As an optional optimization, set test_newline=False is token doesn't contain a newline.
  97. """
  98. if test_newline:
  99. newlines = token.count(self.newline_char)
  100. if newlines:
  101. self.line += newlines
  102. self.line_start_pos = self.char_pos + token.rindex(self.newline_char) + 1
  103. self.char_pos += len(token)
  104. self.column = self.char_pos - self.line_start_pos + 1
  105. class _Lex:
  106. "Built to serve both Lexer and ContextualLexer"
  107. def __init__(self, lexer, state=None):
  108. self.lexer = lexer
  109. self.state = state
  110. def lex(self, stream, newline_types, ignore_types):
  111. newline_types = frozenset(newline_types)
  112. ignore_types = frozenset(ignore_types)
  113. line_ctr = LineCounter()
  114. while line_ctr.char_pos < len(stream):
  115. lexer = self.lexer
  116. for mre, type_from_index in lexer.mres:
  117. m = mre.match(stream, line_ctr.char_pos)
  118. if not m:
  119. continue
  120. t = None
  121. value = m.group(0)
  122. type_ = type_from_index[m.lastindex]
  123. if type_ not in ignore_types:
  124. t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  125. if t.type in lexer.callback:
  126. t = lexer.callback[t.type](t)
  127. if not isinstance(t, Token):
  128. raise ValueError("Callbacks must return a token (returned %r)" % t)
  129. yield t
  130. else:
  131. if type_ in lexer.callback:
  132. t = Token(type_, value, line_ctr.char_pos, line_ctr.line, line_ctr.column)
  133. lexer.callback[type_](t)
  134. line_ctr.feed(value, type_ in newline_types)
  135. if t:
  136. t.end_line = line_ctr.line
  137. t.end_column = line_ctr.column
  138. break
  139. else:
  140. allowed = [v for m, tfi in lexer.mres for v in tfi.values()]
  141. raise UnexpectedCharacters(stream, line_ctr.char_pos, line_ctr.line, line_ctr.column, allowed=allowed, state=self.state)
  142. class UnlessCallback:
  143. def __init__(self, mres):
  144. self.mres = mres
  145. def __call__(self, t):
  146. for mre, type_from_index in self.mres:
  147. m = mre.match(t.value)
  148. if m:
  149. t.type = type_from_index[m.lastindex]
  150. break
  151. return t
  152. class CallChain:
  153. def __init__(self, callback1, callback2, cond):
  154. self.callback1 = callback1
  155. self.callback2 = callback2
  156. self.cond = cond
  157. def __call__(self, t):
  158. t2 = self.callback1(t)
  159. return self.callback2(t) if self.cond(t2) else t2
  160. ###}
  161. def _create_unless(terminals):
  162. tokens_by_type = classify(terminals, lambda t: type(t.pattern))
  163. assert len(tokens_by_type) <= 2, tokens_by_type.keys()
  164. embedded_strs = set()
  165. callback = {}
  166. for retok in tokens_by_type.get(PatternRE, []):
  167. unless = [] # {}
  168. for strtok in tokens_by_type.get(PatternStr, []):
  169. if strtok.priority > retok.priority:
  170. continue
  171. s = strtok.pattern.value
  172. m = re.match(retok.pattern.to_regexp(), s)
  173. if m and m.group(0) == s:
  174. unless.append(strtok)
  175. if strtok.pattern.flags <= retok.pattern.flags:
  176. embedded_strs.add(strtok)
  177. if unless:
  178. callback[retok.name] = UnlessCallback(build_mres(unless, match_whole=True))
  179. terminals = [t for t in terminals if t not in embedded_strs]
  180. return terminals, callback
  181. def _build_mres(terminals, max_size, match_whole):
  182. # Python sets an unreasonable group limit (currently 100) in its re module
  183. # Worse, the only way to know we reached it is by catching an AssertionError!
  184. # This function recursively tries less and less groups until it's successful.
  185. postfix = '$' if match_whole else ''
  186. mres = []
  187. while terminals:
  188. try:
  189. mre = re.compile(u'|'.join(u'(?P<%s>%s)'%(t.name, t.pattern.to_regexp()+postfix) for t in terminals[:max_size]))
  190. except AssertionError: # Yes, this is what Python provides us.. :/
  191. return _build_mres(terminals, max_size//2, match_whole)
  192. # terms_from_name = {t.name: t for t in terminals[:max_size]}
  193. mres.append((mre, {i:n for n,i in mre.groupindex.items()} ))
  194. terminals = terminals[max_size:]
  195. return mres
  196. def build_mres(terminals, match_whole=False):
  197. return _build_mres(terminals, len(terminals), match_whole)
  198. def _regexp_has_newline(r):
  199. """Expressions that may indicate newlines in a regexp:
  200. - newlines (\n)
  201. - escaped newline (\\n)
  202. - anything but ([^...])
  203. - any-char (.) when the flag (?s) exists
  204. """
  205. return '\n' in r or '\\n' in r or '[^' in r or ('(?s' in r and '.' in r)
  206. class Lexer(Serialize):
  207. """Lexer interface
  208. Method Signatures:
  209. lex(self, stream) -> Iterator[Token]
  210. set_parser_state(self, state) # Optional
  211. """
  212. set_parser_state = NotImplemented
  213. lex = NotImplemented
  214. class TraditionalLexer(Lexer):
  215. __serialize_fields__ = 'terminals', 'ignore_types', 'newline_types'
  216. __serialize_namespace__ = lambda: (TerminalDef,)
  217. def _deserialize(self):
  218. self.mres = build_mres(self.terminals)
  219. self.callback = {} # TODO implement
  220. def __init__(self, terminals, ignore=(), user_callbacks={}):
  221. assert all(isinstance(t, TerminalDef) for t in terminals), terminals
  222. terminals = list(terminals)
  223. # Sanitization
  224. for t in terminals:
  225. try:
  226. re.compile(t.pattern.to_regexp())
  227. except:
  228. raise LexError("Cannot compile token %s: %s" % (t.name, t.pattern))
  229. if t.pattern.min_width == 0:
  230. raise LexError("Lexer does not allow zero-width terminals. (%s: %s)" % (t.name, t.pattern))
  231. assert set(ignore) <= {t.name for t in terminals}
  232. # Init
  233. self.newline_types = [t.name for t in terminals if _regexp_has_newline(t.pattern.to_regexp())]
  234. self.ignore_types = list(ignore)
  235. terminals.sort(key=lambda x:(-x.priority, -x.pattern.max_width, -len(x.pattern.value), x.name))
  236. terminals, self.callback = _create_unless(terminals)
  237. assert all(self.callback.values())
  238. for type_, f in user_callbacks.items():
  239. if type_ in self.callback:
  240. # Already a callback there, probably UnlessCallback
  241. self.callback[type_] = CallChain(self.callback[type_], f, lambda t: t.type == type_)
  242. else:
  243. self.callback[type_] = f
  244. self.terminals = terminals
  245. self.mres = build_mres(terminals)
  246. def lex(self, stream):
  247. return _Lex(self).lex(stream, self.newline_types, self.ignore_types)
  248. class ContextualLexer(Lexer):
  249. __serialize_fields__ = 'root_lexer', 'lexers'
  250. __serialize_namespace__ = lambda: (TraditionalLexer,)
  251. def __init__(self, terminals, states, ignore=(), always_accept=(), user_callbacks={}):
  252. tokens_by_name = {}
  253. for t in terminals:
  254. assert t.name not in tokens_by_name, t
  255. tokens_by_name[t.name] = t
  256. lexer_by_tokens = {}
  257. self.lexers = {}
  258. for state, accepts in states.items():
  259. key = frozenset(accepts)
  260. try:
  261. lexer = lexer_by_tokens[key]
  262. except KeyError:
  263. accepts = set(accepts) | set(ignore) | set(always_accept)
  264. state_tokens = [tokens_by_name[n] for n in accepts if n and n in tokens_by_name]
  265. lexer = TraditionalLexer(state_tokens, ignore=ignore, user_callbacks=user_callbacks)
  266. lexer_by_tokens[key] = lexer
  267. self.lexers[state] = lexer
  268. self.root_lexer = TraditionalLexer(terminals, ignore=ignore, user_callbacks=user_callbacks)
  269. self.set_parser_state(None) # Needs to be set on the outside
  270. def set_parser_state(self, state):
  271. self.parser_state = state
  272. def lex(self, stream):
  273. l = _Lex(self.lexers[self.parser_state], self.parser_state)
  274. for x in l.lex(stream, self.root_lexer.newline_types, self.root_lexer.ignore_types):
  275. yield x
  276. l.lexer = self.lexers[self.parser_state]
  277. l.state = self.parser_state