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.

397 lines
13 KiB

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