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.

400 lines
13 KiB

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