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.

394 lines
13 KiB

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